diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs new file mode 100644 index 00000000..b3b54ab5 --- /dev/null +++ b/crates/ec-h264/src/cabac.rs @@ -0,0 +1,559 @@ +//! CABAC slice-data parsing (spec clause 9.3): arithmetic decoding engine, +//! context variables, binarizations and context selection. +//! +//! Scope is what an I slice of a frame-coded 4:2:0 8-bit stream needs; every +//! other tool the decoder refuses by name before reaching this module, so the +//! contexts, block categories and initialisation columns that only P, B, field +//! or 8x8-transform coding reads are absent rather than transcribed untested. +//! +//! The engine keeps codIRange and codIOffset in `u32` with the spec's exact +//! integer steps — no probability floats, no shortcuts — and reads its bits +//! from the same [`BitCursor`] the CAVLC path uses. Past the end of the RBSP the +//! cursor is treated as zero-filled: a conformant stream never depends on those +//! bits (the last one read is the rbsp_stop_one_bit), and the macroblock loop, +//! not the bit supply, is what bounds a truncated one. + +use ec_core::error::{Error, Result}; + +use crate::bits::BitCursor; +use crate::cabac_tables::{ + INIT_60_69, INIT_70_275, INIT_399_401, INIT_MB_TYPE_I, RANGE_LPS, TRANS_LPS, TRANS_MPS, +}; +use crate::entropy::{BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_PCM, MbCtx, MbInfo}; + +/// Highest ctxIdx this decoder can address, plus one (399..401 is the +/// transform_size_8x8_flag block, the last range an I slice can reach). +const NUM_CTX: usize = 402; + +/// ctxIdx 276 (end_of_slice_flag and the I_PCM bin of mb_type) is decoded by +/// DecodeTerminate and has no adapting state. +const CTX_TERMINATE: usize = 276; + +/// Table 9-40, `ctxIdxBlockCatOffset` for the five 4:2:0 block categories. +const CBF_CAT_OFF: [usize; 5] = [0, 4, 8, 12, 16]; +const SIG_CAT_OFF: [usize; 5] = [0, 15, 29, 44, 47]; +const ABS_CAT_OFF: [usize; 5] = [0, 10, 20, 30, 39]; + +/// ctxIdxOffset values of Table 9-34 used here. +const OFF_MB_TYPE: usize = 3; +const OFF_QP_DELTA: usize = 60; +const OFF_CHROMA_PRED: usize = 64; +const OFF_PREV_I4: usize = 68; +const OFF_REM_I4: usize = 69; +const OFF_CBP_LUMA: usize = 73; +const OFF_CBP_CHROMA: usize = 77; +const OFF_CBF: usize = 85; +const OFF_SIG: usize = 105; +const OFF_LAST: usize = 166; +const OFF_ABS: usize = 227; +const OFF_TRANSFORM_8X8: usize = 399; + +pub(crate) struct Cabac<'a> { + r: BitCursor<'a>, + /// codIRange (9.3.3.2). + range: u32, + /// codIOffset (9.3.3.2). + offset: u32, + /// Context variables: `pStateIdx << 1 | valMPS`, indexed by ctxIdx. + state: [u8; NUM_CTX], + /// Neighbourhood of the macroblock being parsed. + ctx: MbCtx, + /// CodedBlockPatternLuma bins decoded so far in this macroblock, for the + /// within-macroblock neighbours of clause 9.3.3.1.1.4. + cbp_luma_bins: u8, +} + +impl<'a> Cabac<'a> { + /// Start CABAC parsing at `header_bits`: `cabac_alignment_one_bit`s, then + /// the context and engine initialisation of clause 9.3.1. + pub(crate) fn new(rbsp: &'a [u8], header_bits: u64, slice_qp: i32) -> Result> { + let mut r = BitCursor::new(rbsp, header_bits); + // cabac_alignment_one_bit (7.3.4): the stuffing bits are all 1, which + // a corrupt-stream check would only duplicate; skipping to the byte + // boundary is the whole effect. + r.align_to_byte(); + let mut c = Cabac { + r, + range: 510, + offset: 0, + state: [63 << 1; NUM_CTX], + ctx: MbCtx::default(), + cbp_luma_bins: 0, + }; + c.init_contexts(slice_qp); + c.init_engine()?; + Ok(c) + } + + /// 9.3.1.1: pStateIdx and valMPS from the (m, n) table entries and SliceQPY. + fn init_contexts(&mut self, slice_qp: i32) { + let qp = slice_qp.clamp(0, 51); + let set = |state: &mut [u8; NUM_CTX], idx: usize, (m, n): (i8, i8)| { + let pre = (((i32::from(m) * qp) >> 4) + i32::from(n)).clamp(1, 126); + state[idx] = if pre <= 63 { + ((63 - pre) as u8) << 1 + } else { + (((pre - 64) as u8) << 1) | 1 + }; + }; + for (i, &mn) in INIT_MB_TYPE_I.iter().enumerate() { + set(&mut self.state, i, mn); + } + for (i, &mn) in INIT_60_69.iter().enumerate() { + set(&mut self.state, 60 + i, mn); + } + for (i, &mn) in INIT_70_275.iter().enumerate() { + set(&mut self.state, 70 + i, mn); + } + for (i, &mn) in INIT_399_401.iter().enumerate() { + set(&mut self.state, OFF_TRANSFORM_8X8 + i, mn); + } + } + + /// 9.3.1.2: codIRange = 510, codIOffset = read_bits(9). + fn init_engine(&mut self) -> Result<()> { + self.range = 510; + self.offset = self.r.read_bits(9)?; + if self.offset >= 510 { + return Err(Error::corrupt("CABAC codIOffset initialised to 510 or 511")); + } + Ok(()) + } + + /// One bit of slice data; zero past the end (see the module note). + #[inline] + fn bit(&mut self) -> u32 { + u32::from(self.r.read_bit().unwrap_or(false)) + } + + /// 9.3.3.2.2 RenormD. + #[inline] + fn renorm(&mut self) { + while self.range < 256 { + self.range <<= 1; + self.offset = (self.offset << 1) | self.bit(); + } + } + + /// 9.3.3.2.1 DecodeDecision, with the state transition of 9.3.3.2.1.1. + #[inline] + fn decision(&mut self, ctx_idx: usize) -> bool { + let s = self.state[ctx_idx]; + let p = usize::from(s >> 1); + let mps = s & 1; + let lps = u32::from(RANGE_LPS[p][((self.range >> 6) & 3) as usize]); + self.range -= lps; + let bin; + if self.offset >= self.range { + bin = mps ^ 1; + self.offset -= self.range; + self.range = lps; + // Crossing state 0 swaps the most probable symbol. + let mps = if p == 0 { mps ^ 1 } else { mps }; + self.state[ctx_idx] = (TRANS_LPS[p] << 1) | mps; + } else { + bin = mps; + self.state[ctx_idx] = (TRANS_MPS[p] << 1) | mps; + } + self.renorm(); + bin != 0 + } + + /// 9.3.3.2.3 DecodeBypass. + #[inline] + fn bypass(&mut self) -> bool { + self.offset = (self.offset << 1) | self.bit(); + if self.offset >= self.range { + self.offset -= self.range; + true + } else { + false + } + } + + /// 9.3.3.2.4 DecodeTerminate. + #[inline] + fn terminate(&mut self) -> bool { + self.range -= 2; + if self.offset >= self.range { + true + } else { + self.renorm(); + false + } + } + + pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) { + self.ctx = *ctx; + self.cbp_luma_bins = 0; + } + + /// 9.3.3.1.1.3: condTermFlagA + condTermFlagB for mb_type in an I slice, + /// where a neighbour counts unless it is I_NxN. + fn mb_type_inc(&self) -> usize { + let cond = |n: Option| match n { + None => 0, + Some(i) => usize::from(i.flags & (FLAG_I16 | FLAG_PCM) != 0), + }; + cond(self.ctx.a) + cond(self.ctx.b) + } + + /// mb_type of an I slice (Table 9-36). + pub(crate) fn mb_type_i(&mut self) -> Result { + if !self.decision(OFF_MB_TYPE + self.mb_type_inc()) { + return Ok(0); // I_NxN + } + if self.terminate() { + return Ok(25); // I_PCM + } + // b2: CodedBlockPatternLuma 0 or 15; b3 (+ b4): CodedBlockPatternChroma; + // last two bins: Intra_16x16PredMode. The two prediction-mode bins keep + // ctxIdx 9 and 10 either way (Table 9-39 row 3 with Table 9-41). + let cbp_luma = u32::from(self.decision(OFF_MB_TYPE + 3)); + let chroma = if !self.decision(OFF_MB_TYPE + 4) { + 0 + } else if self.decision(OFF_MB_TYPE + 5) { + 2 + } else { + 1 + }; + let mode = u32::from(self.decision(OFF_MB_TYPE + 6)) * 2 + + u32::from(self.decision(OFF_MB_TYPE + 7)); + Ok(1 + mode + chroma * 4 + cbp_luma * 12) + } + + /// transform_size_8x8_flag (9.3.3.1.1.10). + pub(crate) fn transform_size_8x8_flag(&mut self) -> Result { + // No neighbour can carry the flag: a macroblock that set it is refused + // before its state is ever stored, so ctxIdxInc is always 0 here. + Ok(self.decision(OFF_TRANSFORM_8X8)) + } + + /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7 + /// with binIdx 0 the least significant bit. + pub(crate) fn intra4x4_pred_mode(&mut self) -> Result> { + if self.decision(OFF_PREV_I4) { + return Ok(None); + } + let mut rem = 0u8; + for bit in 0..3 { + rem |= u8::from(self.decision(OFF_REM_I4)) << bit; + } + Ok(Some(rem)) + } + + /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8. + pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result { + let cond = |n: Option| match n { + None => 0, + Some(i) => usize::from(i.flags & FLAG_PCM == 0 && i.flags & FLAG_CHROMA_PRED != 0), + }; + let inc = cond(self.ctx.a) + cond(self.ctx.b); + if !self.decision(OFF_CHROMA_PRED + inc) { + return Ok(0); + } + if !self.decision(OFF_CHROMA_PRED + 3) { + return Ok(1); + } + Ok(if self.decision(OFF_CHROMA_PRED + 3) { + 3 + } else { + 2 + }) + } + + /// coded_block_pattern (9.3.2.6): FL cMax=15 luma prefix, TU cMax=2 chroma + /// suffix, both with the neighbour contexts of 9.3.3.1.1.4. + pub(crate) fn coded_block_pattern(&mut self) -> Result<(u8, u8)> { + for bin in 0..4u8 { + // 6.4.11.2: the 8x8 block left of / above block `bin`, which for + // blocks 1, 2 and 3 can be inside this macroblock. + let (a, b) = match bin { + 0 => ( + self.cbp_luma_neighbour(self.ctx.a, 1), + self.cbp_luma_neighbour(self.ctx.b, 2), + ), + 1 => (self.cbp_luma_own(0), self.cbp_luma_neighbour(self.ctx.b, 3)), + 2 => (self.cbp_luma_neighbour(self.ctx.a, 3), self.cbp_luma_own(0)), + _ => (self.cbp_luma_own(2), self.cbp_luma_own(1)), + }; + if self.decision(OFF_CBP_LUMA + a + 2 * b) { + self.cbp_luma_bins |= 1 << bin; + } + } + let luma = self.cbp_luma_bins; + let chroma_cond = |n: Option, bin: u8| match n { + None => 0, + Some(i) if i.flags & FLAG_PCM != 0 => 1, + Some(i) => { + let c = i.cbp >> 4; + usize::from(if bin == 0 { c != 0 } else { c == 2 }) + } + }; + let inc0 = chroma_cond(self.ctx.a, 0) + 2 * chroma_cond(self.ctx.b, 0); + let chroma = if !self.decision(OFF_CBP_CHROMA + inc0) { + 0 + } else { + let inc1 = chroma_cond(self.ctx.a, 1) + 2 * chroma_cond(self.ctx.b, 1) + 4; + if self.decision(OFF_CBP_CHROMA + inc1) { + 2 + } else { + 1 + } + }; + Ok((luma, chroma)) + } + + /// condTermFlagN for a coded_block_pattern luma bin whose neighbouring 8x8 + /// block lies in another macroblock: set when that block has no coefficients. + fn cbp_luma_neighbour(&self, n: Option, blk: u8) -> usize { + match n { + None => 0, + Some(i) if i.flags & FLAG_PCM != 0 => 0, + Some(i) => usize::from(i.cbp & (1 << blk) == 0), + } + } + + /// The same for a neighbouring 8x8 block inside this macroblock, read from + /// the bins already decoded. + fn cbp_luma_own(&self, blk: u8) -> usize { + usize::from(self.cbp_luma_bins & (1 << blk) == 0) + } + + /// mb_qp_delta: unary bin string of the Table 9-3 mapped value. + pub(crate) fn mb_qp_delta(&mut self) -> Result { + let mut k = 0i32; + while self.decision(OFF_QP_DELTA + qp_delta_inc(k, usize::from(self.ctx.qp_delta_inc))) { + k += 1; + if k > 52 { + return Err(Error::corrupt("mb_qp_delta bin string too long")); + } + } + Ok(if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) }) + } + + /// residual_block_cabac (7.3.5.3.3) for one block, in scan order. + pub(crate) fn residual_block( + &mut self, + coeff: &mut [i32; 16], + cat: BlockCat, + na: Option, + nb: Option, + ) -> Result { + *coeff = [0; 16]; + let cat_i = cat.ctx_block_cat(); + let max = cat.max_num_coeff(); + + // coded_block_flag (9.3.3.1.1.9). An unavailable neighbour counts as + // set, because every macroblock of an I slice is intra coded; the + // caller has already folded I_PCM (all coefficients present) into a + // non-zero count. + let cond = |n: Option| usize::from(n.is_none_or(|v| v != 0)); + let (a, b) = match cat { + // The DC blocks' neighbours are per macroblock, not per 4x4 block. + BlockCat::LumaDc => (self.dc_cbf(self.ctx.a, 0), self.dc_cbf(self.ctx.b, 0)), + BlockCat::ChromaDc(c) => ( + self.dc_cbf(self.ctx.a, 1 + c), + self.dc_cbf(self.ctx.b, 1 + c), + ), + _ => (cond(na), cond(nb)), + }; + if !self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b) { + return Ok(0); + } + + // Significance map: significant_coeff_flag / last_significant_coeff_flag + // over scanning positions 0..maxNumCoeff-1. + let sig_base = OFF_SIG + SIG_CAT_OFF[cat_i]; + let last_base = OFF_LAST + SIG_CAT_OFF[cat_i]; + let mut sig = [false; 16]; + let mut num = max; + let mut i = 0; + while i + 1 < num { + let inc = sig_inc(cat, i); + if self.decision(sig_base + inc) { + sig[i] = true; + if self.decision(last_base + inc) { + num = i + 1; + } + } + i += 1; + } + sig[num - 1] = true; + + // Levels, highest scanning position first (9.3.3.1.3 counters). + let abs_base = OFF_ABS + ABS_CAT_OFF[cat_i]; + let mut num_eq1 = 0u32; + let mut num_gt1 = 0u32; + let mut total = 0u8; + for pos in (0..num).rev() { + if !sig[pos] { + continue; + } + let inc0 = if num_gt1 != 0 { + 0 + } else { + 4.min(1 + num_eq1) as usize + }; + let inc1 = 5 + (4 - u32::from(cat_i == 3)).min(num_gt1) as usize; + // Prefix: TU with cMax = uCoff = 14. + let mut prefix = 0u32; + while prefix < 14 { + let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 }; + if !self.decision(ctx_idx) { + break; + } + prefix += 1; + } + let abs_minus1 = if prefix < 14 { + prefix + } else { + 14 + self.ueg0_suffix()? + }; + let level = i64::from(abs_minus1) + 1; + let level = if self.bypass() { -level } else { level }; + coeff[pos] = i32::try_from(level) + .map_err(|_| Error::corrupt("coefficient level out of range"))?; + if abs_minus1 == 0 { + num_eq1 += 1; + } else { + num_gt1 += 1; + } + total += 1; + } + Ok(total) + } + + /// The bypass-coded 0th order Exp-Golomb suffix of a UEG0 bin string (9-6). + fn ueg0_suffix(&mut self) -> Result { + let mut k = 0u32; + let mut value = 0u32; + while self.bypass() { + value += 1 << k; + k += 1; + if k > 30 { + return Err(Error::corrupt("UEG0 suffix prefix too long")); + } + } + while k > 0 { + k -= 1; + value += u32::from(self.bypass()) << k; + } + Ok(value) + } + + /// condTermFlagN for a DC block: bit `which` of the neighbour's DC + /// coded_block_flags, with I_PCM counting as coded and an unavailable + /// neighbour as set (the current macroblock is always intra here). + fn dc_cbf(&self, n: Option, which: u8) -> usize { + match n { + None => 1, + Some(i) if i.flags & FLAG_PCM != 0 => 1, + Some(i) => usize::from(i.dc_cbf & (1 << which) != 0), + } + } + + /// The 384 raw bytes of an I_PCM macroblock. The arithmetic engine restarts + /// afterwards (9.3.1.2); the context variables survive. + pub(crate) fn pcm_block(&mut self) -> Result<&'a [u8]> { + self.r.align_to_byte(); + let bytes = self.r.read_bytes(384)?; + self.init_engine()?; + Ok(bytes) + } + + /// end_of_slice_flag (ctxIdx 276, DecodeTerminate). + pub(crate) fn more_macroblocks(&mut self) -> Result { + debug_assert_eq!(CTX_TERMINATE, 276); + Ok(!self.terminate()) + } +} + +/// ctxIdxInc for mb_qp_delta bin `k` (Table 9-39 row 60). +#[inline] +fn qp_delta_inc(k: i32, first: usize) -> usize { + match k { + 0 => first, + 1 => 2, + _ => 3, + } +} + +/// ctxIdxInc for significant_coeff_flag / last_significant_coeff_flag at +/// scanning position `i` (9.3.3.1.3, frame coded, no 8x8 categories). +#[inline] +fn sig_inc(cat: BlockCat, i: usize) -> usize { + match cat { + // ChromaDC with ChromaArrayType 1: Min( levelListIdx / NumC8x8, 2 ). + BlockCat::ChromaDc(_) => i.min(2), + _ => i, + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The engine tables are transcribed by hand-checked script; these are the + /// structural invariants clause 9.3 states about them, so a shifted row or + /// a dropped column cannot pass silently. + #[test] + fn engine_tables_have_their_stated_shape() { + // Table 9-44 first and last rows (9.3.3.2.1): state 0 is p(LPS) = 0.5, + // state 63 is the near-deterministic one. + assert_eq!(RANGE_LPS[0], [128, 176, 208, 240]); + assert_eq!(RANGE_LPS[63], [2, 2, 2, 2]); + for (p, row) in RANGE_LPS.iter().enumerate() { + // Each row rises with qCodIRangeIdx and falls with the state index. + assert!( + row.windows(2).all(|w| w[0] <= w[1]), + "row {p} not monotonic" + ); + if p > 0 { + assert!( + row[3] <= RANGE_LPS[p - 1][3], + "row {p} above its predecessor" + ); + } + } + // Table 9-45: MPS transitions step up one state until the two sticky + // states at the top, LPS transitions never move up. + for (p, &next) in TRANS_MPS.iter().enumerate().take(62) { + assert_eq!(next, p as u8 + 1); + } + assert_eq!((TRANS_MPS[62], TRANS_MPS[63]), (62, 63)); + for (p, &next) in TRANS_LPS.iter().enumerate() { + assert!(usize::from(next) <= p, "LPS transition {p} moves up"); + } + assert_eq!(TRANS_LPS[63], 63); + assert_eq!(TRANS_LPS[0], 0); + } + + /// 9.3.1.1 worked through by hand for two entries. + #[test] + fn context_initialisation_matches_equation_9_5() { + let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 26).unwrap(); + // ctxIdx 0, (m, n) = (20, -15): preCtxState = ((20*26) >> 4) - 15 = 17, + // so pStateIdx = 63 - 17 = 46 and valMPS = 0. + assert_eq!(c.state[0], 46 << 1); + // ctxIdx 60, (m, n) = (0, 41): preCtxState = 41 -> pStateIdx 22, MPS 0. + assert_eq!(c.state[60], 22 << 1); + // Clip3(1, 126, ...) at a low QP: ctxIdx 6, (m, n) = (-28, 127) at + // QP 0 gives 127, clipped to 126 -> pStateIdx 62, valMPS 1. + let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 0).unwrap(); + assert_eq!(c.state[6], (62 << 1) | 1); + } + + /// The initialisation of 9.3.1.2 reads exactly nine bits after the + /// alignment bits, and every context lands in range. + #[test] + fn engine_initialisation_reads_nine_bits() { + // Header ends mid byte: the alignment bits carry to the boundary, then + // 0b1010_1010_1 is codIOffset. + let data = [0xFF, 0b1010_1010, 0b1000_0000, 0, 0]; + let c = Cabac::new(&data, 3, 30).unwrap(); + assert_eq!(c.range, 510); + assert_eq!(c.offset, 0b1_0101_0101); + assert!(c.state.iter().all(|&s| s >> 1 < 64)); + } +} diff --git a/crates/ec-h264/src/cabac_tables.rs b/crates/ec-h264/src/cabac_tables.rs new file mode 100644 index 00000000..71eded08 --- /dev/null +++ b/crates/ec-h264/src/cabac_tables.rs @@ -0,0 +1,334 @@ +//! CABAC tables transcribed from Rec. ITU-T H.264 (V15) clause 9.3. +//! +//! Only the values an I-slice, frame-coded, 4:2:0 decode reads are here: the +//! "I and SI slices" initialisation column (the cabac_init_idc columns exist +//! only for P and B slices), the frame-coded significance contexts, and no 8x8 +//! transform categories. A later inter slice adds its own columns against its +//! own conformance oracle rather than inheriting untested numbers from here. + +/// Table 9-12, ctxIdx 0..10: mb_type in I slices. +pub(crate) const INIT_MB_TYPE_I: [(i8, i8); 11] = [ + (20, -15), + (2, 54), + (3, 74), + (20, -15), + (2, 54), + (3, 74), + (-28, 127), + (-23, 104), + (-6, 53), + (-1, 54), + (7, 51), +]; + +/// Table 9-17, ctxIdx 60..69: mb_qp_delta, intra_chroma_pred_mode and the two +/// intra 4x4 prediction mode elements. +pub(crate) const INIT_60_69: [(i8, i8); 10] = [ + (0, 41), + (0, 63), + (0, 63), + (0, 63), + (-9, 83), + (4, 86), + (0, 97), + (-7, 72), + (13, 41), + (3, 62), +]; + +/// Tables 9-18 to 9-21, ctxIdx 70..275, "I and SI slices" column: +/// coded_block_pattern, coded_block_flag, significant_coeff_flag, +/// last_significant_coeff_flag and coeff_abs_level_minus1. +pub(crate) const INIT_70_275: [(i8, i8); 206] = [ + (0, 11), + (1, 55), + (0, 69), + (-17, 127), + (-13, 102), + (0, 82), + (-7, 74), + (-21, 107), + (-27, 127), + (-31, 127), + (-24, 127), + (-18, 95), + (-27, 127), + (-21, 114), + (-30, 127), + (-17, 123), + (-12, 115), + (-16, 122), + (-11, 115), + (-12, 63), + (-2, 68), + (-15, 84), + (-13, 104), + (-3, 70), + (-8, 93), + (-10, 90), + (-30, 127), + (-1, 74), + (-6, 97), + (-7, 91), + (-20, 127), + (-4, 56), + (-5, 82), + (-7, 76), + (-22, 125), + (-7, 93), + (-11, 87), + (-3, 77), + (-5, 71), + (-4, 63), + (-4, 68), + (-12, 84), + (-7, 62), + (-7, 65), + (8, 61), + (5, 56), + (-2, 66), + (1, 64), + (0, 61), + (-2, 78), + (1, 50), + (7, 52), + (10, 35), + (0, 44), + (11, 38), + (1, 45), + (0, 46), + (5, 44), + (31, 17), + (1, 51), + (7, 50), + (28, 19), + (16, 33), + (14, 62), + (-13, 108), + (-15, 100), + (-13, 101), + (-13, 91), + (-12, 94), + (-10, 88), + (-16, 84), + (-10, 86), + (-7, 83), + (-13, 87), + (-19, 94), + (1, 70), + (0, 72), + (-5, 74), + (18, 59), + (-8, 102), + (-15, 100), + (0, 95), + (-4, 75), + (2, 72), + (-11, 75), + (-3, 71), + (15, 46), + (-13, 69), + (0, 62), + (0, 65), + (21, 37), + (-15, 72), + (9, 57), + (16, 54), + (0, 62), + (12, 72), + (24, 0), + (15, 9), + (8, 25), + (13, 18), + (15, 9), + (13, 19), + (10, 37), + (12, 18), + (6, 29), + (20, 33), + (15, 30), + (4, 45), + (1, 58), + (0, 62), + (7, 61), + (12, 38), + (11, 45), + (15, 39), + (11, 42), + (13, 44), + (16, 45), + (12, 41), + (10, 49), + (30, 34), + (18, 42), + (10, 55), + (17, 51), + (17, 46), + (0, 89), + (26, -19), + (22, -17), + (26, -17), + (30, -25), + (28, -20), + (33, -23), + (37, -27), + (33, -23), + (40, -28), + (38, -17), + (33, -11), + (40, -15), + (41, -6), + (38, 1), + (41, 17), + (30, -6), + (27, 3), + (26, 22), + (37, -16), + (35, -4), + (38, -8), + (38, -3), + (37, 3), + (38, 5), + (42, 0), + (35, 16), + (39, 22), + (14, 48), + (27, 37), + (21, 60), + (12, 68), + (2, 97), + (-3, 71), + (-6, 42), + (-5, 50), + (-3, 54), + (-2, 62), + (0, 58), + (1, 63), + (-2, 72), + (-1, 74), + (-9, 91), + (-5, 67), + (-5, 27), + (-3, 39), + (-2, 44), + (0, 46), + (-16, 64), + (-8, 68), + (-10, 78), + (-6, 77), + (-10, 86), + (-12, 92), + (-15, 55), + (-10, 60), + (-6, 62), + (-4, 65), + (-12, 73), + (-8, 76), + (-7, 80), + (-9, 88), + (-17, 110), + (-11, 97), + (-20, 84), + (-11, 79), + (-6, 73), + (-4, 74), + (-13, 86), + (-13, 96), + (-11, 97), + (-19, 117), + (-8, 78), + (-5, 33), + (-4, 48), + (-2, 53), + (-3, 62), + (-13, 71), + (-10, 79), + (-12, 86), + (-13, 90), + (-14, 97), +]; + +/// Table 9-16, ctxIdx 399..401: transform_size_8x8_flag. +pub(crate) const INIT_399_401: [(i8, i8); 3] = [(31, 21), (31, 31), (25, 50)]; + +/// Table 9-44: rangeTabLPS[pStateIdx][qCodIRangeIdx]. +pub(crate) const RANGE_LPS: [[u8; 4]; 64] = [ + [128, 176, 208, 240], + [128, 167, 197, 227], + [128, 158, 187, 216], + [123, 150, 178, 205], + [116, 142, 169, 195], + [111, 135, 160, 185], + [105, 128, 152, 175], + [100, 122, 144, 166], + [95, 116, 137, 158], + [90, 110, 130, 150], + [85, 104, 123, 142], + [81, 99, 117, 135], + [77, 94, 111, 128], + [73, 89, 105, 122], + [69, 85, 100, 116], + [66, 80, 95, 110], + [62, 76, 90, 104], + [59, 72, 86, 99], + [56, 69, 81, 94], + [53, 65, 77, 89], + [51, 62, 73, 85], + [48, 59, 69, 80], + [46, 56, 66, 76], + [43, 53, 63, 72], + [41, 50, 59, 69], + [39, 48, 56, 65], + [37, 45, 54, 62], + [35, 43, 51, 59], + [33, 41, 48, 56], + [32, 39, 46, 53], + [30, 37, 43, 50], + [29, 35, 41, 48], + [27, 33, 39, 45], + [26, 31, 37, 43], + [24, 30, 35, 41], + [23, 28, 33, 39], + [22, 27, 32, 37], + [21, 26, 30, 35], + [20, 24, 29, 33], + [19, 23, 27, 31], + [18, 22, 26, 30], + [17, 21, 25, 28], + [16, 20, 23, 27], + [15, 19, 22, 25], + [14, 18, 21, 24], + [14, 17, 20, 23], + [13, 16, 19, 22], + [12, 15, 18, 21], + [12, 14, 17, 20], + [11, 14, 16, 19], + [11, 13, 15, 18], + [10, 12, 15, 17], + [10, 12, 14, 16], + [9, 11, 13, 15], + [9, 11, 12, 14], + [8, 10, 12, 14], + [8, 9, 11, 13], + [7, 9, 11, 12], + [7, 9, 10, 12], + [7, 8, 10, 11], + [6, 8, 9, 11], + [6, 7, 9, 10], + [6, 7, 8, 9], + [2, 2, 2, 2], +]; + +/// Table 9-45: transIdxLPS. +pub(crate) const TRANS_LPS: [u8; 64] = [ + 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, + 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, 33, 33, 34, + 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63, +]; + +/// Table 9-45: transIdxMPS. +pub(crate) const TRANS_MPS: [u8; 64] = [ + 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, + 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, + 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63, +]; diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index a2bef463..2913d19e 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -22,7 +22,9 @@ use ec_h264_syntax::{ use crate::deblock::{ chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line, }; -use crate::entropy::{BlockCat, Entropy}; +use crate::entropy::{ + BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_PCM, MbCtx, MbInfo, +}; use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; use crate::tables::{BLK4_POS, CHROMA_QP}; use crate::transform::{ @@ -121,8 +123,14 @@ struct Picture { i4_modes: Vec, /// QPY per macroblock (the prediction-chain value; PCM keeps the chain). mb_qp: Vec, - /// Bit 0: decoded, bit 1: I_PCM, bit 2: Intra_16x16. + /// `FLAG_*` bits per macroblock. mb_flags: Vec, + /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4` per macroblock, + /// read by CABAC context selection (9.3.3.1.1.4). + mb_cbp: Vec, + /// coded_block_flag of the DC blocks per macroblock: bit 0 luma, 1 Cb, + /// 2 Cr (9.3.3.1.1.9 with ctxBlockCat 0 and 3). + mb_dc_cbf: Vec, /// Owning slice index per macroblock, `NO_SLICE` when undecoded. mb_slice: Vec, slices: Vec, @@ -130,9 +138,6 @@ struct Picture { complete: bool, } -const FLAG_DECODED: u8 = 1; -const FLAG_PCM: u8 = 2; - impl Picture { fn start(&mut self, sps: &Sps) { let mb_w = sps.mb_width as usize; @@ -151,6 +156,8 @@ impl Picture { self.i4_modes.resize(mb_w * mb_h * 16, 2); self.mb_qp.resize(mb_w * mb_h, 0); self.mb_flags.resize(mb_w * mb_h, 0); + self.mb_cbp.resize(mb_w * mb_h, 0); + self.mb_dc_cbf.resize(mb_w * mb_h, 0); self.mb_slice.resize(mb_w * mb_h, NO_SLICE); } // Per-MB metadata is rewritten by each decoded macroblock; only the @@ -407,7 +414,11 @@ impl Decoder { cr_qp_offset: pps.second_chroma_qp_index_offset, }); - let mut r = Entropy::cavlc(rbsp, sh.header_bits); + let mut r = if pps.entropy_coding_mode { + Entropy::cabac(rbsp, sh.header_bits, sh.slice_qp)? + } else { + Entropy::cavlc(rbsp, sh.header_bits) + }; let mut ctx = SliceCtx { slice_id, @@ -415,6 +426,7 @@ impl Decoder { cb_qp_offset: pps.chroma_qp_index_offset, cr_qp_offset: pps.second_chroma_qp_index_offset, transform_8x8_mode: pps.transform_8x8_mode, + qp_delta_inc: 0, }; let mbs = self.pic.mb_w * self.pic.mb_h; let mut mb_addr = first_mb as usize; @@ -439,13 +451,6 @@ impl Decoder { /// conformance suite proves each one against a stream that really uses the /// feature. fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> { - if pps.entropy_coding_mode { - return Err(Error::unsupported( - "CABAC entropy coding", - "entropy_coding_mode_flag 1 needs the arithmetic decoder and the \ - context models of clause 9.3; only CAVLC (9.2) is implemented", - )); - } if pps.num_slice_groups > 1 { return Err(Error::unsupported( "FMO slice groups", @@ -507,6 +512,9 @@ struct SliceCtx { cb_qp_offset: i32, cr_qp_offset: i32, transform_8x8_mode: bool, + /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the + /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5). + qp_delta_inc: u8, } /// Neighbour-availability snapshot for one macroblock (left, top, @@ -581,6 +589,16 @@ fn decode_macroblock( return Err(Error::corrupt("macroblock decoded twice")); } let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id); + let info = |addr: usize| MbInfo { + flags: pic.mb_flags[addr], + cbp: pic.mb_cbp[addr], + dc_cbf: pic.mb_dc_cbf[addr], + }; + r.begin_mb(&MbCtx { + a: nbr.a.then(|| info(mb_addr - 1)), + b: nbr.b.then(|| info(mb_addr - pic.mb_w)), + qp_delta_inc: ctx.qp_delta_inc, + }); let w4 = pic.mb_w * 4; let w2 = pic.mb_w * 2; let (bx0, by0) = (mb_x * 4, mb_y * 4); @@ -617,6 +635,9 @@ fn decode_macroblock( // the deblocker substitutes 0 via FLAG_PCM (spec 8.7.2). pic.mb_qp[mb_addr] = ctx.qp as u8; pic.mb_flags[mb_addr] = FLAG_DECODED | FLAG_PCM; + pic.mb_cbp[mb_addr] = 0x3F; + pic.mb_dc_cbf[mb_addr] = 0b111; + ctx.qp_delta_inc = 0; pic.mb_slice[mb_addr] = ctx.slice_id; pic.decoded_mbs += 1; return Ok(()); @@ -684,12 +705,21 @@ fn decode_macroblock( }; // mb_qp_delta (7.4.5). + let mut qp_delta = 0; if cbp_luma != 0 || cbp_chroma != 0 || is_i16 { - let delta = r.mb_qp_delta()?; - ctx.qp = (ctx.qp + delta + 52) % 52; + qp_delta = r.mb_qp_delta()?; + ctx.qp = (ctx.qp + qp_delta + 52) % 52; } + ctx.qp_delta_inc = u8::from(qp_delta != 0); pic.mb_qp[mb_addr] = ctx.qp as u8; - pic.mb_flags[mb_addr] = FLAG_DECODED; + pic.mb_flags[mb_addr] = FLAG_DECODED + | if is_i16 { FLAG_I16 } else { 0 } + | if chroma_mode != 0 { + FLAG_CHROMA_PRED + } else { + 0 + }; + pic.mb_cbp[mb_addr] = cbp_luma | (cbp_chroma << 4); pic.mb_slice[mb_addr] = ctx.slice_id; pic.decoded_mbs += 1; let qp_y = ctx.qp; @@ -702,6 +732,7 @@ fn decode_macroblock( // AC) equals reconstruction dependency order, so each block reconstructs // the moment its levels are parsed: no per-MB coefficient arrays, and // empty blocks cost one coeff_token read plus a prediction write. + let mut dc_cbf = 0u8; let mut scan = [0i32; 16]; let mut raster = [0i32; 16]; let mut resid = [0i32; 16]; @@ -714,7 +745,8 @@ fn decode_macroblock( pred_16x16(i16_mode, &mut w, nbr.b, nbr.a); // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale. let (na, nb) = luma_nz_pair(pic, &nbr, bx0, by0); - r.residual_block(&mut scan, BlockCat::LumaDc, na, nb)?; + let dc_tc = r.residual_block(&mut scan, BlockCat::LumaDc, na, nb)?; + dc_cbf |= u8::from(dc_tc != 0); unzigzag(&scan, &mut raster); luma_dc_transform(&mut raster, &ls[0], qp_y); let dc = raster; @@ -798,7 +830,8 @@ fn decode_macroblock( let mut chroma_dc = [[0i32; 4]; 2]; if cbp_chroma != 0 { for (comp, c) in chroma_dc.iter_mut().enumerate() { - r.residual_block(&mut scan, BlockCat::ChromaDc, None, None)?; + let tc = r.residual_block(&mut scan, BlockCat::ChromaDc(comp as u8), None, None)?; + dc_cbf |= u8::from(tc != 0) << (1 + comp); c.copy_from_slice(&scan[..4]); let (ls_c, qp_c) = if comp == 0 { (&ls[1], qp_cb) @@ -842,6 +875,7 @@ fn decode_macroblock( add_residual_4x4(&mut plane.data, plane.stride, origin, &resid); } } + pic.mb_dc_cbf[mb_addr] = dc_cbf; Ok(()) } diff --git a/crates/ec-h264/src/entropy.rs b/crates/ec-h264/src/entropy.rs index c2cc2bb8..0c441793 100644 --- a/crates/ec-h264/src/entropy.rs +++ b/crates/ec-h264/src/entropy.rs @@ -19,8 +19,20 @@ use ec_core::error::{Error, Result}; use crate::bits::BitCursor; +use crate::cabac::Cabac; use crate::tables::CBP_INTRA_420; +/// Macroblock state bits (`Picture::mb_flags`, and `MbInfo::flags` for a +/// neighbour). CABAC context selection reads all of them. +/// The macroblock has been decoded in this picture. +pub(crate) const FLAG_DECODED: u8 = 1; +/// mb_type is I_PCM. +pub(crate) const FLAG_PCM: u8 = 2; +/// mb_type is one of the Intra_16x16 types. +pub(crate) const FLAG_I16: u8 = 4; +/// intra_chroma_pred_mode is not 0 (DC). +pub(crate) const FLAG_CHROMA_PRED: u8 = 8; + /// Residual block class (spec Table 9-42, the 4:2:0 subset this decoder codes). #[derive(Clone, Copy, PartialEq, Eq, Debug)] pub(crate) enum BlockCat { @@ -30,8 +42,8 @@ pub(crate) enum BlockCat { LumaAc, /// LumaLevel4x4, `ctxBlockCat` 2. Luma4x4, - /// ChromaDCLevel, `ctxBlockCat` 3. - ChromaDc, + /// ChromaDCLevel of component `iCbCr`, `ctxBlockCat` 3. + ChromaDc(u8), /// ChromaACLevel, `ctxBlockCat` 4. ChromaAc, } @@ -42,14 +54,55 @@ impl BlockCat { match self { BlockCat::LumaDc | BlockCat::Luma4x4 => 16, BlockCat::LumaAc | BlockCat::ChromaAc => 15, - BlockCat::ChromaDc => 4, + BlockCat::ChromaDc(_) => 4, + } + } + + /// `ctxBlockCat` (Table 9-42). + pub(crate) const fn ctx_block_cat(self) -> usize { + match self { + BlockCat::LumaDc => 0, + BlockCat::LumaAc => 1, + BlockCat::Luma4x4 => 2, + BlockCat::ChromaDc(_) => 3, + BlockCat::ChromaAc => 4, } } } +/// What a context-adaptive reader needs to know about one neighbouring +/// macroblock. +#[derive(Clone, Copy)] +pub(crate) struct MbInfo { + /// The `FLAG_*` bits above. + pub flags: u8, + /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4`. + pub cbp: u8, + /// coded_block_flag of the DC blocks: bit 0 luma, bit 1 Cb, bit 2 Cr. + pub dc_cbf: u8, +} + +/// Neighbourhood of the macroblock about to be parsed: left (A) and above (B) +/// per clause 6.4.11.1, `None` when outside the picture or in another slice. +#[derive(Clone, Copy, Default)] +pub(crate) struct MbCtx { + pub a: Option, + pub b: Option, + /// ctxIdxInc for the first mb_qp_delta bin (clause 9.3.3.1.1.5), derived by + /// the caller from the previous macroblock in decoding order. + pub qp_delta_inc: u8, +} + /// The slice-data syntax reader. +/// +/// The CABAC variant is much the larger of the two (it carries 402 context +/// variables), and stays inline on purpose: one of these lives per slice on the +/// stack, so boxing it would trade a compile-time size warning for a heap +/// allocation in a decode loop that is otherwise allocation free. +#[allow(clippy::large_enum_variant)] pub(crate) enum Entropy<'a> { Cavlc(BitCursor<'a>), + Cabac(Cabac<'a>), } impl<'a> Entropy<'a> { @@ -58,6 +111,20 @@ impl<'a> Entropy<'a> { Entropy::Cavlc(BitCursor::new(rbsp, header_bits)) } + /// A CABAC reader: consumes the `cabac_alignment_one_bit`s and initialises + /// the context variables and the arithmetic decoding engine (clause 9.3.1). + pub(crate) fn cabac(rbsp: &'a [u8], header_bits: u64, slice_qp: i32) -> Result> { + Ok(Entropy::Cabac(Cabac::new(rbsp, header_bits, slice_qp)?)) + } + + /// Publish the neighbourhood of the macroblock about to be parsed. + #[inline] + pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) { + if let Entropy::Cabac(c) = self { + c.begin_mb(ctx); + } + } + /// `mb_type` of an I slice: 0 (I_NxN), 1..24 (Intra_16x16), 25 (I_PCM). pub(crate) fn mb_type_i(&mut self) -> Result { match self { @@ -68,6 +135,7 @@ impl<'a> Entropy<'a> { } Ok(t) } + Entropy::Cabac(c) => c.mb_type_i(), } } @@ -75,6 +143,7 @@ impl<'a> Entropy<'a> { pub(crate) fn transform_size_8x8_flag(&mut self) -> Result { match self { Entropy::Cavlc(r) => r.read_bit(), + Entropy::Cabac(c) => c.transform_size_8x8_flag(), } } @@ -90,6 +159,7 @@ impl<'a> Entropy<'a> { Ok(Some(r.read_bits(3)? as u8)) } } + Entropy::Cabac(c) => c.intra4x4_pred_mode(), } } @@ -103,6 +173,7 @@ impl<'a> Entropy<'a> { } Ok(m as u8) } + Entropy::Cabac(c) => c.intra_chroma_pred_mode(), } } @@ -118,6 +189,7 @@ impl<'a> Entropy<'a> { .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 47"))?; Ok((cbp & 15, cbp >> 4)) } + Entropy::Cabac(c) => c.coded_block_pattern(), } } @@ -125,6 +197,7 @@ impl<'a> Entropy<'a> { pub(crate) fn mb_qp_delta(&mut self) -> Result { let delta = match self { Entropy::Cavlc(r) => r.read_se()?, + Entropy::Cabac(c) => c.mb_qp_delta()?, }; if !(-26..=25).contains(&delta) { return Err(Error::corrupt("mb_qp_delta outside [-26, 25]")); @@ -149,7 +222,7 @@ impl<'a> Entropy<'a> { ) -> Result { match self { Entropy::Cavlc(r) => { - let nc = if cat == BlockCat::ChromaDc { + let nc = if matches!(cat, BlockCat::ChromaDc(_)) { -1 } else { match (na, nb) { @@ -161,6 +234,7 @@ impl<'a> Entropy<'a> { }; crate::cavlc::residual_block(r, coeff, cat.max_num_coeff(), nc) } + Entropy::Cabac(c) => c.residual_block(coeff, cat, na, nb), } } @@ -173,6 +247,7 @@ impl<'a> Entropy<'a> { r.align_to_byte(); r.read_bytes(384) } + Entropy::Cabac(c) => c.pcm_block(), } } @@ -181,6 +256,7 @@ impl<'a> Entropy<'a> { pub(crate) fn more_macroblocks(&mut self) -> Result { match self { Entropy::Cavlc(r) => Ok(r.more_rbsp_data()), + Entropy::Cabac(c) => c.more_macroblocks(), } } } diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs index 079fe39b..f0c89054 100644 --- a/crates/ec-h264/src/lib.rs +++ b/crates/ec-h264/src/lib.rs @@ -31,6 +31,8 @@ #![forbid(unsafe_code)] mod bits; +mod cabac; +mod cabac_tables; mod cavlc; mod codec; mod deblock; diff --git a/crates/ec-h264/tests/conformance.rs b/crates/ec-h264/tests/conformance.rs index 1916b585..fb1a9372 100644 --- a/crates/ec-h264/tests/conformance.rs +++ b/crates/ec-h264/tests/conformance.rs @@ -624,10 +624,21 @@ fn refusals_name_a_feature_the_stream_really_uses() { let dir = scratch("refusals"); // (tag, encoder arguments, the words the refusal must contain) let cases: &[(&str, &[&str], &str)] = &[ + // Field or macroblock-adaptive frame/field coding: the neighbour + // derivation of 6.4.9 is not implemented, under either entropy coder. ( - "cabac", - &["-profile:v", "main", "-qp", "26", "-x264-params", "cabac=1"], - "CABAC", + "interlaced", + &[ + "-profile:v", + "main", + "-coder", + "ac", + "-qp", + "26", + "-x264-params", + "interlaced=1", + ], + "frame_mbs_only_flag 0", ), ( "transform8x8",