diff --git a/crates/ec-h264-syntax/src/lib.rs b/crates/ec-h264-syntax/src/lib.rs index a645369c..e796dc99 100644 --- a/crates/ec-h264-syntax/src/lib.rs +++ b/crates/ec-h264-syntax/src/lib.rs @@ -22,8 +22,11 @@ pub mod sps; pub use nal::{AnnexBIter, NalHeader, NalUnitType, unescape_rbsp}; pub use pps::Pps; -pub use slice::{DeblockControl, SliceHeader, SliceType}; -pub use sps::{Hrd, ScalingLists, Sps, Vui}; +pub use slice::{ + DeblockControl, DecRefPicMarking, Mmco, PredWeightTable, RefPicListMod, SliceHeader, + SliceType, WeightEntry, +}; +pub use sps::{BitstreamRestriction, Hrd, ScalingLists, Sps, Vui}; /// True when there is at least one more RBSP syntax element before the /// `rbsp_stop_one_bit` (spec 7.2 `more_rbsp_data()`). diff --git a/crates/ec-h264/src/cabac.rs b/crates/ec-h264/src/cabac.rs index b3b54ab5..a4ca9bf2 100644 --- a/crates/ec-h264/src/cabac.rs +++ b/crates/ec-h264/src/cabac.rs @@ -1,10 +1,10 @@ //! 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 +//! Scope is what a frame-coded 4:2:0 8-bit stream needs, I, P and B; 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. +//! contexts, block categories and initialisation columns that only 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 @@ -17,12 +17,15 @@ 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, + INIT_11_59, 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_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, MbCtx, MbInfo, }; -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). +/// transform_size_8x8_flag block, the last range a frame-coded slice reaches). const NUM_CTX: usize = 402; /// ctxIdx 276 (end_of_slice_flag and the I_PCM bin of mb_type) is decoded by @@ -36,6 +39,14 @@ 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_SKIP_P: usize = 11; +const OFF_MB_TYPE_P: usize = 14; +const OFF_SUB_TYPE_P: usize = 21; +const OFF_SKIP_B: usize = 24; +const OFF_MB_TYPE_B: usize = 27; +const OFF_SUB_TYPE_B: usize = 36; +const OFF_MVD: [usize; 2] = [40, 47]; +const OFF_REF_IDX: usize = 54; const OFF_QP_DELTA: usize = 60; const OFF_CHROMA_PRED: usize = 64; const OFF_PREV_I4: usize = 68; @@ -48,6 +59,18 @@ const OFF_LAST: usize = 166; const OFF_ABS: usize = 227; const OFF_TRANSFORM_8X8: usize = 399; +/// The ctxIdx values the Intra_16x16 part of an mb_type bin string uses, in +/// bin order: `[b0, CodedBlockPatternLuma, chroma bin 0, chroma bin 1, +/// prediction mode bin 0, prediction mode bin 1]`. +/// +/// Table 9-39 lists these per binIdx, but the chroma element is one or two bins +/// long, which shifts the prediction-mode bins; resolving the table to fixed +/// ctxIdx values here is what makes the two spellings (I slice at ctxIdxOffset +/// 3, intra suffix at 17 or 32) one piece of code. +const I_MB_TYPE_CTX: [usize; 6] = [3, 6, 7, 8, 9, 10]; +const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20]; +const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35]; + pub(crate) struct Cabac<'a> { r: BitCursor<'a>, /// codIRange (9.3.3.2). @@ -61,12 +84,23 @@ pub(crate) struct Cabac<'a> { /// 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, + /// The macroblock being parsed is intra coded, which flips the + /// coded_block_flag context of an unavailable neighbour (9.3.3.1.1.9). + cur_intra: bool, } 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> { + /// + /// `init_column` selects the initialisation column: 0 for I and SI slices, + /// `cabac_init_idc + 1` otherwise. + pub(crate) fn new( + rbsp: &'a [u8], + header_bits: u64, + slice_qp: i32, + init_column: usize, + ) -> 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 @@ -79,14 +113,15 @@ impl<'a> Cabac<'a> { state: [63 << 1; NUM_CTX], ctx: MbCtx::default(), cbp_luma_bins: 0, + cur_intra: true, }; - c.init_contexts(slice_qp); + c.init_contexts(slice_qp, init_column.min(3)); 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) { + fn init_contexts(&mut self, slice_qp: i32, column: usize) { 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); @@ -99,14 +134,17 @@ impl<'a> Cabac<'a> { for (i, &mn) in INIT_MB_TYPE_I.iter().enumerate() { set(&mut self.state, i, mn); } + for (i, &mn) in INIT_11_59.iter().enumerate() { + set(&mut self.state, 11 + i, mn[column]); + } 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); + set(&mut self.state, 70 + i, mn[column]); } for (i, &mn) in INIT_399_401.iter().enumerate() { - set(&mut self.state, OFF_TRANSFORM_8X8 + i, mn); + set(&mut self.state, OFF_TRANSFORM_8X8 + i, mn[column]); } } @@ -186,42 +224,193 @@ impl<'a> Cabac<'a> { pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) { self.ctx = *ctx; self.cbp_luma_bins = 0; + self.cur_intra = true; } - /// 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 { + /// Declare whether the macroblock being parsed is intra coded + /// (9.3.3.1.1.9 reads it for every coded_block_flag). + pub(crate) fn set_intra(&mut self, intra: bool) { + self.cur_intra = intra; + } + + /// 9.3.3.1.1.3: condTermFlagA + condTermFlagB for mb_type. At ctxIdxOffset + /// 3 a neighbour counts unless it is I_NxN; at 27 (B slices) unless it is + /// B_Skip or B_Direct_16x16. + fn mb_type_inc(&self, offset: usize) -> usize { let cond = |n: Option| match n { None => 0, - Some(i) => usize::from(i.flags & (FLAG_I16 | FLAG_PCM) != 0), + Some(i) if offset == OFF_MB_TYPE => usize::from(i.flags & (FLAG_I16 | FLAG_PCM) != 0), + Some(i) => usize::from(i.flags & FLAG_DIRECT == 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()) { + let mut ctx = I_MB_TYPE_CTX; + ctx[0] = OFF_MB_TYPE + self.mb_type_inc(OFF_MB_TYPE); + self.mb_type_intra(&ctx) + } + + /// The Intra part of an mb_type bin string (Table 9-36), whose `ctx` is + /// resolved by [`I_MB_TYPE_CTX`]. `ctx[0]` has already had its neighbour + /// increment applied where the offset uses one. + fn mb_type_intra(&mut self, ctx: &[usize; 6]) -> Result { + if !self.decision(ctx[0]) { 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) { + let cbp_luma = u32::from(self.decision(ctx[1])); + let chroma = if !self.decision(ctx[2]) { 0 - } else if self.decision(OFF_MB_TYPE + 5) { + } else if self.decision(ctx[3]) { 2 } else { 1 }; - let mode = u32::from(self.decision(OFF_MB_TYPE + 6)) * 2 - + u32::from(self.decision(OFF_MB_TYPE + 7)); + let mode = u32::from(self.decision(ctx[4])) * 2 + u32::from(self.decision(ctx[5])); Ok(1 + mode + chroma * 4 + cbp_luma * 12) } + /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB. + pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool { + let off = if b_slice { OFF_SKIP_B } else { OFF_SKIP_P }; + self.decision(off + inc) + } + + /// mb_type of a P or SP slice (Table 9-37): values 0..3, or 5 + the I-slice + /// mb_type for an intra macroblock. + pub(crate) fn mb_type_p(&mut self) -> Result { + if self.decision(OFF_MB_TYPE_P) { + return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?); + } + let b1 = self.decision(OFF_MB_TYPE_P + 1); + // Table 9-41: binIdx 2 takes ctxIdxInc 2 when b1 is not 1, else 3. + let b2 = self.decision(OFF_MB_TYPE_P + if b1 { 3 } else { 2 }); + Ok(match (b1, b2) { + (false, false) => 0, // P_L0_16x16 + (false, true) => 3, // P_8x8 + (true, true) => 1, // P_L0_L0_16x8 + (true, false) => 2, // P_L0_L0_8x16 + }) + } + + /// mb_type of a B slice (Table 9-37): values 0..22, or 23 + the I-slice + /// mb_type for an intra macroblock. + pub(crate) fn mb_type_b(&mut self) -> Result { + if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) { + return Ok(0); // B_Direct_16x16 + } + if !self.decision(OFF_MB_TYPE_B + 3) { + // "10x": B_L0_16x16 or B_L1_16x16. binIdx 2 with b1 == 0 takes 5. + return Ok(1 + u32::from(self.decision(OFF_MB_TYPE_B + 5))); + } + let tail = OFF_MB_TYPE_B + 5; + if !self.decision(OFF_MB_TYPE_B + 4) { + // "110" + three bins: 3..10. + let mut v = 0u32; + for _ in 0..3 { + v = v * 2 + u32::from(self.decision(tail)); + } + return Ok(3 + v); + } + if !self.decision(tail) { + // "1110" + three bins: 12..19. + let mut v = 0u32; + for _ in 0..3 { + v = v * 2 + u32::from(self.decision(tail)); + } + return Ok(12 + v); + } + if self.decision(tail) { + // "11111": B_L1_L0_8x16 or B_8x8. + return Ok(if self.decision(tail) { 22 } else { 11 }); + } + if self.decision(tail) { + // "111101": the intra prefix. + return Ok(23 + self.mb_type_intra(&I_SUFFIX_CTX_B)?); + } + // "111100" + one bin: B_Bi_Bi_16x8 or B_Bi_Bi_8x16. + Ok(20 + u32::from(self.decision(tail))) + } + + /// sub_mb_type of a P macroblock (Table 9-38). + pub(crate) fn sub_mb_type_p(&mut self) -> u32 { + if self.decision(OFF_SUB_TYPE_P) { + return 0; + } + if !self.decision(OFF_SUB_TYPE_P + 1) { + return 1; + } + if self.decision(OFF_SUB_TYPE_P + 2) { 2 } else { 3 } + } + + /// sub_mb_type of a B macroblock (Table 9-38). + pub(crate) fn sub_mb_type_b(&mut self) -> u32 { + if !self.decision(OFF_SUB_TYPE_B) { + return 0; // B_Direct_8x8 + } + let tail = OFF_SUB_TYPE_B + 3; + if !self.decision(OFF_SUB_TYPE_B + 1) { + return 1 + u32::from(self.decision(tail)); + } + if !self.decision(OFF_SUB_TYPE_B + 2) { + let v = u32::from(self.decision(tail)) * 2 + u32::from(self.decision(tail)); + return 3 + v; + } + if !self.decision(tail) { + let v = u32::from(self.decision(tail)) * 2 + u32::from(self.decision(tail)); + return 7 + v; + } + 11 + u32::from(self.decision(tail)) + } + + /// ref_idx_lX: unary, with the neighbour increment of 9.3.3.1.1.6 on the + /// first bin (Table 9-39 row 54). + pub(crate) fn ref_idx(&mut self, inc: usize) -> Result { + if !self.decision(OFF_REF_IDX + inc) { + return Ok(0); + } + if !self.decision(OFF_REF_IDX + 4) { + return Ok(1); + } + let mut v = 2u32; + while self.decision(OFF_REF_IDX + 5) { + v += 1; + if v > 32 { + return Err(Error::corrupt("ref_idx bin string too long")); + } + } + Ok(v) + } + + /// mvd_lX component `comp` (0 horizontal, 1 vertical): UEG3 with + /// signedValFlag 1 and uCoff 9 (clause 9.3.2.3), `inc` from 9.3.3.1.1.7. + pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result { + let off = OFF_MVD[comp]; + if !self.decision(off + inc) { + return Ok(0); + } + let mut prefix = 1u32; + // Table 9-39: binIdx 1..4 take 3..6, binIdx 5 and beyond take 6. + while prefix < 9 { + let ctx = off + (2 + prefix as usize).min(6); + if !self.decision(ctx) { + break; + } + prefix += 1; + } + let abs = if prefix < 9 { + prefix + } else { + 9 + self.ueg_suffix(3)? + }; + let value = i32::try_from(abs).map_err(|_| Error::corrupt("mvd out of range"))?; + Ok(if self.bypass() { -value } else { value }) + } + /// 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 @@ -246,7 +435,9 @@ impl<'a> Cabac<'a> { 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), + Some(i) => usize::from( + i.flags & (FLAG_PCM | FLAG_INTER) == 0 && i.flags & FLAG_CHROMA_PRED != 0, + ), }; let inc = cond(self.ctx.a) + cond(self.ctx.b); if !self.decision(OFF_CHROMA_PRED + inc) { @@ -345,10 +536,14 @@ impl<'a> Cabac<'a> { 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)); + // set for an intra macroblock and clear for an inter one; the caller + // has already folded I_PCM (all coefficients present) and P_Skip / + // B_Skip (none) into the neighbouring counts. + let intra = self.cur_intra; + let cond = |n: Option| match n { + None => usize::from(intra), + Some(v) => usize::from(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)), @@ -408,7 +603,7 @@ impl<'a> Cabac<'a> { let abs_minus1 = if prefix < 14 { prefix } else { - 14 + self.ueg0_suffix()? + 14 + self.ueg_suffix(0)? }; let level = i64::from(abs_minus1) + 1; let level = if self.bypass() { -level } else { level }; @@ -424,9 +619,10 @@ impl<'a> Cabac<'a> { 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; + /// The bypass-coded k-th order Exp-Golomb suffix of a UEGk bin string + /// (clause 9.3.2.3): k = 0 for coeff_abs_level_minus1, 3 for mvd. + fn ueg_suffix(&mut self, k0: u32) -> Result { + let mut k = k0; let mut value = 0u32; while self.bypass() { value += 1 << k; @@ -532,7 +728,7 @@ mod tests { /// 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(); + let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 26, 0).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); @@ -540,7 +736,7 @@ mod tests { 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(); + let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 0, 0).unwrap(); assert_eq!(c.state[6], (62 << 1) | 1); } @@ -551,7 +747,7 @@ mod tests { // 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(); + let c = Cabac::new(&data, 3, 30, 0).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 index 71eded08..fd061702 100644 --- a/crates/ec-h264/src/cabac_tables.rs +++ b/crates/ec-h264/src/cabac_tables.rs @@ -1,10 +1,18 @@ //! 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. +//! The initialisation values of Tables 9-12 to 9-21 for every ctxIdx a +//! frame-coded 4:2:0 slice can reach: 0..10 (I-slice mb_type), 11..59 (the +//! inter elements: mb_skip_flag, P and B mb_type and sub_mb_type, mvd, +//! ref_idx), 60..69 (shared by all slice types), 70..275 and 399..401. +//! +//! Where a ctxIdx has cabac_init_idc columns they are stored as +//! `[I/SI, idc 0, idc 1, idc 2]` and [`crate::cabac::Cabac`] selects the column +//! once per slice. ctxIdx 11..53 are never read by an I slice; their I column +//! repeats the idc-0 values so the arrays stay rectangular. +//! +//! Absent on purpose: the field-coded significance contexts (277..398) and the +//! 8x8 transform categories (402..1023) — both tools are refused by name, so +//! transcribing their numbers would ship values no oracle here exercises. /// Table 9-12, ctxIdx 0..10: mb_type in I slices. pub(crate) const INIT_MB_TYPE_I: [(i8, i8); 11] = [ @@ -21,8 +29,8 @@ pub(crate) const INIT_MB_TYPE_I: [(i8, i8); 11] = [ (7, 51), ]; -/// Table 9-17, ctxIdx 60..69: mb_qp_delta, intra_chroma_pred_mode and the two -/// intra 4x4 prediction mode elements. +/// Table 9-17, ctxIdx 60..69: mb_qp_delta, intra_chroma_pred_mode and the +/// two intra 4x4 prediction mode elements. One column for every slice type. pub(crate) const INIT_60_69: [(i8, i8); 10] = [ (0, 41), (0, 63), @@ -36,220 +44,278 @@ pub(crate) const INIT_60_69: [(i8, i8); 10] = [ (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), +/// Tables 9-13 to 9-16, ctxIdx 11..59: mb_skip_flag, mb_type and sub_mb_type +/// for P and B slices, mvd and ref_idx. +pub(crate) const INIT_11_59: [[(i8, i8); 4]; 49] = [ + [(23, 33), (23, 33), (22, 25), (29, 16)], + [(23, 2), (23, 2), (34, 0), (25, 0)], + [(21, 0), (21, 0), (16, 0), (14, 0)], + [(1, 9), (1, 9), (-2, 9), (-10, 51)], + [(0, 49), (0, 49), (4, 41), (-3, 62)], + [(-37, 118), (-37, 118), (-29, 118), (-27, 99)], + [(5, 57), (5, 57), (2, 65), (26, 16)], + [(-13, 78), (-13, 78), (-6, 71), (-4, 85)], + [(-11, 65), (-11, 65), (-13, 79), (-24, 102)], + [(1, 62), (1, 62), (5, 52), (5, 57)], + [(12, 49), (12, 49), (9, 50), (6, 57)], + [(-4, 73), (-4, 73), (-3, 70), (-17, 73)], + [(17, 50), (17, 50), (10, 54), (14, 57)], + [(18, 64), (18, 64), (26, 34), (20, 40)], + [(9, 43), (9, 43), (19, 22), (20, 10)], + [(29, 0), (29, 0), (40, 0), (29, 0)], + [(26, 67), (26, 67), (57, 2), (54, 0)], + [(16, 90), (16, 90), (41, 36), (37, 42)], + [(9, 104), (9, 104), (26, 69), (12, 97)], + [(-46, 127), (-46, 127), (-45, 127), (-32, 127)], + [(-20, 104), (-20, 104), (-15, 101), (-22, 117)], + [(1, 67), (1, 67), (-4, 76), (-2, 74)], + [(-13, 78), (-13, 78), (-6, 71), (-4, 85)], + [(-11, 65), (-11, 65), (-13, 79), (-24, 102)], + [(1, 62), (1, 62), (5, 52), (5, 57)], + [(-6, 86), (-6, 86), (6, 69), (-6, 93)], + [(-17, 95), (-17, 95), (-13, 90), (-14, 88)], + [(-6, 61), (-6, 61), (0, 52), (-6, 44)], + [(9, 45), (9, 45), (8, 43), (4, 55)], + [(-3, 69), (-3, 69), (-2, 69), (-11, 89)], + [(-6, 81), (-6, 81), (-5, 82), (-15, 103)], + [(-11, 96), (-11, 96), (-10, 96), (-21, 116)], + [(6, 55), (6, 55), (2, 59), (19, 57)], + [(7, 67), (7, 67), (2, 75), (20, 58)], + [(-5, 86), (-5, 86), (-3, 87), (4, 84)], + [(2, 88), (2, 88), (-3, 100), (6, 96)], + [(0, 58), (0, 58), (1, 56), (1, 63)], + [(-3, 76), (-3, 76), (-3, 74), (-5, 85)], + [(-10, 94), (-10, 94), (-6, 85), (-13, 106)], + [(5, 54), (5, 54), (0, 59), (5, 63)], + [(4, 69), (4, 69), (-3, 81), (6, 75)], + [(-3, 81), (-3, 81), (-7, 86), (-3, 90)], + [(0, 88), (0, 88), (-5, 95), (-1, 101)], + [(-7, 67), (-7, 67), (-1, 66), (3, 55)], + [(-5, 74), (-5, 74), (-1, 77), (-4, 79)], + [(-4, 74), (-4, 74), (1, 70), (-2, 75)], + [(-5, 80), (-5, 80), (-2, 86), (-12, 97)], + [(-7, 72), (-7, 72), (-5, 72), (-7, 50)], + [(1, 58), (1, 58), (0, 61), (1, 60)], +]; + +/// Tables 9-18 to 9-21, ctxIdx 70..275: 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); 4]; 206] = [ + [(0, 11), (0, 45), (13, 15), (7, 34)], + [(1, 55), (-4, 78), (7, 51), (-9, 88)], + [(0, 69), (-3, 96), (2, 80), (-20, 127)], + [(-17, 127), (-27, 126), (-39, 127), (-36, 127)], + [(-13, 102), (-28, 98), (-18, 91), (-17, 91)], + [(0, 82), (-25, 101), (-17, 96), (-14, 95)], + [(-7, 74), (-23, 67), (-26, 81), (-25, 84)], + [(-21, 107), (-28, 82), (-35, 98), (-25, 86)], + [(-27, 127), (-20, 94), (-24, 102), (-12, 89)], + [(-31, 127), (-16, 83), (-23, 97), (-17, 91)], + [(-24, 127), (-22, 110), (-27, 119), (-31, 127)], + [(-18, 95), (-21, 91), (-24, 99), (-14, 76)], + [(-27, 127), (-18, 102), (-21, 110), (-18, 103)], + [(-21, 114), (-13, 93), (-18, 102), (-13, 90)], + [(-30, 127), (-29, 127), (-36, 127), (-37, 127)], + [(-17, 123), (-7, 92), (0, 80), (11, 80)], + [(-12, 115), (-5, 89), (-5, 89), (5, 76)], + [(-16, 122), (-7, 96), (-7, 94), (2, 84)], + [(-11, 115), (-13, 108), (-4, 92), (5, 78)], + [(-12, 63), (-3, 46), (0, 39), (-6, 55)], + [(-2, 68), (-1, 65), (0, 65), (4, 61)], + [(-15, 84), (-1, 57), (-15, 84), (-14, 83)], + [(-13, 104), (-9, 93), (-35, 127), (-37, 127)], + [(-3, 70), (-3, 74), (-2, 73), (-5, 79)], + [(-8, 93), (-9, 92), (-12, 104), (-11, 104)], + [(-10, 90), (-8, 87), (-9, 91), (-11, 91)], + [(-30, 127), (-23, 126), (-31, 127), (-30, 127)], + [(-1, 74), (5, 54), (3, 55), (0, 65)], + [(-6, 97), (6, 60), (7, 56), (-2, 79)], + [(-7, 91), (6, 59), (7, 55), (0, 72)], + [(-20, 127), (6, 69), (8, 61), (-4, 92)], + [(-4, 56), (-1, 48), (-3, 53), (-6, 56)], + [(-5, 82), (0, 68), (0, 68), (3, 68)], + [(-7, 76), (-4, 69), (-7, 74), (-8, 71)], + [(-22, 125), (-8, 88), (-9, 88), (-13, 98)], + [(-7, 93), (-2, 85), (-13, 103), (-4, 86)], + [(-11, 87), (-6, 78), (-13, 91), (-12, 88)], + [(-3, 77), (-1, 75), (-9, 89), (-5, 82)], + [(-5, 71), (-7, 77), (-14, 92), (-3, 72)], + [(-4, 63), (2, 54), (-8, 76), (-4, 67)], + [(-4, 68), (5, 50), (-12, 87), (-8, 72)], + [(-12, 84), (-3, 68), (-23, 110), (-16, 89)], + [(-7, 62), (1, 50), (-24, 105), (-9, 69)], + [(-7, 65), (6, 42), (-10, 78), (-1, 59)], + [(8, 61), (-4, 81), (-20, 112), (5, 66)], + [(5, 56), (1, 63), (-17, 99), (4, 57)], + [(-2, 66), (-4, 70), (-78, 127), (-4, 71)], + [(1, 64), (0, 67), (-70, 127), (-2, 71)], + [(0, 61), (2, 57), (-50, 127), (2, 58)], + [(-2, 78), (-2, 76), (-46, 127), (-1, 74)], + [(1, 50), (11, 35), (-4, 66), (-4, 44)], + [(7, 52), (4, 64), (-5, 78), (-1, 69)], + [(10, 35), (1, 61), (-4, 71), (0, 62)], + [(0, 44), (11, 35), (-8, 72), (-7, 51)], + [(11, 38), (18, 25), (2, 59), (-4, 47)], + [(1, 45), (12, 24), (-1, 55), (-6, 42)], + [(0, 46), (13, 29), (-7, 70), (-3, 41)], + [(5, 44), (13, 36), (-6, 75), (-6, 53)], + [(31, 17), (-10, 93), (-8, 89), (8, 76)], + [(1, 51), (-7, 73), (-34, 119), (-9, 78)], + [(7, 50), (-2, 73), (-3, 75), (-11, 83)], + [(28, 19), (13, 46), (32, 20), (9, 52)], + [(16, 33), (9, 49), (30, 22), (0, 67)], + [(14, 62), (-7, 100), (-44, 127), (-5, 90)], + [(-13, 108), (9, 53), (0, 54), (1, 67)], + [(-15, 100), (2, 53), (-5, 61), (-15, 72)], + [(-13, 101), (5, 53), (0, 58), (-5, 75)], + [(-13, 91), (-2, 61), (-1, 60), (-8, 80)], + [(-12, 94), (0, 56), (-3, 61), (-21, 83)], + [(-10, 88), (0, 56), (-8, 67), (-21, 64)], + [(-16, 84), (-13, 63), (-25, 84), (-13, 31)], + [(-10, 86), (-5, 60), (-14, 74), (-25, 64)], + [(-7, 83), (-1, 62), (-5, 65), (-29, 94)], + [(-13, 87), (4, 57), (5, 52), (9, 75)], + [(-19, 94), (-6, 69), (2, 57), (17, 63)], + [(1, 70), (4, 57), (0, 61), (-8, 74)], + [(0, 72), (14, 39), (-9, 69), (-5, 35)], + [(-5, 74), (4, 51), (-11, 70), (-2, 27)], + [(18, 59), (13, 68), (18, 55), (13, 91)], + [(-8, 102), (3, 64), (-4, 71), (3, 65)], + [(-15, 100), (1, 61), (0, 58), (-7, 69)], + [(0, 95), (9, 63), (7, 61), (8, 77)], + [(-4, 75), (7, 50), (9, 41), (-10, 66)], + [(2, 72), (16, 39), (18, 25), (3, 62)], + [(-11, 75), (5, 44), (9, 32), (-3, 68)], + [(-3, 71), (4, 52), (5, 43), (-20, 81)], + [(15, 46), (11, 48), (9, 47), (0, 30)], + [(-13, 69), (-5, 60), (0, 44), (1, 7)], + [(0, 62), (-1, 59), (0, 51), (-3, 23)], + [(0, 65), (0, 59), (2, 46), (-21, 74)], + [(21, 37), (22, 33), (19, 38), (16, 66)], + [(-15, 72), (5, 44), (-4, 66), (-23, 124)], + [(9, 57), (14, 43), (15, 38), (17, 37)], + [(16, 54), (-1, 78), (12, 42), (44, -18)], + [(0, 62), (0, 60), (9, 34), (50, -34)], + [(12, 72), (9, 69), (0, 89), (-22, 127)], + [(24, 0), (11, 28), (4, 45), (4, 39)], + [(15, 9), (2, 40), (10, 28), (0, 42)], + [(8, 25), (3, 44), (10, 31), (7, 34)], + [(13, 18), (0, 49), (33, -11), (11, 29)], + [(15, 9), (0, 46), (52, -43), (8, 31)], + [(13, 19), (2, 44), (18, 15), (6, 37)], + [(10, 37), (2, 51), (28, 0), (7, 42)], + [(12, 18), (0, 47), (35, -22), (3, 40)], + [(6, 29), (4, 39), (38, -25), (8, 33)], + [(20, 33), (2, 62), (34, 0), (13, 43)], + [(15, 30), (6, 46), (39, -18), (13, 36)], + [(4, 45), (0, 54), (32, -12), (4, 47)], + [(1, 58), (3, 54), (102, -94), (3, 55)], + [(0, 62), (2, 58), (0, 0), (2, 58)], + [(7, 61), (4, 63), (56, -15), (6, 60)], + [(12, 38), (6, 51), (33, -4), (8, 44)], + [(11, 45), (6, 57), (29, 10), (11, 44)], + [(15, 39), (7, 53), (37, -5), (14, 42)], + [(11, 42), (6, 52), (51, -29), (7, 48)], + [(13, 44), (6, 55), (39, -9), (4, 56)], + [(16, 45), (11, 45), (52, -34), (4, 52)], + [(12, 41), (14, 36), (69, -58), (13, 37)], + [(10, 49), (8, 53), (67, -63), (9, 49)], + [(30, 34), (-1, 82), (44, -5), (19, 58)], + [(18, 42), (7, 55), (32, 7), (10, 48)], + [(10, 55), (-3, 78), (55, -29), (12, 45)], + [(17, 51), (15, 46), (32, 1), (0, 69)], + [(17, 46), (22, 31), (0, 0), (20, 33)], + [(0, 89), (-1, 84), (27, 36), (8, 63)], + [(26, -19), (25, 7), (33, -25), (35, -18)], + [(22, -17), (30, -7), (34, -30), (33, -25)], + [(26, -17), (28, 3), (36, -28), (28, -3)], + [(30, -25), (28, 4), (38, -28), (24, 10)], + [(28, -20), (32, 0), (38, -27), (27, 0)], + [(33, -23), (34, -1), (34, -18), (34, -14)], + [(37, -27), (30, 6), (35, -16), (52, -44)], + [(33, -23), (30, 6), (34, -14), (39, -24)], + [(40, -28), (32, 9), (32, -8), (19, 17)], + [(38, -17), (31, 19), (37, -6), (31, 25)], + [(33, -11), (26, 27), (35, 0), (36, 29)], + [(40, -15), (26, 30), (30, 10), (24, 33)], + [(41, -6), (37, 20), (28, 18), (34, 15)], + [(38, 1), (28, 34), (26, 25), (30, 20)], + [(41, 17), (17, 70), (29, 41), (22, 73)], + [(30, -6), (1, 67), (0, 75), (20, 34)], + [(27, 3), (5, 59), (2, 72), (19, 31)], + [(26, 22), (9, 67), (8, 77), (27, 44)], + [(37, -16), (16, 30), (14, 35), (19, 16)], + [(35, -4), (18, 32), (18, 31), (15, 36)], + [(38, -8), (18, 35), (17, 35), (15, 36)], + [(38, -3), (22, 29), (21, 30), (21, 28)], + [(37, 3), (24, 31), (17, 45), (25, 21)], + [(38, 5), (23, 38), (20, 42), (30, 20)], + [(42, 0), (18, 43), (18, 45), (31, 12)], + [(35, 16), (20, 41), (27, 26), (27, 16)], + [(39, 22), (11, 63), (16, 54), (24, 42)], + [(14, 48), (9, 59), (7, 66), (0, 93)], + [(27, 37), (9, 64), (16, 56), (14, 56)], + [(21, 60), (-1, 94), (11, 73), (15, 57)], + [(12, 68), (-2, 89), (10, 67), (26, 38)], + [(2, 97), (-9, 108), (-10, 116), (-24, 127)], + [(-3, 71), (-6, 76), (-23, 112), (-24, 115)], + [(-6, 42), (-2, 44), (-15, 71), (-22, 82)], + [(-5, 50), (0, 45), (-7, 61), (-9, 62)], + [(-3, 54), (0, 52), (0, 53), (0, 53)], + [(-2, 62), (-3, 64), (-5, 66), (0, 59)], + [(0, 58), (-2, 59), (-11, 77), (-14, 85)], + [(1, 63), (-4, 70), (-9, 80), (-13, 89)], + [(-2, 72), (-4, 75), (-9, 84), (-13, 94)], + [(-1, 74), (-8, 82), (-10, 87), (-11, 92)], + [(-9, 91), (-17, 102), (-34, 127), (-29, 127)], + [(-5, 67), (-9, 77), (-21, 101), (-21, 100)], + [(-5, 27), (3, 24), (-3, 39), (-14, 57)], + [(-3, 39), (0, 42), (-5, 53), (-12, 67)], + [(-2, 44), (0, 48), (-7, 61), (-11, 71)], + [(0, 46), (0, 55), (-11, 75), (-10, 77)], + [(-16, 64), (-6, 59), (-15, 77), (-21, 85)], + [(-8, 68), (-7, 71), (-17, 91), (-16, 88)], + [(-10, 78), (-12, 83), (-25, 107), (-23, 104)], + [(-6, 77), (-11, 87), (-25, 111), (-15, 98)], + [(-10, 86), (-30, 119), (-28, 122), (-37, 127)], + [(-12, 92), (1, 58), (-11, 76), (-10, 82)], + [(-15, 55), (-3, 29), (-10, 44), (-8, 48)], + [(-10, 60), (-1, 36), (-10, 52), (-8, 61)], + [(-6, 62), (1, 38), (-10, 57), (-8, 66)], + [(-4, 65), (2, 43), (-9, 58), (-7, 70)], + [(-12, 73), (-6, 55), (-16, 72), (-14, 75)], + [(-8, 76), (0, 58), (-7, 69), (-10, 79)], + [(-7, 80), (0, 64), (-4, 69), (-9, 83)], + [(-9, 88), (-3, 74), (-5, 74), (-12, 92)], + [(-17, 110), (-10, 90), (-9, 86), (-18, 108)], + [(-11, 97), (0, 70), (2, 66), (-4, 79)], + [(-20, 84), (-4, 29), (-9, 34), (-22, 69)], + [(-11, 79), (5, 31), (1, 32), (-16, 75)], + [(-6, 73), (7, 42), (11, 31), (-2, 58)], + [(-4, 74), (1, 59), (5, 52), (1, 58)], + [(-13, 86), (-2, 58), (-2, 55), (-13, 78)], + [(-13, 96), (-3, 72), (-2, 67), (-9, 83)], + [(-11, 97), (-3, 81), (0, 73), (-4, 81)], + [(-19, 117), (-11, 97), (-8, 89), (-13, 99)], + [(-8, 78), (0, 58), (3, 52), (-13, 81)], + [(-5, 33), (8, 5), (7, 4), (-6, 38)], + [(-4, 48), (10, 14), (10, 8), (-13, 62)], + [(-2, 53), (14, 18), (17, 8), (-6, 58)], + [(-3, 62), (13, 27), (16, 19), (-2, 59)], + [(-13, 71), (2, 40), (3, 37), (-16, 73)], + [(-10, 79), (0, 58), (-1, 61), (-10, 76)], + [(-12, 86), (-3, 70), (-5, 73), (-13, 86)], + [(-13, 90), (-6, 79), (-1, 70), (-9, 83)], + [(-14, 97), (-8, 85), (-4, 78), (-10, 87)], ]; /// 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)]; +pub(crate) const INIT_399_401: [[(i8, i8); 4]; 3] = [ + [(31, 21), (12, 40), (25, 32), (21, 33)], + [(31, 31), (11, 51), (21, 49), (19, 50)], + [(25, 50), (14, 59), (21, 54), (17, 61)], +]; /// Table 9-44: rangeTabLPS[pStateIdx][qCodIRangeIdx]. pub(crate) const RANGE_LPS: [[u8; 4]; 64] = [ @@ -321,14 +387,16 @@ pub(crate) const RANGE_LPS: [[u8; 4]; 64] = [ /// 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, + 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, + 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/codec.rs b/crates/ec-h264/src/codec.rs index d856fa64..a50433ab 100644 --- a/crates/ec-h264/src/codec.rs +++ b/crates/ec-h264/src/codec.rs @@ -17,7 +17,7 @@ use ec_core::registry::{CodecId, CodecParameters, MediaParameters}; use ec_core::timebase::Timestamp; use ec_h264_syntax::AnnexBIter; -use crate::decoder::{Decoder, NalOutcome}; +use crate::decoder::{Decoder, NalOutcome, OutputOrder}; /// H.264 decoder behind the codec registry's packet/frame contract. pub struct H264Decoder { @@ -27,7 +27,6 @@ pub struct H264Decoder { /// `None` means Annex B start codes. nal_length_size: Option, frames: VecDeque, - pending_pts: Option, end_of_stream: bool, } @@ -50,7 +49,6 @@ impl H264Decoder { inner: Decoder::new(), nal_length_size: None, frames: VecDeque::new(), - pending_pts: None, end_of_stream: false, }; // 7 bytes is the shortest record that can hold the fixed header plus a @@ -64,6 +62,21 @@ impl H264Decoder { Ok(decoder) } + /// Choose the order frames come back in. + /// + /// The default is display order, which is the order a player presents + /// pictures in and the only correct one for a stream with B pictures. A + /// caller that does its own reordering — or that wants the lowest possible + /// latency and knows the stream never reorders — can ask for decode order. + pub fn set_output_order(&mut self, order: OutputOrder) { + self.inner.set_output_order(order); + } + + /// The order frames come back in. + pub fn output_order(&self) -> OutputOrder { + self.inner.output_order() + } + /// Read an `avcC` record: the NAL length size and the in-band parameter /// sets (ISO/IEC 14496-15 clause 5.3.3.1). fn parse_avcc(&mut self, extradata: &[u8]) -> Result<()> { @@ -133,18 +146,23 @@ impl H264Decoder { Ok(()) } - /// Emit the open picture, if there is one, as a frame. + /// Complete the open picture, if there is one, and drain whatever that + /// made ready for output. fn finish_picture(&mut self) -> Result<()> { - if !self.inner.picture_open() { - return Ok(()); + if self.inner.picture_open() { + self.inner.end_picture()?; } - self.inner.end_picture()?; - let mut frame = self.inner.frame()?; - frame.pts = self.pending_pts.take(); - self.frames.push_back(Frame::Video(frame)); + self.drain(); Ok(()) } + /// Move every frame the decoder has released into the output queue. + fn drain(&mut self) { + while let Some(frame) = self.inner.next_frame() { + self.frames.push_back(Frame::Video(frame)); + } + } + /// Publish the active SPS geometry on `params`, the way a demuxer that /// only had an `avcC` expects to read it back. fn sync_parameters(&mut self) { @@ -166,9 +184,13 @@ impl ec_core::registry::Decoder for H264Decoder { fn send_packet(&mut self, packet: &Packet) -> Result<()> { self.end_of_stream = false; - self.pending_pts = packet - .pts - .map(|ticks| Timestamp::new(ticks, packet.time_base)); + // The timestamp belongs to the picture, not to the packet: display + // order hands pictures back in a different order than they arrive. + self.inner.set_next_pts( + packet + .pts + .map(|ticks| Timestamp::new(ticks, packet.time_base)), + ); self.decode_packet_payload(&packet.data)?; // One packet is one access unit, so whatever picture it started is // complete once the packet is consumed. @@ -184,7 +206,8 @@ impl ec_core::registry::Decoder for H264Decoder { } fn flush(&mut self) -> Result<()> { - self.finish_picture()?; + self.inner.flush()?; + self.drain(); self.end_of_stream = true; Ok(()) } @@ -194,7 +217,6 @@ impl ec_core::registry::Decoder for H264Decoder { // state does not. self.inner.reset_pictures(); self.frames.clear(); - self.pending_pts = None; self.end_of_stream = false; } } diff --git a/crates/ec-h264/src/decoder.rs b/crates/ec-h264/src/decoder.rs index 2913d19e..68f3b545 100644 --- a/crates/ec-h264/src/decoder.rs +++ b/crates/ec-h264/src/decoder.rs @@ -1,29 +1,49 @@ -//! Decoder core: parameter-set store, flat per-picture context, macroblock +//! Decoder core: parameter-set store, decoded picture buffer, macroblock //! decode loop, reconstruction and the in-loop filter driver. //! //! Layout choices (perf-first): -//! - Planes are padded (`PAD_Y`/`PAD_C` samples each side), so neighbour -//! gathers and future inter-prediction overreach never bounds-check per -//! sample and edge availability is data, not arithmetic. -//! - All per-macroblock state lives in flat struct-of-arrays keyed by -//! macroblock address or 4x4-block coordinate: non-zero coefficient counts -//! (`nz_y`, `nz_c`), intra 4x4 modes, QP, flags, owning slice. No per-MB -//! heap objects anywhere. -//! - Buffers are reused across pictures; a picture start is O(macroblocks) -//! fills, and the slice decode loop performs zero allocations. +//! - Planes are padded (`PAD_Y`/`PAD_C` samples each side) and their borders +//! replicated once per picture, so neighbour gathers and inter-prediction +//! overreach never bounds-check per sample and edge availability is data, +//! not arithmetic. +//! - All per-macroblock and per-4x4-block state lives in flat struct-of-arrays +//! keyed by macroblock address or block coordinate: coefficient counts, intra +//! modes, QP, flags, owning slice, motion vectors, reference identities. No +//! per-macroblock heap objects anywhere. +//! - Pictures are pooled by the [`Dpb`], so a steady-state decode loop reuses +//! every buffer and performs zero allocations. +//! +//! Output is in display order: pictures leave the decoded picture buffer by the +//! bumping process, smallest picture order count first, which is the order a +//! player presents them in. [`OutputOrder::Decode`] switches that off for a +//! caller that wants pictures as they are decoded. + +use std::collections::VecDeque; use ec_core::BitReader; use ec_core::error::{Error, Result}; use ec_core::frame::{PixelFormat, Plane, VideoFrame}; +use ec_core::timebase::Timestamp; use ec_h264_syntax::{ - AnnexBIter, NalHeader, NalUnitType, Pps, SliceHeader, SliceType, Sps, unescape_rbsp, + AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader, + SliceType, Sps, WeightEntry, unescape_rbsp, }; use crate::deblock::{ chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line, }; +use crate::dpb::{ + BLK_DIRECT, BLK_INTRA, BLK_SKIP, Dpb, Mark, NO_SLICE, PicInfo, Picture, Plane8, RefList, + SliceParams, +}; use crate::entropy::{ - BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_PCM, MbCtx, MbInfo, + BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, + FLAG_SKIP, MbCtx, MbInfo, +}; +use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma}; +use crate::mv::{ + B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, + neighbour_mvd, predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd, }; use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; use crate::tables::{BLK4_POS, CHROMA_QP}; @@ -32,14 +52,6 @@ use crate::transform::{ unzigzag, unzigzag_ac15, }; -/// Luma plane padding on every side, sized for future inter-prediction -/// filter overreach (16 MB + margin). -const PAD_Y: usize = 32; -/// Chroma plane padding on every side. -const PAD_C: usize = 16; -/// `mb_slice` value for a not-yet-decoded macroblock. -const NO_SLICE: u16 = u16::MAX; - /// Where a 4x4 block's top-right neighbour samples come from, per /// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule). #[derive(Clone, Copy, PartialEq)] @@ -73,117 +85,47 @@ const TR_KIND: [TrKind; 16] = [ TrKind::None, ]; -/// A padded 8-bit plane. -#[derive(Debug, Default)] -struct Plane8 { - data: Vec, - stride: usize, - /// Index of sample (0, 0) of the picture. - origin: usize, +/// The order [`Decoder`] hands decoded pictures back in. +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum OutputOrder { + /// Display order: pictures leave the decoded picture buffer by the bumping + /// process of clause C.4.5.3. This is what a player needs, and the only + /// order that is correct for a stream with B pictures. + #[default] + Display, + /// Decode order: each picture is emitted the moment it is complete. Lower + /// latency, wrong presentation order whenever the stream reorders. + Decode, } -impl Plane8 { - fn resize(&mut self, width: usize, height: usize, pad: usize) { - self.stride = width + 2 * pad; - self.origin = pad * self.stride + pad; - self.data.clear(); - self.data.resize(self.stride * (height + 2 * pad), 0); - } - - #[inline] - fn at(&self, x: usize, y: usize) -> usize { - self.origin + y * self.stride + x - } -} - -/// Per-slice values the deblocking filter needs after slice decode ends. -#[derive(Debug, Clone, Copy)] -struct SliceParams { - disable_deblock_idc: u8, - alpha_offset: i32, - beta_offset: i32, - cb_qp_offset: i32, - cr_qp_offset: i32, -} - -/// Flat per-picture decode context (see module docs for the layout story). -#[derive(Debug, Default)] -struct Picture { - sps_id: u8, - mb_w: usize, - mb_h: usize, - y: Plane8, - cb: Plane8, - cr: Plane8, - /// TotalCoeff per luma 4x4 block, `(mb_w * 4) x (mb_h * 4)`. - nz_y: Vec, - /// TotalCoeff per chroma 4x4 block, `(mb_w * 2) x (mb_h * 2)`, Cb and Cr. - nz_c: [Vec; 2], - /// Intra4x4PredMode per luma 4x4 block (2 = DC for non-I4x4 MBs). - i4_modes: Vec, - /// QPY per macroblock (the prediction-chain value; PCM keeps the chain). - mb_qp: Vec, - /// `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, - decoded_mbs: usize, - complete: bool, -} - -impl Picture { - fn start(&mut self, sps: &Sps) { - let mb_w = sps.mb_width as usize; - let mb_h = sps.mb_height as usize; - if self.mb_w != mb_w || self.mb_h != mb_h || self.sps_id != sps.id { - self.mb_w = mb_w; - self.mb_h = mb_h; - self.sps_id = sps.id; - self.y.resize(mb_w * 16, mb_h * 16, PAD_Y); - self.cb.resize(mb_w * 8, mb_h * 8, PAD_C); - self.cr.resize(mb_w * 8, mb_h * 8, PAD_C); - self.nz_y.resize(mb_w * mb_h * 16, 0); - for c in &mut self.nz_c { - c.resize(mb_w * mb_h * 4, 0); - } - 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 - // "who is decoded" state must be wiped between pictures. - self.mb_slice.fill(NO_SLICE); - self.mb_flags.fill(0); - self.slices.clear(); - self.decoded_mbs = 0; - self.complete = false; - } -} - -/// Streaming H.264 decoder (CAVLC intra scope; unsupported features come back -/// as named [`Error::Unsupported`] values, never wrong pixels). +/// Streaming H.264 decoder (frame-coded 4:2:0 8-bit; unsupported features come +/// back as named [`Error::Unsupported`] values, never wrong pixels). pub struct Decoder { sps_map: Vec>, pps_map: Vec>, rbsp: Vec, - pic: Picture, + /// The picture being decoded, held out of the buffer pool. + cur: Picture, + dpb: Dpb, has_picture: bool, - /// Scaling factors for intra Y/Cb/Cr 4x4 lists of the active PPS/SPS. - ls: [LevelScale4x4; 3], + /// Scaling factors of the active PPS/SPS, `[intra, inter][Y, Cb, Cr]`. + ls: [[LevelScale4x4; 3]; 2], active_pps: Option, /// `seq_parameter_set_id` of the most recently stored SPS, so a container /// entry path can publish the picture size before the first slice. last_sps: Option, + /// Clause 8.2 view of the open picture, from its first slice header. + cur_info: PicInfo, + /// `dec_ref_pic_marking( )` of the open picture, kept in place so a + /// steady-state loop does not reallocate its MMCO list. + cur_marking: DecRefPicMarking, + has_marking: bool, + /// Identity of the picture `end_picture` completed most recently. + last_decoded: i32, + output_order: OutputOrder, + out: VecDeque, + /// Presentation timestamp to attach to the next picture started. + pending_pts: Option, } /// What [`Decoder::push_nal`] did with a NAL unit. @@ -196,7 +138,7 @@ pub enum NalOutcome { /// A slice was decoded into the open picture. SliceDecoded, /// The NAL starts a new picture while one is open; it was not consumed. - /// Call [`Decoder::end_picture`] + [`Decoder::frame`], then push it again. + /// Call [`Decoder::end_picture`], then push it again. PictureBoundary, } @@ -206,6 +148,21 @@ impl Default for Decoder { } } +fn flat_scaling() -> [[LevelScale4x4; 3]; 2] { + [ + [ + LevelScale4x4::new(&[16; 16]), + LevelScale4x4::new(&[16; 16]), + LevelScale4x4::new(&[16; 16]), + ], + [ + LevelScale4x4::new(&[16; 16]), + LevelScale4x4::new(&[16; 16]), + LevelScale4x4::new(&[16; 16]), + ], + ] +} + impl Decoder { /// A fresh decoder with no parameter sets. pub fn new() -> Decoder { @@ -213,18 +170,46 @@ impl Decoder { sps_map: vec![None; 32], pps_map: vec![None; 256], rbsp: Vec::new(), - pic: Picture::default(), + cur: Picture::default(), + dpb: Dpb::default(), has_picture: false, - ls: [ - LevelScale4x4::new(&[16; 16]), - LevelScale4x4::new(&[16; 16]), - LevelScale4x4::new(&[16; 16]), - ], + ls: flat_scaling(), active_pps: None, last_sps: None, + cur_info: PicInfo { + is_idr: false, + is_reference: false, + frame_num: 0, + pic_order_cnt_lsb: 0, + delta_pic_order_cnt_bottom: 0, + delta_pic_order_cnt: [0; 2], + }, + cur_marking: DecRefPicMarking::default(), + has_marking: false, + last_decoded: -1, + output_order: OutputOrder::default(), + out: VecDeque::new(), + pending_pts: None, } } + /// Choose between display order (the default) and decode order. + pub fn set_output_order(&mut self, order: OutputOrder) { + self.output_order = order; + } + + /// The order pictures are handed back in. + pub fn output_order(&self) -> OutputOrder { + self.output_order + } + + /// Attach `pts` to the next picture started, so a presentation timestamp + /// follows its picture through reordering instead of staying with the + /// packet that carried it. + pub fn set_next_pts(&mut self, pts: Option) { + self.pending_pts = pts; + } + /// Cropped picture size of the most recently stored SPS, `None` until one /// arrives. Lets a container entry path fill in stream parameters from an /// `avcC` record without decoding a picture first. @@ -264,6 +249,7 @@ impl Decoder { self.rbsp = rbsp; let sps = sps?; let id = sps.id; + self.dpb.configure(&sps); self.sps_map[id as usize] = Some(sps); self.last_sps = Some(id); Ok(NalOutcome::ParameterSet) @@ -296,22 +282,94 @@ impl Decoder { } } - /// Run the deblocking filter over the open picture and mark it complete. + /// Run the deblocking filter over the open picture, store it in the decoded + /// picture buffer and queue whatever pictures that makes ready for output. pub fn end_picture(&mut self) -> Result<()> { - if !self.has_picture || self.pic.complete { + if !self.has_picture || self.cur.complete { return Err(Error::corrupt("end_picture without an open picture")); } - deblock_picture(&mut self.pic); - self.pic.complete = true; - Ok(()) + deblock_picture(&mut self.cur); + self.cur.extend_borders(); + self.cur.complete = true; + self.last_decoded = self.cur.id; + let sps = self.sps_map[self.cur.sps_id as usize] + .as_ref() + .ok_or_else(|| Error::corrupt("active SPS vanished"))? + .clone(); + let pic = core::mem::take(&mut self.cur); + let marking = self.has_marking.then_some(&self.cur_marking); + self.dpb.store(pic, &sps, &self.cur_info, marking)?; + self.has_picture = false; + self.pump_output(false) + } + + /// Emit every remaining picture (end of stream). + pub fn flush(&mut self) -> Result<()> { + if self.has_picture && !self.cur.complete { + self.end_picture()?; + } + self.pump_output(true) + } + + /// The next frame ready for output, in the configured order. + pub fn next_frame(&mut self) -> Option { + self.out.pop_front() } - /// Copy the completed picture out as a cropped I420 frame. + /// The picture `end_picture` completed most recently, in decode order. + /// + /// Kept for a caller that drives one picture at a time; a player wants + /// [`Decoder::next_frame`], which respects the reordering the stream asks + /// for. pub fn frame(&self) -> Result { - if !self.pic.complete { - return Err(Error::corrupt("frame() before end_picture()")); + let id = self.last_decoded; + let pic = self + .dpb + .frames + .iter() + .find(|p| p.id == id) + .ok_or_else(|| Error::corrupt("frame() before end_picture()"))?; + self.picture_to_frame(pic) + } + + /// True while a picture is open (started, not completed). + pub fn picture_open(&self) -> bool { + self.has_picture && !self.cur.complete + } + + /// Drop picture state after a seek. Parameter sets survive, because the + /// container does not resend them at every seek point. + pub fn reset_pictures(&mut self) { + self.has_picture = false; + self.cur.complete = false; + self.dpb.clear(); + self.out.clear(); + self.last_decoded = -1; + self.pending_pts = None; + } + + /// Move pictures out of the decoded picture buffer into the output queue. + fn pump_output(&mut self, flush: bool) -> Result<()> { + if self.output_order == OutputOrder::Decode && !flush { + let id = self.last_decoded; + if let Some(i) = self.dpb.frames.iter().position(|p| p.id == id && p.output) { + let frame = self.picture_to_frame(&self.dpb.frames[i])?; + self.out.push_back(frame); + self.dpb.released(i); + } + return Ok(()); + } + while let Some(i) = self.dpb.next_output(flush) { + let frame = self.picture_to_frame(&self.dpb.frames[i])?; + self.out.push_back(frame); + self.dpb.released(i); } - let sps = self.sps_map[self.pic.sps_id as usize] + Ok(()) + } + + /// Copy a stored picture out as a cropped I420 frame. + fn picture_to_frame(&self, pic: &Picture) -> Result { + let sps = self.sps_map[pic.sps_id as usize] .as_ref() .ok_or_else(|| Error::corrupt("active SPS vanished"))?; let (w, h) = (sps.width as usize, sps.height as usize); @@ -325,9 +383,9 @@ impl Decoder { Plane::new(out, w) }; let planes = vec![ - copy(&self.pic.y, cx, cy, w, h), - copy(&self.pic.cb, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), - copy(&self.pic.cr, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), + copy(&pic.y, cx, cy, w, h), + copy(&pic.cb, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), + copy(&pic.cr, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), ]; let mut frame = VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)?; if let Some(vui) = &sps.vui { @@ -338,21 +396,10 @@ impl Decoder { frame.color.matrix = m; } } + frame.pts = pic.pts; Ok(frame) } - /// True while a picture is open (started, not completed). - pub fn picture_open(&self) -> bool { - self.has_picture && !self.pic.complete - } - - /// Drop picture state after a seek. Parameter sets survive, because the - /// container does not resend them at every seek point. - pub fn reset_pictures(&mut self) { - self.has_picture = false; - self.pic.complete = false; - } - fn decode_slice_rbsp(&mut self, header: NalHeader, rbsp: &[u8]) -> Result { // Peek first_mb / slice_type / pps_id to select parameter sets. let mut peek = BitReader::new(rbsp); @@ -362,7 +409,7 @@ impl Decoder { if pps_id > 255 { return Err(Error::corrupt("pic_parameter_set_id > 255")); } - if self.has_picture && !self.pic.complete && first_mb == 0 && self.pic.decoded_mbs > 0 { + if self.has_picture && !self.cur.complete && first_mb == 0 && self.cur.decoded_mbs > 0 { return Ok(NalOutcome::PictureBoundary); } let pps = self.pps_map[pps_id as usize] @@ -374,39 +421,20 @@ impl Decoder { check_supported(sps, pps, slice_type_code)?; let sh = SliceHeader::parse(rbsp, header, sps, pps)?; - if sh.slice_type != SliceType::I { - return Err(Error::unsupported( - "non-I slice", - "P/B/SP/SI slices need inter prediction and a decoded picture \ - buffer (clause 8.4); only intra slices are decoded", - )); - } + let sps = sps.clone(); + let pps = pps.clone(); - if !self.has_picture || self.pic.complete { - self.pic.start(sps); - self.has_picture = true; - if self.active_pps != Some(pps.id) { - let lists = pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref()); - let weights = match lists { - Some(l) => [&l.list_4x4[0], &l.list_4x4[1], &l.list_4x4[2]], - None => [&[16u8; 16]; 3], - }; - self.ls = [ - LevelScale4x4::new(weights[0]), - LevelScale4x4::new(weights[1]), - LevelScale4x4::new(weights[2]), - ]; - self.active_pps = Some(pps.id); - } + if !self.has_picture || self.cur.complete { + self.start_picture(&sps, &pps, &sh, header)?; } - if self.pic.sps_id != sps.id { + if self.cur.sps_id != sps.id { return Err(Error::corrupt("SPS changed mid-picture")); } - if self.pic.slices.len() >= usize::from(u16::MAX) { + if self.cur.slices.len() >= usize::from(u16::MAX) { return Err(Error::corrupt("more than 65534 slices in a picture")); } - let slice_id = self.pic.slices.len() as u16; - self.pic.slices.push(SliceParams { + let slice_id = self.cur.slices.len() as u16; + self.cur.slices.push(SliceParams { disable_deblock_idc: sh.deblock.disable_idc, alpha_offset: sh.deblock.alpha_c0_offset, beta_offset: sh.deblock.beta_offset, @@ -414,34 +442,236 @@ impl Decoder { cr_qp_offset: pps.second_chroma_qp_index_offset, }); + // Reference picture lists (clause 8.2.4), rebuilt per slice because + // num_ref_idx_active and the modification list are slice header state. + let max_pic_num = 1i32 << sps.log2_max_frame_num; + let lists = if sh.slice_type.is_intra() { + [RefList::default(), RefList::default()] + } else { + self.dpb.number_short_term(sh.frame_num, &sps); + self.dpb.build_ref_lists( + sh.slice_type, + self.cur.poc, + sh.frame_num as i32, + max_pic_num, + sh.num_ref_idx_l0_active as usize, + sh.num_ref_idx_l1_active as usize, + (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1), + )? + }; + let mut r = if pps.entropy_coding_mode { - Entropy::cabac(rbsp, sh.header_bits, sh.slice_qp)? + let column = if sh.slice_type.is_intra() { + 0 + } else { + sh.cabac_init_idc as usize + 1 + }; + Entropy::cabac(rbsp, sh.header_bits, sh.slice_qp, column)? } else { Entropy::cavlc(rbsp, sh.header_bits) }; let mut ctx = SliceCtx { slice_id, + slice_type: sh.slice_type, qp: sh.slice_qp, cb_qp_offset: pps.chroma_qp_index_offset, cr_qp_offset: pps.second_chroma_qp_index_offset, transform_8x8_mode: pps.transform_8x8_mode, + constrained_intra_pred: pps.constrained_intra_pred, qp_delta_inc: 0, + lists, + num_ref_idx: [ + sh.num_ref_idx_l0_active as usize, + sh.num_ref_idx_l1_active as usize, + ], + direct_spatial: sh.direct_spatial_mv_pred, + direct_8x8_inference: sps.direct_8x8_inference, + weighted_pred: pps.weighted_pred, + weighted_bipred_idc: pps.weighted_bipred_idc, + weights: sh.pred_weight_table.clone(), + poc: self.cur.poc, }; - let mbs = self.pic.mb_w * self.pic.mb_h; + let intra_slice = sh.slice_type.is_intra(); + let b_slice = sh.slice_type == SliceType::B; + if !intra_slice && ctx.lists[0].len() == 0 { + return Err(Error::corrupt("inter slice with no reference pictures")); + } + + let mbs = self.cur.mb_w * self.cur.mb_h; let mut mb_addr = first_mb as usize; - loop { + let mut more = true; + while more { if mb_addr >= mbs { return Err(Error::corrupt("macroblock address beyond the picture")); } - decode_macroblock(&mut self.pic, &self.ls, &mut r, &mut ctx, mb_addr)?; - if !r.more_macroblocks()? { - break; + let mut decode_mb = true; + if !intra_slice { + if r.is_cabac() { + self.begin_mb(&mut r, &ctx, mb_addr); + let inc = self.skip_inc(&ctx, mb_addr); + if r.mb_skip_flag(b_slice, inc)? { + decode_macroblock( + &mut self.cur, + &self.dpb.frames, + &self.ls, + &mut r, + &mut ctx, + mb_addr, + true, + )?; + decode_mb = false; + } + } else { + let run = r.mb_skip_run()?; + for _ in 0..run { + if mb_addr >= mbs { + return Err(Error::corrupt("mb_skip_run past the picture")); + } + decode_macroblock( + &mut self.cur, + &self.dpb.frames, + &self.ls, + &mut r, + &mut ctx, + mb_addr, + true, + )?; + mb_addr += 1; + } + if run > 0 { + more = r.more_macroblocks()?; + if !more { + break; + } + if mb_addr >= mbs { + return Err(Error::corrupt("macroblock address beyond the picture")); + } + } + } + } + if decode_mb { + decode_macroblock( + &mut self.cur, + &self.dpb.frames, + &self.ls, + &mut r, + &mut ctx, + mb_addr, + false, + )?; } + more = r.more_macroblocks()?; mb_addr += 1; } Ok(NalOutcome::SliceDecoded) } + + /// Publish the neighbourhood of `mb_addr` to a CABAC reader ahead of + /// mb_skip_flag, which is decoded before the macroblock layer. + fn begin_mb(&self, r: &mut Entropy<'_>, ctx: &SliceCtx, mb_addr: usize) { + let pic = &self.cur; + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + 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, + }); + } + + /// ctxIdxInc for mb_skip_flag (9.3.3.1.1.1): a neighbour counts unless it + /// is unavailable or was itself skipped. + fn skip_inc(&self, ctx: &SliceCtx, mb_addr: usize) -> usize { + let pic = &self.cur; + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id); + let cond = |avail: bool, addr: usize| { + usize::from(avail && pic.mb_flags[addr] & FLAG_SKIP == 0) + }; + cond(nbr.a, mb_addr.wrapping_sub(1)) + cond(nbr.b, mb_addr.wrapping_sub(pic.mb_w)) + } + + /// Open a new picture: clause 8.2 bookkeeping, then the geometry reset. + fn start_picture( + &mut self, + sps: &Sps, + pps: &Pps, + sh: &SliceHeader, + header: NalHeader, + ) -> Result<()> { + let info = PicInfo { + is_idr: header.is_idr(), + is_reference: header.ref_idc != 0, + frame_num: sh.frame_num, + pic_order_cnt_lsb: sh.pic_order_cnt_lsb, + delta_pic_order_cnt_bottom: sh.delta_pic_order_cnt_bottom, + delta_pic_order_cnt: sh.delta_pic_order_cnt, + }; + // A frame_num gap is what a seek or a dropped packet looks like: the + // pictures it names never arrive, so clause 8.2.5.2 infers them and + // decoding continues rather than stalling until the next IDR. + if !info.is_idr && self.dpb.frame_num_gap(sps, sh.frame_num) { + if !sps.gaps_in_frame_num_allowed { + // Not a conformant gap: pictures were lost. Same repair. + self.dpb.fill_frame_num_gap(sps, sh.frame_num)?; + } else { + self.dpb.fill_frame_num_gap(sps, sh.frame_num)?; + } + self.pump_output(false)?; + } + let poc = self.dpb.picture_order_count(sps, &info)?; + let mut pic = self.dpb.take_picture(); + pic.start(sps); + pic.poc = poc.value; + pic.poc_msb = poc.msb; + pic.poc_lsb = poc.lsb; + pic.frame_num_offset = poc.frame_num_offset; + pic.frame_num = sh.frame_num; + pic.pts = self.pending_pts.take(); + self.cur = pic; + self.cur_info = info; + self.has_marking = sh.dec_ref_pic_marking.is_some(); + if let Some(m) = &sh.dec_ref_pic_marking { + self.cur_marking.no_output_of_prior_pics = m.no_output_of_prior_pics; + self.cur_marking.long_term_reference = m.long_term_reference; + self.cur_marking.adaptive = m.adaptive; + self.cur_marking.mmcos.clear(); + self.cur_marking.mmcos.extend_from_slice(&m.mmcos); + } + self.has_picture = true; + if self.active_pps != Some(pps.id) { + let lists = pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref()); + let weights = match lists { + Some(l) => [ + [&l.list_4x4[0], &l.list_4x4[1], &l.list_4x4[2]], + [&l.list_4x4[3], &l.list_4x4[4], &l.list_4x4[5]], + ], + None => [[&[16u8; 16]; 3]; 2], + }; + self.ls = [ + [ + LevelScale4x4::new(weights[0][0]), + LevelScale4x4::new(weights[0][1]), + LevelScale4x4::new(weights[0][2]), + ], + [ + LevelScale4x4::new(weights[1][0]), + LevelScale4x4::new(weights[1][1]), + LevelScale4x4::new(weights[1][2]), + ], + ]; + self.active_pps = Some(pps.id); + } + Ok(()) + } } /// Reject unsupported streams with named reasons before touching pixels. @@ -502,24 +732,132 @@ fn check_supported(sps: &Sps, pps: &Pps, slice_type_code: u32) -> Result<()> { if slice_type_code > 9 { return Err(Error::corrupt("slice_type > 9")); } + if matches!(slice_type_code % 5, 3 | 4) { + return Err(Error::unsupported( + "SP and SI slices", + "switching slices need the transform-domain reconstruction of \ + clause 8.5.14 and their own deblocking strengths; not implemented", + )); + } Ok(()) } /// Mutable per-slice decode state. struct SliceCtx { slice_id: u16, + slice_type: SliceType, qp: i32, cb_qp_offset: i32, cr_qp_offset: i32, transform_8x8_mode: bool, + constrained_intra_pred: 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, + /// `RefPicList0` and `RefPicList1` as decoded picture buffer indices. + lists: [RefList; 2], + num_ref_idx: [usize; 2], + direct_spatial: bool, + direct_8x8_inference: bool, + weighted_pred: bool, + weighted_bipred_idc: u8, + weights: Option, + /// `PicOrderCnt( CurrPic )`. + poc: i32, } -/// Neighbour-availability snapshot for one macroblock (left, top, -/// top-right). Top-left availability follows from the modes that read it -/// being conformance-restricted; inter prediction will add it back. +impl SliceCtx { + fn is_b(&self) -> bool { + self.slice_type == SliceType::B + } + + /// The reference picture `RefPicListX[idx]` points at. + fn reference<'a>(&self, refs: &'a [Picture], list: usize, idx: i8) -> Option<&'a Picture> { + if idx < 0 { + return None; + } + refs.get(self.lists[list].get(idx as usize)?) + } + + /// Prediction weights of one component (clause 8.4.3). + fn weights_for( + &self, + refs: &[Picture], + comp: usize, + r0: i8, + r1: i8, + use0: bool, + use1: bool, + ) -> Weights { + let implicit = self.weighted_bipred_idc == 2 && self.is_b() && use0 && use1; + let explicit = (self.weighted_bipred_idc == 1 && self.is_b()) + || (self.weighted_pred && !self.is_b()); + if implicit { + let (Some(p0), Some(p1)) = ( + self.reference(refs, 0, r0), + self.reference(refs, 1, r1), + ) else { + return Weights::DEFAULT; + }; + let td = (p1.poc - p0.poc).clamp(-128, 127); + let long_term = p0.mark == Mark::Long || p1.mark == Mark::Long; + if td == 0 || long_term { + return Weights { + log_wd: 5, + w: [32, 32], + o: [0, 0], + }; + } + let tb = (self.poc - p0.poc).clamp(-128, 127); + let tx = (16384 + (td / 2).abs()) / td; + let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023); + let w1 = dist >> 2; + if !(-64..=128).contains(&w1) { + return Weights { + log_wd: 5, + w: [32, 32], + o: [0, 0], + }; + } + return Weights { + log_wd: 5, + w: [64 - w1, w1], + o: [0, 0], + }; + } + if !explicit { + return Weights::DEFAULT; + } + let Some(t) = &self.weights else { + return Weights::DEFAULT; + }; + let denom = if comp == 0 { + t.luma_log2_weight_denom + } else { + t.chroma_log2_weight_denom + } as i32; + let pick = |list: &[WeightEntry], idx: i8| -> (i32, i32) { + let default = (1 << denom, 0); + if idx < 0 { + return default; + } + match list.get(idx as usize) { + None => default, + Some(e) if comp == 0 => e.luma.unwrap_or(default), + Some(e) => e.chroma.map(|c| c[comp - 1]).unwrap_or(default), + } + }; + let (w0, o0) = pick(&t.l0, r0); + let (w1, o1) = pick(&t.l1, r1); + Weights { + log_wd: denom, + w: [w0, w1], + o: [o0, o1], + } + } +} + +/// Neighbour-availability snapshot for one macroblock (left, top, top-right). #[derive(Clone, Copy)] struct MbNeighbors { a: bool, @@ -538,6 +876,19 @@ fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNei } } +/// The same, with the constrained intra prediction rule of 7.4.2.2 applied: +/// an inter-coded neighbour is not available as an intra prediction source. +fn intra_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, n: MbNeighbors) -> MbNeighbors { + let w = pic.mb_w; + let addr = mb_y * w + mb_x; + let intra = |a: usize| pic.mb_flags[a] & FLAG_INTER == 0; + MbNeighbors { + a: n.a && intra(addr - 1), + b: n.b && intra(addr - w), + c: n.c && intra(addr - w + 1), + } +} + /// Non-zero counts of the left and above neighbours of the luma 4x4 block at /// global block coords `(bx, by)`, `None` when that neighbour is unavailable /// (clause 6.4.11.4 plus the availability rules of 6.4.8). @@ -571,17 +922,30 @@ fn chroma_nz_pair( ) } -/// Decode one macroblock of an I slice (spec 7.3.5, 7.4.5) and reconstruct -/// it. `ctx.qp` carries the QPY prediction chain. +/// Motion data parsed for one macroblock, before prediction derivation. +#[derive(Clone, Copy)] +struct MbMotion { + /// Sub-macroblock types of a P_8x8 / B_8x8 macroblock. + sub: [SubShape; 4], + /// `ref_idx_lX[ mbPartIdx ]`, -1 when the partition does not use the list. + ref_idx: [[i8; 4]; 2], + /// `mvd_lX[ mbPartIdx ][ subMbPartIdx ]`, indexed by 4x4 raster position. + mvd: [[[i16; 2]; 16]; 2], +} + +/// Decode one macroblock (spec 7.3.5, 7.4.5) and reconstruct it. `ctx.qp` +/// carries the QPY prediction chain. // Block loops are indexed: `blk` is simultaneously a bitstream position, a // geometry key (BLK4_POS) and a grid coordinate; iterators obscure that. -#[allow(clippy::needless_range_loop)] +#[allow(clippy::needless_range_loop, clippy::too_many_arguments)] fn decode_macroblock( pic: &mut Picture, - ls: &[LevelScale4x4; 3], + refs: &[Picture], + ls: &[[LevelScale4x4; 3]; 2], r: &mut Entropy<'_>, ctx: &mut SliceCtx, mb_addr: usize, + skipped: bool, ) -> Result<()> { let mb_x = mb_addr % pic.mb_w; let mb_y = mb_addr / pic.mb_w; @@ -589,22 +953,80 @@ 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, - }); + if !skipped || !r.is_cabac() { + 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); let (cx0, cy0) = (mb_x * 2, mb_y * 2); - let mb_type = r.mb_type_i()?; + // Every 4x4 block of this macroblock starts from a known state: the arrays + // survive from the previous picture, and both the CABAC contexts and the + // neighbour derivations read them for blocks of the macroblock in progress. + for py in 0..4 { + let base = (by0 + py) * w4 + bx0; + for idx in base..base + 4 { + pic.mv[idx] = [[0; 2]; 2]; + pic.ref_idx[idx] = [-1; 2]; + pic.ref_id[idx] = [-1; 2]; + pic.mvd_abs[idx] = [0; 4]; + pic.blk[idx] = 0; + } + } + + let mb_type = if skipped { + u32::MAX + } else if ctx.slice_type == SliceType::P { + r.mb_type_p()? + } else if ctx.is_b() { + r.mb_type_b()? + } else { + r.mb_type_i()? + }; + + // Split the P/B numbering into an inter shape or an intra mb_type. + let (shape, intra_type) = if skipped { + let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] }; + (Some(s), None) + } else if ctx.slice_type == SliceType::P { + if mb_type < 5 { + (Some(P_SHAPES[mb_type as usize]), None) + } else { + (None, Some(mb_type - 5)) + } + } else if ctx.is_b() { + if mb_type < 23 { + (Some(B_SHAPES[mb_type as usize]), None) + } else { + (None, Some(mb_type - 23)) + } + } else { + (None, Some(mb_type)) + }; + r.set_intra(intra_type.is_some()); + + if let Some(shape) = shape { + return decode_inter_mb( + pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr, + ); + } + let mb_type = intra_type.expect("an intra macroblock type"); + write_intra_mb(pic, mb_x, mb_y); + let intra_nbr = if ctx.constrained_intra_pred { + intra_neighbors(pic, mb_x, mb_y, nbr) + } else { + nbr + }; if mb_type == 25 { // I_PCM (7.3.5, 8.3.5): raw samples, byte aligned. @@ -672,8 +1094,8 @@ fn decode_macroblock( let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); // Predicted mode = min of neighbours, DC when either unavailable // (8.3.1.1; non-I4x4 neighbours were written as 2). - let left_avail = if bx % 4 == 0 { nbr.a } else { true }; - let top_avail = if by % 4 == 0 { nbr.b } else { true }; + let left_avail = if bx % 4 == 0 { intra_nbr.a } else { true }; + let top_avail = if by % 4 == 0 { intra_nbr.b } else { true }; let pred = if left_avail && top_avail { let ma = pic.i4_modes[by * w4 + bx - 1]; let mb = pic.i4_modes[(by - 1) * w4 + bx]; @@ -704,17 +1126,77 @@ fn decode_macroblock( r.coded_block_pattern_intra()? }; + finish_macroblock( + pic, + &ls[0], + r, + ctx, + mb_addr, + &intra_nbr, + MbFinish { + is_i16, + i16_mode, + cbp_luma, + cbp_chroma, + modes, + chroma_mode, + intra: true, + flags: if is_i16 { FLAG_I16 } else { 0 }, + }, + ) +} + +/// Everything the shared residual path needs after prediction is decided. +struct MbFinish { + is_i16: bool, + i16_mode: u8, + cbp_luma: u8, + cbp_chroma: u8, + modes: [u8; 16], + chroma_mode: u8, + intra: bool, + flags: u8, +} + +/// The residual half of a macroblock (7.3.5.3 + 8.5), shared by the intra and +/// inter paths. +/// +/// Bitstream order (luma blocks in Z-order, then chroma DC, then chroma AC) +/// equals reconstruction dependency order, so each block reconstructs the +/// moment its levels are parsed: no per-macroblock coefficient arrays, and +/// empty blocks cost one coeff_token read plus a prediction write. For an inter +/// macroblock the prediction is already in the plane, so the intra branches +/// below are simply skipped. +#[allow(clippy::needless_range_loop, clippy::too_many_arguments)] +fn finish_macroblock( + pic: &mut Picture, + ls: &[LevelScale4x4; 3], + r: &mut Entropy<'_>, + ctx: &mut SliceCtx, + mb_addr: usize, + nbr: &MbNeighbors, + m: MbFinish, +) -> Result<()> { + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + let w4 = pic.mb_w * 4; + let w2 = pic.mb_w * 2; + let (bx0, by0) = (mb_x * 4, mb_y * 4); + let (cx0, cy0) = (mb_x * 2, mb_y * 2); + let (cbp_luma, cbp_chroma) = (m.cbp_luma, m.cbp_chroma); + // mb_qp_delta (7.4.5). let mut qp_delta = 0; - if cbp_luma != 0 || cbp_chroma != 0 || is_i16 { + if cbp_luma != 0 || cbp_chroma != 0 || m.is_i16 { 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 - | if is_i16 { FLAG_I16 } else { 0 } - | if chroma_mode != 0 { + | m.flags + | if !m.intra { FLAG_INTER } else { 0 } + | if m.intra && m.chroma_mode != 0 { FLAG_CHROMA_PRED } else { 0 @@ -726,25 +1208,19 @@ fn decode_macroblock( let qp_cb = i32::from(CHROMA_QP[(qp_y + ctx.cb_qp_offset).clamp(0, 51) as usize]); let qp_cr = i32::from(CHROMA_QP[(qp_y + ctx.cr_qp_offset).clamp(0, 51) as usize]); - // ---- residual parse fused with reconstruction (7.3.5.3 + 8.5) ---- - // - // Bitstream order (luma blocks in Z-order, then chroma DC, then chroma - // 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]; - if is_i16 { + if m.is_i16 { let mut w = PlaneWindow { data: &mut pic.y.data, stride: pic.y.stride, origin: pic.y.origin + (mb_y * 16) * pic.y.stride + mb_x * 16, }; - pred_16x16(i16_mode, &mut w, nbr.b, nbr.a); + pred_16x16(m.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); + let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0); let dc_tc = r.residual_block(&mut scan, BlockCat::LumaDc, na, nb)?; dc_cbf |= u8::from(dc_tc != 0); unzigzag(&scan, &mut raster); @@ -754,7 +1230,7 @@ fn decode_macroblock( let (dx, dy) = BLK4_POS[blk]; let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); let tc = if cbp_luma != 0 { - let (na, nb) = luma_nz_pair(pic, &nbr, bx, by); + let (na, nb) = luma_nz_pair(pic, nbr, bx, by); r.residual_block(&mut scan, BlockCat::LumaAc, na, nb)? } else { 0 @@ -782,50 +1258,61 @@ fn decode_macroblock( let (dx, dy) = BLK4_POS[blk]; let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); let tc = if cbp_luma & (1 << (blk >> 2)) != 0 { - let (na, nb) = luma_nz_pair(pic, &nbr, bx, by); + let (na, nb) = luma_nz_pair(pic, nbr, bx, by); r.residual_block(&mut scan, BlockCat::Luma4x4, na, nb)? } else { 0 }; pic.nz_y[by * w4 + bx] = tc; let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); - let n = gather_nbr4(pic, &nbr, blk, x, y); - let mut p = [0u8; 16]; - pred_4x4(modes[blk], &n, &mut p); let origin = pic.y.at(x, y); let stride = pic.y.stride; - if tc == 0 { - // Pure prediction: copy the 16 samples in. + if m.intra { + let n = gather_nbr4(pic, nbr, blk, x, y); + let mut p = [0u8; 16]; + pred_4x4(m.modes[blk], &n, &mut p); + if tc == 0 { + // Pure prediction: copy the 16 samples in. + for ry in 0..4 { + let row = origin + ry * stride; + pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); + } + continue; + } + unzigzag(&scan, &mut raster); + dequant_4x4(&mut raster, &ls[0], qp_y, false); + inverse_transform_4x4(&raster, &mut resid); for ry in 0..4 { let row = origin + ry * stride; - pic.y.data[row..row + 4].copy_from_slice(&p[ry * 4..ry * 4 + 4]); + for rx in 0..4 { + let v = i32::from(p[ry * 4 + rx]) + resid[ry * 4 + rx]; + pic.y.data[row + rx] = v.clamp(0, 255) as u8; + } } - continue; - } - unzigzag(&scan, &mut raster); - dequant_4x4(&mut raster, &ls[0], qp_y, false); - inverse_transform_4x4(&raster, &mut resid); - for ry in 0..4 { - let row = origin + ry * stride; - for rx in 0..4 { - let v = i32::from(p[ry * 4 + rx]) + resid[ry * 4 + rx]; - pic.y.data[row + rx] = v.clamp(0, 255) as u8; + } else { + if tc == 0 { + continue; // motion-compensated prediction already in place } + unzigzag(&scan, &mut raster); + dequant_4x4(&mut raster, &ls[0], qp_y, false); + inverse_transform_4x4(&raster, &mut resid); + add_residual_4x4(&mut pic.y.data, stride, origin, &resid); } } } - // Chroma: predict both components, then DC (Cb, Cr), then AC in - // bitstream order (all Cb blocks, all Cr blocks), reconstructing as - // levels arrive. - for comp in 0..2 { - let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; - let mut w = PlaneWindow { - data: &mut plane.data, - stride: plane.stride, - origin: plane.origin + (mb_y * 8) * plane.stride + mb_x * 8, - }; - pred_chroma_8x8(chroma_mode, &mut w, nbr.b, nbr.a); + // Chroma: predict both components (intra only), then DC (Cb, Cr), then AC + // in bitstream order, reconstructing as levels arrive. + if m.intra { + for comp in 0..2 { + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let mut w = PlaneWindow { + data: &mut plane.data, + stride: plane.stride, + origin: plane.origin + (mb_y * 8) * plane.stride + mb_x * 8, + }; + pred_chroma_8x8(m.chroma_mode, &mut w, nbr.b, nbr.a); + } } let mut chroma_dc = [[0i32; 4]; 2]; if cbp_chroma != 0 { @@ -845,7 +1332,7 @@ fn decode_macroblock( for blk in 0..4 { let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); let tc = if cbp_chroma == 2 { - let (na, nb) = chroma_nz_pair(pic, &nbr, comp, cx, cy); + let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy); r.residual_block(&mut scan, BlockCat::ChromaAc, na, nb)? } else { 0 @@ -879,6 +1366,620 @@ fn decode_macroblock( Ok(()) } +/// Decode an inter macroblock: sub-macroblock types, reference indices and +/// motion vector differences (7.3.5.1, 7.3.5.2), then motion compensation +/// (8.4.2) and the shared residual path. +#[allow(clippy::too_many_arguments)] +fn decode_inter_mb( + pic: &mut Picture, + refs: &[Picture], + ls: &[[LevelScale4x4; 3]; 2], + r: &mut Entropy<'_>, + ctx: &mut SliceCtx, + mb_addr: usize, + shape: MbShape, + skipped: bool, + mb_type: u32, + nbr: MbNeighbors, +) -> Result<()> { + let mb_x = mb_addr % pic.mb_w; + let mb_y = mb_addr / pic.mb_w; + let b = ctx.is_b(); + let mut mvc = MvCtx { + mb_x, + mb_y, + slice_id: ctx.slice_id, + written: 0, + }; + let mut motion = MbMotion { + sub: [P_SUB[0]; 4], + ref_idx: [[-1; 4]; 2], + mvd: [[[0; 2]; 16]; 2], + }; + // A direct or skipped block contributes nothing to the ref_idx and mvd + // contexts of its neighbours (9.3.3.1.1.6, 9.3.3.1.1.7), so the flag has to + // be in place before any of this macroblock's syntax is parsed. + let direct_mb = skipped || (b && mb_type == 0); + if direct_mb { + let f = BLK_DIRECT | if skipped { BLK_SKIP } else { 0 }; + for py in 0..4 { + let base = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4; + for idx in base..base + 4 { + pic.blk[idx] = f; + } + } + } + + if shape.sub && !skipped { + for part in 0..4 { + let t = r.sub_mb_type(b)? as usize; + motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] }; + if motion.sub[part].pred == Pred::Direct { + for k in 0..4 { + let (px, py) = (part % 2 * 2 + k % 2, part / 2 * 2 + k / 2); + let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px; + pic.blk[idx] = BLK_DIRECT; + } + } + } + } + + // ---- ref_idx_lX (7.3.5.1, 7.3.5.2) ---- + // P_8x8ref0 infers reference index 0 for every partition. + let infer_ref0 = ctx.slice_type == SliceType::P && mb_type == 4; + if !skipped { + for list in 0..2 { + for part in 0..shape.parts { + let uses = if shape.sub { + motion.sub[part].pred.uses(list) + } else { + shape.pred[part.min(1)].uses(list) + }; + if !uses { + continue; + } + let idx = if infer_ref0 || ctx.num_ref_idx[list] <= 1 { + 0 + } else { + let (px, py) = part_origin(&shape, part, (0, 0)); + let bx = (mb_x * 4 + px) as i32; + let by = (mb_y * 4 + py) as i32; + let inc = ref_idx_cond(pic, &mvc, bx - 1, by, list) + + 2 * ref_idx_cond(pic, &mvc, bx, by - 1, list); + r.ref_idx(ctx.num_ref_idx[list] as u32 - 1, inc)? as i8 + }; + motion.ref_idx[list][part] = idx; + // Publish it so the next partition's context can see it. + let (px, py) = part_origin(&shape, part, (0, 0)); + let (pw, ph) = part_size(&shape, &motion, part); + for dy in 0..ph { + for dx in 0..pw { + let bi = (mb_y * 4 + py + dy) * pic.mb_w * 4 + mb_x * 4 + px + dx; + pic.ref_idx[bi][list] = idx; + mvc.written |= 1 << ((py + dy) * 4 + px + dx); + } + } + } + } + if infer_ref0 { + for part in 0..4 { + motion.ref_idx[0][part] = 0; + } + } + + // ---- mvd_lX ---- + mvc.written = 0; + for list in 0..2 { + for part in 0..shape.parts { + let uses = if shape.sub { + motion.sub[part].pred.uses(list) + } else { + shape.pred[part.min(1)].uses(list) + }; + if !uses { + continue; + } + let subparts = if shape.sub { motion.sub[part].parts } else { 1 }; + for sp in 0..subparts { + let (px, py) = part_origin(&shape, part, sp_offset(&shape, &motion, part, sp)); + let (pw, ph) = part_size(&shape, &motion, part); + let bx = (mb_x * 4 + px) as i32; + let by = (mb_y * 4 + py) as i32; + let mut mvd = [0i16; 2]; + for comp in 0..2 { + let a = neighbour_mvd(pic, &mvc, bx - 1, by, list)[comp]; + let bb = neighbour_mvd(pic, &mvc, bx, by - 1, list)[comp]; + let sum = a + bb; + let inc = if sum > 32 { + 2 + } else if sum > 2 { + 1 + } else { + 0 + }; + let v = r.mvd(comp, inc)?; + mvd[comp] = i16::try_from(v) + .map_err(|_| Error::corrupt("mvd outside the level limits"))?; + } + for dy in 0..ph { + for dx in 0..pw { + motion.mvd[list][(py + dy) * 4 + px + dx] = mvd; + write_mvd(pic, mb_x, mb_y, px + dx, py + dy, list, mvd); + mvc.written |= 1 << ((py + dy) * 4 + px + dx); + } + } + } + } + } + } + + // ---- motion vector derivation and compensation (8.4.1, 8.4.2) ---- + mvc.written = 0; + if direct_mb && !b { + predict_p_skip(pic, refs, ctx, &mut mvc)?; + } else if direct_mb { + predict_direct(pic, refs, ctx, &mut mvc, true)?; + } else { + for part in 0..shape.parts { + if shape.sub && motion.sub[part].pred == Pred::Direct { + predict_direct_8x8(pic, refs, ctx, &mut mvc, part)?; + continue; + } + let subparts = if shape.sub { motion.sub[part].parts } else { 1 }; + let pred = if shape.sub { + motion.sub[part].pred + } else { + shape.pred[part.min(1)] + }; + for sp in 0..subparts { + let (px, py) = part_origin(&shape, part, sp_offset(&shape, &motion, part, sp)); + let (pw, ph) = part_size(&shape, &motion, part); + let mut mv = [[0i16; 2]; 2]; + let mut ref_idx = [-1i8; 2]; + let mut ref_id = [-1i32; 2]; + for list in 0..2 { + if !pred.uses(list) { + continue; + } + let idx = motion.ref_idx[list][part]; + // predPartWidth of 6.4.11.7: the macroblock partition width + // for a whole-macroblock partition, the sub-macroblock + // partition width inside an 8x8. + let n = mvc.neighbours(pic, px, py, pw, list); + let mvp = predict_mv(&n, idx, shape.w, shape.h, part); + let d = motion.mvd[list][py * 4 + px]; + mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])]; + ref_idx[list] = idx; + ref_id[list] = ctx + .reference(refs, list, idx) + .map(|p| p.id) + .unwrap_or(-1); + } + for dy in 0..ph { + for dx in 0..pw { + write_block(pic, &mut mvc, px + dx, py + dy, mv, ref_idx, ref_id, 0); + } + } + compensate(pic, refs, ctx, mb_x, mb_y, px, py, pw, ph, mv, ref_idx)?; + } + } + } + + if skipped { + // 7.4.5: a skipped macroblock has no residual and does not change QPY. + let w4 = pic.mb_w * 4; + let w2 = pic.mb_w * 2; + for dy in 0..4 { + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; + pic.nz_y[base..base + 4].fill(0); + pic.i4_modes[base..base + 4].fill(2); + } + for comp in 0..2 { + for dy in 0..2 { + let base = (mb_y * 2 + dy) * w2 + mb_x * 2; + pic.nz_c[comp][base..base + 2].fill(0); + } + } + pic.mb_qp[mb_addr] = ctx.qp as u8; + pic.mb_flags[mb_addr] = + FLAG_DECODED | FLAG_INTER | FLAG_SKIP | if b { FLAG_DIRECT } else { 0 }; + pic.mb_cbp[mb_addr] = 0; + pic.mb_dc_cbf[mb_addr] = 0; + pic.mb_slice[mb_addr] = ctx.slice_id; + pic.decoded_mbs += 1; + ctx.qp_delta_inc = 0; + return Ok(()); + } + + let w4 = pic.mb_w * 4; + for dy in 0..4 { + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; + pic.i4_modes[base..base + 4].fill(2); + } + let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?; + // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual. + finish_macroblock( + pic, + &ls[1], + r, + ctx, + mb_addr, + &nbr, + MbFinish { + is_i16: false, + i16_mode: 0, + cbp_luma, + cbp_chroma, + modes: [2; 16], + chroma_mode: 0, + intra: false, + flags: if b && mb_type == 0 { FLAG_DIRECT } else { 0 }, + }, + ) +} + +/// Top-left 4x4 block of macroblock partition `part`, offset by `sp` blocks in +/// raster order within the 8x8. +fn part_origin(shape: &MbShape, part: usize, sp: (usize, usize)) -> (usize, usize) { + let (px, py) = if shape.sub { + (part % 2 * 2, part / 2 * 2) + } else if shape.parts == 1 { + (0, 0) + } else if shape.w == 4 { + (0, part * 2) // 16x8 + } else { + (part * 2, 0) // 8x16 + }; + (px + sp.0, py + sp.1) +} + +/// Block offset of sub-macroblock partition `sp` inside its 8x8. +fn sp_offset(shape: &MbShape, m: &MbMotion, part: usize, sp: usize) -> (usize, usize) { + if !shape.sub { + return (0, 0); + } + let s = m.sub[part]; + match (s.w, s.h) { + (2, 2) => (0, 0), + (2, 1) => (0, sp), + (1, 2) => (sp, 0), + _ => (sp % 2, sp / 2), + } +} + +/// Size of one (sub-)macroblock partition in 4x4 blocks. +fn part_size(shape: &MbShape, m: &MbMotion, part: usize) -> (usize, usize) { + if shape.sub { + let s = m.sub[part]; + (s.w, s.h) + } else { + (shape.w, shape.h) + } +} + +/// P_Skip (clause 8.4.1.1). +fn predict_p_skip( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &mut MvCtx, +) -> Result<()> { + let n = mvc.neighbours(pic, 0, 0, 4, 0); + let zero = !n[0].avail + || !n[1].avail + || (n[0].ref_idx == 0 && n[0].mv == [0, 0]) + || (n[1].ref_idx == 0 && n[1].mv == [0, 0]); + let mv = if zero { + [0i16; 2] + } else { + predict_mv(&n, 0, 4, 4, 0) + }; + let ref_id = ctx.reference(refs, 0, 0).map(|p| p.id).unwrap_or(-1); + for py in 0..4 { + for px in 0..4 { + write_block( + pic, + mvc, + px, + py, + [mv, [0; 2]], + [0, -1], + [ref_id, -1], + BLK_SKIP | BLK_DIRECT, + ); + } + } + compensate( + pic, + refs, + ctx, + mvc.mb_x, + mvc.mb_y, + 0, + 0, + 4, + 4, + [mv, [0; 2]], + [0, -1], + ) +} + +/// B_Skip / B_Direct_16x16 (clause 8.4.1.2) over the whole macroblock. +fn predict_direct( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &mut MvCtx, + skip: bool, +) -> Result<()> { + for quad in 0..4 { + direct_quadrant(pic, refs, ctx, mvc, quad, skip)?; + } + Ok(()) +} + +/// B_Direct_8x8 for one 8x8 sub-macroblock. +fn predict_direct_8x8( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &mut MvCtx, + part: usize, +) -> Result<()> { + direct_quadrant(pic, refs, ctx, mvc, part, false) +} + +/// One 8x8 quadrant of a direct-mode macroblock. With +/// `direct_8x8_inference_flag` the whole quadrant shares the motion of its +/// outer corner 4x4 block; without it each 4x4 block is derived on its own. +fn direct_quadrant( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &mut MvCtx, + quad: usize, + skip: bool, +) -> Result<()> { + let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); + let (qx, qy) = (quad % 2 * 2, quad / 2 * 2); + let flags = BLK_DIRECT | if skip { BLK_SKIP } else { 0 }; + if ctx.direct_8x8_inference { + // 8.4.1.2.1: luma4x4BlkIdx = 5 * mbPartIdx, i.e. the quadrant's own + // outer corner of the macroblock. + let corner = (quad % 2 * 3, quad / 2 * 3); + let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, corner)?; + for dy in 0..2 { + for dx in 0..2 { + write_block(pic, mvc, qx + dx, qy + dy, mv, ref_idx, ref_id, flags); + } + } + compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx) + } else { + for dy in 0..2 { + for dx in 0..2 { + let (px, py) = (qx + dx, qy + dy); + let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, (px, py))?; + write_block(pic, mvc, px, py, mv, ref_idx, ref_id, flags); + compensate(pic, refs, ctx, mb_x, mb_y, px, py, 1, 1, mv, ref_idx)?; + } + } + Ok(()) + } +} + +/// Motion of one direct-mode 4x4 block: spatial (8.4.1.2.2) or temporal +/// (8.4.1.2.3). +fn direct_block( + pic: &Picture, + refs: &[Picture], + ctx: &SliceCtx, + mvc: &MvCtx, + at: (usize, usize), +) -> Result<([[i16; 2]; 2], [i8; 2], [i32; 2])> { + // The co-located block, in both modes. + let col = ctx.lists[1].get(0).and_then(|i| refs.get(i)); + let (col_ref_id, col_mv, col_list) = match col { + Some(c) => { + let bx = mvc.mb_x * 4 + at.0; + let by = mvc.mb_y * 4 + at.1; + let idx = by * c.mb_w.max(1) * 4 + bx; + if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 { + let list = usize::from(c.ref_id[idx][0] < 0); + (c.ref_id[idx][list], c.mv[idx][list], list) + } else { + (-1, [0i16; 2], 0) + } + } + None => (-1, [0i16; 2], 0), + }; + let _ = col_list; + + if ctx.direct_spatial { + // Reference indices from the macroblock's own neighbours, once. + let mut ref_idx = [-1i8; 2]; + let mut mvp = [[0i16; 2]; 2]; + for list in 0..2 { + let n = mvc.neighbours(pic, 0, 0, 4, list); + ref_idx[list] = min_positive(n[0].ref_idx, min_positive(n[1].ref_idx, n[2].ref_idx)); + mvp[list] = predict_mv(&n, ref_idx[list], 4, 4, 0); + } + let zero_prediction = ref_idx[0] < 0 && ref_idx[1] < 0; + if zero_prediction { + ref_idx = [0, 0]; + } + // colZeroFlag: the co-located block sits still on a short-term picture. + let col_short = col.is_some_and(|c| c.mark == Mark::Short); + let col_zero = col_short + && col_ref_id >= 0 + && col.is_some_and(|c| { + let bx = mvc.mb_x * 4 + at.0; + let by = mvc.mb_y * 4 + at.1; + let idx = by * c.mb_w.max(1) * 4 + bx; + idx < c.ref_idx.len() && (c.ref_idx[idx][0] == 0 || c.ref_idx[idx][1] == 0) + }) + && (-1..=1).contains(&col_mv[0]) + && (-1..=1).contains(&col_mv[1]); + let mut mv = [[0i16; 2]; 2]; + let mut ref_id = [-1i32; 2]; + for list in 0..2 { + if ref_idx[list] < 0 { + continue; + } + ref_id[list] = ctx + .reference(refs, list, ref_idx[list]) + .map(|p| p.id) + .unwrap_or(-1); + if zero_prediction || (ref_idx[list] == 0 && col_zero) { + mv[list] = [0; 2]; + } else { + mv[list] = mvp[list]; + } + } + return Ok((mv, ref_idx, ref_id)); + } + + // Temporal direct (8.4.1.2.3). + let ref_idx0 = if col_ref_id < 0 { + 0 + } else { + map_col_to_list0(ctx, refs, col_ref_id) + }; + let pic0 = ctx.reference(refs, 0, ref_idx0); + let pic1 = ctx.reference(refs, 1, 0); + let ref_id = [ + pic0.map(|p| p.id).unwrap_or(-1), + pic1.map(|p| p.id).unwrap_or(-1), + ]; + let (Some(p0), Some(p1)) = (pic0, pic1) else { + return Ok(([[0; 2]; 2], [ref_idx0, 0], ref_id)); + }; + let td = (p1.poc - p0.poc).clamp(-128, 127); + if p0.mark == Mark::Long || td == 0 { + return Ok(([col_mv, [0; 2]], [ref_idx0, 0], ref_id)); + } + let tb = (ctx.poc - p0.poc).clamp(-128, 127); + let tx = (16384 + (td / 2).abs()) / td; + let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023); + let mv0 = [ + ((dist * i32::from(col_mv[0]) + 128) >> 8) as i16, + ((dist * i32::from(col_mv[1]) + 128) >> 8) as i16, + ]; + let mv1 = [mv0[0] - col_mv[0], mv0[1] - col_mv[1]]; + Ok(([mv0, mv1], [ref_idx0, 0], ref_id)) +} + +/// `MapColToList0` (8.4.1.2.3): the lowest RefPicList0 index that names the +/// picture the co-located block referenced. +fn map_col_to_list0(ctx: &SliceCtx, refs: &[Picture], col_ref_id: i32) -> i8 { + for i in 0..ctx.lists[0].len() { + if ctx + .lists[0] + .get(i) + .and_then(|k| refs.get(k)) + .is_some_and(|p| p.id == col_ref_id) + { + return i as i8; + } + } + 0 +} + +/// Motion compensation of one partition (clause 8.4.2): interpolate each list's +/// prediction, then combine them by the weighting of 8.4.2.3 and write the +/// result straight into the picture, where the residual is added on top. +/// +/// `(px, py)` and `(pw, ph)` are in 4x4 blocks within the macroblock. +#[allow(clippy::too_many_arguments)] +fn compensate( + pic: &mut Picture, + refs: &[Picture], + ctx: &SliceCtx, + mb_x: usize, + mb_y: usize, + px: usize, + py: usize, + pw: usize, + ph: usize, + mv: [[i16; 2]; 2], + ref_idx: [i8; 2], +) -> Result<()> { + let use0 = ref_idx[0] >= 0; + let use1 = ref_idx[1] >= 0; + if !use0 && !use1 { + return Ok(()); + } + let x0 = (mb_x * 16 + px * 4) as i32; + let y0 = (mb_y * 16 + py * 4) as i32; + let (w, h) = (pw * 4, ph * 4); + + let mut part = [[0u8; 256]; 2]; + for list in 0..2 { + if ref_idx[list] < 0 { + continue; + } + let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| { + Error::corrupt("reference index names a picture the buffer does not hold") + })?; + let plane = RefPlane { + data: &rp.y.data, + stride: rp.y.stride, + origin: rp.y.origin, + width: rp.y.width, + height: rp.y.height, + pad: rp.y.pad, + }; + mc_luma(&plane, x0, y0, mv[list], w, h, &mut part[list]); + } + let wt = ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1); + let mut out = [0u8; 256]; + let (p0, p1) = part.split_at(1); + combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h); + let stride = pic.y.stride; + let origin = pic.y.at(x0 as usize, y0 as usize); + for row in 0..h { + let dst = origin + row * stride; + pic.y.data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]); + } + + // Chroma (8.4.1.4): for 4:2:0 frame coding the chroma vector is the luma + // vector, read as eighth-sample units over the half-resolution plane. + let (cw, ch) = (w / 2, h / 2); + let (cx0, cy0) = (x0 / 2, y0 / 2); + for comp in 0..2 { + let mut cpart = [[0u8; 64]; 2]; + for list in 0..2 { + if ref_idx[list] < 0 { + continue; + } + let rp = ctx + .reference(refs, list, ref_idx[list]) + .expect("checked above"); + let src = if comp == 0 { &rp.cb } else { &rp.cr }; + let plane = RefPlane { + data: &src.data, + stride: src.stride, + origin: src.origin, + width: src.width, + height: src.height, + pad: src.pad, + }; + mc_chroma(&plane, cx0, cy0, mv[list], cw, ch, &mut cpart[list]); + } + let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1); + let mut cout = [0u8; 64]; + let (c0, c1) = cpart.split_at(1); + combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch); + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; + let stride = plane.stride; + let origin = plane.at(cx0 as usize, cy0 as usize); + for row in 0..ch { + let dst = origin + row * stride; + plane.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]); + } + } + Ok(()) +} + /// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2), /// including the top-right substitution rule. fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) -> Nbr4 { @@ -944,6 +2045,20 @@ fn deblock_picture(pic: &mut Picture) { }; let qp_q = qp_of(addr); + // Boundary strengths, per 4-sample segment of each edge (8.7.2.1). + let mut bs_v = [[0u8; 4]; 4]; + let mut bs_h = [[0u8; 4]; 4]; + for e in 0..4 { + for k in 0..4 { + if e > 0 || filter_left { + bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true); + } + if e > 0 || filter_top { + bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false); + } + } + } + // ---- luma ---- { let stride = pic.y.stride; @@ -953,21 +2068,29 @@ fn deblock_picture(pic: &mut Picture) { if e == 0 && !filter_left { continue; } - let (bs, qp_p) = if e == 0 { - (4, qp_of(addr - 1)) - } else { - (3, qp_q) - }; - let params = - edge_params((qp_p + qp_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); - if params.alpha == 0 || params.beta == 0 { - continue; - } + let qp_p = if e == 0 { qp_of(addr - 1) } else { qp_q }; + let qp_avg = (qp_p + qp_q + 1) >> 1; // Vertical edges stay scalar: a gather/scatter SIMD // variant measured slower than this loop (strided // per-lane loads dominate). - for k in 0..16 { - filter_luma_line(&mut pic.y.data, base + k * stride + e * 4, 1, ¶ms); + for j in 0..4 { + let bs = bs_v[e][j]; + if bs == 0 { + continue; + } + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs); + if params.alpha == 0 || params.beta == 0 { + continue; + } + for k in 0..4 { + let row = j * 4 + k; + filter_luma_line( + &mut pic.y.data, + base + row * stride + e * 4, + 1, + ¶ms, + ); + } } } // Horizontal edges, top to bottom. @@ -975,17 +2098,40 @@ fn deblock_picture(pic: &mut Picture) { if e == 0 && !filter_top { continue; } - let (bs, qp_p) = if e == 0 { - (4, qp_of(addr - mb_w)) - } else { - (3, qp_q) - }; - let params = - edge_params((qp_p + qp_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); - if params.alpha == 0 || params.beta == 0 { + let qp_p = if e == 0 { qp_of(addr - mb_w) } else { qp_q }; + let qp_avg = (qp_p + qp_q + 1) >> 1; + let bs = bs_h[e]; + let uniform = bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3]; + if uniform { + if bs[0] == 0 { + continue; + } + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0]); + if params.alpha == 0 || params.beta == 0 { + continue; + } + // Eight rows around the edge are contiguous, so the + // whole 16-sample edge filters in one pass. + filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, ¶ms); continue; } - filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, ¶ms); + for j in 0..4 { + if bs[j] == 0 { + continue; + } + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[j]); + if params.alpha == 0 || params.beta == 0 { + continue; + } + for k in 0..4 { + filter_luma_line( + &mut pic.y.data, + base + e * 4 * stride + j * 4 + k, + stride, + ¶ms, + ); + } + } } } @@ -1009,21 +2155,24 @@ fn deblock_picture(pic: &mut Picture) { } }; let cq_q = cqp(addr); + // A chroma edge inherits the boundary strength of the luma edge + // it sits on: chroma sample k maps to luma sample 2k, so a + // chroma 4-sample run spans two luma 4x4 block rows. for e in 0..2 { if e == 0 && !filter_left { continue; } - let (bs, cq_p) = if e == 0 { - (4, cqp(addr - 1)) - } else { - (3, cq_q) - }; - let params = - edge_params((cq_p + cq_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); - if params.alpha == 0 || params.beta == 0 { - continue; - } + let cq_p = if e == 0 { cqp(addr - 1) } else { cq_q }; + let qp_avg = (cq_p + cq_q + 1) >> 1; for k in 0..8 { + let bs = bs_v[e * 2][k / 2]; + if bs == 0 { + continue; + } + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs); + if params.alpha == 0 || params.beta == 0 { + continue; + } filter_chroma_line(&mut plane.data, base + k * stride + e * 4, 1, ¶ms); } } @@ -1031,17 +2180,17 @@ fn deblock_picture(pic: &mut Picture) { if e == 0 && !filter_top { continue; } - let (bs, cq_p) = if e == 0 { - (4, cqp(addr - mb_w)) - } else { - (3, cq_q) - }; - let params = - edge_params((cq_p + cq_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); - if params.alpha == 0 || params.beta == 0 { - continue; - } + let cq_p = if e == 0 { cqp(addr - mb_w) } else { cq_q }; + let qp_avg = (cq_p + cq_q + 1) >> 1; for k in 0..8 { + let bs = bs_h[e * 2][k / 2]; + if bs == 0 { + continue; + } + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs); + if params.alpha == 0 || params.beta == 0 { + continue; + } filter_chroma_line( &mut plane.data, base + e * 4 * stride + k, @@ -1054,3 +2203,79 @@ fn deblock_picture(pic: &mut Picture) { } } } + +/// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1). +/// +/// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the +/// macroblock, `seg` the 4-sample run along it. Edge 0 is the macroblock edge. +fn boundary_strength( + pic: &Picture, + mb_x: usize, + mb_y: usize, + edge: usize, + seg: usize, + vertical: bool, +) -> u8 { + let w4 = pic.mb_w * 4; + let (qbx, qby) = if vertical { + (mb_x * 4 + edge, mb_y * 4 + seg) + } else { + (mb_x * 4 + seg, mb_y * 4 + edge) + }; + let (pbx, pby) = if vertical { + (qbx - 1, qby) + } else { + (qbx, qby - 1) + }; + let q = qby * w4 + qbx; + let p = pby * w4 + pbx; + let mb_edge = edge == 0; + let q_mb = (qby / 4) * pic.mb_w + qbx / 4; + let p_mb = (pby / 4) * pic.mb_w + pbx / 4; + let intra = pic.mb_flags[q_mb] & FLAG_INTER == 0 || pic.mb_flags[p_mb] & FLAG_INTER == 0; + if intra { + return if mb_edge { 4 } else { 3 }; + } + if pic.nz_y[p] != 0 || pic.nz_y[q] != 0 { + return 2; + } + let (pr, qr) = (pic.ref_id[p], pic.ref_id[q]); + let pn = u8::from(pr[0] >= 0) + u8::from(pr[1] >= 0); + let qn = u8::from(qr[0] >= 0) + u8::from(qr[1] >= 0); + if pn != qn { + return 1; + } + let (pm, qm) = (pic.mv[p], pic.mv[q]); + let differs = |a: [i16; 2], b: [i16; 2]| { + (i32::from(a[0]) - i32::from(b[0])).abs() >= 4 + || (i32::from(a[1]) - i32::from(b[1])).abs() >= 4 + }; + if pn == 1 { + let pl = usize::from(pr[0] < 0); + let ql = usize::from(qr[0] < 0); + if pr[pl] != qr[ql] { + return 1; + } + return u8::from(differs(pm[pl], qm[ql])); + } + if pn == 0 { + return 0; + } + // Two motion vectors each: compare the two partitions by which pictures + // they reference, not by list position (NOTE 1 of 8.7.2.1). + let same_set = (pr[0] == qr[0] && pr[1] == qr[1]) || (pr[0] == qr[1] && pr[1] == qr[0]); + if !same_set { + return 1; + } + if pr[0] != pr[1] { + return if pr[0] == qr[0] { + u8::from(differs(pm[0], qm[0]) || differs(pm[1], qm[1])) + } else { + u8::from(differs(pm[0], qm[1]) || differs(pm[1], qm[0])) + }; + } + // Both lists name the same picture: either pairing agreeing is enough. + let straight = !differs(pm[0], qm[0]) && !differs(pm[1], qm[1]); + let crossed = !differs(pm[0], qm[1]) && !differs(pm[1], qm[0]); + u8::from(!(straight || crossed)) +} diff --git a/crates/ec-h264/src/dpb.rs b/crates/ec-h264/src/dpb.rs new file mode 100644 index 00000000..3a16d62d --- /dev/null +++ b/crates/ec-h264/src/dpb.rs @@ -0,0 +1,1277 @@ +//! Decoded picture buffer (spec clause 8.2): picture storage, picture order +//! count, reference marking, reference list construction and output order. +//! +//! The buffer owns every decoded picture, including the one being decoded — the +//! decoder holds that one *out* of the pool while a picture is open, which is +//! what lets motion compensation borrow reference planes immutably while +//! writing the current planes mutably. +//! +//! Pictures are pooled, never freed: a picture that is neither referenced nor +//! awaiting output goes back on the free list with its plane and motion +//! allocations intact, so a steady-state decode loop reuses the same buffers +//! forever and allocates nothing. +//! +//! Output order is display order. Every picture leaves through the bumping +//! process of clause C.4.5.3 — smallest picture order count first, released +//! when the buffer is over its reordering or storage limit — so a stream with +//! B pictures comes out in the order a player has to present it, not the order +//! it was coded in. + +use ec_core::error::{Error, Result}; +use ec_h264_syntax::{DecRefPicMarking, RefPicListMod, SliceType, Sps}; + +/// Luma plane padding on every side, sized for inter-prediction filter +/// overreach: a 16-wide partition plus the two/three sample reach of the 6-tap +/// filter, rounded up. +pub(crate) const PAD_Y: usize = 32; +/// Chroma plane padding on every side (8-wide block plus one bilinear tap). +pub(crate) const PAD_C: usize = 16; +/// `mb_slice` value for a not-yet-decoded macroblock. +pub(crate) const NO_SLICE: u16 = u16::MAX; +/// Hard cap on stored pictures: 16 reference frames (Annex A) plus the current. +const MAX_STORED: usize = 17; + +/// Per-4x4-block flags recorded for inter neighbour derivation. +/// The block belongs to an intra macroblock. +pub(crate) const BLK_INTRA: u8 = 1; +/// The block belongs to a P_Skip or B_Skip macroblock. +pub(crate) const BLK_SKIP: u8 = 2; +/// The block is predicted in direct mode (B_Skip, B_Direct_16x16 or a +/// B_Direct_8x8 sub-macroblock). +pub(crate) const BLK_DIRECT: u8 = 4; + +/// Reference marking of a stored picture (clause 8.2.5). +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] +pub(crate) enum Mark { + /// "unused for reference". + #[default] + Unused, + /// "used for short-term reference". + Short, + /// "used for long-term reference". + Long, +} + +/// A padded 8-bit plane. +#[derive(Debug, Default)] +pub(crate) struct Plane8 { + pub data: Vec, + pub stride: usize, + /// Index of sample (0, 0) of the picture. + pub origin: usize, + pub width: usize, + pub height: usize, + pub pad: usize, +} + +impl Plane8 { + fn resize(&mut self, width: usize, height: usize, pad: usize) { + self.stride = width + 2 * pad; + self.origin = pad * self.stride + pad; + self.width = width; + self.height = height; + self.pad = pad; + self.data.clear(); + self.data.resize(self.stride * (height + 2 * pad), 0); + } + + #[inline] + pub(crate) fn at(&self, x: usize, y: usize) -> usize { + self.origin + y * self.stride + x + } + + /// Replicate the edge samples into the padding, which turns the per-sample + /// `Clip3` of Equations 8-239/8-240 into ordinary reads (see + /// [`crate::inter`]). + fn extend_borders(&mut self) { + let (w, h, pad, stride) = (self.width, self.height, self.pad, self.stride); + for y in 0..h { + let row = self.origin + y * stride; + let (left, right) = (self.data[row], self.data[row + w - 1]); + self.data[row - pad..row].fill(left); + self.data[row + w..row + w + pad].fill(right); + } + let full = self.origin - pad; + for y in 0..pad { + let (src, dst) = (full, full - (y + 1) * stride); + self.data.copy_within(src..src + stride, dst); + let src = full + (h - 1) * stride; + self.data.copy_within(src..src + stride, src + (y + 1) * stride); + } + } +} + +/// Per-slice values the deblocking filter needs after slice decode ends. +#[derive(Debug, Clone, Copy)] +pub(crate) struct SliceParams { + pub disable_deblock_idc: u8, + pub alpha_offset: i32, + pub beta_offset: i32, + pub cb_qp_offset: i32, + pub cr_qp_offset: i32, +} + +/// Flat per-picture decode context. +/// +/// All per-macroblock and per-4x4-block state lives in struct-of-arrays keyed +/// by macroblock address or 4x4-block coordinate: no per-macroblock heap +/// objects anywhere, and the whole picture is one reusable allocation set. +#[derive(Debug, Default)] +pub(crate) struct Picture { + pub sps_id: u8, + pub mb_w: usize, + pub mb_h: usize, + pub y: Plane8, + pub cb: Plane8, + pub cr: Plane8, + /// TotalCoeff per luma 4x4 block, `(mb_w * 4) x (mb_h * 4)`. + pub nz_y: Vec, + /// TotalCoeff per chroma 4x4 block, `(mb_w * 2) x (mb_h * 2)`, Cb and Cr. + pub nz_c: [Vec; 2], + /// Intra4x4PredMode per luma 4x4 block (2 = DC for non-I4x4 MBs). + pub i4_modes: Vec, + /// QPY per macroblock (the prediction-chain value; PCM keeps the chain). + pub mb_qp: Vec, + /// `FLAG_*` bits per macroblock. + pub mb_flags: Vec, + /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4` per macroblock. + pub mb_cbp: Vec, + /// coded_block_flag of the DC blocks per macroblock: bit 0 luma, 1 Cb, 2 Cr. + pub mb_dc_cbf: Vec, + /// Owning slice index per macroblock, `NO_SLICE` when undecoded. + pub mb_slice: Vec, + /// `MvLX[..][..]` per luma 4x4 block, `[list][component]`, quarter samples. + pub mv: Vec<[[i16; 2]; 2]>, + /// `RefIdxLX` per luma 4x4 block, -1 when the list is not used. + pub ref_idx: Vec<[i8; 2]>, + /// Identity ([`Picture::id`]) of the referenced picture per list, -1 when + /// unused. Reference *indices* are per slice, so only the picture identity + /// answers "same reference picture?" for boundary strength (8.7.2.1) and + /// `MapColToList0` (8.4.1.2.3). + pub ref_id: Vec<[i32; 2]>, + /// `Abs( mvd_lX[..][..][comp] )` per block, `[l0x, l0y, l1x, l1y]`, + /// saturated (the thresholds of 9.3.3.1.1.7 are 2 and 32). + pub mvd_abs: Vec<[u8; 4]>, + /// `BLK_*` flags per luma 4x4 block. + pub blk: Vec, + pub slices: Vec, + pub decoded_mbs: usize, + pub complete: bool, + + // ---- clause 8.2 picture state ---- + /// Stream-unique identity, assigned when the picture is started. + pub id: i32, + /// `PicOrderCnt( )` of the frame. + pub poc: i32, + pub frame_num: u32, + /// `FrameNumWrap` (8-27), recomputed for every decoded picture. + pub frame_num_wrap: i32, + /// `PicNum` (8-28) for short-term, `LongTermPicNum` (8-29) for long-term. + pub pic_num: i32, + pub long_term_frame_idx: u32, + pub mark: Mark, + /// The picture has not been output yet. + pub output: bool, + /// Inferred by the frame_num gap process of 8.2.5.2 rather than decoded. + pub non_existing: bool, + /// `FrameNumOffset` (8-6 / 8-11), carried to the next picture. + pub frame_num_offset: i32, + /// `PicOrderCntMsb` (8-3), carried to the next picture for POC type 0. + pub poc_msb: i32, + /// `pic_order_cnt_lsb` as coded, carried alongside `poc_msb`. + pub poc_lsb: i32, + /// Presentation timestamp of the access unit this picture came from. It + /// travels with the picture rather than with the packet, because display + /// order reorders the two apart. + pub pts: Option, +} + +impl Picture { + /// Reset for a new picture of `sps`'s geometry, reallocating only when the + /// geometry actually changed. + pub(crate) fn start(&mut self, sps: &Sps) { + let mb_w = sps.mb_width as usize; + let mb_h = sps.mb_height as usize; + if self.mb_w != mb_w || self.mb_h != mb_h || self.sps_id != sps.id { + self.mb_w = mb_w; + self.mb_h = mb_h; + self.sps_id = sps.id; + self.y.resize(mb_w * 16, mb_h * 16, PAD_Y); + self.cb.resize(mb_w * 8, mb_h * 8, PAD_C); + self.cr.resize(mb_w * 8, mb_h * 8, PAD_C); + let blocks = mb_w * mb_h * 16; + self.nz_y.resize(blocks, 0); + for c in &mut self.nz_c { + c.resize(mb_w * mb_h * 4, 0); + } + self.i4_modes.resize(blocks, 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); + self.mv.resize(blocks, [[0; 2]; 2]); + self.ref_idx.resize(blocks, [-1; 2]); + self.ref_id.resize(blocks, [-1; 2]); + self.mvd_abs.resize(blocks, [0; 4]); + self.blk.resize(blocks, 0); + } + // Per-MB metadata is rewritten by each decoded macroblock; only the + // "who is decoded" state must be wiped between pictures. + self.mb_slice.fill(NO_SLICE); + self.mb_flags.fill(0); + self.slices.clear(); + self.decoded_mbs = 0; + self.complete = false; + self.mark = Mark::Unused; + self.output = false; + self.non_existing = false; + self.long_term_frame_idx = 0; + } + + /// Replicate every plane's borders once the picture is fully reconstructed. + pub(crate) fn extend_borders(&mut self) { + self.y.extend_borders(); + self.cb.extend_borders(); + self.cr.extend_borders(); + } + + /// Fill the picture with mid-grey, for a frame the stream never sent. + fn fill_grey(&mut self) { + self.y.data.fill(128); + self.cb.data.fill(128); + self.cr.data.fill(128); + } + + fn copy_samples_from(&mut self, src: &Picture) { + self.y.data.copy_from_slice(&src.y.data); + self.cb.data.copy_from_slice(&src.cb.data); + self.cr.data.copy_from_slice(&src.cr.data); + } + + /// True while the picture occupies a decoded picture buffer slot. + fn stored(&self) -> bool { + self.mark != Mark::Unused || self.output + } +} + +/// One reference picture list (`RefPicList0` / `RefPicList1`). +/// +/// Entries are indices into [`Dpb::frames`]; the list is a fixed array because +/// Annex A caps it at 32 entries, so building it allocates nothing. +#[derive(Clone, Copy, Debug)] +pub(crate) struct RefList { + entries: [u8; 33], + len: usize, +} + +impl Default for RefList { + fn default() -> RefList { + RefList { + entries: [0; 33], + len: 0, + } + } +} + +impl RefList { + pub(crate) fn len(&self) -> usize { + self.len + } + + /// The DPB index of `RefPicListX[idx]`, `None` past the end. + #[inline] + pub(crate) fn get(&self, idx: usize) -> Option { + (idx < self.len).then(|| usize::from(self.entries[idx])) + } + + fn push(&mut self, idx: usize) { + if self.len < self.entries.len() { + self.entries[self.len] = idx as u8; + self.len += 1; + } + } +} + +/// The decoded picture buffer and the clause 8.2 state that spans pictures. +pub(crate) struct Dpb { + /// Stored pictures, in no particular order. + pub frames: Vec, + /// Recycled picture buffers. + free: Vec, + next_id: i32, + /// `max_dec_frame_buffering`. + max_frames: usize, + /// `max_num_reorder_frames`. + max_reorder: usize, + /// `MaxLongTermFrameIdx`, `None` = "no long-term frame indices". + max_long_term_idx: Option, + // Picture order count state (8.2.1). + prev_poc_msb: i32, + prev_poc_lsb: i32, + prev_frame_num: u32, + prev_frame_num_offset: i32, + prev_has_mmco5: bool, + /// `PrevRefFrameNum` for the gap detection of 8.2.5.2. + prev_ref_frame_num: u32, + /// Set once a picture has been decoded since the last reset. + started: bool, + /// Everything stored before [`Dpb::last_id`] must be output before it. + pending_flush: bool, + /// Identity of the most recently stored picture. + last_id: i32, +} + +impl Default for Dpb { + fn default() -> Dpb { + Dpb { + frames: Vec::new(), + free: Vec::new(), + next_id: 0, + max_frames: 16, + max_reorder: 16, + max_long_term_idx: None, + prev_poc_msb: 0, + prev_poc_lsb: 0, + prev_frame_num: 0, + prev_frame_num_offset: 0, + prev_has_mmco5: false, + prev_ref_frame_num: 0, + started: false, + pending_flush: false, + last_id: -1, + } + } +} + +/// Output of the picture order count derivation (clause 8.2.1). +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct Poc { + /// `PicOrderCnt( )` of the frame. + pub value: i32, + /// `FrameNumOffset`, predicted from by the next picture. + pub frame_num_offset: i32, + /// `PicOrderCntMsb` (POC type 0 only). + pub msb: i32, + /// `pic_order_cnt_lsb` (POC type 0 only). + pub lsb: i32, +} + +/// Everything about the current picture the DPB needs, gathered from the first +/// slice header of that picture. +#[derive(Clone, Copy, Debug)] +pub(crate) struct PicInfo { + pub is_idr: bool, + pub is_reference: bool, + pub frame_num: u32, + pub pic_order_cnt_lsb: u32, + pub delta_pic_order_cnt_bottom: i32, + pub delta_pic_order_cnt: [i32; 2], +} + +impl Dpb { + /// Adopt the buffer limits of `sps` (Annex A / VUI), keeping whatever is + /// already stored. + pub(crate) fn configure(&mut self, sps: &Sps) { + let level_frames = max_dpb_frames(sps); + let (buffering, reorder) = match sps.vui.as_ref().and_then(|v| v.bitstream_restriction) { + Some(r) => ( + (r.max_dec_frame_buffering as usize).min(MAX_STORED - 1), + (r.max_num_reorder_frames as usize).min(MAX_STORED - 1), + ), + // Without the VUI restriction the level limit is all we know. It + // over-buffers a low-delay stream, which costs latency but never + // order: pictures still leave smallest-POC-first. + None => (level_frames, level_frames), + }; + self.max_frames = buffering.max(sps.max_num_ref_frames as usize).max(1); + self.max_reorder = reorder.min(self.max_frames); + } + + /// A picture buffer to decode into, off the free list when possible. + pub(crate) fn take_picture(&mut self) -> Picture { + let mut pic = self.free.pop().unwrap_or_default(); + pic.id = self.next_id; + self.next_id = self.next_id.wrapping_add(1); + pic + } + + /// Hand a picture buffer back for reuse. + pub(crate) fn recycle(&mut self, pic: Picture) { + if self.free.len() < MAX_STORED { + self.free.push(pic); + } + } + + /// Drop every stored picture (seek / stream discontinuity). + pub(crate) fn clear(&mut self) { + while let Some(pic) = self.frames.pop() { + self.recycle(pic); + } + self.max_long_term_idx = None; + self.prev_poc_msb = 0; + self.prev_poc_lsb = 0; + self.prev_frame_num = 0; + self.prev_frame_num_offset = 0; + self.prev_has_mmco5 = false; + self.prev_ref_frame_num = 0; + self.started = false; + self.pending_flush = false; + self.last_id = -1; + } + + /// `PicOrderCnt( )` of a picture about to be decoded (clause 8.2.1), + /// together with the `FrameNumOffset` and `PicOrderCntMsb` the next + /// picture predicts from. + pub(crate) fn picture_order_count(&self, sps: &Sps, info: &PicInfo) -> Result { + match sps.pic_order_cnt_type { + 0 => { + let max_lsb = 1i32 << sps.log2_max_pic_order_cnt_lsb; + let (prev_msb, prev_lsb) = if info.is_idr { + (0, 0) + } else { + (self.prev_poc_msb, self.prev_poc_lsb) + }; + let lsb = info.pic_order_cnt_lsb as i32; + let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 { + prev_msb + max_lsb + } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 { + prev_msb - max_lsb + } else { + prev_msb + }; + let top = msb + lsb; + let bottom = top + info.delta_pic_order_cnt_bottom; + Ok(Poc { + value: top.min(bottom), + frame_num_offset: 0, + msb, + lsb, + }) + } + 1 => { + let max_frame_num = 1i32 << sps.log2_max_frame_num; + let offset = self.frame_num_offset(info, max_frame_num); + let cycle_len = sps.offsets_for_ref_frame.len() as i32; + let mut abs_frame_num = if cycle_len != 0 { + offset + info.frame_num as i32 + } else { + 0 + }; + if !info.is_reference && abs_frame_num > 0 { + abs_frame_num -= 1; + } + let mut expected = 0i32; + if abs_frame_num > 0 { + let expected_delta: i32 = sps.offsets_for_ref_frame.iter().sum(); + let cycle_cnt = (abs_frame_num - 1) / cycle_len; + let in_cycle = (abs_frame_num - 1) % cycle_len; + expected = cycle_cnt.wrapping_mul(expected_delta); + for i in 0..=in_cycle as usize { + expected = expected.wrapping_add(sps.offsets_for_ref_frame[i]); + } + } + if !info.is_reference { + expected = expected.wrapping_add(sps.offset_for_non_ref_pic); + } + let top = expected.wrapping_add(info.delta_pic_order_cnt[0]); + let bottom = top + .wrapping_add(sps.offset_for_top_to_bottom_field) + .wrapping_add(info.delta_pic_order_cnt[1]); + Ok(Poc { + value: top.min(bottom), + frame_num_offset: offset, + msb: 0, + lsb: 0, + }) + } + 2 => { + let max_frame_num = 1i32 << sps.log2_max_frame_num; + let offset = self.frame_num_offset(info, max_frame_num); + let poc = if info.is_idr { + 0 + } else if !info.is_reference { + 2 * (offset + info.frame_num as i32) - 1 + } else { + 2 * (offset + info.frame_num as i32) + }; + Ok(Poc { + value: poc, + frame_num_offset: offset, + msb: 0, + lsb: 0, + }) + } + other => Err(Error::corrupt(format!("pic_order_cnt_type {other}"))), + } + } + + /// `FrameNumOffset` (Equations 8-6 and 8-11). + fn frame_num_offset(&self, info: &PicInfo, max_frame_num: i32) -> i32 { + if info.is_idr { + return 0; + } + let prev = if self.prev_has_mmco5 { + 0 + } else { + self.prev_frame_num_offset + }; + if self.prev_frame_num > info.frame_num { + prev + max_frame_num + } else { + prev + } + } + + /// True when `frame_num` skips values, i.e. pictures are missing + /// (clause 8.2.5.2). Editor seeks and lossy transports both produce this; + /// it is a normal condition, not a corrupt stream. + pub(crate) fn frame_num_gap(&self, sps: &Sps, frame_num: u32) -> bool { + let max = 1u32 << sps.log2_max_frame_num; + self.started + && frame_num != self.prev_ref_frame_num + && frame_num != (self.prev_ref_frame_num + 1) % max + } + + /// Insert the "non-existing" frames of clause 8.2.5.2 for a frame_num gap, + /// so that reference numbering stays aligned with the encoder's and the + /// pictures that follow decode instead of being dropped. + pub(crate) fn fill_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> Result<()> { + let max = 1u32 << sps.log2_max_frame_num; + let mut unused = (self.prev_ref_frame_num + 1) % max; + // A gap can be as wide as MaxFrameNum; every inferred frame costs a + // sliding-window step, so bound the work at the buffer size. + let mut budget = MAX_STORED; + while unused != frame_num && budget > 0 { + budget -= 1; + let mut pic = self.take_picture(); + pic.start(sps); + // The samples are unspecified; the last reference picture is a far + // better guess than grey when a later picture wrongly predicts + // from the gap. + match self.frames.iter().max_by_key(|p| p.frame_num_wrap) { + Some(src) if src.y.data.len() == pic.y.data.len() => pic.copy_samples_from(src), + _ => pic.fill_grey(), + } + pic.non_existing = true; + pic.frame_num = unused; + pic.output = false; + pic.complete = true; + let info = PicInfo { + is_idr: false, + is_reference: true, + frame_num: unused, + pic_order_cnt_lsb: 0, + delta_pic_order_cnt_bottom: 0, + delta_pic_order_cnt: [0; 2], + }; + // 8.2.5.2: picture order count is only derived for a non-existing + // frame when pic_order_cnt_type is not 0. Under type 0 the frame + // has no output order, and 8.2.4.2.3 keeps it out of the B lists. + let poc = if sps.pic_order_cnt_type == 0 { + Poc::default() + } else { + self.picture_order_count(sps, &info)? + }; + pic.poc = poc.value; + pic.frame_num_offset = poc.frame_num_offset; + pic.mark = Mark::Short; + self.number_short_term(unused, sps); + self.sliding_window(sps)?; + pic.frame_num_wrap = unused as i32; + pic.pic_num = unused as i32; + self.frames.push(pic); + self.prev_frame_num = unused; + self.prev_frame_num_offset = poc.frame_num_offset; + self.prev_has_mmco5 = false; + self.prev_ref_frame_num = unused; + unused = (unused + 1) % max; + } + Ok(()) + } + + /// Recompute `FrameNumWrap` and `PicNum` for every stored reference + /// picture against the current `frame_num` (clause 8.2.4.1). + pub(crate) fn number_short_term(&mut self, frame_num: u32, sps: &Sps) { + let max_frame_num = 1i32 << sps.log2_max_frame_num; + for pic in &mut self.frames { + match pic.mark { + Mark::Short => { + pic.frame_num_wrap = if pic.frame_num > frame_num { + pic.frame_num as i32 - max_frame_num + } else { + pic.frame_num as i32 + }; + pic.pic_num = pic.frame_num_wrap; + } + Mark::Long => pic.pic_num = pic.long_term_frame_idx as i32, + Mark::Unused => {} + } + } + } + + /// Build `RefPicList0` and `RefPicList1` for one slice: initialisation + /// (8.2.4.2.1 / 8.2.4.2.3) followed by modification (8.2.4.3). + pub(crate) fn build_ref_lists( + &self, + slice_type: SliceType, + curr_poc: i32, + curr_pic_num: i32, + max_pic_num: i32, + num_l0: usize, + num_l1: usize, + mods: (&[RefPicListMod], &[RefPicListMod]), + ) -> Result<[RefList; 2]> { + let mut lists = [RefList::default(), RefList::default()]; + // Short-term candidates, then long-term, both by index into `frames`. + let mut short: [usize; MAX_STORED] = [0; MAX_STORED]; + let mut n_short = 0usize; + let mut long: [usize; MAX_STORED] = [0; MAX_STORED]; + let mut n_long = 0usize; + for (i, pic) in self.frames.iter().enumerate() { + // A frame inferred for a frame_num gap has no output order, so it + // cannot take part in the POC ordering a B list is built from + // (8.2.4.2.3); it stays a legal P reference by PicNum. + if pic.non_existing && slice_type == SliceType::B { + continue; + } + match pic.mark { + Mark::Short if n_short < MAX_STORED => { + short[n_short] = i; + n_short += 1; + } + Mark::Long if n_long < MAX_STORED => { + long[n_long] = i; + n_long += 1; + } + _ => {} + } + } + let long = &mut long[..n_long]; + long.sort_unstable_by_key(|&i| self.frames[i].long_term_frame_idx); + + if slice_type == SliceType::B { + let short = &mut short[..n_short]; + // List 0: earlier pictures by descending POC, then later ascending. + short.sort_unstable_by_key(|&i| { + let poc = self.frames[i].poc; + if poc < curr_poc { + (0i32, -poc) + } else { + (1, poc) + } + }); + for &i in short.iter() { + lists[0].push(i); + } + for &i in long.iter() { + lists[0].push(i); + } + // List 1: later pictures by ascending POC, then earlier descending. + short.sort_unstable_by_key(|&i| { + let poc = self.frames[i].poc; + if poc > curr_poc { + (0i32, poc) + } else { + (1, -poc) + } + }); + for &i in short.iter() { + lists[1].push(i); + } + for &i in long.iter() { + lists[1].push(i); + } + // 8.2.4.2.3 step 3. + if lists[1].len > 1 && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len] + { + lists[1].entries.swap(0, 1); + } + } else { + let short = &mut short[..n_short]; + short.sort_unstable_by_key(|&i| -self.frames[i].pic_num); + for &i in short.iter() { + lists[0].push(i); + } + for &i in long.iter() { + lists[0].push(i); + } + } + + let wanted = [num_l0, num_l1]; + let mods = [mods.0, mods.1]; + for x in 0..2 { + if x == 1 && slice_type != SliceType::B { + lists[1].len = 0; + continue; + } + if lists[x].len == 0 { + return Err(Error::corrupt("inter slice with an empty reference list")); + } + // 8.2.4.2: the initial list is truncated to the active count. A + // list shorter than that leaves the tail unspecified, and a + // conformant stream fills it by modification; repeating entry 0 + // keeps every index in range meanwhile. + let first = lists[x].entries[0]; + while lists[x].len < wanted[x] { + lists[x].push(usize::from(first)); + } + lists[x].len = wanted[x]; + self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num); + } + Ok(lists) + } + + /// Reference picture list modification (clause 8.2.4.3), following the + /// insert-and-compact of Equations 8-37 and 8-38 with the one-longer + /// temporary list those equations use. + /// + /// Comparing DPB indices stands in for `PicNumF`/`LongTermPicNumF`: a + /// picture appears in the buffer once, and the sentinel those functions + /// return for a wrongly marked picture can never equal the target. + fn modify_list( + &self, + list: &mut RefList, + mods: &[RefPicListMod], + curr_pic_num: i32, + max_pic_num: i32, + ) { + if mods.is_empty() { + return; + } + let active = list.len; + let mut tmp = [0u8; 34]; + tmp[..active].copy_from_slice(&list.entries[..active]); + let mut pred = curr_pic_num; + let mut ref_idx = 0usize; + for op in mods { + let target = match *op { + RefPicListMod::ShortTerm { + abs_diff_pic_num_minus1, + add, + } => { + let diff = abs_diff_pic_num_minus1 as i32 + 1; + let no_wrap = if add { + if pred + diff >= max_pic_num { + pred + diff - max_pic_num + } else { + pred + diff + } + } else if pred - diff < 0 { + pred - diff + max_pic_num + } else { + pred - diff + }; + pred = no_wrap; + let pic_num = if no_wrap > curr_pic_num { + no_wrap - max_pic_num + } else { + no_wrap + }; + self.frames + .iter() + .position(|p| p.mark == Mark::Short && p.pic_num == pic_num) + } + RefPicListMod::LongTerm(num) => self + .frames + .iter() + .position(|p| p.mark == Mark::Long && p.pic_num == num as i32), + }; + // A modification naming a picture the buffer never received points + // at something that was lost; keeping the initial entry decodes a + // seek or a dropped packet instead of failing the slice. + let Some(target) = target else { continue }; + if ref_idx >= active { + break; + } + for c in (ref_idx + 1..=active).rev() { + tmp[c] = tmp[c - 1]; + } + tmp[ref_idx] = target as u8; + ref_idx += 1; + let mut n = ref_idx; + for c in ref_idx..=active { + if usize::from(tmp[c]) != target { + tmp[n] = tmp[c]; + n += 1; + } + } + } + list.entries[..active].copy_from_slice(&tmp[..active]); + list.len = active; + } + + /// Store a decoded picture and apply the reference marking of 8.2.5. + pub(crate) fn store( + &mut self, + mut pic: Picture, + sps: &Sps, + info: &PicInfo, + marking: Option<&DecRefPicMarking>, + ) -> Result<()> { + let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5)); + pic.output = true; + pic.complete = true; + + if info.is_idr { + let no_output = marking.is_some_and(|m| m.no_output_of_prior_pics); + self.drain_prior(no_output); + pic.mark = Mark::Short; + if marking.is_some_and(|m| m.long_term_reference) { + pic.mark = Mark::Long; + pic.long_term_frame_idx = 0; + self.max_long_term_idx = Some(0); + } else { + self.max_long_term_idx = None; + } + } else if info.is_reference { + let m = marking.expect("a reference picture carries dec_ref_pic_marking"); + pic.mark = Mark::Short; + if m.adaptive { + self.apply_mmco(&mut pic, m, info)?; + } else { + self.sliding_window(sps)?; + } + } + + if has_mmco5 { + // 8.2.1: an MMCO 5 restarts frame_num and picture order count at + // this picture, so everything before it must leave first. + pic.poc = 0; + pic.frame_num = 0; + pic.frame_num_offset = 0; + pic.poc_msb = 0; + pic.poc_lsb = 0; + } + + self.prev_frame_num = pic.frame_num; + self.prev_frame_num_offset = pic.frame_num_offset; + self.prev_has_mmco5 = has_mmco5; + if info.is_reference { + self.prev_ref_frame_num = pic.frame_num; + self.prev_poc_msb = pic.poc_msb; + self.prev_poc_lsb = pic.poc_lsb; + } + self.started = true; + // An IDR or an MMCO 5 restarts picture order count, so POC no longer + // orders across the boundary: everything already in the buffer belongs + // ahead of this picture and has to leave first. + if (info.is_idr || has_mmco5) && self.frames.iter().any(|p| p.output) { + self.pending_flush = true; + } + self.last_id = pic.id; + + if self.frames.len() >= MAX_STORED { + // Every stored picture is either a reference or waiting to be + // output, and both limits were enforced above; a stream that still + // overflows is not conformant. + return Err(Error::corrupt("decoded picture buffer overflow")); + } + self.frames.push(pic); + Ok(()) + } + + /// Output and remove every stored picture (IDR boundary or MMCO 5). + fn drain_prior(&mut self, discard: bool) { + for pic in &mut self.frames { + pic.mark = Mark::Unused; + if discard { + pic.output = false; + } + } + } + + /// Sliding window marking (clause 8.2.5.3). + fn sliding_window(&mut self, sps: &Sps) -> Result<()> { + let max_refs = (sps.max_num_ref_frames as usize).max(1); + loop { + let n = self + .frames + .iter() + .filter(|p| p.mark != Mark::Unused) + .count(); + if n < max_refs { + return Ok(()); + } + let Some(oldest) = self + .frames + .iter_mut() + .filter(|p| p.mark == Mark::Short) + .min_by_key(|p| p.frame_num_wrap) + else { + // Only long-term references left and the window is full: the + // stream must free one by MMCO, so refusing here would break a + // conformant stream. Leave the buffer as is. + return Ok(()); + }; + oldest.mark = Mark::Unused; + } + } + + /// Adaptive marking (clause 8.2.5.4). + fn apply_mmco(&mut self, pic: &mut Picture, m: &DecRefPicMarking, info: &PicInfo) -> Result<()> { + let curr_pic_num = info.frame_num as i32; + for op in &m.mmcos { + match op.op { + 1 => { + let target = curr_pic_num - (op.arg1 as i32 + 1); + if let Some(p) = self + .frames + .iter_mut() + .find(|p| p.mark == Mark::Short && p.pic_num == target) + { + p.mark = Mark::Unused; + } + } + 2 => { + if let Some(p) = self + .frames + .iter_mut() + .find(|p| p.mark == Mark::Long && p.pic_num == op.arg1 as i32) + { + p.mark = Mark::Unused; + } + } + 3 => { + let target = curr_pic_num - (op.arg1 as i32 + 1); + let idx = op.arg2; + for p in &mut self.frames { + if p.mark == Mark::Long && p.long_term_frame_idx == idx { + p.mark = Mark::Unused; + } + } + if let Some(p) = self + .frames + .iter_mut() + .find(|p| p.mark == Mark::Short && p.pic_num == target) + { + p.mark = Mark::Long; + p.long_term_frame_idx = idx; + p.pic_num = idx as i32; + } + } + 4 => { + self.max_long_term_idx = op.arg1.checked_sub(1); + let limit = self.max_long_term_idx; + for p in &mut self.frames { + if p.mark == Mark::Long + && limit.is_none_or(|max| p.long_term_frame_idx > max) + { + p.mark = Mark::Unused; + } + } + } + 5 => { + for p in &mut self.frames { + p.mark = Mark::Unused; + } + self.max_long_term_idx = None; + } + 6 => { + let idx = op.arg1; + for p in &mut self.frames { + if p.mark == Mark::Long && p.long_term_frame_idx == idx { + p.mark = Mark::Unused; + } + } + pic.mark = Mark::Long; + pic.long_term_frame_idx = idx; + pic.pic_num = idx as i32; + } + other => { + return Err(Error::corrupt(format!( + "memory_management_control_operation {other}" + ))); + } + } + } + Ok(()) + } + + /// The next picture to output, or `None` while the buffer is still within + /// its reordering and storage limits (the bumping process of C.4.5.3). + /// + /// `flush` empties the buffer, which is what end of stream and a seek do. + pub(crate) fn next_output(&mut self, flush: bool) -> Option { + if self.pending_flush { + let last = self.last_id; + let best = self + .frames + .iter() + .enumerate() + .filter(|(_, p)| p.output && p.id != last) + .min_by_key(|(_, p)| p.poc) + .map(|(i, _)| i); + if best.is_some() { + return best; + } + self.pending_flush = false; + } + let pending = self.frames.iter().filter(|p| p.output).count(); + let stored = self.frames.iter().filter(|p| p.stored()).count(); + if !flush && pending <= self.max_reorder && stored <= self.max_frames { + return None; + } + let mut best: Option = None; + for (i, pic) in self.frames.iter().enumerate() { + if !pic.output { + continue; + } + if best.is_none_or(|b| pic.poc < self.frames[b].poc) { + best = Some(i); + } + } + best + } + + /// Mark picture `idx` as output and reclaim every slot that is now free. + pub(crate) fn released(&mut self, idx: usize) { + self.frames[idx].output = false; + let mut i = 0; + while i < self.frames.len() { + if self.frames[i].stored() { + i += 1; + continue; + } + let pic = self.frames.swap_remove(i); + self.recycle(pic); + } + } +} + +/// `MaxDpbFrames` from the level limits of Table A-1, the buffer size a stream +/// is allowed to assume when its VUI does not state one. +fn max_dpb_frames(sps: &Sps) -> usize { + let max_dpb_mbs = match sps.level_idc { + 0..=10 => 396, + 11 => { + // constraint_set3_flag distinguishes level 1b from level 1.1; both + // have the same MaxDpbMbs, so the flag does not change the answer. + 396 + } + 12..=20 => 2376, + 21 => 4752, + 22..=30 => 8100, + 31 => 18000, + 32 => 20480, + 33..=41 => 32768, + 42 => 34816, + 50 => 110400, + 51..=52 => 184320, + _ => 696320, + }; + let per_frame = (sps.mb_width as usize * sps.mb_height as usize).max(1); + (max_dpb_mbs / per_frame).clamp(1, 16) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn plane(w: usize, h: usize) -> Plane8 { + let mut p = Plane8::default(); + p.resize(w, h, 4); + for y in 0..h { + for x in 0..w { + let at = p.at(x, y); + p.data[at] = (x + y * 10) as u8; + } + } + p + } + + /// Border replication makes an out-of-picture read equal the clipped + /// in-picture read, which is what [`crate::inter`] relies on. + #[test] + fn extend_borders_replicates_edges() { + let mut p = plane(6, 5); + p.extend_borders(); + let at = |x: i32, y: i32| -> u8 { + p.data[(p.origin as i32 + y * p.stride as i32 + x) as usize] + }; + for y in -4..9i32 { + for x in -4..10i32 { + let cx = x.clamp(0, 5) as usize; + let cy = y.clamp(0, 4) as usize; + assert_eq!(at(x, y), p.data[p.at(cx, cy)], "({x}, {y})"); + } + } + } + + fn sps_for(poc_type: u8) -> Sps { + use ec_core::BitWriter; + let mut w = BitWriter::new(); + w.write_bits(66, 8); + w.write_bits(0, 8); + w.write_bits(30, 8); + w.write_ue(0); // sps id + w.write_ue(4); // log2_max_frame_num_minus4 -> 8 + w.write_ue(u32::from(poc_type)); + match poc_type { + 0 => w.write_ue(4), // log2_max_pic_order_cnt_lsb_minus4 -> 8 + 1 => { + w.write_bit(false); // delta_pic_order_always_zero + w.write_se(0); + w.write_se(0); + w.write_ue(1); // one offset_for_ref_frame + w.write_se(2); + } + _ => {} + } + w.write_ue(2); // max_num_ref_frames + w.write_bit(false); + w.write_ue(10); + w.write_ue(8); + w.write_bit(true); // frame_mbs_only + w.write_bit(true); // direct_8x8_inference + w.write_bit(false); // no cropping + w.write_bit(false); // no vui + w.align_to_byte(); + Sps::parse(w.as_bytes()).unwrap() + } + + fn info(frame_num: u32, lsb: u32, is_ref: bool, is_idr: bool) -> PicInfo { + PicInfo { + is_idr, + is_reference: is_ref, + frame_num, + pic_order_cnt_lsb: lsb, + delta_pic_order_cnt_bottom: 0, + delta_pic_order_cnt: [0; 2], + } + } + + /// Picture order count type 0 wraps when pic_order_cnt_lsb rolls over. + #[test] + fn poc_type_0_tracks_the_msb_across_a_wrap() { + let sps = sps_for(0); + let mut dpb = Dpb::default(); + let mut expect = |i: PicInfo, want: i32| { + let poc = dpb.picture_order_count(&sps, &i).unwrap(); + assert_eq!(poc.value, want, "{i:?}"); + // Emulate the reference-picture bookkeeping of `store`. + if i.is_reference { + dpb.prev_poc_msb = poc.msb; + dpb.prev_poc_lsb = poc.lsb; + } + }; + expect(info(0, 0, true, true), 0); + expect(info(1, 100, true, false), 100); + expect(info(2, 200, true, false), 200); + // 200 -> 40 is more than half of MaxPicOrderCntLsb backwards, so it is + // read as a wrap forward rather than a jump back. + expect(info(3, 40, true, false), 296); + // A genuine step back stays a step back. + expect(info(4, 100, true, false), 356); + } + + /// Type 2 counts pictures in decode order, so a non-reference picture sits + /// just before the reference picture that follows it. + #[test] + fn poc_type_2_is_twice_the_frame_number() { + let sps = sps_for(2); + let dpb = Dpb::default(); + assert_eq!(dpb.picture_order_count(&sps, &info(0, 0, true, true)).unwrap().value, 0); + assert_eq!(dpb.picture_order_count(&sps, &info(3, 0, true, false)).unwrap().value, 6); + assert_eq!(dpb.picture_order_count(&sps, &info(3, 0, false, false)).unwrap().value, 5); + } + + /// Type 1 walks the offset_for_ref_frame cycle. + #[test] + fn poc_type_1_follows_the_offset_cycle() { + let sps = sps_for(1); + let dpb = Dpb::default(); + // One-entry cycle of +2: frame n has expectedPicOrderCnt 2n. + assert_eq!(dpb.picture_order_count(&sps, &info(0, 0, true, true)).unwrap().value, 0); + assert_eq!(dpb.picture_order_count(&sps, &info(1, 0, true, false)).unwrap().value, 2); + assert_eq!(dpb.picture_order_count(&sps, &info(4, 0, true, false)).unwrap().value, 8); + } + + fn push_ref(dpb: &mut Dpb, frame_num: u32, poc: i32, mark: Mark) { + let mut pic = dpb.take_picture(); + pic.frame_num = frame_num; + pic.frame_num_wrap = frame_num as i32; + pic.pic_num = frame_num as i32; + pic.poc = poc; + pic.mark = mark; + dpb.frames.push(pic); + } + + /// P list 0 is short-term by descending PicNum then long-term ascending. + #[test] + fn p_list_initialisation_orders_by_pic_num() { + let mut dpb = Dpb::default(); + push_ref(&mut dpb, 2, 4, Mark::Short); + push_ref(&mut dpb, 5, 10, Mark::Short); + push_ref(&mut dpb, 3, 6, Mark::Short); + let mut lt = dpb.take_picture(); + lt.mark = Mark::Long; + lt.long_term_frame_idx = 1; + lt.pic_num = 1; + dpb.frames.push(lt); + let lists = dpb + .build_ref_lists(SliceType::P, 12, 6, 256, 4, 0, (&[], &[])) + .unwrap(); + let nums: Vec = (0..lists[0].len()) + .map(|i| dpb.frames[lists[0].get(i).unwrap()].pic_num) + .collect(); + assert_eq!(nums, vec![5, 3, 2, 1]); + } + + /// B lists split around the current POC and mirror each other. + #[test] + fn b_list_initialisation_splits_around_the_current_poc() { + let mut dpb = Dpb::default(); + push_ref(&mut dpb, 0, 0, Mark::Short); + push_ref(&mut dpb, 1, 8, Mark::Short); + push_ref(&mut dpb, 2, 4, Mark::Short); + push_ref(&mut dpb, 3, 12, Mark::Short); + let lists = dpb + .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[])) + .unwrap(); + let poc = |l: &RefList| -> Vec { + (0..l.len()).map(|i| dpb.frames[l.get(i).unwrap()].poc).collect() + }; + assert_eq!(poc(&lists[0]), vec![4, 0, 8, 12]); + assert_eq!(poc(&lists[1]), vec![8, 12, 4, 0]); + } + + /// A single-entry list identical in both directions gets its first two + /// entries swapped (8.2.4.2.3 step 3 only fires above one entry). + #[test] + fn identical_b_lists_swap_the_first_two_entries() { + let mut dpb = Dpb::default(); + push_ref(&mut dpb, 0, 0, Mark::Short); + push_ref(&mut dpb, 1, 2, Mark::Short); + // Both references precede the current picture, so initialisation gives + // list 0 and list 1 the same descending-POC order. + let lists = dpb + .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[])) + .unwrap(); + let l0: Vec = (0..2).map(|i| dpb.frames[lists[0].get(i).unwrap()].poc).collect(); + let l1: Vec = (0..2).map(|i| dpb.frames[lists[1].get(i).unwrap()].poc).collect(); + assert_eq!(l0, vec![2, 0]); + assert_eq!(l1, vec![0, 2], "identical lists swap"); + } + + /// A short-term modification moves the named picture to the front. + #[test] + fn short_term_modification_reorders_the_list() { + let mut dpb = Dpb::default(); + push_ref(&mut dpb, 5, 10, Mark::Short); + push_ref(&mut dpb, 4, 8, Mark::Short); + push_ref(&mut dpb, 3, 6, Mark::Short); + // CurrPicNum 6, abs_diff 3 -> picNum 3, which is the last entry. + let mods = [RefPicListMod::ShortTerm { + abs_diff_pic_num_minus1: 2, + add: false, + }]; + let lists = dpb + .build_ref_lists(SliceType::P, 12, 6, 256, 3, 0, (&mods, &[])) + .unwrap(); + let nums: Vec = (0..3) + .map(|i| dpb.frames[lists[0].get(i).unwrap()].pic_num) + .collect(); + assert_eq!(nums, vec![3, 5, 4]); + } +} diff --git a/crates/ec-h264/src/entropy.rs b/crates/ec-h264/src/entropy.rs index 0c441793..c4491c40 100644 --- a/crates/ec-h264/src/entropy.rs +++ b/crates/ec-h264/src/entropy.rs @@ -20,7 +20,7 @@ use ec_core::error::{Error, Result}; use crate::bits::BitCursor; use crate::cabac::Cabac; -use crate::tables::CBP_INTRA_420; +use crate::tables::{CBP_INTER_420, CBP_INTRA_420}; /// Macroblock state bits (`Picture::mb_flags`, and `MbInfo::flags` for a /// neighbour). CABAC context selection reads all of them. @@ -32,6 +32,12 @@ pub(crate) const FLAG_PCM: u8 = 2; pub(crate) const FLAG_I16: u8 = 4; /// intra_chroma_pred_mode is not 0 (DC). pub(crate) const FLAG_CHROMA_PRED: u8 = 8; +/// The macroblock is inter coded. +pub(crate) const FLAG_INTER: u8 = 16; +/// mb_type is B_Skip or B_Direct_16x16 (9.3.3.1.1.3 at ctxIdxOffset 27). +pub(crate) const FLAG_DIRECT: u8 = 32; +/// mb_type is P_Skip or B_Skip (9.3.3.1.1.1). +pub(crate) const FLAG_SKIP: u8 = 64; /// Residual block class (spec Table 9-42, the 4:2:0 subset this decoder codes). #[derive(Clone, Copy, PartialEq, Eq, Debug)] @@ -113,8 +119,136 @@ impl<'a> Entropy<'a> { /// 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)?)) + /// `init_column` is 0 for I and SI slices, `cabac_init_idc + 1` otherwise. + pub(crate) fn cabac( + rbsp: &'a [u8], + header_bits: u64, + slice_qp: i32, + init_column: usize, + ) -> Result> { + Ok(Entropy::Cabac(Cabac::new( + rbsp, + header_bits, + slice_qp, + init_column, + )?)) + } + + /// True for the CABAC variant. + #[inline] + pub(crate) fn is_cabac(&self) -> bool { + matches!(self, Entropy::Cabac(_)) + } + + /// Declare whether the macroblock being parsed is intra coded, which + /// CABAC needs for the coded_block_flag contexts of 9.3.3.1.1.9. + #[inline] + pub(crate) fn set_intra(&mut self, intra: bool) { + if let Entropy::Cabac(c) = self { + c.set_intra(intra); + } + } + + /// `mb_skip_run` (7.3.4), CAVLC only. + pub(crate) fn mb_skip_run(&mut self) -> Result { + match self { + Entropy::Cavlc(r) => r.read_ue(), + Entropy::Cabac(_) => Err(Error::corrupt("mb_skip_run in a CABAC slice")), + } + } + + /// `mb_skip_flag` (7.3.4), CABAC only; `inc` is condTermFlagA + + /// condTermFlagB per 9.3.3.1.1.1. + pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> Result { + match self { + Entropy::Cavlc(_) => Err(Error::corrupt("mb_skip_flag in a CAVLC slice")), + Entropy::Cabac(c) => Ok(c.mb_skip_flag(b_slice, inc)), + } + } + + /// `mb_type` of a P or SP slice: 0..4, or 5 + the I-slice mb_type. + pub(crate) fn mb_type_p(&mut self) -> Result { + match self { + Entropy::Cavlc(r) => { + let t = r.read_ue()?; + if t > 30 { + return Err(Error::corrupt("P-slice mb_type > 30")); + } + Ok(t) + } + Entropy::Cabac(c) => c.mb_type_p(), + } + } + + /// `mb_type` of a B slice: 0..22, or 23 + the I-slice mb_type. + pub(crate) fn mb_type_b(&mut self) -> Result { + match self { + Entropy::Cavlc(r) => { + let t = r.read_ue()?; + if t > 48 { + return Err(Error::corrupt("B-slice mb_type > 48")); + } + Ok(t) + } + Entropy::Cabac(c) => c.mb_type_b(), + } + } + + /// `sub_mb_type[ ]` of a P (`b_slice` false) or B macroblock. + pub(crate) fn sub_mb_type(&mut self, b_slice: bool) -> Result { + let max = if b_slice { 12 } else { 3 }; + match self { + Entropy::Cavlc(r) => { + let t = r.read_ue()?; + if t > max { + return Err(Error::corrupt("sub_mb_type out of range")); + } + Ok(t) + } + Entropy::Cabac(c) => Ok(if b_slice { + c.sub_mb_type_b() + } else { + c.sub_mb_type_p() + }), + } + } + + /// `ref_idx_lX` (7.3.5.1): te(v) over `0..=cmax` for CAVLC, unary with the + /// neighbour context of 9.3.3.1.1.6 for CABAC. + pub(crate) fn ref_idx(&mut self, cmax: u32, inc: usize) -> Result { + let v = match self { + // te(v), clause 9.1.1: a one-valued range is a single inverted bit. + Entropy::Cavlc(r) if cmax == 1 => u32::from(!r.read_bit()?), + Entropy::Cavlc(r) => r.read_ue()?, + Entropy::Cabac(c) => c.ref_idx(inc)?, + }; + if v > cmax { + return Err(Error::corrupt("ref_idx beyond num_ref_idx_active")); + } + Ok(v) + } + + /// One `mvd_lX` component (7.3.5.1), in quarter luma samples. + pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result { + match self { + Entropy::Cavlc(r) => r.read_se(), + Entropy::Cabac(c) => c.mvd(comp, inc), + } + } + + /// `coded_block_pattern` of an inter macroblock, as + /// `(CodedBlockPatternLuma, CodedBlockPatternChroma)`. + pub(crate) fn coded_block_pattern_inter(&mut self) -> Result<(u8, u8)> { + match self { + Entropy::Cavlc(r) => { + let code = r.read_ue()? as usize; + let cbp = *CBP_INTER_420 + .get(code) + .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 47"))?; + Ok((cbp & 15, cbp >> 4)) + } + Entropy::Cabac(c) => c.coded_block_pattern(), + } } /// Publish the neighbourhood of the macroblock about to be parsed. diff --git a/crates/ec-h264/src/inter.rs b/crates/ec-h264/src/inter.rs new file mode 100644 index 00000000..916eca1c --- /dev/null +++ b/crates/ec-h264/src/inter.rs @@ -0,0 +1,483 @@ +//! Inter prediction sample construction (spec 8.4.2): the quarter-sample luma +//! interpolation of 8.4.2.2.1, the eighth-sample chroma interpolation of +//! 8.4.2.2.2 and the weighted combination of 8.4.2.3. +//! +//! Reference planes are the same padded [`crate::decoder::Plane8`] the decoder +//! writes into, with the borders replicated once per picture +//! (`Plane8::extend_borders`). That turns the per-sample `Clip3` of Equations +//! 8-239 and 8-240 into a single clamp of the block origin: any position the +//! spec would clip to an edge sample lands on the replicated copy of that same +//! edge sample, so the interpolation loop never bounds-checks and never +//! branches per sample. The clamp bounds below are what makes that exact — +//! see [`clamp_origin`]. + +/// A reference picture plane for motion compensation. +pub(crate) struct RefPlane<'a> { + /// The whole padded plane. + pub data: &'a [u8], + /// Row pitch. + pub stride: usize, + /// Index of picture sample (0, 0). + pub origin: usize, + /// Picture width in samples. + pub width: usize, + /// Picture height in samples. + pub height: usize, + /// Replicated border width on every side. + pub pad: usize, +} + +impl RefPlane<'_> { + #[inline] + fn at(&self, x: i32, y: i32) -> usize { + (self.origin as isize + y as isize * self.stride as isize + x as isize) as usize + } +} + +/// Clamp a block origin so that every tap the interpolator reads stays inside +/// the replicated border while producing the samples Equations 8-239/8-240 +/// would have clipped to. +/// +/// `left`/`right` are the tap reach on each side (2 and 3 for the 6-tap luma +/// filter, 0 and 1 for the bilinear chroma filter) and `size` the block extent. +/// Once the block is completely outside the picture every tap resolves to the +/// same edge sample, so clamping the origin to the last position where that is +/// still true is exact rather than approximate. +#[inline] +fn clamp_origin(v: i32, size: usize, extent: usize, pad: usize, left: i32, right: i32) -> i32 { + let lo = -(pad as i32) + left; + let hi = extent as i32 + pad as i32 - right - size as i32; + v.clamp(lo.min(hi), hi) +} + +/// The 6-tap half-sample filter of Equations 8-241/8-242 over samples spaced +/// `step` apart, centred between `p[0]` and `p[step]`. +#[inline] +fn tap6(data: &[u8], at: usize, step: usize) -> i32 { + let s = |k: isize| i32::from(data[(at as isize + k * step as isize) as usize]); + s(-2) - 5 * s(-1) + 20 * s(0) + 20 * s(1) - 5 * s(2) + s(3) +} + +/// The same over already-filtered intermediate values (Equations 8-245/8-246). +#[inline] +fn tap6_i32(v: &[i32], at: usize, step: usize) -> i32 { + let s = |k: isize| v[(at as isize + k * step as isize) as usize]; + s(-2) - 5 * s(-1) + 20 * s(0) + 20 * s(1) - 5 * s(2) + s(3) +} + +#[inline] +fn clip8(v: i32) -> u8 { + v.clamp(0, 255) as u8 +} + +#[inline] +fn avg(a: u8, b: u8) -> u8 { + ((u32::from(a) + u32::from(b) + 1) >> 1) as u8 +} + +/// Widest intermediate row the luma interpolator needs: a 16-wide partition +/// plus the five taps of the horizontal filter. +const TMP_W: usize = 16 + 5; + +/// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose +/// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter +/// samples. Writes `w` x `h` prediction samples into `out` at pitch `w`. +pub(crate) fn mc_luma(r: &RefPlane<'_>, x: i32, y: i32, mv: [i16; 2], w: usize, h: usize, out: &mut [u8]) { + let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize); + let xi = clamp_origin(x + (mv[0] as i32 >> 2), w, r.width, r.pad, 2, 3); + let yi = clamp_origin(y + (mv[1] as i32 >> 2), h, r.height, r.pad, 2, 3); + let stride = r.stride; + let base = r.at(xi, yi); + + // Full sample: a straight copy. + if fx == 0 && fy == 0 { + for row in 0..h { + let src = base + row * stride; + out[row * w..row * w + w].copy_from_slice(&r.data[src..src + w]); + } + return; + } + + // Half-sample rows ("b" of Equation 8-243) for rows yi..yi+h, plus one more + // row when the quarter position also needs "s". + let need_b = fx != 0 && fy != 2; + let need_h = fy != 0 && fx != 2; + let need_j = (fx == 2 && fy != 0) || (fy == 2 && fx != 0); + + let mut bb = [0u8; 16 * 17]; + if need_b { + // "s" is the same filter one row down, so row fy>>1 selects b or s. + let row0 = yi + if fy == 3 { 1 } else { 0 }; + for row in 0..h { + let src = r.at(xi, row0 + row as i32); + for col in 0..w { + bb[row * w + col] = clip8((tap6(r.data, src + col, 1) + 16) >> 5); + } + } + } + let mut hh = [0u8; 16 * 17]; + if need_h { + // "m" is the same filter one column right, so column fx>>1 selects h or m. + let col0 = xi + if fx == 3 { 1 } else { 0 }; + for row in 0..h { + let src = r.at(col0, yi + row as i32); + for col in 0..w { + hh[row * w + col] = clip8((tap6(r.data, src + col, stride) + 16) >> 5); + } + } + } + let mut jj = [0u8; 16 * 16]; + if need_j { + // Equation 8-246: filter horizontally into intermediates, then + // vertically over those. The horizontal pass needs two rows above and + // three below the partition. + let mut inter = [0i32; TMP_W * (16 + 5)]; + for row in 0..h + 5 { + let src = r.at(xi, yi + row as i32 - 2); + for col in 0..w { + inter[row * TMP_W + col] = tap6(r.data, src + col, 1); + } + } + for row in 0..h { + for col in 0..w { + let v = tap6_i32(&inter, (row + 2) * TMP_W + col, TMP_W); + jj[row * w + col] = clip8((v + 512) >> 10); + } + } + } + + for row in 0..h { + for col in 0..w { + let i = row * w + col; + let g = |dx: i32, dy: i32| r.data[base + (row as i32 + dy) as usize * stride + + (col as i32 + dx) as usize]; + out[i] = match (fx, fy) { + // Table 8-12, quarter positions on the integer rows/columns. + (1, 0) => avg(g(0, 0), bb[i]), + (2, 0) => bb[i], + (3, 0) => avg(g(1, 0), bb[i]), + (0, 1) => avg(g(0, 0), hh[i]), + (0, 2) => hh[i], + (0, 3) => avg(g(0, 1), hh[i]), + // Centre column / row: mix with the centre sample j. + (2, 1) | (2, 3) => avg(bb[i], jj[i]), + (1, 2) | (3, 2) => avg(hh[i], jj[i]), + (2, 2) => jj[i], + // Diagonal quarter positions: the two nearest half samples. + _ => avg(bb[i], hh[i]), + }; + } + } +} + +/// Chroma eighth-sample interpolation (Equation 8-270) of a `w` x `h` block. +pub(crate) fn mc_chroma( + r: &RefPlane<'_>, + x: i32, + y: i32, + mv: [i16; 2], + w: usize, + h: usize, + out: &mut [u8], +) { + let (fx, fy) = ((mv[0] & 7) as i32, (mv[1] & 7) as i32); + let xi = clamp_origin(x + (mv[0] as i32 >> 3), w, r.width, r.pad, 0, 1); + let yi = clamp_origin(y + (mv[1] as i32 >> 3), h, r.height, r.pad, 0, 1); + let stride = r.stride; + let base = r.at(xi, yi); + let (wa, wb, wc, wd) = ( + (8 - fx) * (8 - fy), + fx * (8 - fy), + (8 - fx) * fy, + fx * fy, + ); + for row in 0..h { + let src = base + row * stride; + for col in 0..w { + let a = i32::from(r.data[src + col]); + let b = i32::from(r.data[src + col + 1]); + let c = i32::from(r.data[src + col + stride]); + let d = i32::from(r.data[src + col + stride + 1]); + out[row * w + col] = ((wa * a + wb * b + wc * c + wd * d + 32) >> 6) as u8; + } + } +} + +/// Weights of one component for one partition (spec 8.4.3), already resolved +/// to the explicit/implicit/default case. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct Weights { + /// `logWDC`. + pub log_wd: i32, + /// `w0C`, `w1C`. + pub w: [i32; 2], + /// `o0C`, `o1C`. + pub o: [i32; 2], +} + +impl Weights { + /// The identity weighting, which reproduces 8.4.2.3.1 exactly. + pub(crate) const DEFAULT: Weights = Weights { + log_wd: 0, + w: [1, 1], + o: [0, 0], + }; + + fn is_default(&self) -> bool { + *self == Weights::DEFAULT + } +} + +/// Combine the list predictions of one partition into the final prediction +/// (spec 8.4.2.3). `p0`/`p1` hold `n` samples each; the entry for a list that +/// is not used is ignored. +pub(crate) fn combine( + out: &mut [u8], + p0: &[u8], + p1: &[u8], + use0: bool, + use1: bool, + wt: &Weights, + n: usize, +) { + if wt.is_default() { + // 8.4.2.3.1. + match (use0, use1) { + (true, false) => out[..n].copy_from_slice(&p0[..n]), + (false, true) => out[..n].copy_from_slice(&p1[..n]), + _ => { + for i in 0..n { + out[i] = avg(p0[i], p1[i]); + } + } + } + return; + } + // 8.4.2.3.2. + if use0 && use1 { + let round = 1 << wt.log_wd; + let off = (wt.o[0] + wt.o[1] + 1) >> 1; + for i in 0..n { + let v = (i32::from(p0[i]) * wt.w[0] + i32::from(p1[i]) * wt.w[1] + round) + >> (wt.log_wd + 1); + out[i] = clip8(v + off); + } + return; + } + let (src, k) = if use0 { (p0, 0) } else { (p1, 1) }; + if wt.log_wd >= 1 { + let round = 1 << (wt.log_wd - 1); + for i in 0..n { + out[i] = clip8(((i32::from(src[i]) * wt.w[k] + round) >> wt.log_wd) + wt.o[k]); + } + } else { + for i in 0..n { + out[i] = clip8(i32::from(src[i]) * wt.w[k] + wt.o[k]); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// A plane whose interior is a known ramp and whose borders are replicated, + /// the way `Plane8::extend_borders` leaves them. + fn ramp_plane(w: usize, h: usize, pad: usize) -> (Vec, usize, usize) { + let stride = w + 2 * pad; + let origin = pad * stride + pad; + let mut data = vec![0u8; stride * (h + 2 * pad)]; + for y in 0..h { + for x in 0..w { + data[origin + y * stride + x] = ((x * 3 + y * 7) % 251) as u8; + } + } + for y in 0..h { + let row = origin + y * stride; + let (l, r) = (data[row], data[row + w - 1]); + data[row - pad..row].fill(l); + data[row + w..row + w + pad].fill(r); + } + for y in 0..pad { + let top = origin - (y + 1) * stride - pad; + let src = origin - pad; + let (a, b) = data.split_at_mut(src); + a[top..top + stride].copy_from_slice(&b[..stride]); + let bot = origin + (h + y) * stride - pad; + let src = origin + (h - 1) * stride - pad; + let (a, b) = data.split_at_mut(bot); + b[..stride].copy_from_slice(&a[src..src + stride]); + } + (data, stride, origin) + } + + fn plane(data: &[u8], stride: usize, origin: usize, w: usize, h: usize, pad: usize) -> RefPlane<'_> { + RefPlane { + data, + stride, + origin, + width: w, + height: h, + pad, + } + } + + /// The spec's clipped, per-sample definition of the same interpolation, + /// written straight from Equations 8-239 to 8-261 with no padding tricks. + fn spec_luma( + pic: &[u8], + stride: usize, + origin: usize, + w: usize, + h: usize, + x: i32, + y: i32, + mv: [i16; 2], + pw: usize, + ph: usize, + out: &mut [u8], + ) { + let s = |px: i32, py: i32| -> i32 { + let cx = px.clamp(0, w as i32 - 1) as usize; + let cy = py.clamp(0, h as i32 - 1) as usize; + i32::from(pic[origin + cy * stride + cx]) + }; + let hf = |px: i32, py: i32| { + s(px - 2, py) - 5 * s(px - 1, py) + 20 * s(px, py) + 20 * s(px + 1, py) + - 5 * s(px + 2, py) + + s(px + 3, py) + }; + let vf = |px: i32, py: i32| { + s(px, py - 2) - 5 * s(px, py - 1) + 20 * s(px, py) + 20 * s(px, py + 1) + - 5 * s(px, py + 2) + + s(px, py + 3) + }; + let j1 = |px: i32, py: i32| { + let t = |k: i32| hf(px, py + k); + t(-2) - 5 * t(-1) + 20 * t(0) + 20 * t(1) - 5 * t(2) + t(3) + }; + let (fx, fy) = ((mv[0] & 3) as i32, (mv[1] & 3) as i32); + let (xi, yi) = (x + (mv[0] as i32 >> 2), y + (mv[1] as i32 >> 2)); + for row in 0..ph { + for col in 0..pw { + let (px, py) = (xi + col as i32, yi + row as i32); + let g = |dx: i32, dy: i32| s(px + dx, py + dy) as u8; + let b = |dy: i32| clip8((hf(px, py + dy) + 16) >> 5); + let hs = |dx: i32| clip8((vf(px + dx, py) + 16) >> 5); + let j = clip8((j1(px, py) + 512) >> 10); + out[row * pw + col] = match (fx, fy) { + (0, 0) => g(0, 0), + (1, 0) => avg(g(0, 0), b(0)), + (2, 0) => b(0), + (3, 0) => avg(g(1, 0), b(0)), + (0, 1) => avg(g(0, 0), hs(0)), + (0, 2) => hs(0), + (0, 3) => avg(g(0, 1), hs(0)), + (1, 1) => avg(b(0), hs(0)), + (3, 1) => avg(b(0), hs(1)), + (1, 3) => avg(hs(0), b(1)), + (3, 3) => avg(hs(1), b(1)), + (2, 1) => avg(b(0), j), + (2, 3) => avg(b(1), j), + (1, 2) => avg(hs(0), j), + (3, 2) => avg(hs(1), j), + _ => j, + }; + } + } + } + + /// Every fractional position, at interior positions and far outside the + /// picture, agrees with the spec's clipped definition. + #[test] + fn luma_interpolation_matches_the_clipped_definition() { + let (w, h, pad) = (48usize, 32usize, 32usize); + let (data, stride, origin) = ramp_plane(w, h, pad); + let r = plane(&data, stride, origin, w, h, pad); + let mut ours = [0u8; 256]; + let mut theirs = [0u8; 256]; + for &(px, py) in &[(8i32, 8i32), (0, 0), (32, 16), (-40, -40), (60, 44), (44, 4)] { + for fy in 0..4i16 { + for fx in 0..4i16 { + for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] { + let mv = [fx - 20 * 4, fy + 12]; + mc_luma(&r, px, py, mv, pw, ph, &mut ours); + spec_luma( + &data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs, + ); + assert_eq!( + ours[..pw * ph], + theirs[..pw * ph], + "({px},{py}) frac ({fx},{fy}) {pw}x{ph}" + ); + } + } + } + } + } + + #[test] + fn chroma_interpolation_matches_equation_8_270() { + let (w, h, pad) = (24usize, 16usize, 16usize); + let (data, stride, origin) = ramp_plane(w, h, pad); + let r = plane(&data, stride, origin, w, h, pad); + let mut ours = [0u8; 64]; + for &(px, py) in &[(4i32, 4i32), (0, 0), (-30, -30), (30, 22)] { + for fy in 0..8i16 { + for fx in 0..8i16 { + let mv = [fx, fy]; + mc_chroma(&r, px, py, mv, 8, 8, &mut ours); + for row in 0..8i32 { + for col in 0..8i32 { + let s = |dx: i32, dy: i32| -> i32 { + let cx = (px + col + dx).clamp(0, w as i32 - 1) as usize; + let cy = (py + row + dy).clamp(0, h as i32 - 1) as usize; + i32::from(data[origin + cy * stride + cx]) + }; + let (fx, fy) = (i32::from(fx), i32::from(fy)); + let want = ((8 - fx) * (8 - fy) * s(0, 0) + + fx * (8 - fy) * s(1, 0) + + (8 - fx) * fy * s(0, 1) + + fx * fy * s(1, 1) + + 32) + >> 6; + assert_eq!( + i32::from(ours[(row * 8 + col) as usize]), + want, + "({px},{py}) frac ({fx},{fy}) at ({col},{row})" + ); + } + } + } + } + } + } + + #[test] + fn weighted_combination_follows_8_4_2_3() { + let p0 = [100u8; 4]; + let p1 = [200u8; 4]; + let mut out = [0u8; 4]; + combine(&mut out, &p0, &p1, true, true, &Weights::DEFAULT, 4); + assert_eq!(out, [150; 4]); + // Explicit, single list: ((100 * 2 + 2) >> 2) + 5 = 55. + let w = Weights { + log_wd: 2, + w: [2, 3], + o: [5, -5], + }; + combine(&mut out, &p0, &p1, true, false, &w, 4); + assert_eq!(out, [55; 4]); + // Explicit, both lists: ((100*2 + 200*3 + 4) >> 3) + ((5 - 5 + 1) >> 1). + combine(&mut out, &p0, &p1, true, true, &w, 4); + assert_eq!(out, [100; 4]); + // logWD 0 skips the rounding term entirely. + let w0 = Weights { + log_wd: 0, + w: [2, 1], + o: [3, 0], + }; + combine(&mut out, &p0, &p1, true, false, &w0, 4); + assert_eq!(out, [203; 4]); + } +} diff --git a/crates/ec-h264/src/lib.rs b/crates/ec-h264/src/lib.rs index f0c89054..fc1e06f3 100644 --- a/crates/ec-h264/src/lib.rs +++ b/crates/ec-h264/src/lib.rs @@ -1,9 +1,12 @@ //! H.264 software decoder. //! -//! Current scope: CAVLC-coded I slices (Intra_4x4, Intra_16x16, I_PCM) of -//! 8-bit 4:2:0 progressive streams, with the full in-loop deblocking filter, -//! decoded bit-exactly against the JVT conformance suite. Everything outside -//! that scope returns a named [`Error::Unsupported`] — never wrong output. +//! Current scope: I, P and B slices under both entropy coders (CAVLC and +//! CABAC) of 8-bit 4:2:0 progressive streams — intra prediction, inter +//! prediction with the full decoded picture buffer of clause 8.2, weighted +//! prediction, and the in-loop deblocking filter — decoded bit-exactly against +//! the JVT conformance suite. Frames come out in display order. Everything +//! outside that scope returns a named [`Error::Unsupported`] — never wrong +//! output. //! //! Implemented from Rec. ITU-T H.264 (V15, 08/2024) only; no third-party //! decoder source was consulted. @@ -37,11 +40,14 @@ mod cavlc; mod codec; mod deblock; mod decoder; +mod dpb; mod entropy; +mod inter; +mod mv; mod pred; mod tables; mod transform; pub use codec::H264Decoder; -pub use decoder::{Decoder, NalOutcome}; +pub use decoder::{Decoder, NalOutcome, OutputOrder}; pub use ec_core::error::{Error, Result}; diff --git a/crates/ec-h264/src/mv.rs b/crates/ec-h264/src/mv.rs new file mode 100644 index 00000000..686fe703 --- /dev/null +++ b/crates/ec-h264/src/mv.rs @@ -0,0 +1,448 @@ +//! Macroblock partitioning and motion vector derivation (spec 7.4.5, 8.4.1). +//! +//! Motion data lives in the picture's per-4x4-block arrays, written as each +//! partition is derived. Neighbour derivation (8.4.1.3.2) then reads those same +//! arrays, which is what makes "the partition inside this macroblock has not +//! been decoded yet" expressible: a bitmask of the blocks written so far stands +//! in for the availability rule of clause 6.4.11.7, exactly rather than +//! approximately. + +use crate::dpb::{BLK_DIRECT, BLK_INTRA, BLK_SKIP, Picture}; + +/// Prediction mode of a macroblock or sub-macroblock partition (Table 7-13, +/// 7-14, 7-17, 7-18). +#[derive(Clone, Copy, PartialEq, Eq, Debug)] +pub(crate) enum Pred { + /// Pred_L0. + L0, + /// Pred_L1. + L1, + /// BiPred. + Bi, + /// Direct (B_Skip, B_Direct_16x16, B_Direct_8x8). + Direct, +} + +impl Pred { + /// `(predFlagL0, predFlagL1)`; direct mode resolves later. + #[inline] + pub(crate) fn uses(self, list: usize) -> bool { + match self { + Pred::L0 => list == 0, + Pred::L1 => list == 1, + Pred::Bi => true, + Pred::Direct => false, + } + } +} + +/// The partitioning of one inter macroblock. +#[derive(Clone, Copy, Debug)] +pub(crate) struct MbShape { + /// `NumMbPart( mb_type )`. + pub parts: usize, + /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks. + pub w: usize, + pub h: usize, + /// `MbPartPredMode` of each partition. + pub pred: [Pred; 2], + /// mb_type is P_8x8/P_8x8ref0/B_8x8: sub-macroblock types follow. + pub sub: bool, +} + +const fn shape(parts: usize, w: usize, h: usize, p0: Pred, p1: Pred) -> MbShape { + MbShape { + parts, + w, + h, + pred: [p0, p1], + sub: false, + } +} + +const SUB8X8: MbShape = MbShape { + parts: 4, + w: 2, + h: 2, + pred: [Pred::L0, Pred::L0], + sub: true, +}; + +/// Table 7-13, mb_type 0..4 of a P or SP slice. +pub(crate) const P_SHAPES: [MbShape; 5] = [ + shape(1, 4, 4, Pred::L0, Pred::L0), + shape(2, 4, 2, Pred::L0, Pred::L0), + shape(2, 2, 4, Pred::L0, Pred::L0), + SUB8X8, + SUB8X8, // P_8x8ref0: same partitioning, ref_idx inferred 0. +]; + +/// Table 7-14, mb_type 0..22 of a B slice. +pub(crate) const B_SHAPES: [MbShape; 23] = [ + shape(1, 4, 4, Pred::Direct, Pred::Direct), + shape(1, 4, 4, Pred::L0, Pred::L0), + shape(1, 4, 4, Pred::L1, Pred::L1), + shape(1, 4, 4, Pred::Bi, Pred::Bi), + shape(2, 4, 2, Pred::L0, Pred::L0), + shape(2, 2, 4, Pred::L0, Pred::L0), + shape(2, 4, 2, Pred::L1, Pred::L1), + shape(2, 2, 4, Pred::L1, Pred::L1), + shape(2, 4, 2, Pred::L0, Pred::L1), + shape(2, 2, 4, Pred::L0, Pred::L1), + shape(2, 4, 2, Pred::L1, Pred::L0), + shape(2, 2, 4, Pred::L1, Pred::L0), + shape(2, 4, 2, Pred::L0, Pred::Bi), + shape(2, 2, 4, Pred::L0, Pred::Bi), + shape(2, 4, 2, Pred::L1, Pred::Bi), + shape(2, 2, 4, Pred::L1, Pred::Bi), + shape(2, 4, 2, Pred::Bi, Pred::L0), + shape(2, 2, 4, Pred::Bi, Pred::L0), + shape(2, 4, 2, Pred::Bi, Pred::L1), + shape(2, 2, 4, Pred::Bi, Pred::L1), + shape(2, 4, 2, Pred::Bi, Pred::Bi), + shape(2, 2, 4, Pred::Bi, Pred::Bi), + SUB8X8, +]; + +/// The partitioning of one 8x8 sub-macroblock. +#[derive(Clone, Copy, Debug)] +pub(crate) struct SubShape { + /// `NumSubMbPart( sub_mb_type )`. + pub parts: usize, + /// `SubMbPartWidth`/`SubMbPartHeight` in 4x4 blocks. + pub w: usize, + pub h: usize, + /// `SubMbPredMode`. + pub pred: Pred, +} + +const fn sub(parts: usize, w: usize, h: usize, pred: Pred) -> SubShape { + SubShape { parts, w, h, pred } +} + +/// Table 7-17, sub_mb_type of a P macroblock. +pub(crate) const P_SUB: [SubShape; 4] = [ + sub(1, 2, 2, Pred::L0), + sub(2, 2, 1, Pred::L0), + sub(2, 1, 2, Pred::L0), + sub(4, 1, 1, Pred::L0), +]; + +/// Table 7-18, sub_mb_type of a B macroblock. +pub(crate) const B_SUB: [SubShape; 13] = [ + sub(4, 1, 1, Pred::Direct), + sub(1, 2, 2, Pred::L0), + sub(1, 2, 2, Pred::L1), + sub(1, 2, 2, Pred::Bi), + sub(2, 2, 1, Pred::L0), + sub(2, 1, 2, Pred::L0), + sub(2, 2, 1, Pred::L1), + sub(2, 1, 2, Pred::L1), + sub(2, 2, 1, Pred::Bi), + sub(2, 1, 2, Pred::Bi), + sub(4, 1, 1, Pred::L0), + sub(4, 1, 1, Pred::L1), + sub(4, 1, 1, Pred::Bi), +]; + +/// Motion data of one neighbouring partition (8.4.1.3.2). +#[derive(Clone, Copy, Debug, Default)] +pub(crate) struct Nb { + /// The partition exists and has been decoded (clause 6.4.11.7). + pub avail: bool, + pub mv: [i16; 2], + /// -1 when the neighbour does not use this list, or is intra. + pub ref_idx: i8, +} + +/// Where the current macroblock's motion data is being written, and which of +/// its 4x4 blocks already carry it. +pub(crate) struct MvCtx { + pub mb_x: usize, + pub mb_y: usize, + pub slice_id: u16, + /// Bit `y * 4 + x` set once block (x, y) of this macroblock is derived. + pub written: u16, +} + +impl MvCtx { + /// Motion data of the 4x4 block at picture block coordinates `(bx, by)`, + /// for list `list`. + pub(crate) fn at(&self, pic: &Picture, bx: i32, by: i32, list: usize) -> Nb { + let w4 = (pic.mb_w * 4) as i32; + let h4 = (pic.mb_h * 4) as i32; + if bx < 0 || by < 0 || bx >= w4 || by >= h4 { + return Nb::default(); + } + let (mbx, mby) = (bx as usize / 4, by as usize / 4); + let addr = mby * pic.mb_w + mbx; + if mbx == self.mb_x && mby == self.mb_y { + let within = (by as usize % 4) * 4 + bx as usize % 4; + if self.written & (1 << within) == 0 { + return Nb::default(); + } + } else if pic.mb_slice[addr] != self.slice_id { + return Nb::default(); + } + let idx = by as usize * pic.mb_w * 4 + bx as usize; + if pic.blk[idx] & BLK_INTRA != 0 { + // Available as a partition, but contributes no motion (8.4.1.3.2). + return Nb { + avail: true, + mv: [0; 2], + ref_idx: -1, + }; + } + Nb { + avail: true, + mv: pic.mv[idx][list], + ref_idx: pic.ref_idx[idx][list], + } + } + + /// Neighbours A, B and C of a partition whose top-left 4x4 block is at + /// macroblock-relative `(px, py)` and whose `predPartWidth` is `pw` blocks + /// (clause 6.4.11.7, with the C-to-D substitution of 8-214). + pub(crate) fn neighbours(&self, pic: &Picture, px: usize, py: usize, pw: usize, list: usize) -> [Nb; 3] { + let bx = (self.mb_x * 4 + px) as i32; + let by = (self.mb_y * 4 + py) as i32; + let a = self.at(pic, bx - 1, by, list); + let b = self.at(pic, bx, by - 1, list); + let mut c = self.at(pic, bx + pw as i32, by - 1, list); + if !c.avail { + c = self.at(pic, bx - 1, by - 1, list); + } + [a, b, c] + } +} + +#[inline] +fn median(a: i16, b: i16, c: i16) -> i16 { + a.max(b).min(a.min(b).max(c)) +} + +/// Motion vector prediction (clause 8.4.1.3), including the directional +/// segmentation shortcuts of Equations 8-203 to 8-206. +/// +/// `part_w`/`part_h` are `MbPartWidth`/`MbPartHeight` in 4x4 blocks and only +/// select those shortcuts; `part` is the macroblock partition index. +pub(crate) fn predict_mv(n: &[Nb; 3], ref_idx: i8, part_w: usize, part_h: usize, part: usize) -> [i16; 2] { + let [a, mut b, mut c] = *n; + match (part_w, part_h, part) { + (4, 2, 0) if b.ref_idx == ref_idx => return b.mv, + (4, 2, 1) if a.ref_idx == ref_idx => return a.mv, + (2, 4, 0) if a.ref_idx == ref_idx => return a.mv, + (2, 4, 1) if c.ref_idx == ref_idx => return c.mv, + _ => {} + } + // 8.4.1.3.1 step 1. + if !b.avail && !c.avail && a.avail { + b = a; + c = a; + } + let matches = u8::from(a.ref_idx == ref_idx) + + u8::from(b.ref_idx == ref_idx) + + u8::from(c.ref_idx == ref_idx); + if matches == 1 { + if a.ref_idx == ref_idx { + return a.mv; + } + if b.ref_idx == ref_idx { + return b.mv; + } + return c.mv; + } + [ + median(a.mv[0], b.mv[0], c.mv[0]), + median(a.mv[1], b.mv[1], c.mv[1]), + ] +} + +/// `MinPositive` (Equation 8-187). +#[inline] +pub(crate) fn min_positive(x: i8, y: i8) -> i8 { + if x >= 0 && y >= 0 { x.min(y) } else { x.max(y) } +} + +/// Record one 4x4 block's motion data into the picture arrays. +#[allow(clippy::too_many_arguments)] +pub(crate) fn write_block( + pic: &mut Picture, + ctx: &mut MvCtx, + px: usize, + py: usize, + mv: [[i16; 2]; 2], + ref_idx: [i8; 2], + ref_id: [i32; 2], + flags: u8, +) { + let bx = ctx.mb_x * 4 + px; + let by = ctx.mb_y * 4 + py; + let idx = by * pic.mb_w * 4 + bx; + pic.mv[idx] = mv; + pic.ref_idx[idx] = ref_idx; + pic.ref_id[idx] = ref_id; + pic.blk[idx] = flags; + ctx.written |= 1 << (py * 4 + px); +} + +/// Mark every 4x4 block of the current macroblock as intra, clearing the motion +/// data an inter neighbour would otherwise read (8.4.1.3.2, 9.3.3.1.1.7). +pub(crate) fn write_intra_mb(pic: &mut Picture, mb_x: usize, mb_y: usize) { + let w4 = pic.mb_w * 4; + for py in 0..4 { + let base = (mb_y * 4 + py) * w4 + mb_x * 4; + for idx in base..base + 4 { + pic.mv[idx] = [[0; 2]; 2]; + pic.ref_idx[idx] = [-1; 2]; + pic.ref_id[idx] = [-1; 2]; + pic.mvd_abs[idx] = [0; 4]; + pic.blk[idx] = BLK_INTRA; + } + } +} + +/// Record `Abs( mvd )` for one 4x4 block, saturated at the largest value the +/// context thresholds of 9.3.3.1.1.7 can distinguish. +#[inline] +pub(crate) fn write_mvd(pic: &mut Picture, mb_x: usize, mb_y: usize, px: usize, py: usize, list: usize, mvd: [i16; 2]) { + let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px; + let e = &mut pic.mvd_abs[idx]; + e[list * 2] = mvd[0].unsigned_abs().min(127) as u8; + e[list * 2 + 1] = mvd[1].unsigned_abs().min(127) as u8; +} + +/// `absMvdCompN` of the neighbouring partition at picture block coordinates +/// `(bx, by)` (9.3.3.1.1.7): zero when the neighbour is unavailable, skipped, +/// intra or direct coded. +pub(crate) fn neighbour_mvd(pic: &Picture, ctx: &MvCtx, bx: i32, by: i32, list: usize) -> [u32; 2] { + let w4 = (pic.mb_w * 4) as i32; + let h4 = (pic.mb_h * 4) as i32; + if bx < 0 || by < 0 || bx >= w4 || by >= h4 { + return [0; 2]; + } + let (mbx, mby) = (bx as usize / 4, by as usize / 4); + if mbx == ctx.mb_x && mby == ctx.mb_y { + let within = (by as usize % 4) * 4 + bx as usize % 4; + if ctx.written & (1 << within) == 0 { + return [0; 2]; + } + } else if pic.mb_slice[mby * pic.mb_w + mbx] != ctx.slice_id { + return [0; 2]; + } + let idx = by as usize * pic.mb_w * 4 + bx as usize; + if pic.blk[idx] & (BLK_INTRA | BLK_SKIP | BLK_DIRECT) != 0 || pic.ref_idx[idx][list] < 0 { + return [0; 2]; + } + let e = pic.mvd_abs[idx]; + [u32::from(e[list * 2]), u32::from(e[list * 2 + 1])] +} + +/// `condTermFlagN` for ref_idx_lX (9.3.3.1.1.6). +pub(crate) fn ref_idx_cond(pic: &Picture, ctx: &MvCtx, bx: i32, by: i32, list: usize) -> usize { + let w4 = (pic.mb_w * 4) as i32; + let h4 = (pic.mb_h * 4) as i32; + if bx < 0 || by < 0 || bx >= w4 || by >= h4 { + return 0; + } + let (mbx, mby) = (bx as usize / 4, by as usize / 4); + if mbx == ctx.mb_x && mby == ctx.mb_y { + let within = (by as usize % 4) * 4 + bx as usize % 4; + if ctx.written & (1 << within) == 0 { + return 0; + } + } else if pic.mb_slice[mby * pic.mb_w + mbx] != ctx.slice_id { + return 0; + } + let idx = by as usize * pic.mb_w * 4 + bx as usize; + if pic.blk[idx] & (BLK_INTRA | BLK_SKIP | BLK_DIRECT) != 0 { + return 0; + } + usize::from(pic.ref_idx[idx][list] > 0) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn nb(avail: bool, mv: [i16; 2], ref_idx: i8) -> Nb { + Nb { + avail, + mv, + ref_idx, + } + } + + /// With exactly one neighbour on the same reference picture, that + /// neighbour's vector is the prediction (Equation 8-211). + #[test] + fn single_matching_reference_wins() { + let n = [ + nb(true, [4, 4], 1), + nb(true, [8, 8], 0), + nb(true, [12, 12], 2), + ]; + assert_eq!(predict_mv(&n, 0, 4, 4, 0), [8, 8]); + } + + /// Otherwise the prediction is the component-wise median (8-212, 8-213). + #[test] + fn median_of_three_when_several_match() { + let n = [ + nb(true, [4, -8], 0), + nb(true, [8, 2], 0), + nb(true, [-2, 6], 1), + ]; + assert_eq!(predict_mv(&n, 0, 4, 4, 0), [4, 2]); + } + + /// B and C unavailable with A available copies A into both, which turns the + /// median into A (8-207 to 8-210). + #[test] + fn unavailable_b_and_c_fall_back_to_a() { + let n = [nb(true, [6, -6], 3), nb(false, [0, 0], -1), nb(false, [0, 0], -1)]; + assert_eq!(predict_mv(&n, 0, 4, 4, 0), [6, -6]); + // With refIdx 3 the single-match rule fires first, same answer. + assert_eq!(predict_mv(&n, 3, 4, 4, 0), [6, -6]); + } + + /// The 16x8 and 8x16 shortcuts bypass the median entirely. + #[test] + fn directional_segmentation_shortcuts() { + let n = [ + nb(true, [1, 1], 0), + nb(true, [2, 2], 0), + nb(true, [3, 3], 0), + ]; + assert_eq!(predict_mv(&n, 0, 4, 2, 0), [2, 2], "16x8 part 0 takes B"); + assert_eq!(predict_mv(&n, 0, 4, 2, 1), [1, 1], "16x8 part 1 takes A"); + assert_eq!(predict_mv(&n, 0, 2, 4, 0), [1, 1], "8x16 part 0 takes A"); + assert_eq!(predict_mv(&n, 0, 2, 4, 1), [3, 3], "8x16 part 1 takes C"); + // A shortcut that does not match the reference index falls through. + assert_eq!(predict_mv(&n, 1, 4, 2, 0), [2, 2], "median of 1,2,3"); + } + + #[test] + fn min_positive_prefers_the_non_negative() { + assert_eq!(min_positive(2, 5), 2); + assert_eq!(min_positive(-1, 5), 5); + assert_eq!(min_positive(-1, -1), -1); + assert_eq!(min_positive(0, -1), 0); + } + + /// Every B macroblock type maps to the partition shape Table 7-14 states. + #[test] + fn b_shapes_match_table_7_14() { + assert_eq!(B_SHAPES[0].pred[0], Pred::Direct); + assert_eq!((B_SHAPES[3].parts, B_SHAPES[3].pred[0]), (1, Pred::Bi)); + // The 16x8 / 8x16 pairs alternate, starting at mb_type 4. + for t in 4..22 { + let s = B_SHAPES[t]; + assert_eq!(s.parts, 2, "mb_type {t}"); + let (w, h) = if t % 2 == 0 { (4, 2) } else { (2, 4) }; + assert_eq!((s.w, s.h), (w, h), "mb_type {t}"); + } + assert!(B_SHAPES[22].sub); + assert!(P_SHAPES[3].sub && P_SHAPES[4].sub); + } +} diff --git a/crates/ec-h264/src/tables.rs b/crates/ec-h264/src/tables.rs index 0ec97456..09fba7c8 100644 --- a/crates/ec-h264/src/tables.rs +++ b/crates/ec-h264/src/tables.rs @@ -468,6 +468,13 @@ pub const CBP_INTRA_420: [u8; 48] = [ 35, 37, 42, 44, 1, 2, 4, 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41, ]; +/// Table 9-4 (a), Inter column: codeNum -> coded_block_pattern for +/// ChromaArrayType 1 or 2. +pub const CBP_INTER_420: [u8; 48] = [ + 0, 16, 1, 2, 4, 8, 32, 3, 5, 10, 12, 15, 47, 7, 11, 13, 14, 6, 9, 31, 35, 37, 42, 44, 33, 34, + 36, 40, 39, 43, 45, 46, 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41, +]; + /// Table 9-4 (b), Intra column: codeNum -> coded_block_pattern for /// ChromaArrayType 0 or 3. Unused until monochrome / 4:4:4 decode lands; /// kept beside its sibling so the spec table lives in one place. @@ -510,14 +517,19 @@ pub const BETA: [u8; 52] = [ ]; /// Table 8-17: tC0' by [bS - 1][indexA]. +/// +/// The bS 1 and 2 rows are unreachable from an intra-only decoder, so they went +/// in transcribed but unexercised and both were wrong — a whole-row shift, the +/// classic transcription defect. They are re-derived here from the printed +/// table and now carry oracle coverage (inter edges reach every row). pub const TC0: [[u8; 52]; 3] = [ [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, + 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, 9, 10, 11, 13, ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, - 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 8, 8, 10, 11, 12, 13, 15, + 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 8, 8, 10, 11, 12, 13, 15, 17, ], [ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 2, 2, 2,