Inter prediction, decoded picture buffer, display-order output
Browse files at this commitcd996f4051d004f8d0474490a8e9067a1ed7bb8aParent: 6432e08- feat
- inter prediction, decoded picture buffer, display-order output
11 changed files +4411 -537
- crates/ec-h264-syntax/src/lib.rs +5 -2
- crates/ec-h264/src/cabac.rs +232 -36
- crates/ec-h264/src/cabac_tables.rs +292 -224
- crates/ec-h264/src/codec.rs +36 -14
- crates/ec-h264/src/decoder.rs +1476 -251
- crates/ec-h264/src/dpb.rs +1277 -0
- crates/ec-h264/src/entropy.rs +137 -3
- crates/ec-h264/src/inter.rs +483 -0
- crates/ec-h264/src/lib.rs +11 -5
- crates/ec-h264/src/mv.rs +448 -0
- crates/ec-h264/src/tables.rs +14 -2
crates/ec-h264-syntax/src/lib.rsmodified+5 -2
| @@ -22,8 +22,11 @@ pub mod sps; | |||
| 22 | 22 | ||
| 23 | pub use nal::{AnnexBIter, NalHeader, NalUnitType, unescape_rbsp}; | 23 | pub use nal::{AnnexBIter, NalHeader, NalUnitType, unescape_rbsp}; |
| 24 | pub use pps::Pps; | 24 | pub use pps::Pps; |
| 25 | -pub use slice::{DeblockControl, SliceHeader, SliceType}; | 25 | +pub use slice::{ |
| 26 | -pub use sps::{Hrd, ScalingLists, Sps, Vui}; | 26 | + DeblockControl, DecRefPicMarking, Mmco, PredWeightTable, RefPicListMod, SliceHeader, |
| 27 | + SliceType, WeightEntry, | ||
| 28 | +}; | ||
| 29 | +pub use sps::{BitstreamRestriction, Hrd, ScalingLists, Sps, Vui}; | ||
| 27 | 30 | ||
| 28 | /// True when there is at least one more RBSP syntax element before the | 31 | /// True when there is at least one more RBSP syntax element before the |
| 29 | /// `rbsp_stop_one_bit` (spec 7.2 `more_rbsp_data()`). | 32 | /// `rbsp_stop_one_bit` (spec 7.2 `more_rbsp_data()`). |
crates/ec-h264/src/cabac.rsmodified+232 -36
| @@ -1,10 +1,10 @@ | |||
| 1 | //! CABAC slice-data parsing (spec clause 9.3): arithmetic decoding engine, | 1 | //! CABAC slice-data parsing (spec clause 9.3): arithmetic decoding engine, |
| 2 | //! context variables, binarizations and context selection. | 2 | //! context variables, binarizations and context selection. |
| 3 | //! | 3 | //! |
| 4 | -//! Scope is what an I slice of a frame-coded 4:2:0 8-bit stream needs; every | 4 | +//! Scope is what a frame-coded 4:2:0 8-bit stream needs, I, P and B; every |
| 5 | //! other tool the decoder refuses by name before reaching this module, so the | 5 | //! other tool the decoder refuses by name before reaching this module, so the |
| 6 | -//! contexts, block categories and initialisation columns that only P, B, field | 6 | +//! contexts, block categories and initialisation columns that only field or |
| 7 | -//! or 8x8-transform coding reads are absent rather than transcribed untested. | 7 | +//! 8x8-transform coding reads are absent rather than transcribed untested. |
| 8 | //! | 8 | //! |
| 9 | //! The engine keeps codIRange and codIOffset in `u32` with the spec's exact | 9 | //! The engine keeps codIRange and codIOffset in `u32` with the spec's exact |
| 10 | //! integer steps — no probability floats, no shortcuts — and reads its bits | 10 | //! integer steps — no probability floats, no shortcuts — and reads its bits |
| @@ -17,12 +17,15 @@ use ec_core::error::{Error, Result}; | |||
| 17 | 17 | ||
| 18 | use crate::bits::BitCursor; | 18 | use crate::bits::BitCursor; |
| 19 | use crate::cabac_tables::{ | 19 | use crate::cabac_tables::{ |
| 20 | - INIT_60_69, INIT_70_275, INIT_399_401, INIT_MB_TYPE_I, RANGE_LPS, TRANS_LPS, TRANS_MPS, | 20 | + INIT_11_59, INIT_60_69, INIT_70_275, INIT_399_401, INIT_MB_TYPE_I, RANGE_LPS, TRANS_LPS, |
| 21 | + TRANS_MPS, | ||
| 22 | +}; | ||
| 23 | +use crate::entropy::{ | ||
| 24 | + BlockCat, FLAG_CHROMA_PRED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, MbCtx, MbInfo, | ||
| 21 | }; | 25 | }; |
| 22 | -use crate::entropy::{BlockCat, FLAG_CHROMA_PRED, FLAG_I16, FLAG_PCM, MbCtx, MbInfo}; | ||
| 23 | 26 | ||
| 24 | /// Highest ctxIdx this decoder can address, plus one (399..401 is the | 27 | /// Highest ctxIdx this decoder can address, plus one (399..401 is the |
| 25 | -/// transform_size_8x8_flag block, the last range an I slice can reach). | 28 | +/// transform_size_8x8_flag block, the last range a frame-coded slice reaches). |
| 26 | const NUM_CTX: usize = 402; | 29 | const NUM_CTX: usize = 402; |
| 27 | 30 | ||
| 28 | /// ctxIdx 276 (end_of_slice_flag and the I_PCM bin of mb_type) is decoded by | 31 | /// 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]; | |||
| 36 | 39 | ||
| 37 | /// ctxIdxOffset values of Table 9-34 used here. | 40 | /// ctxIdxOffset values of Table 9-34 used here. |
| 38 | const OFF_MB_TYPE: usize = 3; | 41 | const OFF_MB_TYPE: usize = 3; |
| 42 | +const OFF_SKIP_P: usize = 11; | ||
| 43 | +const OFF_MB_TYPE_P: usize = 14; | ||
| 44 | +const OFF_SUB_TYPE_P: usize = 21; | ||
| 45 | +const OFF_SKIP_B: usize = 24; | ||
| 46 | +const OFF_MB_TYPE_B: usize = 27; | ||
| 47 | +const OFF_SUB_TYPE_B: usize = 36; | ||
| 48 | +const OFF_MVD: [usize; 2] = [40, 47]; | ||
| 49 | +const OFF_REF_IDX: usize = 54; | ||
| 39 | const OFF_QP_DELTA: usize = 60; | 50 | const OFF_QP_DELTA: usize = 60; |
| 40 | const OFF_CHROMA_PRED: usize = 64; | 51 | const OFF_CHROMA_PRED: usize = 64; |
| 41 | const OFF_PREV_I4: usize = 68; | 52 | const OFF_PREV_I4: usize = 68; |
| @@ -48,6 +59,18 @@ const OFF_LAST: usize = 166; | |||
| 48 | const OFF_ABS: usize = 227; | 59 | const OFF_ABS: usize = 227; |
| 49 | const OFF_TRANSFORM_8X8: usize = 399; | 60 | const OFF_TRANSFORM_8X8: usize = 399; |
| 50 | 61 | ||
| 62 | +/// The ctxIdx values the Intra_16x16 part of an mb_type bin string uses, in | ||
| 63 | +/// bin order: `[b0, CodedBlockPatternLuma, chroma bin 0, chroma bin 1, | ||
| 64 | +/// prediction mode bin 0, prediction mode bin 1]`. | ||
| 65 | +/// | ||
| 66 | +/// Table 9-39 lists these per binIdx, but the chroma element is one or two bins | ||
| 67 | +/// long, which shifts the prediction-mode bins; resolving the table to fixed | ||
| 68 | +/// ctxIdx values here is what makes the two spellings (I slice at ctxIdxOffset | ||
| 69 | +/// 3, intra suffix at 17 or 32) one piece of code. | ||
| 70 | +const I_MB_TYPE_CTX: [usize; 6] = [3, 6, 7, 8, 9, 10]; | ||
| 71 | +const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20]; | ||
| 72 | +const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35]; | ||
| 73 | + | ||
| 51 | pub(crate) struct Cabac<'a> { | 74 | pub(crate) struct Cabac<'a> { |
| 52 | r: BitCursor<'a>, | 75 | r: BitCursor<'a>, |
| 53 | /// codIRange (9.3.3.2). | 76 | /// codIRange (9.3.3.2). |
| @@ -61,12 +84,23 @@ pub(crate) struct Cabac<'a> { | |||
| 61 | /// CodedBlockPatternLuma bins decoded so far in this macroblock, for the | 84 | /// CodedBlockPatternLuma bins decoded so far in this macroblock, for the |
| 62 | /// within-macroblock neighbours of clause 9.3.3.1.1.4. | 85 | /// within-macroblock neighbours of clause 9.3.3.1.1.4. |
| 63 | cbp_luma_bins: u8, | 86 | cbp_luma_bins: u8, |
| 87 | + /// The macroblock being parsed is intra coded, which flips the | ||
| 88 | + /// coded_block_flag context of an unavailable neighbour (9.3.3.1.1.9). | ||
| 89 | + cur_intra: bool, | ||
| 64 | } | 90 | } |
| 65 | 91 | ||
| 66 | impl<'a> Cabac<'a> { | 92 | impl<'a> Cabac<'a> { |
| 67 | /// Start CABAC parsing at `header_bits`: `cabac_alignment_one_bit`s, then | 93 | /// Start CABAC parsing at `header_bits`: `cabac_alignment_one_bit`s, then |
| 68 | /// the context and engine initialisation of clause 9.3.1. | 94 | /// the context and engine initialisation of clause 9.3.1. |
| 69 | - pub(crate) fn new(rbsp: &'a [u8], header_bits: u64, slice_qp: i32) -> Result<Cabac<'a>> { | 95 | + /// |
| 96 | + /// `init_column` selects the initialisation column: 0 for I and SI slices, | ||
| 97 | + /// `cabac_init_idc + 1` otherwise. | ||
| 98 | + pub(crate) fn new( | ||
| 99 | + rbsp: &'a [u8], | ||
| 100 | + header_bits: u64, | ||
| 101 | + slice_qp: i32, | ||
| 102 | + init_column: usize, | ||
| 103 | + ) -> Result<Cabac<'a>> { | ||
| 70 | let mut r = BitCursor::new(rbsp, header_bits); | 104 | let mut r = BitCursor::new(rbsp, header_bits); |
| 71 | // cabac_alignment_one_bit (7.3.4): the stuffing bits are all 1, which | 105 | // cabac_alignment_one_bit (7.3.4): the stuffing bits are all 1, which |
| 72 | // a corrupt-stream check would only duplicate; skipping to the byte | 106 | // a corrupt-stream check would only duplicate; skipping to the byte |
| @@ -79,14 +113,15 @@ impl<'a> Cabac<'a> { | |||
| 79 | state: [63 << 1; NUM_CTX], | 113 | state: [63 << 1; NUM_CTX], |
| 80 | ctx: MbCtx::default(), | 114 | ctx: MbCtx::default(), |
| 81 | cbp_luma_bins: 0, | 115 | cbp_luma_bins: 0, |
| 116 | + cur_intra: true, | ||
| 82 | }; | 117 | }; |
| 83 | - c.init_contexts(slice_qp); | 118 | + c.init_contexts(slice_qp, init_column.min(3)); |
| 84 | c.init_engine()?; | 119 | c.init_engine()?; |
| 85 | Ok(c) | 120 | Ok(c) |
| 86 | } | 121 | } |
| 87 | 122 | ||
| 88 | /// 9.3.1.1: pStateIdx and valMPS from the (m, n) table entries and SliceQPY. | 123 | /// 9.3.1.1: pStateIdx and valMPS from the (m, n) table entries and SliceQPY. |
| 89 | - fn init_contexts(&mut self, slice_qp: i32) { | 124 | + fn init_contexts(&mut self, slice_qp: i32, column: usize) { |
| 90 | let qp = slice_qp.clamp(0, 51); | 125 | let qp = slice_qp.clamp(0, 51); |
| 91 | let set = |state: &mut [u8; NUM_CTX], idx: usize, (m, n): (i8, i8)| { | 126 | let set = |state: &mut [u8; NUM_CTX], idx: usize, (m, n): (i8, i8)| { |
| 92 | let pre = (((i32::from(m) * qp) >> 4) + i32::from(n)).clamp(1, 126); | 127 | let pre = (((i32::from(m) * qp) >> 4) + i32::from(n)).clamp(1, 126); |
| @@ -99,14 +134,17 @@ impl<'a> Cabac<'a> { | |||
| 99 | for (i, &mn) in INIT_MB_TYPE_I.iter().enumerate() { | 134 | for (i, &mn) in INIT_MB_TYPE_I.iter().enumerate() { |
| 100 | set(&mut self.state, i, mn); | 135 | set(&mut self.state, i, mn); |
| 101 | } | 136 | } |
| 137 | + for (i, &mn) in INIT_11_59.iter().enumerate() { | ||
| 138 | + set(&mut self.state, 11 + i, mn[column]); | ||
| 139 | + } | ||
| 102 | for (i, &mn) in INIT_60_69.iter().enumerate() { | 140 | for (i, &mn) in INIT_60_69.iter().enumerate() { |
| 103 | set(&mut self.state, 60 + i, mn); | 141 | set(&mut self.state, 60 + i, mn); |
| 104 | } | 142 | } |
| 105 | for (i, &mn) in INIT_70_275.iter().enumerate() { | 143 | for (i, &mn) in INIT_70_275.iter().enumerate() { |
| 106 | - set(&mut self.state, 70 + i, mn); | 144 | + set(&mut self.state, 70 + i, mn[column]); |
| 107 | } | 145 | } |
| 108 | for (i, &mn) in INIT_399_401.iter().enumerate() { | 146 | for (i, &mn) in INIT_399_401.iter().enumerate() { |
| 109 | - set(&mut self.state, OFF_TRANSFORM_8X8 + i, mn); | 147 | + set(&mut self.state, OFF_TRANSFORM_8X8 + i, mn[column]); |
| 110 | } | 148 | } |
| 111 | } | 149 | } |
| 112 | 150 | ||
| @@ -186,42 +224,193 @@ impl<'a> Cabac<'a> { | |||
| 186 | pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) { | 224 | pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) { |
| 187 | self.ctx = *ctx; | 225 | self.ctx = *ctx; |
| 188 | self.cbp_luma_bins = 0; | 226 | self.cbp_luma_bins = 0; |
| 227 | + self.cur_intra = true; | ||
| 189 | } | 228 | } |
| 190 | 229 | ||
| 191 | - /// 9.3.3.1.1.3: condTermFlagA + condTermFlagB for mb_type in an I slice, | 230 | + /// Declare whether the macroblock being parsed is intra coded |
| 192 | - /// where a neighbour counts unless it is I_NxN. | 231 | + /// (9.3.3.1.1.9 reads it for every coded_block_flag). |
| 193 | - fn mb_type_inc(&self) -> usize { | 232 | + pub(crate) fn set_intra(&mut self, intra: bool) { |
| 233 | + self.cur_intra = intra; | ||
| 234 | + } | ||
| 235 | + | ||
| 236 | + /// 9.3.3.1.1.3: condTermFlagA + condTermFlagB for mb_type. At ctxIdxOffset | ||
| 237 | + /// 3 a neighbour counts unless it is I_NxN; at 27 (B slices) unless it is | ||
| 238 | + /// B_Skip or B_Direct_16x16. | ||
| 239 | + fn mb_type_inc(&self, offset: usize) -> usize { | ||
| 194 | let cond = |n: Option<MbInfo>| match n { | 240 | let cond = |n: Option<MbInfo>| match n { |
| 195 | None => 0, | 241 | None => 0, |
| 196 | - Some(i) => usize::from(i.flags & (FLAG_I16 | FLAG_PCM) != 0), | 242 | + Some(i) if offset == OFF_MB_TYPE => usize::from(i.flags & (FLAG_I16 | FLAG_PCM) != 0), |
| 243 | + Some(i) => usize::from(i.flags & FLAG_DIRECT == 0), | ||
| 197 | }; | 244 | }; |
| 198 | cond(self.ctx.a) + cond(self.ctx.b) | 245 | cond(self.ctx.a) + cond(self.ctx.b) |
| 199 | } | 246 | } |
| 200 | 247 | ||
| 201 | /// mb_type of an I slice (Table 9-36). | 248 | /// mb_type of an I slice (Table 9-36). |
| 202 | pub(crate) fn mb_type_i(&mut self) -> Result<u32> { | 249 | pub(crate) fn mb_type_i(&mut self) -> Result<u32> { |
| 203 | - if !self.decision(OFF_MB_TYPE + self.mb_type_inc()) { | 250 | + let mut ctx = I_MB_TYPE_CTX; |
| 251 | + ctx[0] = OFF_MB_TYPE + self.mb_type_inc(OFF_MB_TYPE); | ||
| 252 | + self.mb_type_intra(&ctx) | ||
| 253 | + } | ||
| 254 | + | ||
| 255 | + /// The Intra part of an mb_type bin string (Table 9-36), whose `ctx` is | ||
| 256 | + /// resolved by [`I_MB_TYPE_CTX`]. `ctx[0]` has already had its neighbour | ||
| 257 | + /// increment applied where the offset uses one. | ||
| 258 | + fn mb_type_intra(&mut self, ctx: &[usize; 6]) -> Result<u32> { | ||
| 259 | + if !self.decision(ctx[0]) { | ||
| 204 | return Ok(0); // I_NxN | 260 | return Ok(0); // I_NxN |
| 205 | } | 261 | } |
| 206 | if self.terminate() { | 262 | if self.terminate() { |
| 207 | return Ok(25); // I_PCM | 263 | return Ok(25); // I_PCM |
| 208 | } | 264 | } |
| 209 | - // b2: CodedBlockPatternLuma 0 or 15; b3 (+ b4): CodedBlockPatternChroma; | 265 | + let cbp_luma = u32::from(self.decision(ctx[1])); |
| 210 | - // last two bins: Intra_16x16PredMode. The two prediction-mode bins keep | 266 | + let chroma = if !self.decision(ctx[2]) { |
| 211 | - // ctxIdx 9 and 10 either way (Table 9-39 row 3 with Table 9-41). | ||
| 212 | - let cbp_luma = u32::from(self.decision(OFF_MB_TYPE + 3)); | ||
| 213 | - let chroma = if !self.decision(OFF_MB_TYPE + 4) { | ||
| 214 | 0 | 267 | 0 |
| 215 | - } else if self.decision(OFF_MB_TYPE + 5) { | 268 | + } else if self.decision(ctx[3]) { |
| 216 | 2 | 269 | 2 |
| 217 | } else { | 270 | } else { |
| 218 | 1 | 271 | 1 |
| 219 | }; | 272 | }; |
| 220 | - let mode = u32::from(self.decision(OFF_MB_TYPE + 6)) * 2 | 273 | + let mode = u32::from(self.decision(ctx[4])) * 2 + u32::from(self.decision(ctx[5])); |
| 221 | - + u32::from(self.decision(OFF_MB_TYPE + 7)); | ||
| 222 | Ok(1 + mode + chroma * 4 + cbp_luma * 12) | 274 | Ok(1 + mode + chroma * 4 + cbp_luma * 12) |
| 223 | } | 275 | } |
| 224 | 276 | ||
| 277 | + /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB. | ||
| 278 | + pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool { | ||
| 279 | + let off = if b_slice { OFF_SKIP_B } else { OFF_SKIP_P }; | ||
| 280 | + self.decision(off + inc) | ||
| 281 | + } | ||
| 282 | + | ||
| 283 | + /// mb_type of a P or SP slice (Table 9-37): values 0..3, or 5 + the I-slice | ||
| 284 | + /// mb_type for an intra macroblock. | ||
| 285 | + pub(crate) fn mb_type_p(&mut self) -> Result<u32> { | ||
| 286 | + if self.decision(OFF_MB_TYPE_P) { | ||
| 287 | + return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?); | ||
| 288 | + } | ||
| 289 | + let b1 = self.decision(OFF_MB_TYPE_P + 1); | ||
| 290 | + // Table 9-41: binIdx 2 takes ctxIdxInc 2 when b1 is not 1, else 3. | ||
| 291 | + let b2 = self.decision(OFF_MB_TYPE_P + if b1 { 3 } else { 2 }); | ||
| 292 | + Ok(match (b1, b2) { | ||
| 293 | + (false, false) => 0, // P_L0_16x16 | ||
| 294 | + (false, true) => 3, // P_8x8 | ||
| 295 | + (true, true) => 1, // P_L0_L0_16x8 | ||
| 296 | + (true, false) => 2, // P_L0_L0_8x16 | ||
| 297 | + }) | ||
| 298 | + } | ||
| 299 | + | ||
| 300 | + /// mb_type of a B slice (Table 9-37): values 0..22, or 23 + the I-slice | ||
| 301 | + /// mb_type for an intra macroblock. | ||
| 302 | + pub(crate) fn mb_type_b(&mut self) -> Result<u32> { | ||
| 303 | + if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) { | ||
| 304 | + return Ok(0); // B_Direct_16x16 | ||
| 305 | + } | ||
| 306 | + if !self.decision(OFF_MB_TYPE_B + 3) { | ||
| 307 | + // "10x": B_L0_16x16 or B_L1_16x16. binIdx 2 with b1 == 0 takes 5. | ||
| 308 | + return Ok(1 + u32::from(self.decision(OFF_MB_TYPE_B + 5))); | ||
| 309 | + } | ||
| 310 | + let tail = OFF_MB_TYPE_B + 5; | ||
| 311 | + if !self.decision(OFF_MB_TYPE_B + 4) { | ||
| 312 | + // "110" + three bins: 3..10. | ||
| 313 | + let mut v = 0u32; | ||
| 314 | + for _ in 0..3 { | ||
| 315 | + v = v * 2 + u32::from(self.decision(tail)); | ||
| 316 | + } | ||
| 317 | + return Ok(3 + v); | ||
| 318 | + } | ||
| 319 | + if !self.decision(tail) { | ||
| 320 | + // "1110" + three bins: 12..19. | ||
| 321 | + let mut v = 0u32; | ||
| 322 | + for _ in 0..3 { | ||
| 323 | + v = v * 2 + u32::from(self.decision(tail)); | ||
| 324 | + } | ||
| 325 | + return Ok(12 + v); | ||
| 326 | + } | ||
| 327 | + if self.decision(tail) { | ||
| 328 | + // "11111": B_L1_L0_8x16 or B_8x8. | ||
| 329 | + return Ok(if self.decision(tail) { 22 } else { 11 }); | ||
| 330 | + } | ||
| 331 | + if self.decision(tail) { | ||
| 332 | + // "111101": the intra prefix. | ||
| 333 | + return Ok(23 + self.mb_type_intra(&I_SUFFIX_CTX_B)?); | ||
| 334 | + } | ||
| 335 | + // "111100" + one bin: B_Bi_Bi_16x8 or B_Bi_Bi_8x16. | ||
| 336 | + Ok(20 + u32::from(self.decision(tail))) | ||
| 337 | + } | ||
| 338 | + | ||
| 339 | + /// sub_mb_type of a P macroblock (Table 9-38). | ||
| 340 | + pub(crate) fn sub_mb_type_p(&mut self) -> u32 { | ||
| 341 | + if self.decision(OFF_SUB_TYPE_P) { | ||
| 342 | + return 0; | ||
| 343 | + } | ||
| 344 | + if !self.decision(OFF_SUB_TYPE_P + 1) { | ||
| 345 | + return 1; | ||
| 346 | + } | ||
| 347 | + if self.decision(OFF_SUB_TYPE_P + 2) { 2 } else { 3 } | ||
| 348 | + } | ||
| 349 | + | ||
| 350 | + /// sub_mb_type of a B macroblock (Table 9-38). | ||
| 351 | + pub(crate) fn sub_mb_type_b(&mut self) -> u32 { | ||
| 352 | + if !self.decision(OFF_SUB_TYPE_B) { | ||
| 353 | + return 0; // B_Direct_8x8 | ||
| 354 | + } | ||
| 355 | + let tail = OFF_SUB_TYPE_B + 3; | ||
| 356 | + if !self.decision(OFF_SUB_TYPE_B + 1) { | ||
| 357 | + return 1 + u32::from(self.decision(tail)); | ||
| 358 | + } | ||
| 359 | + if !self.decision(OFF_SUB_TYPE_B + 2) { | ||
| 360 | + let v = u32::from(self.decision(tail)) * 2 + u32::from(self.decision(tail)); | ||
| 361 | + return 3 + v; | ||
| 362 | + } | ||
| 363 | + if !self.decision(tail) { | ||
| 364 | + let v = u32::from(self.decision(tail)) * 2 + u32::from(self.decision(tail)); | ||
| 365 | + return 7 + v; | ||
| 366 | + } | ||
| 367 | + 11 + u32::from(self.decision(tail)) | ||
| 368 | + } | ||
| 369 | + | ||
| 370 | + /// ref_idx_lX: unary, with the neighbour increment of 9.3.3.1.1.6 on the | ||
| 371 | + /// first bin (Table 9-39 row 54). | ||
| 372 | + pub(crate) fn ref_idx(&mut self, inc: usize) -> Result<u32> { | ||
| 373 | + if !self.decision(OFF_REF_IDX + inc) { | ||
| 374 | + return Ok(0); | ||
| 375 | + } | ||
| 376 | + if !self.decision(OFF_REF_IDX + 4) { | ||
| 377 | + return Ok(1); | ||
| 378 | + } | ||
| 379 | + let mut v = 2u32; | ||
| 380 | + while self.decision(OFF_REF_IDX + 5) { | ||
| 381 | + v += 1; | ||
| 382 | + if v > 32 { | ||
| 383 | + return Err(Error::corrupt("ref_idx bin string too long")); | ||
| 384 | + } | ||
| 385 | + } | ||
| 386 | + Ok(v) | ||
| 387 | + } | ||
| 388 | + | ||
| 389 | + /// mvd_lX component `comp` (0 horizontal, 1 vertical): UEG3 with | ||
| 390 | + /// signedValFlag 1 and uCoff 9 (clause 9.3.2.3), `inc` from 9.3.3.1.1.7. | ||
| 391 | + pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> { | ||
| 392 | + let off = OFF_MVD[comp]; | ||
| 393 | + if !self.decision(off + inc) { | ||
| 394 | + return Ok(0); | ||
| 395 | + } | ||
| 396 | + let mut prefix = 1u32; | ||
| 397 | + // Table 9-39: binIdx 1..4 take 3..6, binIdx 5 and beyond take 6. | ||
| 398 | + while prefix < 9 { | ||
| 399 | + let ctx = off + (2 + prefix as usize).min(6); | ||
| 400 | + if !self.decision(ctx) { | ||
| 401 | + break; | ||
| 402 | + } | ||
| 403 | + prefix += 1; | ||
| 404 | + } | ||
| 405 | + let abs = if prefix < 9 { | ||
| 406 | + prefix | ||
| 407 | + } else { | ||
| 408 | + 9 + self.ueg_suffix(3)? | ||
| 409 | + }; | ||
| 410 | + let value = i32::try_from(abs).map_err(|_| Error::corrupt("mvd out of range"))?; | ||
| 411 | + Ok(if self.bypass() { -value } else { value }) | ||
| 412 | + } | ||
| 413 | + | ||
| 225 | /// transform_size_8x8_flag (9.3.3.1.1.10). | 414 | /// transform_size_8x8_flag (9.3.3.1.1.10). |
| 226 | pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> { | 415 | pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> { |
| 227 | // No neighbour can carry the flag: a macroblock that set it is refused | 416 | // No neighbour can carry the flag: a macroblock that set it is refused |
| @@ -246,7 +435,9 @@ impl<'a> Cabac<'a> { | |||
| 246 | pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> { | 435 | pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> { |
| 247 | let cond = |n: Option<MbInfo>| match n { | 436 | let cond = |n: Option<MbInfo>| match n { |
| 248 | None => 0, | 437 | None => 0, |
| 249 | - Some(i) => usize::from(i.flags & FLAG_PCM == 0 && i.flags & FLAG_CHROMA_PRED != 0), | 438 | + Some(i) => usize::from( |
| 439 | + i.flags & (FLAG_PCM | FLAG_INTER) == 0 && i.flags & FLAG_CHROMA_PRED != 0, | ||
| 440 | + ), | ||
| 250 | }; | 441 | }; |
| 251 | let inc = cond(self.ctx.a) + cond(self.ctx.b); | 442 | let inc = cond(self.ctx.a) + cond(self.ctx.b); |
| 252 | if !self.decision(OFF_CHROMA_PRED + inc) { | 443 | if !self.decision(OFF_CHROMA_PRED + inc) { |
| @@ -345,10 +536,14 @@ impl<'a> Cabac<'a> { | |||
| 345 | let max = cat.max_num_coeff(); | 536 | let max = cat.max_num_coeff(); |
| 346 | 537 | ||
| 347 | // coded_block_flag (9.3.3.1.1.9). An unavailable neighbour counts as | 538 | // coded_block_flag (9.3.3.1.1.9). An unavailable neighbour counts as |
| 348 | - // set, because every macroblock of an I slice is intra coded; the | 539 | + // set for an intra macroblock and clear for an inter one; the caller |
| 349 | - // caller has already folded I_PCM (all coefficients present) into a | 540 | + // has already folded I_PCM (all coefficients present) and P_Skip / |
| 350 | - // non-zero count. | 541 | + // B_Skip (none) into the neighbouring counts. |
| 351 | - let cond = |n: Option<u8>| usize::from(n.is_none_or(|v| v != 0)); | 542 | + let intra = self.cur_intra; |
| 543 | + let cond = |n: Option<u8>| match n { | ||
| 544 | + None => usize::from(intra), | ||
| 545 | + Some(v) => usize::from(v != 0), | ||
| 546 | + }; | ||
| 352 | let (a, b) = match cat { | 547 | let (a, b) = match cat { |
| 353 | // The DC blocks' neighbours are per macroblock, not per 4x4 block. | 548 | // The DC blocks' neighbours are per macroblock, not per 4x4 block. |
| 354 | BlockCat::LumaDc => (self.dc_cbf(self.ctx.a, 0), self.dc_cbf(self.ctx.b, 0)), | 549 | BlockCat::LumaDc => (self.dc_cbf(self.ctx.a, 0), self.dc_cbf(self.ctx.b, 0)), |
| @@ -408,7 +603,7 @@ impl<'a> Cabac<'a> { | |||
| 408 | let abs_minus1 = if prefix < 14 { | 603 | let abs_minus1 = if prefix < 14 { |
| 409 | prefix | 604 | prefix |
| 410 | } else { | 605 | } else { |
| 411 | - 14 + self.ueg0_suffix()? | 606 | + 14 + self.ueg_suffix(0)? |
| 412 | }; | 607 | }; |
| 413 | let level = i64::from(abs_minus1) + 1; | 608 | let level = i64::from(abs_minus1) + 1; |
| 414 | let level = if self.bypass() { -level } else { level }; | 609 | let level = if self.bypass() { -level } else { level }; |
| @@ -424,9 +619,10 @@ impl<'a> Cabac<'a> { | |||
| 424 | Ok(total) | 619 | Ok(total) |
| 425 | } | 620 | } |
| 426 | 621 | ||
| 427 | - /// The bypass-coded 0th order Exp-Golomb suffix of a UEG0 bin string (9-6). | 622 | + /// The bypass-coded k-th order Exp-Golomb suffix of a UEGk bin string |
| 428 | - fn ueg0_suffix(&mut self) -> Result<u32> { | 623 | + /// (clause 9.3.2.3): k = 0 for coeff_abs_level_minus1, 3 for mvd. |
| 429 | - let mut k = 0u32; | 624 | + fn ueg_suffix(&mut self, k0: u32) -> Result<u32> { |
| 625 | + let mut k = k0; | ||
| 430 | let mut value = 0u32; | 626 | let mut value = 0u32; |
| 431 | while self.bypass() { | 627 | while self.bypass() { |
| 432 | value += 1 << k; | 628 | value += 1 << k; |
| @@ -532,7 +728,7 @@ mod tests { | |||
| 532 | /// 9.3.1.1 worked through by hand for two entries. | 728 | /// 9.3.1.1 worked through by hand for two entries. |
| 533 | #[test] | 729 | #[test] |
| 534 | fn context_initialisation_matches_equation_9_5() { | 730 | fn context_initialisation_matches_equation_9_5() { |
| 535 | - let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 26).unwrap(); | 731 | + let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 26, 0).unwrap(); |
| 536 | // ctxIdx 0, (m, n) = (20, -15): preCtxState = ((20*26) >> 4) - 15 = 17, | 732 | // ctxIdx 0, (m, n) = (20, -15): preCtxState = ((20*26) >> 4) - 15 = 17, |
| 537 | // so pStateIdx = 63 - 17 = 46 and valMPS = 0. | 733 | // so pStateIdx = 63 - 17 = 46 and valMPS = 0. |
| 538 | assert_eq!(c.state[0], 46 << 1); | 734 | assert_eq!(c.state[0], 46 << 1); |
| @@ -540,7 +736,7 @@ mod tests { | |||
| 540 | assert_eq!(c.state[60], 22 << 1); | 736 | assert_eq!(c.state[60], 22 << 1); |
| 541 | // Clip3(1, 126, ...) at a low QP: ctxIdx 6, (m, n) = (-28, 127) at | 737 | // Clip3(1, 126, ...) at a low QP: ctxIdx 6, (m, n) = (-28, 127) at |
| 542 | // QP 0 gives 127, clipped to 126 -> pStateIdx 62, valMPS 1. | 738 | // QP 0 gives 127, clipped to 126 -> pStateIdx 62, valMPS 1. |
| 543 | - let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 0).unwrap(); | 739 | + let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 0, 0).unwrap(); |
| 544 | assert_eq!(c.state[6], (62 << 1) | 1); | 740 | assert_eq!(c.state[6], (62 << 1) | 1); |
| 545 | } | 741 | } |
| 546 | 742 | ||
| @@ -551,7 +747,7 @@ mod tests { | |||
| 551 | // Header ends mid byte: the alignment bits carry to the boundary, then | 747 | // Header ends mid byte: the alignment bits carry to the boundary, then |
| 552 | // 0b1010_1010_1 is codIOffset. | 748 | // 0b1010_1010_1 is codIOffset. |
| 553 | let data = [0xFF, 0b1010_1010, 0b1000_0000, 0, 0]; | 749 | let data = [0xFF, 0b1010_1010, 0b1000_0000, 0, 0]; |
| 554 | - let c = Cabac::new(&data, 3, 30).unwrap(); | 750 | + let c = Cabac::new(&data, 3, 30, 0).unwrap(); |
| 555 | assert_eq!(c.range, 510); | 751 | assert_eq!(c.range, 510); |
| 556 | assert_eq!(c.offset, 0b1_0101_0101); | 752 | assert_eq!(c.offset, 0b1_0101_0101); |
| 557 | assert!(c.state.iter().all(|&s| s >> 1 < 64)); | 753 | assert!(c.state.iter().all(|&s| s >> 1 < 64)); |
crates/ec-h264/src/cabac_tables.rsmodified+292 -224
| @@ -1,10 +1,18 @@ | |||
| 1 | //! CABAC tables transcribed from Rec. ITU-T H.264 (V15) clause 9.3. | 1 | //! CABAC tables transcribed from Rec. ITU-T H.264 (V15) clause 9.3. |
| 2 | //! | 2 | //! |
| 3 | -//! Only the values an I-slice, frame-coded, 4:2:0 decode reads are here: the | 3 | +//! The initialisation values of Tables 9-12 to 9-21 for every ctxIdx a |
| 4 | -//! "I and SI slices" initialisation column (the cabac_init_idc columns exist | 4 | +//! frame-coded 4:2:0 slice can reach: 0..10 (I-slice mb_type), 11..59 (the |
| 5 | -//! only for P and B slices), the frame-coded significance contexts, and no 8x8 | 5 | +//! inter elements: mb_skip_flag, P and B mb_type and sub_mb_type, mvd, |
| 6 | -//! transform categories. A later inter slice adds its own columns against its | 6 | +//! ref_idx), 60..69 (shared by all slice types), 70..275 and 399..401. |
| 7 | -//! own conformance oracle rather than inheriting untested numbers from here. | 7 | +//! |
| 8 | +//! Where a ctxIdx has cabac_init_idc columns they are stored as | ||
| 9 | +//! `[I/SI, idc 0, idc 1, idc 2]` and [`crate::cabac::Cabac`] selects the column | ||
| 10 | +//! once per slice. ctxIdx 11..53 are never read by an I slice; their I column | ||
| 11 | +//! repeats the idc-0 values so the arrays stay rectangular. | ||
| 12 | +//! | ||
| 13 | +//! Absent on purpose: the field-coded significance contexts (277..398) and the | ||
| 14 | +//! 8x8 transform categories (402..1023) — both tools are refused by name, so | ||
| 15 | +//! transcribing their numbers would ship values no oracle here exercises. | ||
| 8 | 16 | ||
| 9 | /// Table 9-12, ctxIdx 0..10: mb_type in I slices. | 17 | /// Table 9-12, ctxIdx 0..10: mb_type in I slices. |
| 10 | pub(crate) const INIT_MB_TYPE_I: [(i8, i8); 11] = [ | 18 | pub(crate) const INIT_MB_TYPE_I: [(i8, i8); 11] = [ |
| @@ -21,8 +29,8 @@ pub(crate) const INIT_MB_TYPE_I: [(i8, i8); 11] = [ | |||
| 21 | (7, 51), | 29 | (7, 51), |
| 22 | ]; | 30 | ]; |
| 23 | 31 | ||
| 24 | -/// Table 9-17, ctxIdx 60..69: mb_qp_delta, intra_chroma_pred_mode and the two | 32 | +/// Table 9-17, ctxIdx 60..69: mb_qp_delta, intra_chroma_pred_mode and the |
| 25 | -/// intra 4x4 prediction mode elements. | 33 | +/// two intra 4x4 prediction mode elements. One column for every slice type. |
| 26 | pub(crate) const INIT_60_69: [(i8, i8); 10] = [ | 34 | pub(crate) const INIT_60_69: [(i8, i8); 10] = [ |
| 27 | (0, 41), | 35 | (0, 41), |
| 28 | (0, 63), | 36 | (0, 63), |
| @@ -36,220 +44,278 @@ pub(crate) const INIT_60_69: [(i8, i8); 10] = [ | |||
| 36 | (3, 62), | 44 | (3, 62), |
| 37 | ]; | 45 | ]; |
| 38 | 46 | ||
| 39 | -/// Tables 9-18 to 9-21, ctxIdx 70..275, "I and SI slices" column: | 47 | +/// Tables 9-13 to 9-16, ctxIdx 11..59: mb_skip_flag, mb_type and sub_mb_type |
| 40 | -/// coded_block_pattern, coded_block_flag, significant_coeff_flag, | 48 | +/// for P and B slices, mvd and ref_idx. |
| 41 | -/// last_significant_coeff_flag and coeff_abs_level_minus1. | 49 | +pub(crate) const INIT_11_59: [[(i8, i8); 4]; 49] = [ |
| 42 | -pub(crate) const INIT_70_275: [(i8, i8); 206] = [ | 50 | + [(23, 33), (23, 33), (22, 25), (29, 16)], |
| 43 | - (0, 11), | 51 | + [(23, 2), (23, 2), (34, 0), (25, 0)], |
| 44 | - (1, 55), | 52 | + [(21, 0), (21, 0), (16, 0), (14, 0)], |
| 45 | - (0, 69), | 53 | + [(1, 9), (1, 9), (-2, 9), (-10, 51)], |
| 46 | - (-17, 127), | 54 | + [(0, 49), (0, 49), (4, 41), (-3, 62)], |
| 47 | - (-13, 102), | 55 | + [(-37, 118), (-37, 118), (-29, 118), (-27, 99)], |
| 48 | - (0, 82), | 56 | + [(5, 57), (5, 57), (2, 65), (26, 16)], |
| 49 | - (-7, 74), | 57 | + [(-13, 78), (-13, 78), (-6, 71), (-4, 85)], |
| 50 | - (-21, 107), | 58 | + [(-11, 65), (-11, 65), (-13, 79), (-24, 102)], |
| 51 | - (-27, 127), | 59 | + [(1, 62), (1, 62), (5, 52), (5, 57)], |
| 52 | - (-31, 127), | 60 | + [(12, 49), (12, 49), (9, 50), (6, 57)], |
| 53 | - (-24, 127), | 61 | + [(-4, 73), (-4, 73), (-3, 70), (-17, 73)], |
| 54 | - (-18, 95), | 62 | + [(17, 50), (17, 50), (10, 54), (14, 57)], |
| 55 | - (-27, 127), | 63 | + [(18, 64), (18, 64), (26, 34), (20, 40)], |
| 56 | - (-21, 114), | 64 | + [(9, 43), (9, 43), (19, 22), (20, 10)], |
| 57 | - (-30, 127), | 65 | + [(29, 0), (29, 0), (40, 0), (29, 0)], |
| 58 | - (-17, 123), | 66 | + [(26, 67), (26, 67), (57, 2), (54, 0)], |
| 59 | - (-12, 115), | 67 | + [(16, 90), (16, 90), (41, 36), (37, 42)], |
| 60 | - (-16, 122), | 68 | + [(9, 104), (9, 104), (26, 69), (12, 97)], |
| 61 | - (-11, 115), | 69 | + [(-46, 127), (-46, 127), (-45, 127), (-32, 127)], |
| 62 | - (-12, 63), | 70 | + [(-20, 104), (-20, 104), (-15, 101), (-22, 117)], |
| 63 | - (-2, 68), | 71 | + [(1, 67), (1, 67), (-4, 76), (-2, 74)], |
| 64 | - (-15, 84), | 72 | + [(-13, 78), (-13, 78), (-6, 71), (-4, 85)], |
| 65 | - (-13, 104), | 73 | + [(-11, 65), (-11, 65), (-13, 79), (-24, 102)], |
| 66 | - (-3, 70), | 74 | + [(1, 62), (1, 62), (5, 52), (5, 57)], |
| 67 | - (-8, 93), | 75 | + [(-6, 86), (-6, 86), (6, 69), (-6, 93)], |
| 68 | - (-10, 90), | 76 | + [(-17, 95), (-17, 95), (-13, 90), (-14, 88)], |
| 69 | - (-30, 127), | 77 | + [(-6, 61), (-6, 61), (0, 52), (-6, 44)], |
| 70 | - (-1, 74), | 78 | + [(9, 45), (9, 45), (8, 43), (4, 55)], |
| 71 | - (-6, 97), | 79 | + [(-3, 69), (-3, 69), (-2, 69), (-11, 89)], |
| 72 | - (-7, 91), | 80 | + [(-6, 81), (-6, 81), (-5, 82), (-15, 103)], |
| 73 | - (-20, 127), | 81 | + [(-11, 96), (-11, 96), (-10, 96), (-21, 116)], |
| 74 | - (-4, 56), | 82 | + [(6, 55), (6, 55), (2, 59), (19, 57)], |
| 75 | - (-5, 82), | 83 | + [(7, 67), (7, 67), (2, 75), (20, 58)], |
| 76 | - (-7, 76), | 84 | + [(-5, 86), (-5, 86), (-3, 87), (4, 84)], |
| 77 | - (-22, 125), | 85 | + [(2, 88), (2, 88), (-3, 100), (6, 96)], |
| 78 | - (-7, 93), | 86 | + [(0, 58), (0, 58), (1, 56), (1, 63)], |
| 79 | - (-11, 87), | 87 | + [(-3, 76), (-3, 76), (-3, 74), (-5, 85)], |
| 80 | - (-3, 77), | 88 | + [(-10, 94), (-10, 94), (-6, 85), (-13, 106)], |
| 81 | - (-5, 71), | 89 | + [(5, 54), (5, 54), (0, 59), (5, 63)], |
| 82 | - (-4, 63), | 90 | + [(4, 69), (4, 69), (-3, 81), (6, 75)], |
| 83 | - (-4, 68), | 91 | + [(-3, 81), (-3, 81), (-7, 86), (-3, 90)], |
| 84 | - (-12, 84), | 92 | + [(0, 88), (0, 88), (-5, 95), (-1, 101)], |
| 85 | - (-7, 62), | 93 | + [(-7, 67), (-7, 67), (-1, 66), (3, 55)], |
| 86 | - (-7, 65), | 94 | + [(-5, 74), (-5, 74), (-1, 77), (-4, 79)], |
| 87 | - (8, 61), | 95 | + [(-4, 74), (-4, 74), (1, 70), (-2, 75)], |
| 88 | - (5, 56), | 96 | + [(-5, 80), (-5, 80), (-2, 86), (-12, 97)], |
| 89 | - (-2, 66), | 97 | + [(-7, 72), (-7, 72), (-5, 72), (-7, 50)], |
| 90 | - (1, 64), | 98 | + [(1, 58), (1, 58), (0, 61), (1, 60)], |
| 91 | - (0, 61), | 99 | +]; |
| 92 | - (-2, 78), | 100 | + |
| 93 | - (1, 50), | 101 | +/// Tables 9-18 to 9-21, ctxIdx 70..275: coded_block_pattern, |
| 94 | - (7, 52), | 102 | +/// coded_block_flag, significant_coeff_flag, last_significant_coeff_flag |
| 95 | - (10, 35), | 103 | +/// and coeff_abs_level_minus1. |
| 96 | - (0, 44), | 104 | +pub(crate) const INIT_70_275: [[(i8, i8); 4]; 206] = [ |
| 97 | - (11, 38), | 105 | + [(0, 11), (0, 45), (13, 15), (7, 34)], |
| 98 | - (1, 45), | 106 | + [(1, 55), (-4, 78), (7, 51), (-9, 88)], |
| 99 | - (0, 46), | 107 | + [(0, 69), (-3, 96), (2, 80), (-20, 127)], |
| 100 | - (5, 44), | 108 | + [(-17, 127), (-27, 126), (-39, 127), (-36, 127)], |
| 101 | - (31, 17), | 109 | + [(-13, 102), (-28, 98), (-18, 91), (-17, 91)], |
| 102 | - (1, 51), | 110 | + [(0, 82), (-25, 101), (-17, 96), (-14, 95)], |
| 103 | - (7, 50), | 111 | + [(-7, 74), (-23, 67), (-26, 81), (-25, 84)], |
| 104 | - (28, 19), | 112 | + [(-21, 107), (-28, 82), (-35, 98), (-25, 86)], |
| 105 | - (16, 33), | 113 | + [(-27, 127), (-20, 94), (-24, 102), (-12, 89)], |
| 106 | - (14, 62), | 114 | + [(-31, 127), (-16, 83), (-23, 97), (-17, 91)], |
| 107 | - (-13, 108), | 115 | + [(-24, 127), (-22, 110), (-27, 119), (-31, 127)], |
| 108 | - (-15, 100), | 116 | + [(-18, 95), (-21, 91), (-24, 99), (-14, 76)], |
| 109 | - (-13, 101), | 117 | + [(-27, 127), (-18, 102), (-21, 110), (-18, 103)], |
| 110 | - (-13, 91), | 118 | + [(-21, 114), (-13, 93), (-18, 102), (-13, 90)], |
| 111 | - (-12, 94), | 119 | + [(-30, 127), (-29, 127), (-36, 127), (-37, 127)], |
| 112 | - (-10, 88), | 120 | + [(-17, 123), (-7, 92), (0, 80), (11, 80)], |
| 113 | - (-16, 84), | 121 | + [(-12, 115), (-5, 89), (-5, 89), (5, 76)], |
| 114 | - (-10, 86), | 122 | + [(-16, 122), (-7, 96), (-7, 94), (2, 84)], |
| 115 | - (-7, 83), | 123 | + [(-11, 115), (-13, 108), (-4, 92), (5, 78)], |
| 116 | - (-13, 87), | 124 | + [(-12, 63), (-3, 46), (0, 39), (-6, 55)], |
| 117 | - (-19, 94), | 125 | + [(-2, 68), (-1, 65), (0, 65), (4, 61)], |
| 118 | - (1, 70), | 126 | + [(-15, 84), (-1, 57), (-15, 84), (-14, 83)], |
| 119 | - (0, 72), | 127 | + [(-13, 104), (-9, 93), (-35, 127), (-37, 127)], |
| 120 | - (-5, 74), | 128 | + [(-3, 70), (-3, 74), (-2, 73), (-5, 79)], |
| 121 | - (18, 59), | 129 | + [(-8, 93), (-9, 92), (-12, 104), (-11, 104)], |
| 122 | - (-8, 102), | 130 | + [(-10, 90), (-8, 87), (-9, 91), (-11, 91)], |
| 123 | - (-15, 100), | 131 | + [(-30, 127), (-23, 126), (-31, 127), (-30, 127)], |
| 124 | - (0, 95), | 132 | + [(-1, 74), (5, 54), (3, 55), (0, 65)], |
| 125 | - (-4, 75), | 133 | + [(-6, 97), (6, 60), (7, 56), (-2, 79)], |
| 126 | - (2, 72), | 134 | + [(-7, 91), (6, 59), (7, 55), (0, 72)], |
| 127 | - (-11, 75), | 135 | + [(-20, 127), (6, 69), (8, 61), (-4, 92)], |
| 128 | - (-3, 71), | 136 | + [(-4, 56), (-1, 48), (-3, 53), (-6, 56)], |
| 129 | - (15, 46), | 137 | + [(-5, 82), (0, 68), (0, 68), (3, 68)], |
| 130 | - (-13, 69), | 138 | + [(-7, 76), (-4, 69), (-7, 74), (-8, 71)], |
| 131 | - (0, 62), | 139 | + [(-22, 125), (-8, 88), (-9, 88), (-13, 98)], |
| 132 | - (0, 65), | 140 | + [(-7, 93), (-2, 85), (-13, 103), (-4, 86)], |
| 133 | - (21, 37), | 141 | + [(-11, 87), (-6, 78), (-13, 91), (-12, 88)], |
| 134 | - (-15, 72), | 142 | + [(-3, 77), (-1, 75), (-9, 89), (-5, 82)], |
| 135 | - (9, 57), | 143 | + [(-5, 71), (-7, 77), (-14, 92), (-3, 72)], |
| 136 | - (16, 54), | 144 | + [(-4, 63), (2, 54), (-8, 76), (-4, 67)], |
| 137 | - (0, 62), | 145 | + [(-4, 68), (5, 50), (-12, 87), (-8, 72)], |
| 138 | - (12, 72), | 146 | + [(-12, 84), (-3, 68), (-23, 110), (-16, 89)], |
| 139 | - (24, 0), | 147 | + [(-7, 62), (1, 50), (-24, 105), (-9, 69)], |
| 140 | - (15, 9), | 148 | + [(-7, 65), (6, 42), (-10, 78), (-1, 59)], |
| 141 | - (8, 25), | 149 | + [(8, 61), (-4, 81), (-20, 112), (5, 66)], |
| 142 | - (13, 18), | 150 | + [(5, 56), (1, 63), (-17, 99), (4, 57)], |
| 143 | - (15, 9), | 151 | + [(-2, 66), (-4, 70), (-78, 127), (-4, 71)], |
| 144 | - (13, 19), | 152 | + [(1, 64), (0, 67), (-70, 127), (-2, 71)], |
| 145 | - (10, 37), | 153 | + [(0, 61), (2, 57), (-50, 127), (2, 58)], |
| 146 | - (12, 18), | 154 | + [(-2, 78), (-2, 76), (-46, 127), (-1, 74)], |
| 147 | - (6, 29), | 155 | + [(1, 50), (11, 35), (-4, 66), (-4, 44)], |
| 148 | - (20, 33), | 156 | + [(7, 52), (4, 64), (-5, 78), (-1, 69)], |
| 149 | - (15, 30), | 157 | + [(10, 35), (1, 61), (-4, 71), (0, 62)], |
| 150 | - (4, 45), | 158 | + [(0, 44), (11, 35), (-8, 72), (-7, 51)], |
| 151 | - (1, 58), | 159 | + [(11, 38), (18, 25), (2, 59), (-4, 47)], |
| 152 | - (0, 62), | 160 | + [(1, 45), (12, 24), (-1, 55), (-6, 42)], |
| 153 | - (7, 61), | 161 | + [(0, 46), (13, 29), (-7, 70), (-3, 41)], |
| 154 | - (12, 38), | 162 | + [(5, 44), (13, 36), (-6, 75), (-6, 53)], |
| 155 | - (11, 45), | 163 | + [(31, 17), (-10, 93), (-8, 89), (8, 76)], |
| 156 | - (15, 39), | 164 | + [(1, 51), (-7, 73), (-34, 119), (-9, 78)], |
| 157 | - (11, 42), | 165 | + [(7, 50), (-2, 73), (-3, 75), (-11, 83)], |
| 158 | - (13, 44), | 166 | + [(28, 19), (13, 46), (32, 20), (9, 52)], |
| 159 | - (16, 45), | 167 | + [(16, 33), (9, 49), (30, 22), (0, 67)], |
| 160 | - (12, 41), | 168 | + [(14, 62), (-7, 100), (-44, 127), (-5, 90)], |
| 161 | - (10, 49), | 169 | + [(-13, 108), (9, 53), (0, 54), (1, 67)], |
| 162 | - (30, 34), | 170 | + [(-15, 100), (2, 53), (-5, 61), (-15, 72)], |
| 163 | - (18, 42), | 171 | + [(-13, 101), (5, 53), (0, 58), (-5, 75)], |
| 164 | - (10, 55), | 172 | + [(-13, 91), (-2, 61), (-1, 60), (-8, 80)], |
| 165 | - (17, 51), | 173 | + [(-12, 94), (0, 56), (-3, 61), (-21, 83)], |
| 166 | - (17, 46), | 174 | + [(-10, 88), (0, 56), (-8, 67), (-21, 64)], |
| 167 | - (0, 89), | 175 | + [(-16, 84), (-13, 63), (-25, 84), (-13, 31)], |
| 168 | - (26, -19), | 176 | + [(-10, 86), (-5, 60), (-14, 74), (-25, 64)], |
| 169 | - (22, -17), | 177 | + [(-7, 83), (-1, 62), (-5, 65), (-29, 94)], |
| 170 | - (26, -17), | 178 | + [(-13, 87), (4, 57), (5, 52), (9, 75)], |
| 171 | - (30, -25), | 179 | + [(-19, 94), (-6, 69), (2, 57), (17, 63)], |
| 172 | - (28, -20), | 180 | + [(1, 70), (4, 57), (0, 61), (-8, 74)], |
| 173 | - (33, -23), | 181 | + [(0, 72), (14, 39), (-9, 69), (-5, 35)], |
| 174 | - (37, -27), | 182 | + [(-5, 74), (4, 51), (-11, 70), (-2, 27)], |
| 175 | - (33, -23), | 183 | + [(18, 59), (13, 68), (18, 55), (13, 91)], |
| 176 | - (40, -28), | 184 | + [(-8, 102), (3, 64), (-4, 71), (3, 65)], |
| 177 | - (38, -17), | 185 | + [(-15, 100), (1, 61), (0, 58), (-7, 69)], |
| 178 | - (33, -11), | 186 | + [(0, 95), (9, 63), (7, 61), (8, 77)], |
| 179 | - (40, -15), | 187 | + [(-4, 75), (7, 50), (9, 41), (-10, 66)], |
| 180 | - (41, -6), | 188 | + [(2, 72), (16, 39), (18, 25), (3, 62)], |
| 181 | - (38, 1), | 189 | + [(-11, 75), (5, 44), (9, 32), (-3, 68)], |
| 182 | - (41, 17), | 190 | + [(-3, 71), (4, 52), (5, 43), (-20, 81)], |
| 183 | - (30, -6), | 191 | + [(15, 46), (11, 48), (9, 47), (0, 30)], |
| 184 | - (27, 3), | 192 | + [(-13, 69), (-5, 60), (0, 44), (1, 7)], |
| 185 | - (26, 22), | 193 | + [(0, 62), (-1, 59), (0, 51), (-3, 23)], |
| 186 | - (37, -16), | 194 | + [(0, 65), (0, 59), (2, 46), (-21, 74)], |
| 187 | - (35, -4), | 195 | + [(21, 37), (22, 33), (19, 38), (16, 66)], |
| 188 | - (38, -8), | 196 | + [(-15, 72), (5, 44), (-4, 66), (-23, 124)], |
| 189 | - (38, -3), | 197 | + [(9, 57), (14, 43), (15, 38), (17, 37)], |
| 190 | - (37, 3), | 198 | + [(16, 54), (-1, 78), (12, 42), (44, -18)], |
| 191 | - (38, 5), | 199 | + [(0, 62), (0, 60), (9, 34), (50, -34)], |
| 192 | - (42, 0), | 200 | + [(12, 72), (9, 69), (0, 89), (-22, 127)], |
| 193 | - (35, 16), | 201 | + [(24, 0), (11, 28), (4, 45), (4, 39)], |
| 194 | - (39, 22), | 202 | + [(15, 9), (2, 40), (10, 28), (0, 42)], |
| 195 | - (14, 48), | 203 | + [(8, 25), (3, 44), (10, 31), (7, 34)], |
| 196 | - (27, 37), | 204 | + [(13, 18), (0, 49), (33, -11), (11, 29)], |
| 197 | - (21, 60), | 205 | + [(15, 9), (0, 46), (52, -43), (8, 31)], |
| 198 | - (12, 68), | 206 | + [(13, 19), (2, 44), (18, 15), (6, 37)], |
| 199 | - (2, 97), | 207 | + [(10, 37), (2, 51), (28, 0), (7, 42)], |
| 200 | - (-3, 71), | 208 | + [(12, 18), (0, 47), (35, -22), (3, 40)], |
| 201 | - (-6, 42), | 209 | + [(6, 29), (4, 39), (38, -25), (8, 33)], |
| 202 | - (-5, 50), | 210 | + [(20, 33), (2, 62), (34, 0), (13, 43)], |
| 203 | - (-3, 54), | 211 | + [(15, 30), (6, 46), (39, -18), (13, 36)], |
| 204 | - (-2, 62), | 212 | + [(4, 45), (0, 54), (32, -12), (4, 47)], |
| 205 | - (0, 58), | 213 | + [(1, 58), (3, 54), (102, -94), (3, 55)], |
| 206 | - (1, 63), | 214 | + [(0, 62), (2, 58), (0, 0), (2, 58)], |
| 207 | - (-2, 72), | 215 | + [(7, 61), (4, 63), (56, -15), (6, 60)], |
| 208 | - (-1, 74), | 216 | + [(12, 38), (6, 51), (33, -4), (8, 44)], |
| 209 | - (-9, 91), | 217 | + [(11, 45), (6, 57), (29, 10), (11, 44)], |
| 210 | - (-5, 67), | 218 | + [(15, 39), (7, 53), (37, -5), (14, 42)], |
| 211 | - (-5, 27), | 219 | + [(11, 42), (6, 52), (51, -29), (7, 48)], |
| 212 | - (-3, 39), | 220 | + [(13, 44), (6, 55), (39, -9), (4, 56)], |
| 213 | - (-2, 44), | 221 | + [(16, 45), (11, 45), (52, -34), (4, 52)], |
| 214 | - (0, 46), | 222 | + [(12, 41), (14, 36), (69, -58), (13, 37)], |
| 215 | - (-16, 64), | 223 | + [(10, 49), (8, 53), (67, -63), (9, 49)], |
| 216 | - (-8, 68), | 224 | + [(30, 34), (-1, 82), (44, -5), (19, 58)], |
| 217 | - (-10, 78), | 225 | + [(18, 42), (7, 55), (32, 7), (10, 48)], |
| 218 | - (-6, 77), | 226 | + [(10, 55), (-3, 78), (55, -29), (12, 45)], |
| 219 | - (-10, 86), | 227 | + [(17, 51), (15, 46), (32, 1), (0, 69)], |
| 220 | - (-12, 92), | 228 | + [(17, 46), (22, 31), (0, 0), (20, 33)], |
| 221 | - (-15, 55), | 229 | + [(0, 89), (-1, 84), (27, 36), (8, 63)], |
| 222 | - (-10, 60), | 230 | + [(26, -19), (25, 7), (33, -25), (35, -18)], |
| 223 | - (-6, 62), | 231 | + [(22, -17), (30, -7), (34, -30), (33, -25)], |
| 224 | - (-4, 65), | 232 | + [(26, -17), (28, 3), (36, -28), (28, -3)], |
| 225 | - (-12, 73), | 233 | + [(30, -25), (28, 4), (38, -28), (24, 10)], |
| 226 | - (-8, 76), | 234 | + [(28, -20), (32, 0), (38, -27), (27, 0)], |
| 227 | - (-7, 80), | 235 | + [(33, -23), (34, -1), (34, -18), (34, -14)], |
| 228 | - (-9, 88), | 236 | + [(37, -27), (30, 6), (35, -16), (52, -44)], |
| 229 | - (-17, 110), | 237 | + [(33, -23), (30, 6), (34, -14), (39, -24)], |
| 230 | - (-11, 97), | 238 | + [(40, -28), (32, 9), (32, -8), (19, 17)], |
| 231 | - (-20, 84), | 239 | + [(38, -17), (31, 19), (37, -6), (31, 25)], |
| 232 | - (-11, 79), | 240 | + [(33, -11), (26, 27), (35, 0), (36, 29)], |
| 233 | - (-6, 73), | 241 | + [(40, -15), (26, 30), (30, 10), (24, 33)], |
| 234 | - (-4, 74), | 242 | + [(41, -6), (37, 20), (28, 18), (34, 15)], |
| 235 | - (-13, 86), | 243 | + [(38, 1), (28, 34), (26, 25), (30, 20)], |
| 236 | - (-13, 96), | 244 | + [(41, 17), (17, 70), (29, 41), (22, 73)], |
| 237 | - (-11, 97), | 245 | + [(30, -6), (1, 67), (0, 75), (20, 34)], |
| 238 | - (-19, 117), | 246 | + [(27, 3), (5, 59), (2, 72), (19, 31)], |
| 239 | - (-8, 78), | 247 | + [(26, 22), (9, 67), (8, 77), (27, 44)], |
| 240 | - (-5, 33), | 248 | + [(37, -16), (16, 30), (14, 35), (19, 16)], |
| 241 | - (-4, 48), | 249 | + [(35, -4), (18, 32), (18, 31), (15, 36)], |
| 242 | - (-2, 53), | 250 | + [(38, -8), (18, 35), (17, 35), (15, 36)], |
| 243 | - (-3, 62), | 251 | + [(38, -3), (22, 29), (21, 30), (21, 28)], |
| 244 | - (-13, 71), | 252 | + [(37, 3), (24, 31), (17, 45), (25, 21)], |
| 245 | - (-10, 79), | 253 | + [(38, 5), (23, 38), (20, 42), (30, 20)], |
| 246 | - (-12, 86), | 254 | + [(42, 0), (18, 43), (18, 45), (31, 12)], |
| 247 | - (-13, 90), | 255 | + [(35, 16), (20, 41), (27, 26), (27, 16)], |
| 248 | - (-14, 97), | 256 | + [(39, 22), (11, 63), (16, 54), (24, 42)], |
| 257 | + [(14, 48), (9, 59), (7, 66), (0, 93)], | ||
| 258 | + [(27, 37), (9, 64), (16, 56), (14, 56)], | ||
| 259 | + [(21, 60), (-1, 94), (11, 73), (15, 57)], | ||
| 260 | + [(12, 68), (-2, 89), (10, 67), (26, 38)], | ||
| 261 | + [(2, 97), (-9, 108), (-10, 116), (-24, 127)], | ||
| 262 | + [(-3, 71), (-6, 76), (-23, 112), (-24, 115)], | ||
| 263 | + [(-6, 42), (-2, 44), (-15, 71), (-22, 82)], | ||
| 264 | + [(-5, 50), (0, 45), (-7, 61), (-9, 62)], | ||
| 265 | + [(-3, 54), (0, 52), (0, 53), (0, 53)], | ||
| 266 | + [(-2, 62), (-3, 64), (-5, 66), (0, 59)], | ||
| 267 | + [(0, 58), (-2, 59), (-11, 77), (-14, 85)], | ||
| 268 | + [(1, 63), (-4, 70), (-9, 80), (-13, 89)], | ||
| 269 | + [(-2, 72), (-4, 75), (-9, 84), (-13, 94)], | ||
| 270 | + [(-1, 74), (-8, 82), (-10, 87), (-11, 92)], | ||
| 271 | + [(-9, 91), (-17, 102), (-34, 127), (-29, 127)], | ||
| 272 | + [(-5, 67), (-9, 77), (-21, 101), (-21, 100)], | ||
| 273 | + [(-5, 27), (3, 24), (-3, 39), (-14, 57)], | ||
| 274 | + [(-3, 39), (0, 42), (-5, 53), (-12, 67)], | ||
| 275 | + [(-2, 44), (0, 48), (-7, 61), (-11, 71)], | ||
| 276 | + [(0, 46), (0, 55), (-11, 75), (-10, 77)], | ||
| 277 | + [(-16, 64), (-6, 59), (-15, 77), (-21, 85)], | ||
| 278 | + [(-8, 68), (-7, 71), (-17, 91), (-16, 88)], | ||
| 279 | + [(-10, 78), (-12, 83), (-25, 107), (-23, 104)], | ||
| 280 | + [(-6, 77), (-11, 87), (-25, 111), (-15, 98)], | ||
| 281 | + [(-10, 86), (-30, 119), (-28, 122), (-37, 127)], | ||
| 282 | + [(-12, 92), (1, 58), (-11, 76), (-10, 82)], | ||
| 283 | + [(-15, 55), (-3, 29), (-10, 44), (-8, 48)], | ||
| 284 | + [(-10, 60), (-1, 36), (-10, 52), (-8, 61)], | ||
| 285 | + [(-6, 62), (1, 38), (-10, 57), (-8, 66)], | ||
| 286 | + [(-4, 65), (2, 43), (-9, 58), (-7, 70)], | ||
| 287 | + [(-12, 73), (-6, 55), (-16, 72), (-14, 75)], | ||
| 288 | + [(-8, 76), (0, 58), (-7, 69), (-10, 79)], | ||
| 289 | + [(-7, 80), (0, 64), (-4, 69), (-9, 83)], | ||
| 290 | + [(-9, 88), (-3, 74), (-5, 74), (-12, 92)], | ||
| 291 | + [(-17, 110), (-10, 90), (-9, 86), (-18, 108)], | ||
| 292 | + [(-11, 97), (0, 70), (2, 66), (-4, 79)], | ||
| 293 | + [(-20, 84), (-4, 29), (-9, 34), (-22, 69)], | ||
| 294 | + [(-11, 79), (5, 31), (1, 32), (-16, 75)], | ||
| 295 | + [(-6, 73), (7, 42), (11, 31), (-2, 58)], | ||
| 296 | + [(-4, 74), (1, 59), (5, 52), (1, 58)], | ||
| 297 | + [(-13, 86), (-2, 58), (-2, 55), (-13, 78)], | ||
| 298 | + [(-13, 96), (-3, 72), (-2, 67), (-9, 83)], | ||
| 299 | + [(-11, 97), (-3, 81), (0, 73), (-4, 81)], | ||
| 300 | + [(-19, 117), (-11, 97), (-8, 89), (-13, 99)], | ||
| 301 | + [(-8, 78), (0, 58), (3, 52), (-13, 81)], | ||
| 302 | + [(-5, 33), (8, 5), (7, 4), (-6, 38)], | ||
| 303 | + [(-4, 48), (10, 14), (10, 8), (-13, 62)], | ||
| 304 | + [(-2, 53), (14, 18), (17, 8), (-6, 58)], | ||
| 305 | + [(-3, 62), (13, 27), (16, 19), (-2, 59)], | ||
| 306 | + [(-13, 71), (2, 40), (3, 37), (-16, 73)], | ||
| 307 | + [(-10, 79), (0, 58), (-1, 61), (-10, 76)], | ||
| 308 | + [(-12, 86), (-3, 70), (-5, 73), (-13, 86)], | ||
| 309 | + [(-13, 90), (-6, 79), (-1, 70), (-9, 83)], | ||
| 310 | + [(-14, 97), (-8, 85), (-4, 78), (-10, 87)], | ||
| 249 | ]; | 311 | ]; |
| 250 | 312 | ||
| 251 | /// Table 9-16, ctxIdx 399..401: transform_size_8x8_flag. | 313 | /// Table 9-16, ctxIdx 399..401: transform_size_8x8_flag. |
| 252 | -pub(crate) const INIT_399_401: [(i8, i8); 3] = [(31, 21), (31, 31), (25, 50)]; | 314 | +pub(crate) const INIT_399_401: [[(i8, i8); 4]; 3] = [ |
| 315 | + [(31, 21), (12, 40), (25, 32), (21, 33)], | ||
| 316 | + [(31, 31), (11, 51), (21, 49), (19, 50)], | ||
| 317 | + [(25, 50), (14, 59), (21, 54), (17, 61)], | ||
| 318 | +]; | ||
| 253 | 319 | ||
| 254 | /// Table 9-44: rangeTabLPS[pStateIdx][qCodIRangeIdx]. | 320 | /// Table 9-44: rangeTabLPS[pStateIdx][qCodIRangeIdx]. |
| 255 | pub(crate) const RANGE_LPS: [[u8; 4]; 64] = [ | 321 | pub(crate) const RANGE_LPS: [[u8; 4]; 64] = [ |
| @@ -321,14 +387,16 @@ pub(crate) const RANGE_LPS: [[u8; 4]; 64] = [ | |||
| 321 | 387 | ||
| 322 | /// Table 9-45: transIdxLPS. | 388 | /// Table 9-45: transIdxLPS. |
| 323 | pub(crate) const TRANS_LPS: [u8; 64] = [ | 389 | pub(crate) const TRANS_LPS: [u8; 64] = [ |
| 324 | - 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, | 390 | + 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12, |
| 325 | - 21, 22, 22, 23, 24, 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, 33, 33, 34, | 391 | + 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24, |
| 326 | - 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63, | 392 | + 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33, |
| 393 | + 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63, | ||
| 327 | ]; | 394 | ]; |
| 328 | 395 | ||
| 329 | /// Table 9-45: transIdxMPS. | 396 | /// Table 9-45: transIdxMPS. |
| 330 | pub(crate) const TRANS_MPS: [u8; 64] = [ | 397 | pub(crate) const TRANS_MPS: [u8; 64] = [ |
| 331 | - 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, | 398 | + 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16, |
| 332 | - 27, 28, 29, 30, 31, 32, 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, 49, 50, | 399 | + 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32, |
| 333 | - 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63, | 400 | + 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48, |
| 401 | + 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63, | ||
| 334 | ]; | 402 | ]; |
crates/ec-h264/src/codec.rsmodified+36 -14
| @@ -17,7 +17,7 @@ use ec_core::registry::{CodecId, CodecParameters, MediaParameters}; | |||
| 17 | use ec_core::timebase::Timestamp; | 17 | use ec_core::timebase::Timestamp; |
| 18 | use ec_h264_syntax::AnnexBIter; | 18 | use ec_h264_syntax::AnnexBIter; |
| 19 | 19 | ||
| 20 | -use crate::decoder::{Decoder, NalOutcome}; | 20 | +use crate::decoder::{Decoder, NalOutcome, OutputOrder}; |
| 21 | 21 | ||
| 22 | /// H.264 decoder behind the codec registry's packet/frame contract. | 22 | /// H.264 decoder behind the codec registry's packet/frame contract. |
| 23 | pub struct H264Decoder { | 23 | pub struct H264Decoder { |
| @@ -27,7 +27,6 @@ pub struct H264Decoder { | |||
| 27 | /// `None` means Annex B start codes. | 27 | /// `None` means Annex B start codes. |
| 28 | nal_length_size: Option<usize>, | 28 | nal_length_size: Option<usize>, |
| 29 | frames: VecDeque<Frame>, | 29 | frames: VecDeque<Frame>, |
| 30 | - pending_pts: Option<Timestamp>, | ||
| 31 | end_of_stream: bool, | 30 | end_of_stream: bool, |
| 32 | } | 31 | } |
| 33 | 32 | ||
| @@ -50,7 +49,6 @@ impl H264Decoder { | |||
| 50 | inner: Decoder::new(), | 49 | inner: Decoder::new(), |
| 51 | nal_length_size: None, | 50 | nal_length_size: None, |
| 52 | frames: VecDeque::new(), | 51 | frames: VecDeque::new(), |
| 53 | - pending_pts: None, | ||
| 54 | end_of_stream: false, | 52 | end_of_stream: false, |
| 55 | }; | 53 | }; |
| 56 | // 7 bytes is the shortest record that can hold the fixed header plus a | 54 | // 7 bytes is the shortest record that can hold the fixed header plus a |
| @@ -64,6 +62,21 @@ impl H264Decoder { | |||
| 64 | Ok(decoder) | 62 | Ok(decoder) |
| 65 | } | 63 | } |
| 66 | 64 | ||
| 65 | + /// Choose the order frames come back in. | ||
| 66 | + /// | ||
| 67 | + /// The default is display order, which is the order a player presents | ||
| 68 | + /// pictures in and the only correct one for a stream with B pictures. A | ||
| 69 | + /// caller that does its own reordering — or that wants the lowest possible | ||
| 70 | + /// latency and knows the stream never reorders — can ask for decode order. | ||
| 71 | + pub fn set_output_order(&mut self, order: OutputOrder) { | ||
| 72 | + self.inner.set_output_order(order); | ||
| 73 | + } | ||
| 74 | + | ||
| 75 | + /// The order frames come back in. | ||
| 76 | + pub fn output_order(&self) -> OutputOrder { | ||
| 77 | + self.inner.output_order() | ||
| 78 | + } | ||
| 79 | + | ||
| 67 | /// Read an `avcC` record: the NAL length size and the in-band parameter | 80 | /// Read an `avcC` record: the NAL length size and the in-band parameter |
| 68 | /// sets (ISO/IEC 14496-15 clause 5.3.3.1). | 81 | /// sets (ISO/IEC 14496-15 clause 5.3.3.1). |
| 69 | fn parse_avcc(&mut self, extradata: &[u8]) -> Result<()> { | 82 | fn parse_avcc(&mut self, extradata: &[u8]) -> Result<()> { |
| @@ -133,18 +146,23 @@ impl H264Decoder { | |||
| 133 | Ok(()) | 146 | Ok(()) |
| 134 | } | 147 | } |
| 135 | 148 | ||
| 136 | - /// Emit the open picture, if there is one, as a frame. | 149 | + /// Complete the open picture, if there is one, and drain whatever that |
| 150 | + /// made ready for output. | ||
| 137 | fn finish_picture(&mut self) -> Result<()> { | 151 | fn finish_picture(&mut self) -> Result<()> { |
| 138 | - if !self.inner.picture_open() { | 152 | + if self.inner.picture_open() { |
| 139 | - return Ok(()); | ||
| 140 | - } | ||
| 141 | self.inner.end_picture()?; | 153 | self.inner.end_picture()?; |
| 142 | - let mut frame = self.inner.frame()?; | 154 | + } |
| 143 | - frame.pts = self.pending_pts.take(); | 155 | + self.drain(); |
| 144 | - self.frames.push_back(Frame::Video(frame)); | ||
| 145 | Ok(()) | 156 | Ok(()) |
| 146 | } | 157 | } |
| 147 | 158 | ||
| 159 | + /// Move every frame the decoder has released into the output queue. | ||
| 160 | + fn drain(&mut self) { | ||
| 161 | + while let Some(frame) = self.inner.next_frame() { | ||
| 162 | + self.frames.push_back(Frame::Video(frame)); | ||
| 163 | + } | ||
| 164 | + } | ||
| 165 | + | ||
| 148 | /// Publish the active SPS geometry on `params`, the way a demuxer that | 166 | /// Publish the active SPS geometry on `params`, the way a demuxer that |
| 149 | /// only had an `avcC` expects to read it back. | 167 | /// only had an `avcC` expects to read it back. |
| 150 | fn sync_parameters(&mut self) { | 168 | fn sync_parameters(&mut self) { |
| @@ -166,9 +184,13 @@ impl ec_core::registry::Decoder for H264Decoder { | |||
| 166 | 184 | ||
| 167 | fn send_packet(&mut self, packet: &Packet) -> Result<()> { | 185 | fn send_packet(&mut self, packet: &Packet) -> Result<()> { |
| 168 | self.end_of_stream = false; | 186 | self.end_of_stream = false; |
| 169 | - self.pending_pts = packet | 187 | + // The timestamp belongs to the picture, not to the packet: display |
| 188 | + // order hands pictures back in a different order than they arrive. | ||
| 189 | + self.inner.set_next_pts( | ||
| 190 | + packet | ||
| 170 | .pts | 191 | .pts |
| 171 | - .map(|ticks| Timestamp::new(ticks, packet.time_base)); | 192 | + .map(|ticks| Timestamp::new(ticks, packet.time_base)), |
| 193 | + ); | ||
| 172 | self.decode_packet_payload(&packet.data)?; | 194 | self.decode_packet_payload(&packet.data)?; |
| 173 | // One packet is one access unit, so whatever picture it started is | 195 | // One packet is one access unit, so whatever picture it started is |
| 174 | // complete once the packet is consumed. | 196 | // complete once the packet is consumed. |
| @@ -184,7 +206,8 @@ impl ec_core::registry::Decoder for H264Decoder { | |||
| 184 | } | 206 | } |
| 185 | 207 | ||
| 186 | fn flush(&mut self) -> Result<()> { | 208 | fn flush(&mut self) -> Result<()> { |
| 187 | - self.finish_picture()?; | 209 | + self.inner.flush()?; |
| 210 | + self.drain(); | ||
| 188 | self.end_of_stream = true; | 211 | self.end_of_stream = true; |
| 189 | Ok(()) | 212 | Ok(()) |
| 190 | } | 213 | } |
| @@ -194,7 +217,6 @@ impl ec_core::registry::Decoder for H264Decoder { | |||
| 194 | // state does not. | 217 | // state does not. |
| 195 | self.inner.reset_pictures(); | 218 | self.inner.reset_pictures(); |
| 196 | self.frames.clear(); | 219 | self.frames.clear(); |
| 197 | - self.pending_pts = None; | ||
| 198 | self.end_of_stream = false; | 220 | self.end_of_stream = false; |
| 199 | } | 221 | } |
| 200 | } | 222 | } |
crates/ec-h264/src/decoder.rsmodified+1476 -251
Diff too large; view file
| @@ -1,29 +1,49 @@ | |||
| 1 | -//! Decoder core: parameter-set store, flat per-picture context, macroblock | 1 | +//! Decoder core: parameter-set store, decoded picture buffer, macroblock |
| 2 | //! decode loop, reconstruction and the in-loop filter driver. | 2 | //! decode loop, reconstruction and the in-loop filter driver. |
| 3 | //! | 3 | //! |
| 4 | //! Layout choices (perf-first): | 4 | //! Layout choices (perf-first): |
| 5 | -//! - Planes are padded (`PAD_Y`/`PAD_C` samples each side), so neighbour | 5 | +//! - Planes are padded (`PAD_Y`/`PAD_C` samples each side) and their borders |
| 6 | -//! gathers and future inter-prediction overreach never bounds-check per | 6 | +//! replicated once per picture, so neighbour gathers and inter-prediction |
| 7 | -//! sample and edge availability is data, not arithmetic. | 7 | +//! overreach never bounds-check per sample and edge availability is data, |
| 8 | -//! - All per-macroblock state lives in flat struct-of-arrays keyed by | 8 | +//! not arithmetic. |
| 9 | -//! macroblock address or 4x4-block coordinate: non-zero coefficient counts | 9 | +//! - All per-macroblock and per-4x4-block state lives in flat struct-of-arrays |
| 10 | -//! (`nz_y`, `nz_c`), intra 4x4 modes, QP, flags, owning slice. No per-MB | 10 | +//! keyed by macroblock address or block coordinate: coefficient counts, intra |
| 11 | -//! heap objects anywhere. | 11 | +//! modes, QP, flags, owning slice, motion vectors, reference identities. No |
| 12 | -//! - Buffers are reused across pictures; a picture start is O(macroblocks) | 12 | +//! per-macroblock heap objects anywhere. |
| 13 | -//! fills, and the slice decode loop performs zero allocations. | 13 | +//! - Pictures are pooled by the [`Dpb`], so a steady-state decode loop reuses |
| 14 | +//! every buffer and performs zero allocations. | ||
| 15 | +//! | ||
| 16 | +//! Output is in display order: pictures leave the decoded picture buffer by the | ||
| 17 | +//! bumping process, smallest picture order count first, which is the order a | ||
| 18 | +//! player presents them in. [`OutputOrder::Decode`] switches that off for a | ||
| 19 | +//! caller that wants pictures as they are decoded. | ||
| 20 | + | ||
| 21 | +use std::collections::VecDeque; | ||
| 14 | 22 | ||
| 15 | use ec_core::BitReader; | 23 | use ec_core::BitReader; |
| 16 | use ec_core::error::{Error, Result}; | 24 | use ec_core::error::{Error, Result}; |
| 17 | use ec_core::frame::{PixelFormat, Plane, VideoFrame}; | 25 | use ec_core::frame::{PixelFormat, Plane, VideoFrame}; |
| 26 | +use ec_core::timebase::Timestamp; | ||
| 18 | use ec_h264_syntax::{ | 27 | use ec_h264_syntax::{ |
| 19 | - AnnexBIter, NalHeader, NalUnitType, Pps, SliceHeader, SliceType, Sps, unescape_rbsp, | 28 | + AnnexBIter, DecRefPicMarking, NalHeader, NalUnitType, Pps, PredWeightTable, SliceHeader, |
| 29 | + SliceType, Sps, WeightEntry, unescape_rbsp, | ||
| 20 | }; | 30 | }; |
| 21 | 31 | ||
| 22 | use crate::deblock::{ | 32 | use crate::deblock::{ |
| 23 | chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line, | 33 | chroma_qp, edge_params, filter_chroma_line, filter_luma_h_edge16, filter_luma_line, |
| 24 | }; | 34 | }; |
| 35 | +use crate::dpb::{ | ||
| 36 | + BLK_DIRECT, BLK_INTRA, BLK_SKIP, Dpb, Mark, NO_SLICE, PicInfo, Picture, Plane8, RefList, | ||
| 37 | + SliceParams, | ||
| 38 | +}; | ||
| 25 | use crate::entropy::{ | 39 | use crate::entropy::{ |
| 26 | - BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_I16, FLAG_PCM, MbCtx, MbInfo, | 40 | + BlockCat, Entropy, FLAG_CHROMA_PRED, FLAG_DECODED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, |
| 41 | + FLAG_SKIP, MbCtx, MbInfo, | ||
| 42 | +}; | ||
| 43 | +use crate::inter::{RefPlane, Weights, combine, mc_chroma, mc_luma}; | ||
| 44 | +use crate::mv::{ | ||
| 45 | + B_SHAPES, B_SUB, MbShape, MvCtx, P_SHAPES, P_SUB, Pred, SubShape, min_positive, | ||
| 46 | + neighbour_mvd, predict_mv, ref_idx_cond, write_block, write_intra_mb, write_mvd, | ||
| 27 | }; | 47 | }; |
| 28 | use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; | 48 | use crate::pred::{Nbr4, PlaneWindow, add_residual_4x4, pred_4x4, pred_16x16, pred_chroma_8x8}; |
| 29 | use crate::tables::{BLK4_POS, CHROMA_QP}; | 49 | use crate::tables::{BLK4_POS, CHROMA_QP}; |
| @@ -32,14 +52,6 @@ use crate::transform::{ | |||
| 32 | unzigzag, unzigzag_ac15, | 52 | unzigzag, unzigzag_ac15, |
| 33 | }; | 53 | }; |
| 34 | 54 | ||
| 35 | -/// Luma plane padding on every side, sized for future inter-prediction | ||
| 36 | -/// filter overreach (16 MB + margin). | ||
| 37 | -const PAD_Y: usize = 32; | ||
| 38 | -/// Chroma plane padding on every side. | ||
| 39 | -const PAD_C: usize = 16; | ||
| 40 | -/// `mb_slice` value for a not-yet-decoded macroblock. | ||
| 41 | -const NO_SLICE: u16 = u16::MAX; | ||
| 42 | - | ||
| 43 | /// Where a 4x4 block's top-right neighbour samples come from, per | 55 | /// Where a 4x4 block's top-right neighbour samples come from, per |
| 44 | /// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule). | 56 | /// luma4x4BlkIdx (derivation of 6.4.12 + the 8.3.1.2 blkIdx 3/11 rule). |
| 45 | #[derive(Clone, Copy, PartialEq)] | 57 | #[derive(Clone, Copy, PartialEq)] |
| @@ -73,117 +85,47 @@ const TR_KIND: [TrKind; 16] = [ | |||
| 73 | TrKind::None, | 85 | TrKind::None, |
| 74 | ]; | 86 | ]; |
| 75 | 87 | ||
| 76 | -/// A padded 8-bit plane. | 88 | +/// The order [`Decoder`] hands decoded pictures back in. |
| 77 | -#[derive(Debug, Default)] | 89 | +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] |
| 78 | -struct Plane8 { | 90 | +pub enum OutputOrder { |
| 79 | - data: Vec<u8>, | 91 | + /// Display order: pictures leave the decoded picture buffer by the bumping |
| 80 | - stride: usize, | 92 | + /// process of clause C.4.5.3. This is what a player needs, and the only |
| 81 | - /// Index of sample (0, 0) of the picture. | 93 | + /// order that is correct for a stream with B pictures. |
| 82 | - origin: usize, | 94 | + #[default] |
| 83 | -} | 95 | + Display, |
| 84 | - | 96 | + /// Decode order: each picture is emitted the moment it is complete. Lower |
| 85 | -impl Plane8 { | 97 | + /// latency, wrong presentation order whenever the stream reorders. |
| 86 | - fn resize(&mut self, width: usize, height: usize, pad: usize) { | 98 | + Decode, |
| 87 | - self.stride = width + 2 * pad; | ||
| 88 | - self.origin = pad * self.stride + pad; | ||
| 89 | - self.data.clear(); | ||
| 90 | - self.data.resize(self.stride * (height + 2 * pad), 0); | ||
| 91 | - } | ||
| 92 | - | ||
| 93 | - #[inline] | ||
| 94 | - fn at(&self, x: usize, y: usize) -> usize { | ||
| 95 | - self.origin + y * self.stride + x | ||
| 96 | - } | ||
| 97 | -} | ||
| 98 | - | ||
| 99 | -/// Per-slice values the deblocking filter needs after slice decode ends. | ||
| 100 | -#[derive(Debug, Clone, Copy)] | ||
| 101 | -struct SliceParams { | ||
| 102 | - disable_deblock_idc: u8, | ||
| 103 | - alpha_offset: i32, | ||
| 104 | - beta_offset: i32, | ||
| 105 | - cb_qp_offset: i32, | ||
| 106 | - cr_qp_offset: i32, | ||
| 107 | } | 99 | } |
| 108 | 100 | ||
| 109 | -/// Flat per-picture decode context (see module docs for the layout story). | 101 | +/// Streaming H.264 decoder (frame-coded 4:2:0 8-bit; unsupported features come |
| 110 | -#[derive(Debug, Default)] | 102 | +/// back as named [`Error::Unsupported`] values, never wrong pixels). |
| 111 | -struct Picture { | ||
| 112 | - sps_id: u8, | ||
| 113 | - mb_w: usize, | ||
| 114 | - mb_h: usize, | ||
| 115 | - y: Plane8, | ||
| 116 | - cb: Plane8, | ||
| 117 | - cr: Plane8, | ||
| 118 | - /// TotalCoeff per luma 4x4 block, `(mb_w * 4) x (mb_h * 4)`. | ||
| 119 | - nz_y: Vec<u8>, | ||
| 120 | - /// TotalCoeff per chroma 4x4 block, `(mb_w * 2) x (mb_h * 2)`, Cb and Cr. | ||
| 121 | - nz_c: [Vec<u8>; 2], | ||
| 122 | - /// Intra4x4PredMode per luma 4x4 block (2 = DC for non-I4x4 MBs). | ||
| 123 | - i4_modes: Vec<u8>, | ||
| 124 | - /// QPY per macroblock (the prediction-chain value; PCM keeps the chain). | ||
| 125 | - mb_qp: Vec<u8>, | ||
| 126 | - /// `FLAG_*` bits per macroblock. | ||
| 127 | - mb_flags: Vec<u8>, | ||
| 128 | - /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4` per macroblock, | ||
| 129 | - /// read by CABAC context selection (9.3.3.1.1.4). | ||
| 130 | - mb_cbp: Vec<u8>, | ||
| 131 | - /// coded_block_flag of the DC blocks per macroblock: bit 0 luma, 1 Cb, | ||
| 132 | - /// 2 Cr (9.3.3.1.1.9 with ctxBlockCat 0 and 3). | ||
| 133 | - mb_dc_cbf: Vec<u8>, | ||
| 134 | - /// Owning slice index per macroblock, `NO_SLICE` when undecoded. | ||
| 135 | - mb_slice: Vec<u16>, | ||
| 136 | - slices: Vec<SliceParams>, | ||
| 137 | - decoded_mbs: usize, | ||
| 138 | - complete: bool, | ||
| 139 | -} | ||
| 140 | - | ||
| 141 | -impl Picture { | ||
| 142 | - fn start(&mut self, sps: &Sps) { | ||
| 143 | - let mb_w = sps.mb_width as usize; | ||
| 144 | - let mb_h = sps.mb_height as usize; | ||
| 145 | - if self.mb_w != mb_w || self.mb_h != mb_h || self.sps_id != sps.id { | ||
| 146 | - self.mb_w = mb_w; | ||
| 147 | - self.mb_h = mb_h; | ||
| 148 | - self.sps_id = sps.id; | ||
| 149 | - self.y.resize(mb_w * 16, mb_h * 16, PAD_Y); | ||
| 150 | - self.cb.resize(mb_w * 8, mb_h * 8, PAD_C); | ||
| 151 | - self.cr.resize(mb_w * 8, mb_h * 8, PAD_C); | ||
| 152 | - self.nz_y.resize(mb_w * mb_h * 16, 0); | ||
| 153 | - for c in &mut self.nz_c { | ||
| 154 | - c.resize(mb_w * mb_h * 4, 0); | ||
| 155 | - } | ||
| 156 | - self.i4_modes.resize(mb_w * mb_h * 16, 2); | ||
| 157 | - self.mb_qp.resize(mb_w * mb_h, 0); | ||
| 158 | - self.mb_flags.resize(mb_w * mb_h, 0); | ||
| 159 | - self.mb_cbp.resize(mb_w * mb_h, 0); | ||
| 160 | - self.mb_dc_cbf.resize(mb_w * mb_h, 0); | ||
| 161 | - self.mb_slice.resize(mb_w * mb_h, NO_SLICE); | ||
| 162 | - } | ||
| 163 | - // Per-MB metadata is rewritten by each decoded macroblock; only the | ||
| 164 | - // "who is decoded" state must be wiped between pictures. | ||
| 165 | - self.mb_slice.fill(NO_SLICE); | ||
| 166 | - self.mb_flags.fill(0); | ||
| 167 | - self.slices.clear(); | ||
| 168 | - self.decoded_mbs = 0; | ||
| 169 | - self.complete = false; | ||
| 170 | - } | ||
| 171 | -} | ||
| 172 | - | ||
| 173 | -/// Streaming H.264 decoder (CAVLC intra scope; unsupported features come back | ||
| 174 | -/// as named [`Error::Unsupported`] values, never wrong pixels). | ||
| 175 | pub struct Decoder { | 103 | pub struct Decoder { |
| 176 | sps_map: Vec<Option<Sps>>, | 104 | sps_map: Vec<Option<Sps>>, |
| 177 | pps_map: Vec<Option<Pps>>, | 105 | pps_map: Vec<Option<Pps>>, |
| 178 | rbsp: Vec<u8>, | 106 | rbsp: Vec<u8>, |
| 179 | - pic: Picture, | 107 | + /// The picture being decoded, held out of the buffer pool. |
| 108 | + cur: Picture, | ||
| 109 | + dpb: Dpb, | ||
| 180 | has_picture: bool, | 110 | has_picture: bool, |
| 181 | - /// Scaling factors for intra Y/Cb/Cr 4x4 lists of the active PPS/SPS. | 111 | + /// Scaling factors of the active PPS/SPS, `[intra, inter][Y, Cb, Cr]`. |
| 182 | - ls: [LevelScale4x4; 3], | 112 | + ls: [[LevelScale4x4; 3]; 2], |
| 183 | active_pps: Option<u32>, | 113 | active_pps: Option<u32>, |
| 184 | /// `seq_parameter_set_id` of the most recently stored SPS, so a container | 114 | /// `seq_parameter_set_id` of the most recently stored SPS, so a container |
| 185 | /// entry path can publish the picture size before the first slice. | 115 | /// entry path can publish the picture size before the first slice. |
| 186 | last_sps: Option<u8>, | 116 | last_sps: Option<u8>, |
| 117 | + /// Clause 8.2 view of the open picture, from its first slice header. | ||
| 118 | + cur_info: PicInfo, | ||
| 119 | + /// `dec_ref_pic_marking( )` of the open picture, kept in place so a | ||
| 120 | + /// steady-state loop does not reallocate its MMCO list. | ||
| 121 | + cur_marking: DecRefPicMarking, | ||
| 122 | + has_marking: bool, | ||
| 123 | + /// Identity of the picture `end_picture` completed most recently. | ||
| 124 | + last_decoded: i32, | ||
| 125 | + output_order: OutputOrder, | ||
| 126 | + out: VecDeque<VideoFrame>, | ||
| 127 | + /// Presentation timestamp to attach to the next picture started. | ||
| 128 | + pending_pts: Option<Timestamp>, | ||
| 187 | } | 129 | } |
| 188 | 130 | ||
| 189 | /// What [`Decoder::push_nal`] did with a NAL unit. | 131 | /// What [`Decoder::push_nal`] did with a NAL unit. |
| @@ -196,7 +138,7 @@ pub enum NalOutcome { | |||
| 196 | /// A slice was decoded into the open picture. | 138 | /// A slice was decoded into the open picture. |
| 197 | SliceDecoded, | 139 | SliceDecoded, |
| 198 | /// The NAL starts a new picture while one is open; it was not consumed. | 140 | /// The NAL starts a new picture while one is open; it was not consumed. |
| 199 | - /// Call [`Decoder::end_picture`] + [`Decoder::frame`], then push it again. | 141 | + /// Call [`Decoder::end_picture`], then push it again. |
| 200 | PictureBoundary, | 142 | PictureBoundary, |
| 201 | } | 143 | } |
| 202 | 144 | ||
| @@ -206,6 +148,21 @@ impl Default for Decoder { | |||
| 206 | } | 148 | } |
| 207 | } | 149 | } |
| 208 | 150 | ||
| 151 | +fn flat_scaling() -> [[LevelScale4x4; 3]; 2] { | ||
| 152 | + [ | ||
| 153 | + [ | ||
| 154 | + LevelScale4x4::new(&[16; 16]), | ||
| 155 | + LevelScale4x4::new(&[16; 16]), | ||
| 156 | + LevelScale4x4::new(&[16; 16]), | ||
| 157 | + ], | ||
| 158 | + [ | ||
| 159 | + LevelScale4x4::new(&[16; 16]), | ||
| 160 | + LevelScale4x4::new(&[16; 16]), | ||
| 161 | + LevelScale4x4::new(&[16; 16]), | ||
| 162 | + ], | ||
| 163 | + ] | ||
| 164 | +} | ||
| 165 | + | ||
| 209 | impl Decoder { | 166 | impl Decoder { |
| 210 | /// A fresh decoder with no parameter sets. | 167 | /// A fresh decoder with no parameter sets. |
| 211 | pub fn new() -> Decoder { | 168 | pub fn new() -> Decoder { |
| @@ -213,18 +170,46 @@ impl Decoder { | |||
| 213 | sps_map: vec![None; 32], | 170 | sps_map: vec![None; 32], |
| 214 | pps_map: vec![None; 256], | 171 | pps_map: vec![None; 256], |
| 215 | rbsp: Vec::new(), | 172 | rbsp: Vec::new(), |
| 216 | - pic: Picture::default(), | 173 | + cur: Picture::default(), |
| 174 | + dpb: Dpb::default(), | ||
| 217 | has_picture: false, | 175 | has_picture: false, |
| 218 | - ls: [ | 176 | + ls: flat_scaling(), |
| 219 | - LevelScale4x4::new(&[16; 16]), | ||
| 220 | - LevelScale4x4::new(&[16; 16]), | ||
| 221 | - LevelScale4x4::new(&[16; 16]), | ||
| 222 | - ], | ||
| 223 | active_pps: None, | 177 | active_pps: None, |
| 224 | last_sps: None, | 178 | last_sps: None, |
| 179 | + cur_info: PicInfo { | ||
| 180 | + is_idr: false, | ||
| 181 | + is_reference: false, | ||
| 182 | + frame_num: 0, | ||
| 183 | + pic_order_cnt_lsb: 0, | ||
| 184 | + delta_pic_order_cnt_bottom: 0, | ||
| 185 | + delta_pic_order_cnt: [0; 2], | ||
| 186 | + }, | ||
| 187 | + cur_marking: DecRefPicMarking::default(), | ||
| 188 | + has_marking: false, | ||
| 189 | + last_decoded: -1, | ||
| 190 | + output_order: OutputOrder::default(), | ||
| 191 | + out: VecDeque::new(), | ||
| 192 | + pending_pts: None, | ||
| 225 | } | 193 | } |
| 226 | } | 194 | } |
| 227 | 195 | ||
| 196 | + /// Choose between display order (the default) and decode order. | ||
| 197 | + pub fn set_output_order(&mut self, order: OutputOrder) { | ||
| 198 | + self.output_order = order; | ||
| 199 | + } | ||
| 200 | + | ||
| 201 | + /// The order pictures are handed back in. | ||
| 202 | + pub fn output_order(&self) -> OutputOrder { | ||
| 203 | + self.output_order | ||
| 204 | + } | ||
| 205 | + | ||
| 206 | + /// Attach `pts` to the next picture started, so a presentation timestamp | ||
| 207 | + /// follows its picture through reordering instead of staying with the | ||
| 208 | + /// packet that carried it. | ||
| 209 | + pub fn set_next_pts(&mut self, pts: Option<Timestamp>) { | ||
| 210 | + self.pending_pts = pts; | ||
| 211 | + } | ||
| 212 | + | ||
| 228 | /// Cropped picture size of the most recently stored SPS, `None` until one | 213 | /// Cropped picture size of the most recently stored SPS, `None` until one |
| 229 | /// arrives. Lets a container entry path fill in stream parameters from an | 214 | /// arrives. Lets a container entry path fill in stream parameters from an |
| 230 | /// `avcC` record without decoding a picture first. | 215 | /// `avcC` record without decoding a picture first. |
| @@ -264,6 +249,7 @@ impl Decoder { | |||
| 264 | self.rbsp = rbsp; | 249 | self.rbsp = rbsp; |
| 265 | let sps = sps?; | 250 | let sps = sps?; |
| 266 | let id = sps.id; | 251 | let id = sps.id; |
| 252 | + self.dpb.configure(&sps); | ||
| 267 | self.sps_map[id as usize] = Some(sps); | 253 | self.sps_map[id as usize] = Some(sps); |
| 268 | self.last_sps = Some(id); | 254 | self.last_sps = Some(id); |
| 269 | Ok(NalOutcome::ParameterSet) | 255 | Ok(NalOutcome::ParameterSet) |
| @@ -296,22 +282,94 @@ impl Decoder { | |||
| 296 | } | 282 | } |
| 297 | } | 283 | } |
| 298 | 284 | ||
| 299 | - /// Run the deblocking filter over the open picture and mark it complete. | 285 | + /// Run the deblocking filter over the open picture, store it in the decoded |
| 286 | + /// picture buffer and queue whatever pictures that makes ready for output. | ||
| 300 | pub fn end_picture(&mut self) -> Result<()> { | 287 | pub fn end_picture(&mut self) -> Result<()> { |
| 301 | - if !self.has_picture || self.pic.complete { | 288 | + if !self.has_picture || self.cur.complete { |
| 302 | return Err(Error::corrupt("end_picture without an open picture")); | 289 | return Err(Error::corrupt("end_picture without an open picture")); |
| 303 | } | 290 | } |
| 304 | - deblock_picture(&mut self.pic); | 291 | + deblock_picture(&mut self.cur); |
| 305 | - self.pic.complete = true; | 292 | + self.cur.extend_borders(); |
| 306 | - Ok(()) | 293 | + self.cur.complete = true; |
| 294 | + self.last_decoded = self.cur.id; | ||
| 295 | + let sps = self.sps_map[self.cur.sps_id as usize] | ||
| 296 | + .as_ref() | ||
| 297 | + .ok_or_else(|| Error::corrupt("active SPS vanished"))? | ||
| 298 | + .clone(); | ||
| 299 | + let pic = core::mem::take(&mut self.cur); | ||
| 300 | + let marking = self.has_marking.then_some(&self.cur_marking); | ||
| 301 | + self.dpb.store(pic, &sps, &self.cur_info, marking)?; | ||
| 302 | + self.has_picture = false; | ||
| 303 | + self.pump_output(false) | ||
| 307 | } | 304 | } |
| 308 | 305 | ||
| 309 | - /// Copy the completed picture out as a cropped I420 frame. | 306 | + /// Emit every remaining picture (end of stream). |
| 307 | + pub fn flush(&mut self) -> Result<()> { | ||
| 308 | + if self.has_picture && !self.cur.complete { | ||
| 309 | + self.end_picture()?; | ||
| 310 | + } | ||
| 311 | + self.pump_output(true) | ||
| 312 | + } | ||
| 313 | + | ||
| 314 | + /// The next frame ready for output, in the configured order. | ||
| 315 | + pub fn next_frame(&mut self) -> Option<VideoFrame> { | ||
| 316 | + self.out.pop_front() | ||
| 317 | + } | ||
| 318 | + | ||
| 319 | + /// The picture `end_picture` completed most recently, in decode order. | ||
| 320 | + /// | ||
| 321 | + /// Kept for a caller that drives one picture at a time; a player wants | ||
| 322 | + /// [`Decoder::next_frame`], which respects the reordering the stream asks | ||
| 323 | + /// for. | ||
| 310 | pub fn frame(&self) -> Result<VideoFrame> { | 324 | pub fn frame(&self) -> Result<VideoFrame> { |
| 311 | - if !self.pic.complete { | 325 | + let id = self.last_decoded; |
| 312 | - return Err(Error::corrupt("frame() before end_picture()")); | 326 | + let pic = self |
| 327 | + .dpb | ||
| 328 | + .frames | ||
| 329 | + .iter() | ||
| 330 | + .find(|p| p.id == id) | ||
| 331 | + .ok_or_else(|| Error::corrupt("frame() before end_picture()"))?; | ||
| 332 | + self.picture_to_frame(pic) | ||
| 333 | + } | ||
| 334 | + | ||
| 335 | + /// True while a picture is open (started, not completed). | ||
| 336 | + pub fn picture_open(&self) -> bool { | ||
| 337 | + self.has_picture && !self.cur.complete | ||
| 338 | + } | ||
| 339 | + | ||
| 340 | + /// Drop picture state after a seek. Parameter sets survive, because the | ||
| 341 | + /// container does not resend them at every seek point. | ||
| 342 | + pub fn reset_pictures(&mut self) { | ||
| 343 | + self.has_picture = false; | ||
| 344 | + self.cur.complete = false; | ||
| 345 | + self.dpb.clear(); | ||
| 346 | + self.out.clear(); | ||
| 347 | + self.last_decoded = -1; | ||
| 348 | + self.pending_pts = None; | ||
| 349 | + } | ||
| 350 | + | ||
| 351 | + /// Move pictures out of the decoded picture buffer into the output queue. | ||
| 352 | + fn pump_output(&mut self, flush: bool) -> Result<()> { | ||
| 353 | + if self.output_order == OutputOrder::Decode && !flush { | ||
| 354 | + let id = self.last_decoded; | ||
| 355 | + if let Some(i) = self.dpb.frames.iter().position(|p| p.id == id && p.output) { | ||
| 356 | + let frame = self.picture_to_frame(&self.dpb.frames[i])?; | ||
| 357 | + self.out.push_back(frame); | ||
| 358 | + self.dpb.released(i); | ||
| 359 | + } | ||
| 360 | + return Ok(()); | ||
| 313 | } | 361 | } |
| 314 | - let sps = self.sps_map[self.pic.sps_id as usize] | 362 | + while let Some(i) = self.dpb.next_output(flush) { |
| 363 | + let frame = self.picture_to_frame(&self.dpb.frames[i])?; | ||
| 364 | + self.out.push_back(frame); | ||
| 365 | + self.dpb.released(i); | ||
| 366 | + } | ||
| 367 | + Ok(()) | ||
| 368 | + } | ||
| 369 | + | ||
| 370 | + /// Copy a stored picture out as a cropped I420 frame. | ||
| 371 | + fn picture_to_frame(&self, pic: &Picture) -> Result<VideoFrame> { | ||
| 372 | + let sps = self.sps_map[pic.sps_id as usize] | ||
| 315 | .as_ref() | 373 | .as_ref() |
| 316 | .ok_or_else(|| Error::corrupt("active SPS vanished"))?; | 374 | .ok_or_else(|| Error::corrupt("active SPS vanished"))?; |
| 317 | let (w, h) = (sps.width as usize, sps.height as usize); | 375 | let (w, h) = (sps.width as usize, sps.height as usize); |
| @@ -325,9 +383,9 @@ impl Decoder { | |||
| 325 | Plane::new(out, w) | 383 | Plane::new(out, w) |
| 326 | }; | 384 | }; |
| 327 | let planes = vec![ | 385 | let planes = vec![ |
| 328 | - copy(&self.pic.y, cx, cy, w, h), | 386 | + copy(&pic.y, cx, cy, w, h), |
| 329 | - copy(&self.pic.cb, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), | 387 | + copy(&pic.cb, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), |
| 330 | - copy(&self.pic.cr, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), | 388 | + copy(&pic.cr, cx / 2, cy / 2, w.div_ceil(2), h.div_ceil(2)), |
| 331 | ]; | 389 | ]; |
| 332 | let mut frame = VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)?; | 390 | let mut frame = VideoFrame::try_new(PixelFormat::I420, w as u32, h as u32, planes)?; |
| 333 | if let Some(vui) = &sps.vui { | 391 | if let Some(vui) = &sps.vui { |
| @@ -338,21 +396,10 @@ impl Decoder { | |||
| 338 | frame.color.matrix = m; | 396 | frame.color.matrix = m; |
| 339 | } | 397 | } |
| 340 | } | 398 | } |
| 399 | + frame.pts = pic.pts; | ||
| 341 | Ok(frame) | 400 | Ok(frame) |
| 342 | } | 401 | } |
| 343 | 402 | ||
| 344 | - /// True while a picture is open (started, not completed). | ||
| 345 | - pub fn picture_open(&self) -> bool { | ||
| 346 | - self.has_picture && !self.pic.complete | ||
| 347 | - } | ||
| 348 | - | ||
| 349 | - /// Drop picture state after a seek. Parameter sets survive, because the | ||
| 350 | - /// container does not resend them at every seek point. | ||
| 351 | - pub fn reset_pictures(&mut self) { | ||
| 352 | - self.has_picture = false; | ||
| 353 | - self.pic.complete = false; | ||
| 354 | - } | ||
| 355 | - | ||
| 356 | fn decode_slice_rbsp(&mut self, header: NalHeader, rbsp: &[u8]) -> Result<NalOutcome> { | 403 | fn decode_slice_rbsp(&mut self, header: NalHeader, rbsp: &[u8]) -> Result<NalOutcome> { |
| 357 | // Peek first_mb / slice_type / pps_id to select parameter sets. | 404 | // Peek first_mb / slice_type / pps_id to select parameter sets. |
| 358 | let mut peek = BitReader::new(rbsp); | 405 | let mut peek = BitReader::new(rbsp); |
| @@ -362,7 +409,7 @@ impl Decoder { | |||
| 362 | if pps_id > 255 { | 409 | if pps_id > 255 { |
| 363 | return Err(Error::corrupt("pic_parameter_set_id > 255")); | 410 | return Err(Error::corrupt("pic_parameter_set_id > 255")); |
| 364 | } | 411 | } |
| 365 | - if self.has_picture && !self.pic.complete && first_mb == 0 && self.pic.decoded_mbs > 0 { | 412 | + if self.has_picture && !self.cur.complete && first_mb == 0 && self.cur.decoded_mbs > 0 { |
| 366 | return Ok(NalOutcome::PictureBoundary); | 413 | return Ok(NalOutcome::PictureBoundary); |
| 367 | } | 414 | } |
| 368 | let pps = self.pps_map[pps_id as usize] | 415 | let pps = self.pps_map[pps_id as usize] |
| @@ -374,39 +421,20 @@ impl Decoder { | |||
| 374 | 421 | ||
| 375 | check_supported(sps, pps, slice_type_code)?; | 422 | check_supported(sps, pps, slice_type_code)?; |
| 376 | let sh = SliceHeader::parse(rbsp, header, sps, pps)?; | 423 | let sh = SliceHeader::parse(rbsp, header, sps, pps)?; |
| 377 | - if sh.slice_type != SliceType::I { | 424 | + let sps = sps.clone(); |
| 378 | - return Err(Error::unsupported( | 425 | + let pps = pps.clone(); |
| 379 | - "non-I slice", | ||
| 380 | - "P/B/SP/SI slices need inter prediction and a decoded picture \ | ||
| 381 | - buffer (clause 8.4); only intra slices are decoded", | ||
| 382 | - )); | ||
| 383 | - } | ||
| 384 | 426 | ||
| 385 | - if !self.has_picture || self.pic.complete { | 427 | + if !self.has_picture || self.cur.complete { |
| 386 | - self.pic.start(sps); | 428 | + self.start_picture(&sps, &pps, &sh, header)?; |
| 387 | - self.has_picture = true; | ||
| 388 | - if self.active_pps != Some(pps.id) { | ||
| 389 | - let lists = pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref()); | ||
| 390 | - let weights = match lists { | ||
| 391 | - Some(l) => [&l.list_4x4[0], &l.list_4x4[1], &l.list_4x4[2]], | ||
| 392 | - None => [&[16u8; 16]; 3], | ||
| 393 | - }; | ||
| 394 | - self.ls = [ | ||
| 395 | - LevelScale4x4::new(weights[0]), | ||
| 396 | - LevelScale4x4::new(weights[1]), | ||
| 397 | - LevelScale4x4::new(weights[2]), | ||
| 398 | - ]; | ||
| 399 | - self.active_pps = Some(pps.id); | ||
| 400 | } | 429 | } |
| 401 | - } | 430 | + if self.cur.sps_id != sps.id { |
| 402 | - if self.pic.sps_id != sps.id { | ||
| 403 | return Err(Error::corrupt("SPS changed mid-picture")); | 431 | return Err(Error::corrupt("SPS changed mid-picture")); |
| 404 | } | 432 | } |
| 405 | - if self.pic.slices.len() >= usize::from(u16::MAX) { | 433 | + if self.cur.slices.len() >= usize::from(u16::MAX) { |
| 406 | return Err(Error::corrupt("more than 65534 slices in a picture")); | 434 | return Err(Error::corrupt("more than 65534 slices in a picture")); |
| 407 | } | 435 | } |
| 408 | - let slice_id = self.pic.slices.len() as u16; | 436 | + let slice_id = self.cur.slices.len() as u16; |
| 409 | - self.pic.slices.push(SliceParams { | 437 | + self.cur.slices.push(SliceParams { |
| 410 | disable_deblock_idc: sh.deblock.disable_idc, | 438 | disable_deblock_idc: sh.deblock.disable_idc, |
| 411 | alpha_offset: sh.deblock.alpha_c0_offset, | 439 | alpha_offset: sh.deblock.alpha_c0_offset, |
| 412 | beta_offset: sh.deblock.beta_offset, | 440 | beta_offset: sh.deblock.beta_offset, |
| @@ -414,34 +442,236 @@ impl Decoder { | |||
| 414 | cr_qp_offset: pps.second_chroma_qp_index_offset, | 442 | cr_qp_offset: pps.second_chroma_qp_index_offset, |
| 415 | }); | 443 | }); |
| 416 | 444 | ||
| 445 | + // Reference picture lists (clause 8.2.4), rebuilt per slice because | ||
| 446 | + // num_ref_idx_active and the modification list are slice header state. | ||
| 447 | + let max_pic_num = 1i32 << sps.log2_max_frame_num; | ||
| 448 | + let lists = if sh.slice_type.is_intra() { | ||
| 449 | + [RefList::default(), RefList::default()] | ||
| 450 | + } else { | ||
| 451 | + self.dpb.number_short_term(sh.frame_num, &sps); | ||
| 452 | + self.dpb.build_ref_lists( | ||
| 453 | + sh.slice_type, | ||
| 454 | + self.cur.poc, | ||
| 455 | + sh.frame_num as i32, | ||
| 456 | + max_pic_num, | ||
| 457 | + sh.num_ref_idx_l0_active as usize, | ||
| 458 | + sh.num_ref_idx_l1_active as usize, | ||
| 459 | + (&sh.ref_pic_list_mod_l0, &sh.ref_pic_list_mod_l1), | ||
| 460 | + )? | ||
| 461 | + }; | ||
| 462 | + | ||
| 417 | let mut r = if pps.entropy_coding_mode { | 463 | let mut r = if pps.entropy_coding_mode { |
| 418 | - Entropy::cabac(rbsp, sh.header_bits, sh.slice_qp)? | 464 | + let column = if sh.slice_type.is_intra() { |
| 465 | + 0 | ||
| 466 | + } else { | ||
| 467 | + sh.cabac_init_idc as usize + 1 | ||
| 468 | + }; | ||
| 469 | + Entropy::cabac(rbsp, sh.header_bits, sh.slice_qp, column)? | ||
| 419 | } else { | 470 | } else { |
| 420 | Entropy::cavlc(rbsp, sh.header_bits) | 471 | Entropy::cavlc(rbsp, sh.header_bits) |
| 421 | }; | 472 | }; |
| 422 | 473 | ||
| 423 | let mut ctx = SliceCtx { | 474 | let mut ctx = SliceCtx { |
| 424 | slice_id, | 475 | slice_id, |
| 476 | + slice_type: sh.slice_type, | ||
| 425 | qp: sh.slice_qp, | 477 | qp: sh.slice_qp, |
| 426 | cb_qp_offset: pps.chroma_qp_index_offset, | 478 | cb_qp_offset: pps.chroma_qp_index_offset, |
| 427 | cr_qp_offset: pps.second_chroma_qp_index_offset, | 479 | cr_qp_offset: pps.second_chroma_qp_index_offset, |
| 428 | transform_8x8_mode: pps.transform_8x8_mode, | 480 | transform_8x8_mode: pps.transform_8x8_mode, |
| 481 | + constrained_intra_pred: pps.constrained_intra_pred, | ||
| 429 | qp_delta_inc: 0, | 482 | qp_delta_inc: 0, |
| 483 | + lists, | ||
| 484 | + num_ref_idx: [ | ||
| 485 | + sh.num_ref_idx_l0_active as usize, | ||
| 486 | + sh.num_ref_idx_l1_active as usize, | ||
| 487 | + ], | ||
| 488 | + direct_spatial: sh.direct_spatial_mv_pred, | ||
| 489 | + direct_8x8_inference: sps.direct_8x8_inference, | ||
| 490 | + weighted_pred: pps.weighted_pred, | ||
| 491 | + weighted_bipred_idc: pps.weighted_bipred_idc, | ||
| 492 | + weights: sh.pred_weight_table.clone(), | ||
| 493 | + poc: self.cur.poc, | ||
| 430 | }; | 494 | }; |
| 431 | - let mbs = self.pic.mb_w * self.pic.mb_h; | 495 | + let intra_slice = sh.slice_type.is_intra(); |
| 496 | + let b_slice = sh.slice_type == SliceType::B; | ||
| 497 | + if !intra_slice && ctx.lists[0].len() == 0 { | ||
| 498 | + return Err(Error::corrupt("inter slice with no reference pictures")); | ||
| 499 | + } | ||
| 500 | + | ||
| 501 | + let mbs = self.cur.mb_w * self.cur.mb_h; | ||
| 432 | let mut mb_addr = first_mb as usize; | 502 | let mut mb_addr = first_mb as usize; |
| 433 | - loop { | 503 | + let mut more = true; |
| 504 | + while more { | ||
| 434 | if mb_addr >= mbs { | 505 | if mb_addr >= mbs { |
| 435 | return Err(Error::corrupt("macroblock address beyond the picture")); | 506 | return Err(Error::corrupt("macroblock address beyond the picture")); |
| 436 | } | 507 | } |
| 437 | - decode_macroblock(&mut self.pic, &self.ls, &mut r, &mut ctx, mb_addr)?; | 508 | + let mut decode_mb = true; |
| 438 | - if !r.more_macroblocks()? { | 509 | + if !intra_slice { |
| 510 | + if r.is_cabac() { | ||
| 511 | + self.begin_mb(&mut r, &ctx, mb_addr); | ||
| 512 | + let inc = self.skip_inc(&ctx, mb_addr); | ||
| 513 | + if r.mb_skip_flag(b_slice, inc)? { | ||
| 514 | + decode_macroblock( | ||
| 515 | + &mut self.cur, | ||
| 516 | + &self.dpb.frames, | ||
| 517 | + &self.ls, | ||
| 518 | + &mut r, | ||
| 519 | + &mut ctx, | ||
| 520 | + mb_addr, | ||
| 521 | + true, | ||
| 522 | + )?; | ||
| 523 | + decode_mb = false; | ||
| 524 | + } | ||
| 525 | + } else { | ||
| 526 | + let run = r.mb_skip_run()?; | ||
| 527 | + for _ in 0..run { | ||
| 528 | + if mb_addr >= mbs { | ||
| 529 | + return Err(Error::corrupt("mb_skip_run past the picture")); | ||
| 530 | + } | ||
| 531 | + decode_macroblock( | ||
| 532 | + &mut self.cur, | ||
| 533 | + &self.dpb.frames, | ||
| 534 | + &self.ls, | ||
| 535 | + &mut r, | ||
| 536 | + &mut ctx, | ||
| 537 | + mb_addr, | ||
| 538 | + true, | ||
| 539 | + )?; | ||
| 540 | + mb_addr += 1; | ||
| 541 | + } | ||
| 542 | + if run > 0 { | ||
| 543 | + more = r.more_macroblocks()?; | ||
| 544 | + if !more { | ||
| 439 | break; | 545 | break; |
| 440 | } | 546 | } |
| 547 | + if mb_addr >= mbs { | ||
| 548 | + return Err(Error::corrupt("macroblock address beyond the picture")); | ||
| 549 | + } | ||
| 550 | + } | ||
| 551 | + } | ||
| 552 | + } | ||
| 553 | + if decode_mb { | ||
| 554 | + decode_macroblock( | ||
| 555 | + &mut self.cur, | ||
| 556 | + &self.dpb.frames, | ||
| 557 | + &self.ls, | ||
| 558 | + &mut r, | ||
| 559 | + &mut ctx, | ||
| 560 | + mb_addr, | ||
| 561 | + false, | ||
| 562 | + )?; | ||
| 563 | + } | ||
| 564 | + more = r.more_macroblocks()?; | ||
| 441 | mb_addr += 1; | 565 | mb_addr += 1; |
| 442 | } | 566 | } |
| 443 | Ok(NalOutcome::SliceDecoded) | 567 | Ok(NalOutcome::SliceDecoded) |
| 444 | } | 568 | } |
| 569 | + | ||
| 570 | + /// Publish the neighbourhood of `mb_addr` to a CABAC reader ahead of | ||
| 571 | + /// mb_skip_flag, which is decoded before the macroblock layer. | ||
| 572 | + fn begin_mb(&self, r: &mut Entropy<'_>, ctx: &SliceCtx, mb_addr: usize) { | ||
| 573 | + let pic = &self.cur; | ||
| 574 | + let mb_x = mb_addr % pic.mb_w; | ||
| 575 | + let mb_y = mb_addr / pic.mb_w; | ||
| 576 | + let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id); | ||
| 577 | + let info = |addr: usize| MbInfo { | ||
| 578 | + flags: pic.mb_flags[addr], | ||
| 579 | + cbp: pic.mb_cbp[addr], | ||
| 580 | + dc_cbf: pic.mb_dc_cbf[addr], | ||
| 581 | + }; | ||
| 582 | + r.begin_mb(&MbCtx { | ||
| 583 | + a: nbr.a.then(|| info(mb_addr - 1)), | ||
| 584 | + b: nbr.b.then(|| info(mb_addr - pic.mb_w)), | ||
| 585 | + qp_delta_inc: ctx.qp_delta_inc, | ||
| 586 | + }); | ||
| 587 | + } | ||
| 588 | + | ||
| 589 | + /// ctxIdxInc for mb_skip_flag (9.3.3.1.1.1): a neighbour counts unless it | ||
| 590 | + /// is unavailable or was itself skipped. | ||
| 591 | + fn skip_inc(&self, ctx: &SliceCtx, mb_addr: usize) -> usize { | ||
| 592 | + let pic = &self.cur; | ||
| 593 | + let mb_x = mb_addr % pic.mb_w; | ||
| 594 | + let mb_y = mb_addr / pic.mb_w; | ||
| 595 | + let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id); | ||
| 596 | + let cond = |avail: bool, addr: usize| { | ||
| 597 | + usize::from(avail && pic.mb_flags[addr] & FLAG_SKIP == 0) | ||
| 598 | + }; | ||
| 599 | + cond(nbr.a, mb_addr.wrapping_sub(1)) + cond(nbr.b, mb_addr.wrapping_sub(pic.mb_w)) | ||
| 600 | + } | ||
| 601 | + | ||
| 602 | + /// Open a new picture: clause 8.2 bookkeeping, then the geometry reset. | ||
| 603 | + fn start_picture( | ||
| 604 | + &mut self, | ||
| 605 | + sps: &Sps, | ||
| 606 | + pps: &Pps, | ||
| 607 | + sh: &SliceHeader, | ||
| 608 | + header: NalHeader, | ||
| 609 | + ) -> Result<()> { | ||
| 610 | + let info = PicInfo { | ||
| 611 | + is_idr: header.is_idr(), | ||
| 612 | + is_reference: header.ref_idc != 0, | ||
| 613 | + frame_num: sh.frame_num, | ||
| 614 | + pic_order_cnt_lsb: sh.pic_order_cnt_lsb, | ||
| 615 | + delta_pic_order_cnt_bottom: sh.delta_pic_order_cnt_bottom, | ||
| 616 | + delta_pic_order_cnt: sh.delta_pic_order_cnt, | ||
| 617 | + }; | ||
| 618 | + // A frame_num gap is what a seek or a dropped packet looks like: the | ||
| 619 | + // pictures it names never arrive, so clause 8.2.5.2 infers them and | ||
| 620 | + // decoding continues rather than stalling until the next IDR. | ||
| 621 | + if !info.is_idr && self.dpb.frame_num_gap(sps, sh.frame_num) { | ||
| 622 | + if !sps.gaps_in_frame_num_allowed { | ||
| 623 | + // Not a conformant gap: pictures were lost. Same repair. | ||
| 624 | + self.dpb.fill_frame_num_gap(sps, sh.frame_num)?; | ||
| 625 | + } else { | ||
| 626 | + self.dpb.fill_frame_num_gap(sps, sh.frame_num)?; | ||
| 627 | + } | ||
| 628 | + self.pump_output(false)?; | ||
| 629 | + } | ||
| 630 | + let poc = self.dpb.picture_order_count(sps, &info)?; | ||
| 631 | + let mut pic = self.dpb.take_picture(); | ||
| 632 | + pic.start(sps); | ||
| 633 | + pic.poc = poc.value; | ||
| 634 | + pic.poc_msb = poc.msb; | ||
| 635 | + pic.poc_lsb = poc.lsb; | ||
| 636 | + pic.frame_num_offset = poc.frame_num_offset; | ||
| 637 | + pic.frame_num = sh.frame_num; | ||
| 638 | + pic.pts = self.pending_pts.take(); | ||
| 639 | + self.cur = pic; | ||
| 640 | + self.cur_info = info; | ||
| 641 | + self.has_marking = sh.dec_ref_pic_marking.is_some(); | ||
| 642 | + if let Some(m) = &sh.dec_ref_pic_marking { | ||
| 643 | + self.cur_marking.no_output_of_prior_pics = m.no_output_of_prior_pics; | ||
| 644 | + self.cur_marking.long_term_reference = m.long_term_reference; | ||
| 645 | + self.cur_marking.adaptive = m.adaptive; | ||
| 646 | + self.cur_marking.mmcos.clear(); | ||
| 647 | + self.cur_marking.mmcos.extend_from_slice(&m.mmcos); | ||
| 648 | + } | ||
| 649 | + self.has_picture = true; | ||
| 650 | + if self.active_pps != Some(pps.id) { | ||
| 651 | + let lists = pps.scaling_lists.as_ref().or(sps.scaling_lists.as_ref()); | ||
| 652 | + let weights = match lists { | ||
| 653 | + Some(l) => [ | ||
| 654 | + [&l.list_4x4[0], &l.list_4x4[1], &l.list_4x4[2]], | ||
| 655 | + [&l.list_4x4[3], &l.list_4x4[4], &l.list_4x4[5]], | ||
| 656 | + ], | ||
| 657 | + None => [[&[16u8; 16]; 3]; 2], | ||
| 658 | + }; | ||
| 659 | + self.ls = [ | ||
| 660 | + [ | ||
| 661 | + LevelScale4x4::new(weights[0][0]), | ||
| 662 | + LevelScale4x4::new(weights[0][1]), | ||
| 663 | + LevelScale4x4::new(weights[0][2]), | ||
| 664 | + ], | ||
| 665 | + [ | ||
| 666 | + LevelScale4x4::new(weights[1][0]), | ||
| 667 | + LevelScale4x4::new(weights[1][1]), | ||
| 668 | + LevelScale4x4::new(weights[1][2]), | ||
| 669 | + ], | ||
| 670 | + ]; | ||
| 671 | + self.active_pps = Some(pps.id); | ||
| 672 | + } | ||
| 673 | + Ok(()) | ||
| 674 | + } | ||
| 445 | } | 675 | } |
| 446 | 676 | ||
| 447 | /// Reject unsupported streams with named reasons before touching pixels. | 677 | /// 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<()> { | |||
| 502 | if slice_type_code > 9 { | 732 | if slice_type_code > 9 { |
| 503 | return Err(Error::corrupt("slice_type > 9")); | 733 | return Err(Error::corrupt("slice_type > 9")); |
| 504 | } | 734 | } |
| 735 | + if matches!(slice_type_code % 5, 3 | 4) { | ||
| 736 | + return Err(Error::unsupported( | ||
| 737 | + "SP and SI slices", | ||
| 738 | + "switching slices need the transform-domain reconstruction of \ | ||
| 739 | + clause 8.5.14 and their own deblocking strengths; not implemented", | ||
| 740 | + )); | ||
| 741 | + } | ||
| 505 | Ok(()) | 742 | Ok(()) |
| 506 | } | 743 | } |
| 507 | 744 | ||
| 508 | /// Mutable per-slice decode state. | 745 | /// Mutable per-slice decode state. |
| 509 | struct SliceCtx { | 746 | struct SliceCtx { |
| 510 | slice_id: u16, | 747 | slice_id: u16, |
| 748 | + slice_type: SliceType, | ||
| 511 | qp: i32, | 749 | qp: i32, |
| 512 | cb_qp_offset: i32, | 750 | cb_qp_offset: i32, |
| 513 | cr_qp_offset: i32, | 751 | cr_qp_offset: i32, |
| 514 | transform_8x8_mode: bool, | 752 | transform_8x8_mode: bool, |
| 753 | + constrained_intra_pred: bool, | ||
| 515 | /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the | 754 | /// ctxIdxInc for the next macroblock's first mb_qp_delta bin: set when the |
| 516 | /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5). | 755 | /// macroblock just decoded coded a non-zero mb_qp_delta (9.3.3.1.1.5). |
| 517 | qp_delta_inc: u8, | 756 | qp_delta_inc: u8, |
| 757 | + /// `RefPicList0` and `RefPicList1` as decoded picture buffer indices. | ||
| 758 | + lists: [RefList; 2], | ||
| 759 | + num_ref_idx: [usize; 2], | ||
| 760 | + direct_spatial: bool, | ||
| 761 | + direct_8x8_inference: bool, | ||
| 762 | + weighted_pred: bool, | ||
| 763 | + weighted_bipred_idc: u8, | ||
| 764 | + weights: Option<PredWeightTable>, | ||
| 765 | + /// `PicOrderCnt( CurrPic )`. | ||
| 766 | + poc: i32, | ||
| 767 | +} | ||
| 768 | + | ||
| 769 | +impl SliceCtx { | ||
| 770 | + fn is_b(&self) -> bool { | ||
| 771 | + self.slice_type == SliceType::B | ||
| 772 | + } | ||
| 773 | + | ||
| 774 | + /// The reference picture `RefPicListX[idx]` points at. | ||
| 775 | + fn reference<'a>(&self, refs: &'a [Picture], list: usize, idx: i8) -> Option<&'a Picture> { | ||
| 776 | + if idx < 0 { | ||
| 777 | + return None; | ||
| 778 | + } | ||
| 779 | + refs.get(self.lists[list].get(idx as usize)?) | ||
| 518 | } | 780 | } |
| 519 | 781 | ||
| 520 | -/// Neighbour-availability snapshot for one macroblock (left, top, | 782 | + /// Prediction weights of one component (clause 8.4.3). |
| 521 | -/// top-right). Top-left availability follows from the modes that read it | 783 | + fn weights_for( |
| 522 | -/// being conformance-restricted; inter prediction will add it back. | 784 | + &self, |
| 785 | + refs: &[Picture], | ||
| 786 | + comp: usize, | ||
| 787 | + r0: i8, | ||
| 788 | + r1: i8, | ||
| 789 | + use0: bool, | ||
| 790 | + use1: bool, | ||
| 791 | + ) -> Weights { | ||
| 792 | + let implicit = self.weighted_bipred_idc == 2 && self.is_b() && use0 && use1; | ||
| 793 | + let explicit = (self.weighted_bipred_idc == 1 && self.is_b()) | ||
| 794 | + || (self.weighted_pred && !self.is_b()); | ||
| 795 | + if implicit { | ||
| 796 | + let (Some(p0), Some(p1)) = ( | ||
| 797 | + self.reference(refs, 0, r0), | ||
| 798 | + self.reference(refs, 1, r1), | ||
| 799 | + ) else { | ||
| 800 | + return Weights::DEFAULT; | ||
| 801 | + }; | ||
| 802 | + let td = (p1.poc - p0.poc).clamp(-128, 127); | ||
| 803 | + let long_term = p0.mark == Mark::Long || p1.mark == Mark::Long; | ||
| 804 | + if td == 0 || long_term { | ||
| 805 | + return Weights { | ||
| 806 | + log_wd: 5, | ||
| 807 | + w: [32, 32], | ||
| 808 | + o: [0, 0], | ||
| 809 | + }; | ||
| 810 | + } | ||
| 811 | + let tb = (self.poc - p0.poc).clamp(-128, 127); | ||
| 812 | + let tx = (16384 + (td / 2).abs()) / td; | ||
| 813 | + let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023); | ||
| 814 | + let w1 = dist >> 2; | ||
| 815 | + if !(-64..=128).contains(&w1) { | ||
| 816 | + return Weights { | ||
| 817 | + log_wd: 5, | ||
| 818 | + w: [32, 32], | ||
| 819 | + o: [0, 0], | ||
| 820 | + }; | ||
| 821 | + } | ||
| 822 | + return Weights { | ||
| 823 | + log_wd: 5, | ||
| 824 | + w: [64 - w1, w1], | ||
| 825 | + o: [0, 0], | ||
| 826 | + }; | ||
| 827 | + } | ||
| 828 | + if !explicit { | ||
| 829 | + return Weights::DEFAULT; | ||
| 830 | + } | ||
| 831 | + let Some(t) = &self.weights else { | ||
| 832 | + return Weights::DEFAULT; | ||
| 833 | + }; | ||
| 834 | + let denom = if comp == 0 { | ||
| 835 | + t.luma_log2_weight_denom | ||
| 836 | + } else { | ||
| 837 | + t.chroma_log2_weight_denom | ||
| 838 | + } as i32; | ||
| 839 | + let pick = |list: &[WeightEntry], idx: i8| -> (i32, i32) { | ||
| 840 | + let default = (1 << denom, 0); | ||
| 841 | + if idx < 0 { | ||
| 842 | + return default; | ||
| 843 | + } | ||
| 844 | + match list.get(idx as usize) { | ||
| 845 | + None => default, | ||
| 846 | + Some(e) if comp == 0 => e.luma.unwrap_or(default), | ||
| 847 | + Some(e) => e.chroma.map(|c| c[comp - 1]).unwrap_or(default), | ||
| 848 | + } | ||
| 849 | + }; | ||
| 850 | + let (w0, o0) = pick(&t.l0, r0); | ||
| 851 | + let (w1, o1) = pick(&t.l1, r1); | ||
| 852 | + Weights { | ||
| 853 | + log_wd: denom, | ||
| 854 | + w: [w0, w1], | ||
| 855 | + o: [o0, o1], | ||
| 856 | + } | ||
| 857 | + } | ||
| 858 | +} | ||
| 859 | + | ||
| 860 | +/// Neighbour-availability snapshot for one macroblock (left, top, top-right). | ||
| 523 | #[derive(Clone, Copy)] | 861 | #[derive(Clone, Copy)] |
| 524 | struct MbNeighbors { | 862 | struct MbNeighbors { |
| 525 | a: bool, | 863 | a: bool, |
| @@ -538,6 +876,19 @@ fn mb_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, slice_id: u16) -> MbNei | |||
| 538 | } | 876 | } |
| 539 | } | 877 | } |
| 540 | 878 | ||
| 879 | +/// The same, with the constrained intra prediction rule of 7.4.2.2 applied: | ||
| 880 | +/// an inter-coded neighbour is not available as an intra prediction source. | ||
| 881 | +fn intra_neighbors(pic: &Picture, mb_x: usize, mb_y: usize, n: MbNeighbors) -> MbNeighbors { | ||
| 882 | + let w = pic.mb_w; | ||
| 883 | + let addr = mb_y * w + mb_x; | ||
| 884 | + let intra = |a: usize| pic.mb_flags[a] & FLAG_INTER == 0; | ||
| 885 | + MbNeighbors { | ||
| 886 | + a: n.a && intra(addr - 1), | ||
| 887 | + b: n.b && intra(addr - w), | ||
| 888 | + c: n.c && intra(addr - w + 1), | ||
| 889 | + } | ||
| 890 | +} | ||
| 891 | + | ||
| 541 | /// Non-zero counts of the left and above neighbours of the luma 4x4 block at | 892 | /// Non-zero counts of the left and above neighbours of the luma 4x4 block at |
| 542 | /// global block coords `(bx, by)`, `None` when that neighbour is unavailable | 893 | /// global block coords `(bx, by)`, `None` when that neighbour is unavailable |
| 543 | /// (clause 6.4.11.4 plus the availability rules of 6.4.8). | 894 | /// (clause 6.4.11.4 plus the availability rules of 6.4.8). |
| @@ -571,17 +922,30 @@ fn chroma_nz_pair( | |||
| 571 | ) | 922 | ) |
| 572 | } | 923 | } |
| 573 | 924 | ||
| 574 | -/// Decode one macroblock of an I slice (spec 7.3.5, 7.4.5) and reconstruct | 925 | +/// Motion data parsed for one macroblock, before prediction derivation. |
| 575 | -/// it. `ctx.qp` carries the QPY prediction chain. | 926 | +#[derive(Clone, Copy)] |
| 927 | +struct MbMotion { | ||
| 928 | + /// Sub-macroblock types of a P_8x8 / B_8x8 macroblock. | ||
| 929 | + sub: [SubShape; 4], | ||
| 930 | + /// `ref_idx_lX[ mbPartIdx ]`, -1 when the partition does not use the list. | ||
| 931 | + ref_idx: [[i8; 4]; 2], | ||
| 932 | + /// `mvd_lX[ mbPartIdx ][ subMbPartIdx ]`, indexed by 4x4 raster position. | ||
| 933 | + mvd: [[[i16; 2]; 16]; 2], | ||
| 934 | +} | ||
| 935 | + | ||
| 936 | +/// Decode one macroblock (spec 7.3.5, 7.4.5) and reconstruct it. `ctx.qp` | ||
| 937 | +/// carries the QPY prediction chain. | ||
| 576 | // Block loops are indexed: `blk` is simultaneously a bitstream position, a | 938 | // Block loops are indexed: `blk` is simultaneously a bitstream position, a |
| 577 | // geometry key (BLK4_POS) and a grid coordinate; iterators obscure that. | 939 | // geometry key (BLK4_POS) and a grid coordinate; iterators obscure that. |
| 578 | -#[allow(clippy::needless_range_loop)] | 940 | +#[allow(clippy::needless_range_loop, clippy::too_many_arguments)] |
| 579 | fn decode_macroblock( | 941 | fn decode_macroblock( |
| 580 | pic: &mut Picture, | 942 | pic: &mut Picture, |
| 581 | - ls: &[LevelScale4x4; 3], | 943 | + refs: &[Picture], |
| 944 | + ls: &[[LevelScale4x4; 3]; 2], | ||
| 582 | r: &mut Entropy<'_>, | 945 | r: &mut Entropy<'_>, |
| 583 | ctx: &mut SliceCtx, | 946 | ctx: &mut SliceCtx, |
| 584 | mb_addr: usize, | 947 | mb_addr: usize, |
| 948 | + skipped: bool, | ||
| 585 | ) -> Result<()> { | 949 | ) -> Result<()> { |
| 586 | let mb_x = mb_addr % pic.mb_w; | 950 | let mb_x = mb_addr % pic.mb_w; |
| 587 | let mb_y = mb_addr / pic.mb_w; | 951 | let mb_y = mb_addr / pic.mb_w; |
| @@ -589,6 +953,7 @@ fn decode_macroblock( | |||
| 589 | return Err(Error::corrupt("macroblock decoded twice")); | 953 | return Err(Error::corrupt("macroblock decoded twice")); |
| 590 | } | 954 | } |
| 591 | let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id); | 955 | let nbr = mb_neighbors(pic, mb_x, mb_y, ctx.slice_id); |
| 956 | + if !skipped || !r.is_cabac() { | ||
| 592 | let info = |addr: usize| MbInfo { | 957 | let info = |addr: usize| MbInfo { |
| 593 | flags: pic.mb_flags[addr], | 958 | flags: pic.mb_flags[addr], |
| 594 | cbp: pic.mb_cbp[addr], | 959 | cbp: pic.mb_cbp[addr], |
| @@ -599,12 +964,69 @@ fn decode_macroblock( | |||
| 599 | b: nbr.b.then(|| info(mb_addr - pic.mb_w)), | 964 | b: nbr.b.then(|| info(mb_addr - pic.mb_w)), |
| 600 | qp_delta_inc: ctx.qp_delta_inc, | 965 | qp_delta_inc: ctx.qp_delta_inc, |
| 601 | }); | 966 | }); |
| 967 | + } | ||
| 602 | let w4 = pic.mb_w * 4; | 968 | let w4 = pic.mb_w * 4; |
| 603 | let w2 = pic.mb_w * 2; | 969 | let w2 = pic.mb_w * 2; |
| 604 | let (bx0, by0) = (mb_x * 4, mb_y * 4); | 970 | let (bx0, by0) = (mb_x * 4, mb_y * 4); |
| 605 | let (cx0, cy0) = (mb_x * 2, mb_y * 2); | 971 | let (cx0, cy0) = (mb_x * 2, mb_y * 2); |
| 606 | 972 | ||
| 607 | - let mb_type = r.mb_type_i()?; | 973 | + // Every 4x4 block of this macroblock starts from a known state: the arrays |
| 974 | + // survive from the previous picture, and both the CABAC contexts and the | ||
| 975 | + // neighbour derivations read them for blocks of the macroblock in progress. | ||
| 976 | + for py in 0..4 { | ||
| 977 | + let base = (by0 + py) * w4 + bx0; | ||
| 978 | + for idx in base..base + 4 { | ||
| 979 | + pic.mv[idx] = [[0; 2]; 2]; | ||
| 980 | + pic.ref_idx[idx] = [-1; 2]; | ||
| 981 | + pic.ref_id[idx] = [-1; 2]; | ||
| 982 | + pic.mvd_abs[idx] = [0; 4]; | ||
| 983 | + pic.blk[idx] = 0; | ||
| 984 | + } | ||
| 985 | + } | ||
| 986 | + | ||
| 987 | + let mb_type = if skipped { | ||
| 988 | + u32::MAX | ||
| 989 | + } else if ctx.slice_type == SliceType::P { | ||
| 990 | + r.mb_type_p()? | ||
| 991 | + } else if ctx.is_b() { | ||
| 992 | + r.mb_type_b()? | ||
| 993 | + } else { | ||
| 994 | + r.mb_type_i()? | ||
| 995 | + }; | ||
| 996 | + | ||
| 997 | + // Split the P/B numbering into an inter shape or an intra mb_type. | ||
| 998 | + let (shape, intra_type) = if skipped { | ||
| 999 | + let s = if ctx.is_b() { B_SHAPES[0] } else { P_SHAPES[0] }; | ||
| 1000 | + (Some(s), None) | ||
| 1001 | + } else if ctx.slice_type == SliceType::P { | ||
| 1002 | + if mb_type < 5 { | ||
| 1003 | + (Some(P_SHAPES[mb_type as usize]), None) | ||
| 1004 | + } else { | ||
| 1005 | + (None, Some(mb_type - 5)) | ||
| 1006 | + } | ||
| 1007 | + } else if ctx.is_b() { | ||
| 1008 | + if mb_type < 23 { | ||
| 1009 | + (Some(B_SHAPES[mb_type as usize]), None) | ||
| 1010 | + } else { | ||
| 1011 | + (None, Some(mb_type - 23)) | ||
| 1012 | + } | ||
| 1013 | + } else { | ||
| 1014 | + (None, Some(mb_type)) | ||
| 1015 | + }; | ||
| 1016 | + r.set_intra(intra_type.is_some()); | ||
| 1017 | + | ||
| 1018 | + if let Some(shape) = shape { | ||
| 1019 | + return decode_inter_mb( | ||
| 1020 | + pic, refs, ls, r, ctx, mb_addr, shape, skipped, mb_type, nbr, | ||
| 1021 | + ); | ||
| 1022 | + } | ||
| 1023 | + let mb_type = intra_type.expect("an intra macroblock type"); | ||
| 1024 | + write_intra_mb(pic, mb_x, mb_y); | ||
| 1025 | + let intra_nbr = if ctx.constrained_intra_pred { | ||
| 1026 | + intra_neighbors(pic, mb_x, mb_y, nbr) | ||
| 1027 | + } else { | ||
| 1028 | + nbr | ||
| 1029 | + }; | ||
| 608 | 1030 | ||
| 609 | if mb_type == 25 { | 1031 | if mb_type == 25 { |
| 610 | // I_PCM (7.3.5, 8.3.5): raw samples, byte aligned. | 1032 | // I_PCM (7.3.5, 8.3.5): raw samples, byte aligned. |
| @@ -672,8 +1094,8 @@ fn decode_macroblock( | |||
| 672 | let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); | 1094 | let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); |
| 673 | // Predicted mode = min of neighbours, DC when either unavailable | 1095 | // Predicted mode = min of neighbours, DC when either unavailable |
| 674 | // (8.3.1.1; non-I4x4 neighbours were written as 2). | 1096 | // (8.3.1.1; non-I4x4 neighbours were written as 2). |
| 675 | - let left_avail = if bx % 4 == 0 { nbr.a } else { true }; | 1097 | + let left_avail = if bx % 4 == 0 { intra_nbr.a } else { true }; |
| 676 | - let top_avail = if by % 4 == 0 { nbr.b } else { true }; | 1098 | + let top_avail = if by % 4 == 0 { intra_nbr.b } else { true }; |
| 677 | let pred = if left_avail && top_avail { | 1099 | let pred = if left_avail && top_avail { |
| 678 | let ma = pic.i4_modes[by * w4 + bx - 1]; | 1100 | let ma = pic.i4_modes[by * w4 + bx - 1]; |
| 679 | let mb = pic.i4_modes[(by - 1) * w4 + bx]; | 1101 | let mb = pic.i4_modes[(by - 1) * w4 + bx]; |
| @@ -704,17 +1126,77 @@ fn decode_macroblock( | |||
| 704 | r.coded_block_pattern_intra()? | 1126 | r.coded_block_pattern_intra()? |
| 705 | }; | 1127 | }; |
| 706 | 1128 | ||
| 1129 | + finish_macroblock( | ||
| 1130 | + pic, | ||
| 1131 | + &ls[0], | ||
| 1132 | + r, | ||
| 1133 | + ctx, | ||
| 1134 | + mb_addr, | ||
| 1135 | + &intra_nbr, | ||
| 1136 | + MbFinish { | ||
| 1137 | + is_i16, | ||
| 1138 | + i16_mode, | ||
| 1139 | + cbp_luma, | ||
| 1140 | + cbp_chroma, | ||
| 1141 | + modes, | ||
| 1142 | + chroma_mode, | ||
| 1143 | + intra: true, | ||
| 1144 | + flags: if is_i16 { FLAG_I16 } else { 0 }, | ||
| 1145 | + }, | ||
| 1146 | + ) | ||
| 1147 | +} | ||
| 1148 | + | ||
| 1149 | +/// Everything the shared residual path needs after prediction is decided. | ||
| 1150 | +struct MbFinish { | ||
| 1151 | + is_i16: bool, | ||
| 1152 | + i16_mode: u8, | ||
| 1153 | + cbp_luma: u8, | ||
| 1154 | + cbp_chroma: u8, | ||
| 1155 | + modes: [u8; 16], | ||
| 1156 | + chroma_mode: u8, | ||
| 1157 | + intra: bool, | ||
| 1158 | + flags: u8, | ||
| 1159 | +} | ||
| 1160 | + | ||
| 1161 | +/// The residual half of a macroblock (7.3.5.3 + 8.5), shared by the intra and | ||
| 1162 | +/// inter paths. | ||
| 1163 | +/// | ||
| 1164 | +/// Bitstream order (luma blocks in Z-order, then chroma DC, then chroma AC) | ||
| 1165 | +/// equals reconstruction dependency order, so each block reconstructs the | ||
| 1166 | +/// moment its levels are parsed: no per-macroblock coefficient arrays, and | ||
| 1167 | +/// empty blocks cost one coeff_token read plus a prediction write. For an inter | ||
| 1168 | +/// macroblock the prediction is already in the plane, so the intra branches | ||
| 1169 | +/// below are simply skipped. | ||
| 1170 | +#[allow(clippy::needless_range_loop, clippy::too_many_arguments)] | ||
| 1171 | +fn finish_macroblock( | ||
| 1172 | + pic: &mut Picture, | ||
| 1173 | + ls: &[LevelScale4x4; 3], | ||
| 1174 | + r: &mut Entropy<'_>, | ||
| 1175 | + ctx: &mut SliceCtx, | ||
| 1176 | + mb_addr: usize, | ||
| 1177 | + nbr: &MbNeighbors, | ||
| 1178 | + m: MbFinish, | ||
| 1179 | +) -> Result<()> { | ||
| 1180 | + let mb_x = mb_addr % pic.mb_w; | ||
| 1181 | + let mb_y = mb_addr / pic.mb_w; | ||
| 1182 | + let w4 = pic.mb_w * 4; | ||
| 1183 | + let w2 = pic.mb_w * 2; | ||
| 1184 | + let (bx0, by0) = (mb_x * 4, mb_y * 4); | ||
| 1185 | + let (cx0, cy0) = (mb_x * 2, mb_y * 2); | ||
| 1186 | + let (cbp_luma, cbp_chroma) = (m.cbp_luma, m.cbp_chroma); | ||
| 1187 | + | ||
| 707 | // mb_qp_delta (7.4.5). | 1188 | // mb_qp_delta (7.4.5). |
| 708 | let mut qp_delta = 0; | 1189 | let mut qp_delta = 0; |
| 709 | - if cbp_luma != 0 || cbp_chroma != 0 || is_i16 { | 1190 | + if cbp_luma != 0 || cbp_chroma != 0 || m.is_i16 { |
| 710 | qp_delta = r.mb_qp_delta()?; | 1191 | qp_delta = r.mb_qp_delta()?; |
| 711 | ctx.qp = (ctx.qp + qp_delta + 52) % 52; | 1192 | ctx.qp = (ctx.qp + qp_delta + 52) % 52; |
| 712 | } | 1193 | } |
| 713 | ctx.qp_delta_inc = u8::from(qp_delta != 0); | 1194 | ctx.qp_delta_inc = u8::from(qp_delta != 0); |
| 714 | pic.mb_qp[mb_addr] = ctx.qp as u8; | 1195 | pic.mb_qp[mb_addr] = ctx.qp as u8; |
| 715 | pic.mb_flags[mb_addr] = FLAG_DECODED | 1196 | pic.mb_flags[mb_addr] = FLAG_DECODED |
| 716 | - | if is_i16 { FLAG_I16 } else { 0 } | 1197 | + | m.flags |
| 717 | - | if chroma_mode != 0 { | 1198 | + | if !m.intra { FLAG_INTER } else { 0 } |
| 1199 | + | if m.intra && m.chroma_mode != 0 { | ||
| 718 | FLAG_CHROMA_PRED | 1200 | FLAG_CHROMA_PRED |
| 719 | } else { | 1201 | } else { |
| 720 | 0 | 1202 | 0 |
| @@ -726,25 +1208,19 @@ fn decode_macroblock( | |||
| 726 | let qp_cb = i32::from(CHROMA_QP[(qp_y + ctx.cb_qp_offset).clamp(0, 51) as usize]); | 1208 | let qp_cb = i32::from(CHROMA_QP[(qp_y + ctx.cb_qp_offset).clamp(0, 51) as usize]); |
| 727 | let qp_cr = i32::from(CHROMA_QP[(qp_y + ctx.cr_qp_offset).clamp(0, 51) as usize]); | 1209 | let qp_cr = i32::from(CHROMA_QP[(qp_y + ctx.cr_qp_offset).clamp(0, 51) as usize]); |
| 728 | 1210 | ||
| 729 | - // ---- residual parse fused with reconstruction (7.3.5.3 + 8.5) ---- | ||
| 730 | - // | ||
| 731 | - // Bitstream order (luma blocks in Z-order, then chroma DC, then chroma | ||
| 732 | - // AC) equals reconstruction dependency order, so each block reconstructs | ||
| 733 | - // the moment its levels are parsed: no per-MB coefficient arrays, and | ||
| 734 | - // empty blocks cost one coeff_token read plus a prediction write. | ||
| 735 | let mut dc_cbf = 0u8; | 1211 | let mut dc_cbf = 0u8; |
| 736 | let mut scan = [0i32; 16]; | 1212 | let mut scan = [0i32; 16]; |
| 737 | let mut raster = [0i32; 16]; | 1213 | let mut raster = [0i32; 16]; |
| 738 | let mut resid = [0i32; 16]; | 1214 | let mut resid = [0i32; 16]; |
| 739 | - if is_i16 { | 1215 | + if m.is_i16 { |
| 740 | let mut w = PlaneWindow { | 1216 | let mut w = PlaneWindow { |
| 741 | data: &mut pic.y.data, | 1217 | data: &mut pic.y.data, |
| 742 | stride: pic.y.stride, | 1218 | stride: pic.y.stride, |
| 743 | origin: pic.y.origin + (mb_y * 16) * pic.y.stride + mb_x * 16, | 1219 | origin: pic.y.origin + (mb_y * 16) * pic.y.stride + mb_x * 16, |
| 744 | }; | 1220 | }; |
| 745 | - pred_16x16(i16_mode, &mut w, nbr.b, nbr.a); | 1221 | + pred_16x16(m.i16_mode, &mut w, nbr.b, nbr.a); |
| 746 | // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale. | 1222 | // Luma DC: un-zigzag over the 4x4 DC array, Hadamard + scale. |
| 747 | - let (na, nb) = luma_nz_pair(pic, &nbr, bx0, by0); | 1223 | + let (na, nb) = luma_nz_pair(pic, nbr, bx0, by0); |
| 748 | let dc_tc = r.residual_block(&mut scan, BlockCat::LumaDc, na, nb)?; | 1224 | let dc_tc = r.residual_block(&mut scan, BlockCat::LumaDc, na, nb)?; |
| 749 | dc_cbf |= u8::from(dc_tc != 0); | 1225 | dc_cbf |= u8::from(dc_tc != 0); |
| 750 | unzigzag(&scan, &mut raster); | 1226 | unzigzag(&scan, &mut raster); |
| @@ -754,7 +1230,7 @@ fn decode_macroblock( | |||
| 754 | let (dx, dy) = BLK4_POS[blk]; | 1230 | let (dx, dy) = BLK4_POS[blk]; |
| 755 | let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); | 1231 | let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); |
| 756 | let tc = if cbp_luma != 0 { | 1232 | let tc = if cbp_luma != 0 { |
| 757 | - let (na, nb) = luma_nz_pair(pic, &nbr, bx, by); | 1233 | + let (na, nb) = luma_nz_pair(pic, nbr, bx, by); |
| 758 | r.residual_block(&mut scan, BlockCat::LumaAc, na, nb)? | 1234 | r.residual_block(&mut scan, BlockCat::LumaAc, na, nb)? |
| 759 | } else { | 1235 | } else { |
| 760 | 0 | 1236 | 0 |
| @@ -782,18 +1258,19 @@ fn decode_macroblock( | |||
| 782 | let (dx, dy) = BLK4_POS[blk]; | 1258 | let (dx, dy) = BLK4_POS[blk]; |
| 783 | let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); | 1259 | let (bx, by) = (bx0 + dx as usize, by0 + dy as usize); |
| 784 | let tc = if cbp_luma & (1 << (blk >> 2)) != 0 { | 1260 | let tc = if cbp_luma & (1 << (blk >> 2)) != 0 { |
| 785 | - let (na, nb) = luma_nz_pair(pic, &nbr, bx, by); | 1261 | + let (na, nb) = luma_nz_pair(pic, nbr, bx, by); |
| 786 | r.residual_block(&mut scan, BlockCat::Luma4x4, na, nb)? | 1262 | r.residual_block(&mut scan, BlockCat::Luma4x4, na, nb)? |
| 787 | } else { | 1263 | } else { |
| 788 | 0 | 1264 | 0 |
| 789 | }; | 1265 | }; |
| 790 | pic.nz_y[by * w4 + bx] = tc; | 1266 | pic.nz_y[by * w4 + bx] = tc; |
| 791 | let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); | 1267 | let (x, y) = (mb_x * 16 + dx as usize * 4, mb_y * 16 + dy as usize * 4); |
| 792 | - let n = gather_nbr4(pic, &nbr, blk, x, y); | ||
| 793 | - let mut p = [0u8; 16]; | ||
| 794 | - pred_4x4(modes[blk], &n, &mut p); | ||
| 795 | let origin = pic.y.at(x, y); | 1268 | let origin = pic.y.at(x, y); |
| 796 | let stride = pic.y.stride; | 1269 | let stride = pic.y.stride; |
| 1270 | + if m.intra { | ||
| 1271 | + let n = gather_nbr4(pic, nbr, blk, x, y); | ||
| 1272 | + let mut p = [0u8; 16]; | ||
| 1273 | + pred_4x4(m.modes[blk], &n, &mut p); | ||
| 797 | if tc == 0 { | 1274 | if tc == 0 { |
| 798 | // Pure prediction: copy the 16 samples in. | 1275 | // Pure prediction: copy the 16 samples in. |
| 799 | for ry in 0..4 { | 1276 | for ry in 0..4 { |
| @@ -812,12 +1289,21 @@ fn decode_macroblock( | |||
| 812 | pic.y.data[row + rx] = v.clamp(0, 255) as u8; | 1289 | pic.y.data[row + rx] = v.clamp(0, 255) as u8; |
| 813 | } | 1290 | } |
| 814 | } | 1291 | } |
| 1292 | + } else { | ||
| 1293 | + if tc == 0 { | ||
| 1294 | + continue; // motion-compensated prediction already in place | ||
| 1295 | + } | ||
| 1296 | + unzigzag(&scan, &mut raster); | ||
| 1297 | + dequant_4x4(&mut raster, &ls[0], qp_y, false); | ||
| 1298 | + inverse_transform_4x4(&raster, &mut resid); | ||
| 1299 | + add_residual_4x4(&mut pic.y.data, stride, origin, &resid); | ||
| 1300 | + } | ||
| 815 | } | 1301 | } |
| 816 | } | 1302 | } |
| 817 | 1303 | ||
| 818 | - // Chroma: predict both components, then DC (Cb, Cr), then AC in | 1304 | + // Chroma: predict both components (intra only), then DC (Cb, Cr), then AC |
| 819 | - // bitstream order (all Cb blocks, all Cr blocks), reconstructing as | 1305 | + // in bitstream order, reconstructing as levels arrive. |
| 820 | - // levels arrive. | 1306 | + if m.intra { |
| 821 | for comp in 0..2 { | 1307 | for comp in 0..2 { |
| 822 | let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; | 1308 | let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; |
| 823 | let mut w = PlaneWindow { | 1309 | let mut w = PlaneWindow { |
| @@ -825,7 +1311,8 @@ fn decode_macroblock( | |||
| 825 | stride: plane.stride, | 1311 | stride: plane.stride, |
| 826 | origin: plane.origin + (mb_y * 8) * plane.stride + mb_x * 8, | 1312 | origin: plane.origin + (mb_y * 8) * plane.stride + mb_x * 8, |
| 827 | }; | 1313 | }; |
| 828 | - pred_chroma_8x8(chroma_mode, &mut w, nbr.b, nbr.a); | 1314 | + pred_chroma_8x8(m.chroma_mode, &mut w, nbr.b, nbr.a); |
| 1315 | + } | ||
| 829 | } | 1316 | } |
| 830 | let mut chroma_dc = [[0i32; 4]; 2]; | 1317 | let mut chroma_dc = [[0i32; 4]; 2]; |
| 831 | if cbp_chroma != 0 { | 1318 | if cbp_chroma != 0 { |
| @@ -845,7 +1332,7 @@ fn decode_macroblock( | |||
| 845 | for blk in 0..4 { | 1332 | for blk in 0..4 { |
| 846 | let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); | 1333 | let (cx, cy) = (cx0 + (blk & 1), cy0 + (blk >> 1)); |
| 847 | let tc = if cbp_chroma == 2 { | 1334 | let tc = if cbp_chroma == 2 { |
| 848 | - let (na, nb) = chroma_nz_pair(pic, &nbr, comp, cx, cy); | 1335 | + let (na, nb) = chroma_nz_pair(pic, nbr, comp, cx, cy); |
| 849 | r.residual_block(&mut scan, BlockCat::ChromaAc, na, nb)? | 1336 | r.residual_block(&mut scan, BlockCat::ChromaAc, na, nb)? |
| 850 | } else { | 1337 | } else { |
| 851 | 0 | 1338 | 0 |
| @@ -879,6 +1366,620 @@ fn decode_macroblock( | |||
| 879 | Ok(()) | 1366 | Ok(()) |
| 880 | } | 1367 | } |
| 881 | 1368 | ||
| 1369 | +/// Decode an inter macroblock: sub-macroblock types, reference indices and | ||
| 1370 | +/// motion vector differences (7.3.5.1, 7.3.5.2), then motion compensation | ||
| 1371 | +/// (8.4.2) and the shared residual path. | ||
| 1372 | +#[allow(clippy::too_many_arguments)] | ||
| 1373 | +fn decode_inter_mb( | ||
| 1374 | + pic: &mut Picture, | ||
| 1375 | + refs: &[Picture], | ||
| 1376 | + ls: &[[LevelScale4x4; 3]; 2], | ||
| 1377 | + r: &mut Entropy<'_>, | ||
| 1378 | + ctx: &mut SliceCtx, | ||
| 1379 | + mb_addr: usize, | ||
| 1380 | + shape: MbShape, | ||
| 1381 | + skipped: bool, | ||
| 1382 | + mb_type: u32, | ||
| 1383 | + nbr: MbNeighbors, | ||
| 1384 | +) -> Result<()> { | ||
| 1385 | + let mb_x = mb_addr % pic.mb_w; | ||
| 1386 | + let mb_y = mb_addr / pic.mb_w; | ||
| 1387 | + let b = ctx.is_b(); | ||
| 1388 | + let mut mvc = MvCtx { | ||
| 1389 | + mb_x, | ||
| 1390 | + mb_y, | ||
| 1391 | + slice_id: ctx.slice_id, | ||
| 1392 | + written: 0, | ||
| 1393 | + }; | ||
| 1394 | + let mut motion = MbMotion { | ||
| 1395 | + sub: [P_SUB[0]; 4], | ||
| 1396 | + ref_idx: [[-1; 4]; 2], | ||
| 1397 | + mvd: [[[0; 2]; 16]; 2], | ||
| 1398 | + }; | ||
| 1399 | + // A direct or skipped block contributes nothing to the ref_idx and mvd | ||
| 1400 | + // contexts of its neighbours (9.3.3.1.1.6, 9.3.3.1.1.7), so the flag has to | ||
| 1401 | + // be in place before any of this macroblock's syntax is parsed. | ||
| 1402 | + let direct_mb = skipped || (b && mb_type == 0); | ||
| 1403 | + if direct_mb { | ||
| 1404 | + let f = BLK_DIRECT | if skipped { BLK_SKIP } else { 0 }; | ||
| 1405 | + for py in 0..4 { | ||
| 1406 | + let base = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4; | ||
| 1407 | + for idx in base..base + 4 { | ||
| 1408 | + pic.blk[idx] = f; | ||
| 1409 | + } | ||
| 1410 | + } | ||
| 1411 | + } | ||
| 1412 | + | ||
| 1413 | + if shape.sub && !skipped { | ||
| 1414 | + for part in 0..4 { | ||
| 1415 | + let t = r.sub_mb_type(b)? as usize; | ||
| 1416 | + motion.sub[part] = if b { B_SUB[t] } else { P_SUB[t] }; | ||
| 1417 | + if motion.sub[part].pred == Pred::Direct { | ||
| 1418 | + for k in 0..4 { | ||
| 1419 | + let (px, py) = (part % 2 * 2 + k % 2, part / 2 * 2 + k / 2); | ||
| 1420 | + let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px; | ||
| 1421 | + pic.blk[idx] = BLK_DIRECT; | ||
| 1422 | + } | ||
| 1423 | + } | ||
| 1424 | + } | ||
| 1425 | + } | ||
| 1426 | + | ||
| 1427 | + // ---- ref_idx_lX (7.3.5.1, 7.3.5.2) ---- | ||
| 1428 | + // P_8x8ref0 infers reference index 0 for every partition. | ||
| 1429 | + let infer_ref0 = ctx.slice_type == SliceType::P && mb_type == 4; | ||
| 1430 | + if !skipped { | ||
| 1431 | + for list in 0..2 { | ||
| 1432 | + for part in 0..shape.parts { | ||
| 1433 | + let uses = if shape.sub { | ||
| 1434 | + motion.sub[part].pred.uses(list) | ||
| 1435 | + } else { | ||
| 1436 | + shape.pred[part.min(1)].uses(list) | ||
| 1437 | + }; | ||
| 1438 | + if !uses { | ||
| 1439 | + continue; | ||
| 1440 | + } | ||
| 1441 | + let idx = if infer_ref0 || ctx.num_ref_idx[list] <= 1 { | ||
| 1442 | + 0 | ||
| 1443 | + } else { | ||
| 1444 | + let (px, py) = part_origin(&shape, part, (0, 0)); | ||
| 1445 | + let bx = (mb_x * 4 + px) as i32; | ||
| 1446 | + let by = (mb_y * 4 + py) as i32; | ||
| 1447 | + let inc = ref_idx_cond(pic, &mvc, bx - 1, by, list) | ||
| 1448 | + + 2 * ref_idx_cond(pic, &mvc, bx, by - 1, list); | ||
| 1449 | + r.ref_idx(ctx.num_ref_idx[list] as u32 - 1, inc)? as i8 | ||
| 1450 | + }; | ||
| 1451 | + motion.ref_idx[list][part] = idx; | ||
| 1452 | + // Publish it so the next partition's context can see it. | ||
| 1453 | + let (px, py) = part_origin(&shape, part, (0, 0)); | ||
| 1454 | + let (pw, ph) = part_size(&shape, &motion, part); | ||
| 1455 | + for dy in 0..ph { | ||
| 1456 | + for dx in 0..pw { | ||
| 1457 | + let bi = (mb_y * 4 + py + dy) * pic.mb_w * 4 + mb_x * 4 + px + dx; | ||
| 1458 | + pic.ref_idx[bi][list] = idx; | ||
| 1459 | + mvc.written |= 1 << ((py + dy) * 4 + px + dx); | ||
| 1460 | + } | ||
| 1461 | + } | ||
| 1462 | + } | ||
| 1463 | + } | ||
| 1464 | + if infer_ref0 { | ||
| 1465 | + for part in 0..4 { | ||
| 1466 | + motion.ref_idx[0][part] = 0; | ||
| 1467 | + } | ||
| 1468 | + } | ||
| 1469 | + | ||
| 1470 | + // ---- mvd_lX ---- | ||
| 1471 | + mvc.written = 0; | ||
| 1472 | + for list in 0..2 { | ||
| 1473 | + for part in 0..shape.parts { | ||
| 1474 | + let uses = if shape.sub { | ||
| 1475 | + motion.sub[part].pred.uses(list) | ||
| 1476 | + } else { | ||
| 1477 | + shape.pred[part.min(1)].uses(list) | ||
| 1478 | + }; | ||
| 1479 | + if !uses { | ||
| 1480 | + continue; | ||
| 1481 | + } | ||
| 1482 | + let subparts = if shape.sub { motion.sub[part].parts } else { 1 }; | ||
| 1483 | + for sp in 0..subparts { | ||
| 1484 | + let (px, py) = part_origin(&shape, part, sp_offset(&shape, &motion, part, sp)); | ||
| 1485 | + let (pw, ph) = part_size(&shape, &motion, part); | ||
| 1486 | + let bx = (mb_x * 4 + px) as i32; | ||
| 1487 | + let by = (mb_y * 4 + py) as i32; | ||
| 1488 | + let mut mvd = [0i16; 2]; | ||
| 1489 | + for comp in 0..2 { | ||
| 1490 | + let a = neighbour_mvd(pic, &mvc, bx - 1, by, list)[comp]; | ||
| 1491 | + let bb = neighbour_mvd(pic, &mvc, bx, by - 1, list)[comp]; | ||
| 1492 | + let sum = a + bb; | ||
| 1493 | + let inc = if sum > 32 { | ||
| 1494 | + 2 | ||
| 1495 | + } else if sum > 2 { | ||
| 1496 | + 1 | ||
| 1497 | + } else { | ||
| 1498 | + 0 | ||
| 1499 | + }; | ||
| 1500 | + let v = r.mvd(comp, inc)?; | ||
| 1501 | + mvd[comp] = i16::try_from(v) | ||
| 1502 | + .map_err(|_| Error::corrupt("mvd outside the level limits"))?; | ||
| 1503 | + } | ||
| 1504 | + for dy in 0..ph { | ||
| 1505 | + for dx in 0..pw { | ||
| 1506 | + motion.mvd[list][(py + dy) * 4 + px + dx] = mvd; | ||
| 1507 | + write_mvd(pic, mb_x, mb_y, px + dx, py + dy, list, mvd); | ||
| 1508 | + mvc.written |= 1 << ((py + dy) * 4 + px + dx); | ||
| 1509 | + } | ||
| 1510 | + } | ||
| 1511 | + } | ||
| 1512 | + } | ||
| 1513 | + } | ||
| 1514 | + } | ||
| 1515 | + | ||
| 1516 | + // ---- motion vector derivation and compensation (8.4.1, 8.4.2) ---- | ||
| 1517 | + mvc.written = 0; | ||
| 1518 | + if direct_mb && !b { | ||
| 1519 | + predict_p_skip(pic, refs, ctx, &mut mvc)?; | ||
| 1520 | + } else if direct_mb { | ||
| 1521 | + predict_direct(pic, refs, ctx, &mut mvc, true)?; | ||
| 1522 | + } else { | ||
| 1523 | + for part in 0..shape.parts { | ||
| 1524 | + if shape.sub && motion.sub[part].pred == Pred::Direct { | ||
| 1525 | + predict_direct_8x8(pic, refs, ctx, &mut mvc, part)?; | ||
| 1526 | + continue; | ||
| 1527 | + } | ||
| 1528 | + let subparts = if shape.sub { motion.sub[part].parts } else { 1 }; | ||
| 1529 | + let pred = if shape.sub { | ||
| 1530 | + motion.sub[part].pred | ||
| 1531 | + } else { | ||
| 1532 | + shape.pred[part.min(1)] | ||
| 1533 | + }; | ||
| 1534 | + for sp in 0..subparts { | ||
| 1535 | + let (px, py) = part_origin(&shape, part, sp_offset(&shape, &motion, part, sp)); | ||
| 1536 | + let (pw, ph) = part_size(&shape, &motion, part); | ||
| 1537 | + let mut mv = [[0i16; 2]; 2]; | ||
| 1538 | + let mut ref_idx = [-1i8; 2]; | ||
| 1539 | + let mut ref_id = [-1i32; 2]; | ||
| 1540 | + for list in 0..2 { | ||
| 1541 | + if !pred.uses(list) { | ||
| 1542 | + continue; | ||
| 1543 | + } | ||
| 1544 | + let idx = motion.ref_idx[list][part]; | ||
| 1545 | + // predPartWidth of 6.4.11.7: the macroblock partition width | ||
| 1546 | + // for a whole-macroblock partition, the sub-macroblock | ||
| 1547 | + // partition width inside an 8x8. | ||
| 1548 | + let n = mvc.neighbours(pic, px, py, pw, list); | ||
| 1549 | + let mvp = predict_mv(&n, idx, shape.w, shape.h, part); | ||
| 1550 | + let d = motion.mvd[list][py * 4 + px]; | ||
| 1551 | + mv[list] = [mvp[0].wrapping_add(d[0]), mvp[1].wrapping_add(d[1])]; | ||
| 1552 | + ref_idx[list] = idx; | ||
| 1553 | + ref_id[list] = ctx | ||
| 1554 | + .reference(refs, list, idx) | ||
| 1555 | + .map(|p| p.id) | ||
| 1556 | + .unwrap_or(-1); | ||
| 1557 | + } | ||
| 1558 | + for dy in 0..ph { | ||
| 1559 | + for dx in 0..pw { | ||
| 1560 | + write_block(pic, &mut mvc, px + dx, py + dy, mv, ref_idx, ref_id, 0); | ||
| 1561 | + } | ||
| 1562 | + } | ||
| 1563 | + compensate(pic, refs, ctx, mb_x, mb_y, px, py, pw, ph, mv, ref_idx)?; | ||
| 1564 | + } | ||
| 1565 | + } | ||
| 1566 | + } | ||
| 1567 | + | ||
| 1568 | + if skipped { | ||
| 1569 | + // 7.4.5: a skipped macroblock has no residual and does not change QPY. | ||
| 1570 | + let w4 = pic.mb_w * 4; | ||
| 1571 | + let w2 = pic.mb_w * 2; | ||
| 1572 | + for dy in 0..4 { | ||
| 1573 | + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; | ||
| 1574 | + pic.nz_y[base..base + 4].fill(0); | ||
| 1575 | + pic.i4_modes[base..base + 4].fill(2); | ||
| 1576 | + } | ||
| 1577 | + for comp in 0..2 { | ||
| 1578 | + for dy in 0..2 { | ||
| 1579 | + let base = (mb_y * 2 + dy) * w2 + mb_x * 2; | ||
| 1580 | + pic.nz_c[comp][base..base + 2].fill(0); | ||
| 1581 | + } | ||
| 1582 | + } | ||
| 1583 | + pic.mb_qp[mb_addr] = ctx.qp as u8; | ||
| 1584 | + pic.mb_flags[mb_addr] = | ||
| 1585 | + FLAG_DECODED | FLAG_INTER | FLAG_SKIP | if b { FLAG_DIRECT } else { 0 }; | ||
| 1586 | + pic.mb_cbp[mb_addr] = 0; | ||
| 1587 | + pic.mb_dc_cbf[mb_addr] = 0; | ||
| 1588 | + pic.mb_slice[mb_addr] = ctx.slice_id; | ||
| 1589 | + pic.decoded_mbs += 1; | ||
| 1590 | + ctx.qp_delta_inc = 0; | ||
| 1591 | + return Ok(()); | ||
| 1592 | + } | ||
| 1593 | + | ||
| 1594 | + let w4 = pic.mb_w * 4; | ||
| 1595 | + for dy in 0..4 { | ||
| 1596 | + let base = (mb_y * 4 + dy) * w4 + mb_x * 4; | ||
| 1597 | + pic.i4_modes[base..base + 4].fill(2); | ||
| 1598 | + } | ||
| 1599 | + let (cbp_luma, cbp_chroma) = r.coded_block_pattern_inter()?; | ||
| 1600 | + // The inter scaling lists (Table 7-2 lists 3..5) govern an inter residual. | ||
| 1601 | + finish_macroblock( | ||
| 1602 | + pic, | ||
| 1603 | + &ls[1], | ||
| 1604 | + r, | ||
| 1605 | + ctx, | ||
| 1606 | + mb_addr, | ||
| 1607 | + &nbr, | ||
| 1608 | + MbFinish { | ||
| 1609 | + is_i16: false, | ||
| 1610 | + i16_mode: 0, | ||
| 1611 | + cbp_luma, | ||
| 1612 | + cbp_chroma, | ||
| 1613 | + modes: [2; 16], | ||
| 1614 | + chroma_mode: 0, | ||
| 1615 | + intra: false, | ||
| 1616 | + flags: if b && mb_type == 0 { FLAG_DIRECT } else { 0 }, | ||
| 1617 | + }, | ||
| 1618 | + ) | ||
| 1619 | +} | ||
| 1620 | + | ||
| 1621 | +/// Top-left 4x4 block of macroblock partition `part`, offset by `sp` blocks in | ||
| 1622 | +/// raster order within the 8x8. | ||
| 1623 | +fn part_origin(shape: &MbShape, part: usize, sp: (usize, usize)) -> (usize, usize) { | ||
| 1624 | + let (px, py) = if shape.sub { | ||
| 1625 | + (part % 2 * 2, part / 2 * 2) | ||
| 1626 | + } else if shape.parts == 1 { | ||
| 1627 | + (0, 0) | ||
| 1628 | + } else if shape.w == 4 { | ||
| 1629 | + (0, part * 2) // 16x8 | ||
| 1630 | + } else { | ||
| 1631 | + (part * 2, 0) // 8x16 | ||
| 1632 | + }; | ||
| 1633 | + (px + sp.0, py + sp.1) | ||
| 1634 | +} | ||
| 1635 | + | ||
| 1636 | +/// Block offset of sub-macroblock partition `sp` inside its 8x8. | ||
| 1637 | +fn sp_offset(shape: &MbShape, m: &MbMotion, part: usize, sp: usize) -> (usize, usize) { | ||
| 1638 | + if !shape.sub { | ||
| 1639 | + return (0, 0); | ||
| 1640 | + } | ||
| 1641 | + let s = m.sub[part]; | ||
| 1642 | + match (s.w, s.h) { | ||
| 1643 | + (2, 2) => (0, 0), | ||
| 1644 | + (2, 1) => (0, sp), | ||
| 1645 | + (1, 2) => (sp, 0), | ||
| 1646 | + _ => (sp % 2, sp / 2), | ||
| 1647 | + } | ||
| 1648 | +} | ||
| 1649 | + | ||
| 1650 | +/// Size of one (sub-)macroblock partition in 4x4 blocks. | ||
| 1651 | +fn part_size(shape: &MbShape, m: &MbMotion, part: usize) -> (usize, usize) { | ||
| 1652 | + if shape.sub { | ||
| 1653 | + let s = m.sub[part]; | ||
| 1654 | + (s.w, s.h) | ||
| 1655 | + } else { | ||
| 1656 | + (shape.w, shape.h) | ||
| 1657 | + } | ||
| 1658 | +} | ||
| 1659 | + | ||
| 1660 | +/// P_Skip (clause 8.4.1.1). | ||
| 1661 | +fn predict_p_skip( | ||
| 1662 | + pic: &mut Picture, | ||
| 1663 | + refs: &[Picture], | ||
| 1664 | + ctx: &SliceCtx, | ||
| 1665 | + mvc: &mut MvCtx, | ||
| 1666 | +) -> Result<()> { | ||
| 1667 | + let n = mvc.neighbours(pic, 0, 0, 4, 0); | ||
| 1668 | + let zero = !n[0].avail | ||
| 1669 | + || !n[1].avail | ||
| 1670 | + || (n[0].ref_idx == 0 && n[0].mv == [0, 0]) | ||
| 1671 | + || (n[1].ref_idx == 0 && n[1].mv == [0, 0]); | ||
| 1672 | + let mv = if zero { | ||
| 1673 | + [0i16; 2] | ||
| 1674 | + } else { | ||
| 1675 | + predict_mv(&n, 0, 4, 4, 0) | ||
| 1676 | + }; | ||
| 1677 | + let ref_id = ctx.reference(refs, 0, 0).map(|p| p.id).unwrap_or(-1); | ||
| 1678 | + for py in 0..4 { | ||
| 1679 | + for px in 0..4 { | ||
| 1680 | + write_block( | ||
| 1681 | + pic, | ||
| 1682 | + mvc, | ||
| 1683 | + px, | ||
| 1684 | + py, | ||
| 1685 | + [mv, [0; 2]], | ||
| 1686 | + [0, -1], | ||
| 1687 | + [ref_id, -1], | ||
| 1688 | + BLK_SKIP | BLK_DIRECT, | ||
| 1689 | + ); | ||
| 1690 | + } | ||
| 1691 | + } | ||
| 1692 | + compensate( | ||
| 1693 | + pic, | ||
| 1694 | + refs, | ||
| 1695 | + ctx, | ||
| 1696 | + mvc.mb_x, | ||
| 1697 | + mvc.mb_y, | ||
| 1698 | + 0, | ||
| 1699 | + 0, | ||
| 1700 | + 4, | ||
| 1701 | + 4, | ||
| 1702 | + [mv, [0; 2]], | ||
| 1703 | + [0, -1], | ||
| 1704 | + ) | ||
| 1705 | +} | ||
| 1706 | + | ||
| 1707 | +/// B_Skip / B_Direct_16x16 (clause 8.4.1.2) over the whole macroblock. | ||
| 1708 | +fn predict_direct( | ||
| 1709 | + pic: &mut Picture, | ||
| 1710 | + refs: &[Picture], | ||
| 1711 | + ctx: &SliceCtx, | ||
| 1712 | + mvc: &mut MvCtx, | ||
| 1713 | + skip: bool, | ||
| 1714 | +) -> Result<()> { | ||
| 1715 | + for quad in 0..4 { | ||
| 1716 | + direct_quadrant(pic, refs, ctx, mvc, quad, skip)?; | ||
| 1717 | + } | ||
| 1718 | + Ok(()) | ||
| 1719 | +} | ||
| 1720 | + | ||
| 1721 | +/// B_Direct_8x8 for one 8x8 sub-macroblock. | ||
| 1722 | +fn predict_direct_8x8( | ||
| 1723 | + pic: &mut Picture, | ||
| 1724 | + refs: &[Picture], | ||
| 1725 | + ctx: &SliceCtx, | ||
| 1726 | + mvc: &mut MvCtx, | ||
| 1727 | + part: usize, | ||
| 1728 | +) -> Result<()> { | ||
| 1729 | + direct_quadrant(pic, refs, ctx, mvc, part, false) | ||
| 1730 | +} | ||
| 1731 | + | ||
| 1732 | +/// One 8x8 quadrant of a direct-mode macroblock. With | ||
| 1733 | +/// `direct_8x8_inference_flag` the whole quadrant shares the motion of its | ||
| 1734 | +/// outer corner 4x4 block; without it each 4x4 block is derived on its own. | ||
| 1735 | +fn direct_quadrant( | ||
| 1736 | + pic: &mut Picture, | ||
| 1737 | + refs: &[Picture], | ||
| 1738 | + ctx: &SliceCtx, | ||
| 1739 | + mvc: &mut MvCtx, | ||
| 1740 | + quad: usize, | ||
| 1741 | + skip: bool, | ||
| 1742 | +) -> Result<()> { | ||
| 1743 | + let (mb_x, mb_y) = (mvc.mb_x, mvc.mb_y); | ||
| 1744 | + let (qx, qy) = (quad % 2 * 2, quad / 2 * 2); | ||
| 1745 | + let flags = BLK_DIRECT | if skip { BLK_SKIP } else { 0 }; | ||
| 1746 | + if ctx.direct_8x8_inference { | ||
| 1747 | + // 8.4.1.2.1: luma4x4BlkIdx = 5 * mbPartIdx, i.e. the quadrant's own | ||
| 1748 | + // outer corner of the macroblock. | ||
| 1749 | + let corner = (quad % 2 * 3, quad / 2 * 3); | ||
| 1750 | + let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, corner)?; | ||
| 1751 | + for dy in 0..2 { | ||
| 1752 | + for dx in 0..2 { | ||
| 1753 | + write_block(pic, mvc, qx + dx, qy + dy, mv, ref_idx, ref_id, flags); | ||
| 1754 | + } | ||
| 1755 | + } | ||
| 1756 | + compensate(pic, refs, ctx, mb_x, mb_y, qx, qy, 2, 2, mv, ref_idx) | ||
| 1757 | + } else { | ||
| 1758 | + for dy in 0..2 { | ||
| 1759 | + for dx in 0..2 { | ||
| 1760 | + let (px, py) = (qx + dx, qy + dy); | ||
| 1761 | + let (mv, ref_idx, ref_id) = direct_block(pic, refs, ctx, mvc, (px, py))?; | ||
| 1762 | + write_block(pic, mvc, px, py, mv, ref_idx, ref_id, flags); | ||
| 1763 | + compensate(pic, refs, ctx, mb_x, mb_y, px, py, 1, 1, mv, ref_idx)?; | ||
| 1764 | + } | ||
| 1765 | + } | ||
| 1766 | + Ok(()) | ||
| 1767 | + } | ||
| 1768 | +} | ||
| 1769 | + | ||
| 1770 | +/// Motion of one direct-mode 4x4 block: spatial (8.4.1.2.2) or temporal | ||
| 1771 | +/// (8.4.1.2.3). | ||
| 1772 | +fn direct_block( | ||
| 1773 | + pic: &Picture, | ||
| 1774 | + refs: &[Picture], | ||
| 1775 | + ctx: &SliceCtx, | ||
| 1776 | + mvc: &MvCtx, | ||
| 1777 | + at: (usize, usize), | ||
| 1778 | +) -> Result<([[i16; 2]; 2], [i8; 2], [i32; 2])> { | ||
| 1779 | + // The co-located block, in both modes. | ||
| 1780 | + let col = ctx.lists[1].get(0).and_then(|i| refs.get(i)); | ||
| 1781 | + let (col_ref_id, col_mv, col_list) = match col { | ||
| 1782 | + Some(c) => { | ||
| 1783 | + let bx = mvc.mb_x * 4 + at.0; | ||
| 1784 | + let by = mvc.mb_y * 4 + at.1; | ||
| 1785 | + let idx = by * c.mb_w.max(1) * 4 + bx; | ||
| 1786 | + if idx < c.ref_id.len() && c.blk[idx] & BLK_INTRA == 0 { | ||
| 1787 | + let list = usize::from(c.ref_id[idx][0] < 0); | ||
| 1788 | + (c.ref_id[idx][list], c.mv[idx][list], list) | ||
| 1789 | + } else { | ||
| 1790 | + (-1, [0i16; 2], 0) | ||
| 1791 | + } | ||
| 1792 | + } | ||
| 1793 | + None => (-1, [0i16; 2], 0), | ||
| 1794 | + }; | ||
| 1795 | + let _ = col_list; | ||
| 1796 | + | ||
| 1797 | + if ctx.direct_spatial { | ||
| 1798 | + // Reference indices from the macroblock's own neighbours, once. | ||
| 1799 | + let mut ref_idx = [-1i8; 2]; | ||
| 1800 | + let mut mvp = [[0i16; 2]; 2]; | ||
| 1801 | + for list in 0..2 { | ||
| 1802 | + let n = mvc.neighbours(pic, 0, 0, 4, list); | ||
| 1803 | + ref_idx[list] = min_positive(n[0].ref_idx, min_positive(n[1].ref_idx, n[2].ref_idx)); | ||
| 1804 | + mvp[list] = predict_mv(&n, ref_idx[list], 4, 4, 0); | ||
| 1805 | + } | ||
| 1806 | + let zero_prediction = ref_idx[0] < 0 && ref_idx[1] < 0; | ||
| 1807 | + if zero_prediction { | ||
| 1808 | + ref_idx = [0, 0]; | ||
| 1809 | + } | ||
| 1810 | + // colZeroFlag: the co-located block sits still on a short-term picture. | ||
| 1811 | + let col_short = col.is_some_and(|c| c.mark == Mark::Short); | ||
| 1812 | + let col_zero = col_short | ||
| 1813 | + && col_ref_id >= 0 | ||
| 1814 | + && col.is_some_and(|c| { | ||
| 1815 | + let bx = mvc.mb_x * 4 + at.0; | ||
| 1816 | + let by = mvc.mb_y * 4 + at.1; | ||
| 1817 | + let idx = by * c.mb_w.max(1) * 4 + bx; | ||
| 1818 | + idx < c.ref_idx.len() && (c.ref_idx[idx][0] == 0 || c.ref_idx[idx][1] == 0) | ||
| 1819 | + }) | ||
| 1820 | + && (-1..=1).contains(&col_mv[0]) | ||
| 1821 | + && (-1..=1).contains(&col_mv[1]); | ||
| 1822 | + let mut mv = [[0i16; 2]; 2]; | ||
| 1823 | + let mut ref_id = [-1i32; 2]; | ||
| 1824 | + for list in 0..2 { | ||
| 1825 | + if ref_idx[list] < 0 { | ||
| 1826 | + continue; | ||
| 1827 | + } | ||
| 1828 | + ref_id[list] = ctx | ||
| 1829 | + .reference(refs, list, ref_idx[list]) | ||
| 1830 | + .map(|p| p.id) | ||
| 1831 | + .unwrap_or(-1); | ||
| 1832 | + if zero_prediction || (ref_idx[list] == 0 && col_zero) { | ||
| 1833 | + mv[list] = [0; 2]; | ||
| 1834 | + } else { | ||
| 1835 | + mv[list] = mvp[list]; | ||
| 1836 | + } | ||
| 1837 | + } | ||
| 1838 | + return Ok((mv, ref_idx, ref_id)); | ||
| 1839 | + } | ||
| 1840 | + | ||
| 1841 | + // Temporal direct (8.4.1.2.3). | ||
| 1842 | + let ref_idx0 = if col_ref_id < 0 { | ||
| 1843 | + 0 | ||
| 1844 | + } else { | ||
| 1845 | + map_col_to_list0(ctx, refs, col_ref_id) | ||
| 1846 | + }; | ||
| 1847 | + let pic0 = ctx.reference(refs, 0, ref_idx0); | ||
| 1848 | + let pic1 = ctx.reference(refs, 1, 0); | ||
| 1849 | + let ref_id = [ | ||
| 1850 | + pic0.map(|p| p.id).unwrap_or(-1), | ||
| 1851 | + pic1.map(|p| p.id).unwrap_or(-1), | ||
| 1852 | + ]; | ||
| 1853 | + let (Some(p0), Some(p1)) = (pic0, pic1) else { | ||
| 1854 | + return Ok(([[0; 2]; 2], [ref_idx0, 0], ref_id)); | ||
| 1855 | + }; | ||
| 1856 | + let td = (p1.poc - p0.poc).clamp(-128, 127); | ||
| 1857 | + if p0.mark == Mark::Long || td == 0 { | ||
| 1858 | + return Ok(([col_mv, [0; 2]], [ref_idx0, 0], ref_id)); | ||
| 1859 | + } | ||
| 1860 | + let tb = (ctx.poc - p0.poc).clamp(-128, 127); | ||
| 1861 | + let tx = (16384 + (td / 2).abs()) / td; | ||
| 1862 | + let dist = ((tb * tx + 32) >> 6).clamp(-1024, 1023); | ||
| 1863 | + let mv0 = [ | ||
| 1864 | + ((dist * i32::from(col_mv[0]) + 128) >> 8) as i16, | ||
| 1865 | + ((dist * i32::from(col_mv[1]) + 128) >> 8) as i16, | ||
| 1866 | + ]; | ||
| 1867 | + let mv1 = [mv0[0] - col_mv[0], mv0[1] - col_mv[1]]; | ||
| 1868 | + Ok(([mv0, mv1], [ref_idx0, 0], ref_id)) | ||
| 1869 | +} | ||
| 1870 | + | ||
| 1871 | +/// `MapColToList0` (8.4.1.2.3): the lowest RefPicList0 index that names the | ||
| 1872 | +/// picture the co-located block referenced. | ||
| 1873 | +fn map_col_to_list0(ctx: &SliceCtx, refs: &[Picture], col_ref_id: i32) -> i8 { | ||
| 1874 | + for i in 0..ctx.lists[0].len() { | ||
| 1875 | + if ctx | ||
| 1876 | + .lists[0] | ||
| 1877 | + .get(i) | ||
| 1878 | + .and_then(|k| refs.get(k)) | ||
| 1879 | + .is_some_and(|p| p.id == col_ref_id) | ||
| 1880 | + { | ||
| 1881 | + return i as i8; | ||
| 1882 | + } | ||
| 1883 | + } | ||
| 1884 | + 0 | ||
| 1885 | +} | ||
| 1886 | + | ||
| 1887 | +/// Motion compensation of one partition (clause 8.4.2): interpolate each list's | ||
| 1888 | +/// prediction, then combine them by the weighting of 8.4.2.3 and write the | ||
| 1889 | +/// result straight into the picture, where the residual is added on top. | ||
| 1890 | +/// | ||
| 1891 | +/// `(px, py)` and `(pw, ph)` are in 4x4 blocks within the macroblock. | ||
| 1892 | +#[allow(clippy::too_many_arguments)] | ||
| 1893 | +fn compensate( | ||
| 1894 | + pic: &mut Picture, | ||
| 1895 | + refs: &[Picture], | ||
| 1896 | + ctx: &SliceCtx, | ||
| 1897 | + mb_x: usize, | ||
| 1898 | + mb_y: usize, | ||
| 1899 | + px: usize, | ||
| 1900 | + py: usize, | ||
| 1901 | + pw: usize, | ||
| 1902 | + ph: usize, | ||
| 1903 | + mv: [[i16; 2]; 2], | ||
| 1904 | + ref_idx: [i8; 2], | ||
| 1905 | +) -> Result<()> { | ||
| 1906 | + let use0 = ref_idx[0] >= 0; | ||
| 1907 | + let use1 = ref_idx[1] >= 0; | ||
| 1908 | + if !use0 && !use1 { | ||
| 1909 | + return Ok(()); | ||
| 1910 | + } | ||
| 1911 | + let x0 = (mb_x * 16 + px * 4) as i32; | ||
| 1912 | + let y0 = (mb_y * 16 + py * 4) as i32; | ||
| 1913 | + let (w, h) = (pw * 4, ph * 4); | ||
| 1914 | + | ||
| 1915 | + let mut part = [[0u8; 256]; 2]; | ||
| 1916 | + for list in 0..2 { | ||
| 1917 | + if ref_idx[list] < 0 { | ||
| 1918 | + continue; | ||
| 1919 | + } | ||
| 1920 | + let rp = ctx.reference(refs, list, ref_idx[list]).ok_or_else(|| { | ||
| 1921 | + Error::corrupt("reference index names a picture the buffer does not hold") | ||
| 1922 | + })?; | ||
| 1923 | + let plane = RefPlane { | ||
| 1924 | + data: &rp.y.data, | ||
| 1925 | + stride: rp.y.stride, | ||
| 1926 | + origin: rp.y.origin, | ||
| 1927 | + width: rp.y.width, | ||
| 1928 | + height: rp.y.height, | ||
| 1929 | + pad: rp.y.pad, | ||
| 1930 | + }; | ||
| 1931 | + mc_luma(&plane, x0, y0, mv[list], w, h, &mut part[list]); | ||
| 1932 | + } | ||
| 1933 | + let wt = ctx.weights_for(refs, 0, ref_idx[0], ref_idx[1], use0, use1); | ||
| 1934 | + let mut out = [0u8; 256]; | ||
| 1935 | + let (p0, p1) = part.split_at(1); | ||
| 1936 | + combine(&mut out, &p0[0], &p1[0], use0, use1, &wt, w * h); | ||
| 1937 | + let stride = pic.y.stride; | ||
| 1938 | + let origin = pic.y.at(x0 as usize, y0 as usize); | ||
| 1939 | + for row in 0..h { | ||
| 1940 | + let dst = origin + row * stride; | ||
| 1941 | + pic.y.data[dst..dst + w].copy_from_slice(&out[row * w..row * w + w]); | ||
| 1942 | + } | ||
| 1943 | + | ||
| 1944 | + // Chroma (8.4.1.4): for 4:2:0 frame coding the chroma vector is the luma | ||
| 1945 | + // vector, read as eighth-sample units over the half-resolution plane. | ||
| 1946 | + let (cw, ch) = (w / 2, h / 2); | ||
| 1947 | + let (cx0, cy0) = (x0 / 2, y0 / 2); | ||
| 1948 | + for comp in 0..2 { | ||
| 1949 | + let mut cpart = [[0u8; 64]; 2]; | ||
| 1950 | + for list in 0..2 { | ||
| 1951 | + if ref_idx[list] < 0 { | ||
| 1952 | + continue; | ||
| 1953 | + } | ||
| 1954 | + let rp = ctx | ||
| 1955 | + .reference(refs, list, ref_idx[list]) | ||
| 1956 | + .expect("checked above"); | ||
| 1957 | + let src = if comp == 0 { &rp.cb } else { &rp.cr }; | ||
| 1958 | + let plane = RefPlane { | ||
| 1959 | + data: &src.data, | ||
| 1960 | + stride: src.stride, | ||
| 1961 | + origin: src.origin, | ||
| 1962 | + width: src.width, | ||
| 1963 | + height: src.height, | ||
| 1964 | + pad: src.pad, | ||
| 1965 | + }; | ||
| 1966 | + mc_chroma(&plane, cx0, cy0, mv[list], cw, ch, &mut cpart[list]); | ||
| 1967 | + } | ||
| 1968 | + let wt = ctx.weights_for(refs, comp + 1, ref_idx[0], ref_idx[1], use0, use1); | ||
| 1969 | + let mut cout = [0u8; 64]; | ||
| 1970 | + let (c0, c1) = cpart.split_at(1); | ||
| 1971 | + combine(&mut cout, &c0[0], &c1[0], use0, use1, &wt, cw * ch); | ||
| 1972 | + let plane = if comp == 0 { &mut pic.cb } else { &mut pic.cr }; | ||
| 1973 | + let stride = plane.stride; | ||
| 1974 | + let origin = plane.at(cx0 as usize, cy0 as usize); | ||
| 1975 | + for row in 0..ch { | ||
| 1976 | + let dst = origin + row * stride; | ||
| 1977 | + plane.data[dst..dst + cw].copy_from_slice(&cout[row * cw..row * cw + cw]); | ||
| 1978 | + } | ||
| 1979 | + } | ||
| 1980 | + Ok(()) | ||
| 1981 | +} | ||
| 1982 | + | ||
| 882 | /// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2), | 1983 | /// Gather the 13 neighbour samples of a luma 4x4 block (spec 8.3.1.2), |
| 883 | /// including the top-right substitution rule. | 1984 | /// including the top-right substitution rule. |
| 884 | fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) -> Nbr4 { | 1985 | fn gather_nbr4(pic: &Picture, nbr: &MbNeighbors, blk: usize, x: usize, y: usize) -> Nbr4 { |
| @@ -944,6 +2045,20 @@ fn deblock_picture(pic: &mut Picture) { | |||
| 944 | }; | 2045 | }; |
| 945 | let qp_q = qp_of(addr); | 2046 | let qp_q = qp_of(addr); |
| 946 | 2047 | ||
| 2048 | + // Boundary strengths, per 4-sample segment of each edge (8.7.2.1). | ||
| 2049 | + let mut bs_v = [[0u8; 4]; 4]; | ||
| 2050 | + let mut bs_h = [[0u8; 4]; 4]; | ||
| 2051 | + for e in 0..4 { | ||
| 2052 | + for k in 0..4 { | ||
| 2053 | + if e > 0 || filter_left { | ||
| 2054 | + bs_v[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, true); | ||
| 2055 | + } | ||
| 2056 | + if e > 0 || filter_top { | ||
| 2057 | + bs_h[e][k] = boundary_strength(pic, mb_x, mb_y, e, k, false); | ||
| 2058 | + } | ||
| 2059 | + } | ||
| 2060 | + } | ||
| 2061 | + | ||
| 947 | // ---- luma ---- | 2062 | // ---- luma ---- |
| 948 | { | 2063 | { |
| 949 | let stride = pic.y.stride; | 2064 | let stride = pic.y.stride; |
| @@ -953,21 +2068,29 @@ fn deblock_picture(pic: &mut Picture) { | |||
| 953 | if e == 0 && !filter_left { | 2068 | if e == 0 && !filter_left { |
| 954 | continue; | 2069 | continue; |
| 955 | } | 2070 | } |
| 956 | - let (bs, qp_p) = if e == 0 { | 2071 | + let qp_p = if e == 0 { qp_of(addr - 1) } else { qp_q }; |
| 957 | - (4, qp_of(addr - 1)) | 2072 | + let qp_avg = (qp_p + qp_q + 1) >> 1; |
| 958 | - } else { | ||
| 959 | - (3, qp_q) | ||
| 960 | - }; | ||
| 961 | - let params = | ||
| 962 | - edge_params((qp_p + qp_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); | ||
| 963 | - if params.alpha == 0 || params.beta == 0 { | ||
| 964 | - continue; | ||
| 965 | - } | ||
| 966 | // Vertical edges stay scalar: a gather/scatter SIMD | 2073 | // Vertical edges stay scalar: a gather/scatter SIMD |
| 967 | // variant measured slower than this loop (strided | 2074 | // variant measured slower than this loop (strided |
| 968 | // per-lane loads dominate). | 2075 | // per-lane loads dominate). |
| 969 | - for k in 0..16 { | 2076 | + for j in 0..4 { |
| 970 | - filter_luma_line(&mut pic.y.data, base + k * stride + e * 4, 1, ¶ms); | 2077 | + let bs = bs_v[e][j]; |
| 2078 | + if bs == 0 { | ||
| 2079 | + continue; | ||
| 2080 | + } | ||
| 2081 | + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs); | ||
| 2082 | + if params.alpha == 0 || params.beta == 0 { | ||
| 2083 | + continue; | ||
| 2084 | + } | ||
| 2085 | + for k in 0..4 { | ||
| 2086 | + let row = j * 4 + k; | ||
| 2087 | + filter_luma_line( | ||
| 2088 | + &mut pic.y.data, | ||
| 2089 | + base + row * stride + e * 4, | ||
| 2090 | + 1, | ||
| 2091 | + ¶ms, | ||
| 2092 | + ); | ||
| 2093 | + } | ||
| 971 | } | 2094 | } |
| 972 | } | 2095 | } |
| 973 | // Horizontal edges, top to bottom. | 2096 | // Horizontal edges, top to bottom. |
| @@ -975,17 +2098,40 @@ fn deblock_picture(pic: &mut Picture) { | |||
| 975 | if e == 0 && !filter_top { | 2098 | if e == 0 && !filter_top { |
| 976 | continue; | 2099 | continue; |
| 977 | } | 2100 | } |
| 978 | - let (bs, qp_p) = if e == 0 { | 2101 | + let qp_p = if e == 0 { qp_of(addr - mb_w) } else { qp_q }; |
| 979 | - (4, qp_of(addr - mb_w)) | 2102 | + let qp_avg = (qp_p + qp_q + 1) >> 1; |
| 980 | - } else { | 2103 | + let bs = bs_h[e]; |
| 981 | - (3, qp_q) | 2104 | + let uniform = bs[0] == bs[1] && bs[1] == bs[2] && bs[2] == bs[3]; |
| 982 | - }; | 2105 | + if uniform { |
| 983 | - let params = | 2106 | + if bs[0] == 0 { |
| 984 | - edge_params((qp_p + qp_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); | 2107 | + continue; |
| 2108 | + } | ||
| 2109 | + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[0]); | ||
| 985 | if params.alpha == 0 || params.beta == 0 { | 2110 | if params.alpha == 0 || params.beta == 0 { |
| 986 | continue; | 2111 | continue; |
| 987 | } | 2112 | } |
| 2113 | + // Eight rows around the edge are contiguous, so the | ||
| 2114 | + // whole 16-sample edge filters in one pass. | ||
| 988 | filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, ¶ms); | 2115 | filter_luma_h_edge16(&mut pic.y.data, base + e * 4 * stride, stride, ¶ms); |
| 2116 | + continue; | ||
| 2117 | + } | ||
| 2118 | + for j in 0..4 { | ||
| 2119 | + if bs[j] == 0 { | ||
| 2120 | + continue; | ||
| 2121 | + } | ||
| 2122 | + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs[j]); | ||
| 2123 | + if params.alpha == 0 || params.beta == 0 { | ||
| 2124 | + continue; | ||
| 2125 | + } | ||
| 2126 | + for k in 0..4 { | ||
| 2127 | + filter_luma_line( | ||
| 2128 | + &mut pic.y.data, | ||
| 2129 | + base + e * 4 * stride + j * 4 + k, | ||
| 2130 | + stride, | ||
| 2131 | + ¶ms, | ||
| 2132 | + ); | ||
| 2133 | + } | ||
| 2134 | + } | ||
| 989 | } | 2135 | } |
| 990 | } | 2136 | } |
| 991 | 2137 | ||
| @@ -1009,21 +2155,24 @@ fn deblock_picture(pic: &mut Picture) { | |||
| 1009 | } | 2155 | } |
| 1010 | }; | 2156 | }; |
| 1011 | let cq_q = cqp(addr); | 2157 | let cq_q = cqp(addr); |
| 2158 | + // A chroma edge inherits the boundary strength of the luma edge | ||
| 2159 | + // it sits on: chroma sample k maps to luma sample 2k, so a | ||
| 2160 | + // chroma 4-sample run spans two luma 4x4 block rows. | ||
| 1012 | for e in 0..2 { | 2161 | for e in 0..2 { |
| 1013 | if e == 0 && !filter_left { | 2162 | if e == 0 && !filter_left { |
| 1014 | continue; | 2163 | continue; |
| 1015 | } | 2164 | } |
| 1016 | - let (bs, cq_p) = if e == 0 { | 2165 | + let cq_p = if e == 0 { cqp(addr - 1) } else { cq_q }; |
| 1017 | - (4, cqp(addr - 1)) | 2166 | + let qp_avg = (cq_p + cq_q + 1) >> 1; |
| 1018 | - } else { | 2167 | + for k in 0..8 { |
| 1019 | - (3, cq_q) | 2168 | + let bs = bs_v[e * 2][k / 2]; |
| 1020 | - }; | 2169 | + if bs == 0 { |
| 1021 | - let params = | 2170 | + continue; |
| 1022 | - edge_params((cq_p + cq_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); | 2171 | + } |
| 2172 | + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs); | ||
| 1023 | if params.alpha == 0 || params.beta == 0 { | 2173 | if params.alpha == 0 || params.beta == 0 { |
| 1024 | continue; | 2174 | continue; |
| 1025 | } | 2175 | } |
| 1026 | - for k in 0..8 { | ||
| 1027 | filter_chroma_line(&mut plane.data, base + k * stride + e * 4, 1, ¶ms); | 2176 | filter_chroma_line(&mut plane.data, base + k * stride + e * 4, 1, ¶ms); |
| 1028 | } | 2177 | } |
| 1029 | } | 2178 | } |
| @@ -1031,17 +2180,17 @@ fn deblock_picture(pic: &mut Picture) { | |||
| 1031 | if e == 0 && !filter_top { | 2180 | if e == 0 && !filter_top { |
| 1032 | continue; | 2181 | continue; |
| 1033 | } | 2182 | } |
| 1034 | - let (bs, cq_p) = if e == 0 { | 2183 | + let cq_p = if e == 0 { cqp(addr - mb_w) } else { cq_q }; |
| 1035 | - (4, cqp(addr - mb_w)) | 2184 | + let qp_avg = (cq_p + cq_q + 1) >> 1; |
| 1036 | - } else { | 2185 | + for k in 0..8 { |
| 1037 | - (3, cq_q) | 2186 | + let bs = bs_h[e * 2][k / 2]; |
| 1038 | - }; | 2187 | + if bs == 0 { |
| 1039 | - let params = | 2188 | + continue; |
| 1040 | - edge_params((cq_p + cq_q + 1) >> 1, sp.alpha_offset, sp.beta_offset, bs); | 2189 | + } |
| 2190 | + let params = edge_params(qp_avg, sp.alpha_offset, sp.beta_offset, bs); | ||
| 1041 | if params.alpha == 0 || params.beta == 0 { | 2191 | if params.alpha == 0 || params.beta == 0 { |
| 1042 | continue; | 2192 | continue; |
| 1043 | } | 2193 | } |
| 1044 | - for k in 0..8 { | ||
| 1045 | filter_chroma_line( | 2194 | filter_chroma_line( |
| 1046 | &mut plane.data, | 2195 | &mut plane.data, |
| 1047 | base + e * 4 * stride + k, | 2196 | base + e * 4 * stride + k, |
| @@ -1054,3 +2203,79 @@ fn deblock_picture(pic: &mut Picture) { | |||
| 1054 | } | 2203 | } |
| 1055 | } | 2204 | } |
| 1056 | } | 2205 | } |
| 2206 | + | ||
| 2207 | +/// Boundary strength of one 4-sample luma edge segment (clause 8.7.2.1). | ||
| 2208 | +/// | ||
| 2209 | +/// `edge` 0..4 selects the vertical (`vertical`) or horizontal edge inside the | ||
| 2210 | +/// macroblock, `seg` the 4-sample run along it. Edge 0 is the macroblock edge. | ||
| 2211 | +fn boundary_strength( | ||
| 2212 | + pic: &Picture, | ||
| 2213 | + mb_x: usize, | ||
| 2214 | + mb_y: usize, | ||
| 2215 | + edge: usize, | ||
| 2216 | + seg: usize, | ||
| 2217 | + vertical: bool, | ||
| 2218 | +) -> u8 { | ||
| 2219 | + let w4 = pic.mb_w * 4; | ||
crates/ec-h264/src/dpb.rsadded+1277 -0
| @@ -0,0 +1,1277 @@ | |||
| 1 | +//! Decoded picture buffer (spec clause 8.2): picture storage, picture order | ||
| 2 | +//! count, reference marking, reference list construction and output order. | ||
| 3 | +//! | ||
| 4 | +//! The buffer owns every decoded picture, including the one being decoded — the | ||
| 5 | +//! decoder holds that one *out* of the pool while a picture is open, which is | ||
| 6 | +//! what lets motion compensation borrow reference planes immutably while | ||
| 7 | +//! writing the current planes mutably. | ||
| 8 | +//! | ||
| 9 | +//! Pictures are pooled, never freed: a picture that is neither referenced nor | ||
| 10 | +//! awaiting output goes back on the free list with its plane and motion | ||
| 11 | +//! allocations intact, so a steady-state decode loop reuses the same buffers | ||
| 12 | +//! forever and allocates nothing. | ||
| 13 | +//! | ||
| 14 | +//! Output order is display order. Every picture leaves through the bumping | ||
| 15 | +//! process of clause C.4.5.3 — smallest picture order count first, released | ||
| 16 | +//! when the buffer is over its reordering or storage limit — so a stream with | ||
| 17 | +//! B pictures comes out in the order a player has to present it, not the order | ||
| 18 | +//! it was coded in. | ||
| 19 | + | ||
| 20 | +use ec_core::error::{Error, Result}; | ||
| 21 | +use ec_h264_syntax::{DecRefPicMarking, RefPicListMod, SliceType, Sps}; | ||
| 22 | + | ||
| 23 | +/// Luma plane padding on every side, sized for inter-prediction filter | ||
| 24 | +/// overreach: a 16-wide partition plus the two/three sample reach of the 6-tap | ||
| 25 | +/// filter, rounded up. | ||
| 26 | +pub(crate) const PAD_Y: usize = 32; | ||
| 27 | +/// Chroma plane padding on every side (8-wide block plus one bilinear tap). | ||
| 28 | +pub(crate) const PAD_C: usize = 16; | ||
| 29 | +/// `mb_slice` value for a not-yet-decoded macroblock. | ||
| 30 | +pub(crate) const NO_SLICE: u16 = u16::MAX; | ||
| 31 | +/// Hard cap on stored pictures: 16 reference frames (Annex A) plus the current. | ||
| 32 | +const MAX_STORED: usize = 17; | ||
| 33 | + | ||
| 34 | +/// Per-4x4-block flags recorded for inter neighbour derivation. | ||
| 35 | +/// The block belongs to an intra macroblock. | ||
| 36 | +pub(crate) const BLK_INTRA: u8 = 1; | ||
| 37 | +/// The block belongs to a P_Skip or B_Skip macroblock. | ||
| 38 | +pub(crate) const BLK_SKIP: u8 = 2; | ||
| 39 | +/// The block is predicted in direct mode (B_Skip, B_Direct_16x16 or a | ||
| 40 | +/// B_Direct_8x8 sub-macroblock). | ||
| 41 | +pub(crate) const BLK_DIRECT: u8 = 4; | ||
| 42 | + | ||
| 43 | +/// Reference marking of a stored picture (clause 8.2.5). | ||
| 44 | +#[derive(Clone, Copy, PartialEq, Eq, Debug, Default)] | ||
| 45 | +pub(crate) enum Mark { | ||
| 46 | + /// "unused for reference". | ||
| 47 | + #[default] | ||
| 48 | + Unused, | ||
| 49 | + /// "used for short-term reference". | ||
| 50 | + Short, | ||
| 51 | + /// "used for long-term reference". | ||
| 52 | + Long, | ||
| 53 | +} | ||
| 54 | + | ||
| 55 | +/// A padded 8-bit plane. | ||
| 56 | +#[derive(Debug, Default)] | ||
| 57 | +pub(crate) struct Plane8 { | ||
| 58 | + pub data: Vec<u8>, | ||
| 59 | + pub stride: usize, | ||
| 60 | + /// Index of sample (0, 0) of the picture. | ||
| 61 | + pub origin: usize, | ||
| 62 | + pub width: usize, | ||
| 63 | + pub height: usize, | ||
| 64 | + pub pad: usize, | ||
| 65 | +} | ||
| 66 | + | ||
| 67 | +impl Plane8 { | ||
| 68 | + fn resize(&mut self, width: usize, height: usize, pad: usize) { | ||
| 69 | + self.stride = width + 2 * pad; | ||
| 70 | + self.origin = pad * self.stride + pad; | ||
| 71 | + self.width = width; | ||
| 72 | + self.height = height; | ||
| 73 | + self.pad = pad; | ||
| 74 | + self.data.clear(); | ||
| 75 | + self.data.resize(self.stride * (height + 2 * pad), 0); | ||
| 76 | + } | ||
| 77 | + | ||
| 78 | + #[inline] | ||
| 79 | + pub(crate) fn at(&self, x: usize, y: usize) -> usize { | ||
| 80 | + self.origin + y * self.stride + x | ||
| 81 | + } | ||
| 82 | + | ||
| 83 | + /// Replicate the edge samples into the padding, which turns the per-sample | ||
| 84 | + /// `Clip3` of Equations 8-239/8-240 into ordinary reads (see | ||
| 85 | + /// [`crate::inter`]). | ||
| 86 | + fn extend_borders(&mut self) { | ||
| 87 | + let (w, h, pad, stride) = (self.width, self.height, self.pad, self.stride); | ||
| 88 | + for y in 0..h { | ||
| 89 | + let row = self.origin + y * stride; | ||
| 90 | + let (left, right) = (self.data[row], self.data[row + w - 1]); | ||
| 91 | + self.data[row - pad..row].fill(left); | ||
| 92 | + self.data[row + w..row + w + pad].fill(right); | ||
| 93 | + } | ||
| 94 | + let full = self.origin - pad; | ||
| 95 | + for y in 0..pad { | ||
| 96 | + let (src, dst) = (full, full - (y + 1) * stride); | ||
| 97 | + self.data.copy_within(src..src + stride, dst); | ||
| 98 | + let src = full + (h - 1) * stride; | ||
| 99 | + self.data.copy_within(src..src + stride, src + (y + 1) * stride); | ||
| 100 | + } | ||
| 101 | + } | ||
| 102 | +} | ||
| 103 | + | ||
| 104 | +/// Per-slice values the deblocking filter needs after slice decode ends. | ||
| 105 | +#[derive(Debug, Clone, Copy)] | ||
| 106 | +pub(crate) struct SliceParams { | ||
| 107 | + pub disable_deblock_idc: u8, | ||
| 108 | + pub alpha_offset: i32, | ||
| 109 | + pub beta_offset: i32, | ||
| 110 | + pub cb_qp_offset: i32, | ||
| 111 | + pub cr_qp_offset: i32, | ||
| 112 | +} | ||
| 113 | + | ||
| 114 | +/// Flat per-picture decode context. | ||
| 115 | +/// | ||
| 116 | +/// All per-macroblock and per-4x4-block state lives in struct-of-arrays keyed | ||
| 117 | +/// by macroblock address or 4x4-block coordinate: no per-macroblock heap | ||
| 118 | +/// objects anywhere, and the whole picture is one reusable allocation set. | ||
| 119 | +#[derive(Debug, Default)] | ||
| 120 | +pub(crate) struct Picture { | ||
| 121 | + pub sps_id: u8, | ||
| 122 | + pub mb_w: usize, | ||
| 123 | + pub mb_h: usize, | ||
| 124 | + pub y: Plane8, | ||
| 125 | + pub cb: Plane8, | ||
| 126 | + pub cr: Plane8, | ||
| 127 | + /// TotalCoeff per luma 4x4 block, `(mb_w * 4) x (mb_h * 4)`. | ||
| 128 | + pub nz_y: Vec<u8>, | ||
| 129 | + /// TotalCoeff per chroma 4x4 block, `(mb_w * 2) x (mb_h * 2)`, Cb and Cr. | ||
| 130 | + pub nz_c: [Vec<u8>; 2], | ||
| 131 | + /// Intra4x4PredMode per luma 4x4 block (2 = DC for non-I4x4 MBs). | ||
| 132 | + pub i4_modes: Vec<u8>, | ||
| 133 | + /// QPY per macroblock (the prediction-chain value; PCM keeps the chain). | ||
| 134 | + pub mb_qp: Vec<u8>, | ||
| 135 | + /// `FLAG_*` bits per macroblock. | ||
| 136 | + pub mb_flags: Vec<u8>, | ||
| 137 | + /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4` per macroblock. | ||
| 138 | + pub mb_cbp: Vec<u8>, | ||
| 139 | + /// coded_block_flag of the DC blocks per macroblock: bit 0 luma, 1 Cb, 2 Cr. | ||
| 140 | + pub mb_dc_cbf: Vec<u8>, | ||
| 141 | + /// Owning slice index per macroblock, `NO_SLICE` when undecoded. | ||
| 142 | + pub mb_slice: Vec<u16>, | ||
| 143 | + /// `MvLX[..][..]` per luma 4x4 block, `[list][component]`, quarter samples. | ||
| 144 | + pub mv: Vec<[[i16; 2]; 2]>, | ||
| 145 | + /// `RefIdxLX` per luma 4x4 block, -1 when the list is not used. | ||
| 146 | + pub ref_idx: Vec<[i8; 2]>, | ||
| 147 | + /// Identity ([`Picture::id`]) of the referenced picture per list, -1 when | ||
| 148 | + /// unused. Reference *indices* are per slice, so only the picture identity | ||
| 149 | + /// answers "same reference picture?" for boundary strength (8.7.2.1) and | ||
| 150 | + /// `MapColToList0` (8.4.1.2.3). | ||
| 151 | + pub ref_id: Vec<[i32; 2]>, | ||
| 152 | + /// `Abs( mvd_lX[..][..][comp] )` per block, `[l0x, l0y, l1x, l1y]`, | ||
| 153 | + /// saturated (the thresholds of 9.3.3.1.1.7 are 2 and 32). | ||
| 154 | + pub mvd_abs: Vec<[u8; 4]>, | ||
| 155 | + /// `BLK_*` flags per luma 4x4 block. | ||
| 156 | + pub blk: Vec<u8>, | ||
| 157 | + pub slices: Vec<SliceParams>, | ||
| 158 | + pub decoded_mbs: usize, | ||
| 159 | + pub complete: bool, | ||
| 160 | + | ||
| 161 | + // ---- clause 8.2 picture state ---- | ||
| 162 | + /// Stream-unique identity, assigned when the picture is started. | ||
| 163 | + pub id: i32, | ||
| 164 | + /// `PicOrderCnt( )` of the frame. | ||
| 165 | + pub poc: i32, | ||
| 166 | + pub frame_num: u32, | ||
| 167 | + /// `FrameNumWrap` (8-27), recomputed for every decoded picture. | ||
| 168 | + pub frame_num_wrap: i32, | ||
| 169 | + /// `PicNum` (8-28) for short-term, `LongTermPicNum` (8-29) for long-term. | ||
| 170 | + pub pic_num: i32, | ||
| 171 | + pub long_term_frame_idx: u32, | ||
| 172 | + pub mark: Mark, | ||
| 173 | + /// The picture has not been output yet. | ||
| 174 | + pub output: bool, | ||
| 175 | + /// Inferred by the frame_num gap process of 8.2.5.2 rather than decoded. | ||
| 176 | + pub non_existing: bool, | ||
| 177 | + /// `FrameNumOffset` (8-6 / 8-11), carried to the next picture. | ||
| 178 | + pub frame_num_offset: i32, | ||
| 179 | + /// `PicOrderCntMsb` (8-3), carried to the next picture for POC type 0. | ||
| 180 | + pub poc_msb: i32, | ||
| 181 | + /// `pic_order_cnt_lsb` as coded, carried alongside `poc_msb`. | ||
| 182 | + pub poc_lsb: i32, | ||
| 183 | + /// Presentation timestamp of the access unit this picture came from. It | ||
| 184 | + /// travels with the picture rather than with the packet, because display | ||
| 185 | + /// order reorders the two apart. | ||
| 186 | + pub pts: Option<ec_core::timebase::Timestamp>, | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +impl Picture { | ||
| 190 | + /// Reset for a new picture of `sps`'s geometry, reallocating only when the | ||
| 191 | + /// geometry actually changed. | ||
| 192 | + pub(crate) fn start(&mut self, sps: &Sps) { | ||
| 193 | + let mb_w = sps.mb_width as usize; | ||
| 194 | + let mb_h = sps.mb_height as usize; | ||
| 195 | + if self.mb_w != mb_w || self.mb_h != mb_h || self.sps_id != sps.id { | ||
| 196 | + self.mb_w = mb_w; | ||
| 197 | + self.mb_h = mb_h; | ||
| 198 | + self.sps_id = sps.id; | ||
| 199 | + self.y.resize(mb_w * 16, mb_h * 16, PAD_Y); | ||
| 200 | + self.cb.resize(mb_w * 8, mb_h * 8, PAD_C); | ||
| 201 | + self.cr.resize(mb_w * 8, mb_h * 8, PAD_C); | ||
| 202 | + let blocks = mb_w * mb_h * 16; | ||
| 203 | + self.nz_y.resize(blocks, 0); | ||
| 204 | + for c in &mut self.nz_c { | ||
| 205 | + c.resize(mb_w * mb_h * 4, 0); | ||
| 206 | + } | ||
| 207 | + self.i4_modes.resize(blocks, 2); | ||
| 208 | + self.mb_qp.resize(mb_w * mb_h, 0); | ||
| 209 | + self.mb_flags.resize(mb_w * mb_h, 0); | ||
| 210 | + self.mb_cbp.resize(mb_w * mb_h, 0); | ||
| 211 | + self.mb_dc_cbf.resize(mb_w * mb_h, 0); | ||
| 212 | + self.mb_slice.resize(mb_w * mb_h, NO_SLICE); | ||
| 213 | + self.mv.resize(blocks, [[0; 2]; 2]); | ||
| 214 | + self.ref_idx.resize(blocks, [-1; 2]); | ||
| 215 | + self.ref_id.resize(blocks, [-1; 2]); | ||
| 216 | + self.mvd_abs.resize(blocks, [0; 4]); | ||
| 217 | + self.blk.resize(blocks, 0); | ||
| 218 | + } | ||
| 219 | + // Per-MB metadata is rewritten by each decoded macroblock; only the | ||
| 220 | + // "who is decoded" state must be wiped between pictures. | ||
| 221 | + self.mb_slice.fill(NO_SLICE); | ||
| 222 | + self.mb_flags.fill(0); | ||
| 223 | + self.slices.clear(); | ||
| 224 | + self.decoded_mbs = 0; | ||
| 225 | + self.complete = false; | ||
| 226 | + self.mark = Mark::Unused; | ||
| 227 | + self.output = false; | ||
| 228 | + self.non_existing = false; | ||
| 229 | + self.long_term_frame_idx = 0; | ||
| 230 | + } | ||
| 231 | + | ||
| 232 | + /// Replicate every plane's borders once the picture is fully reconstructed. | ||
| 233 | + pub(crate) fn extend_borders(&mut self) { | ||
| 234 | + self.y.extend_borders(); | ||
| 235 | + self.cb.extend_borders(); | ||
| 236 | + self.cr.extend_borders(); | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + /// Fill the picture with mid-grey, for a frame the stream never sent. | ||
| 240 | + fn fill_grey(&mut self) { | ||
| 241 | + self.y.data.fill(128); | ||
| 242 | + self.cb.data.fill(128); | ||
| 243 | + self.cr.data.fill(128); | ||
| 244 | + } | ||
| 245 | + | ||
| 246 | + fn copy_samples_from(&mut self, src: &Picture) { | ||
| 247 | + self.y.data.copy_from_slice(&src.y.data); | ||
| 248 | + self.cb.data.copy_from_slice(&src.cb.data); | ||
| 249 | + self.cr.data.copy_from_slice(&src.cr.data); | ||
| 250 | + } | ||
| 251 | + | ||
| 252 | + /// True while the picture occupies a decoded picture buffer slot. | ||
| 253 | + fn stored(&self) -> bool { | ||
| 254 | + self.mark != Mark::Unused || self.output | ||
| 255 | + } | ||
| 256 | +} | ||
| 257 | + | ||
| 258 | +/// One reference picture list (`RefPicList0` / `RefPicList1`). | ||
| 259 | +/// | ||
| 260 | +/// Entries are indices into [`Dpb::frames`]; the list is a fixed array because | ||
| 261 | +/// Annex A caps it at 32 entries, so building it allocates nothing. | ||
| 262 | +#[derive(Clone, Copy, Debug)] | ||
| 263 | +pub(crate) struct RefList { | ||
| 264 | + entries: [u8; 33], | ||
| 265 | + len: usize, | ||
| 266 | +} | ||
| 267 | + | ||
| 268 | +impl Default for RefList { | ||
| 269 | + fn default() -> RefList { | ||
| 270 | + RefList { | ||
| 271 | + entries: [0; 33], | ||
| 272 | + len: 0, | ||
| 273 | + } | ||
| 274 | + } | ||
| 275 | +} | ||
| 276 | + | ||
| 277 | +impl RefList { | ||
| 278 | + pub(crate) fn len(&self) -> usize { | ||
| 279 | + self.len | ||
| 280 | + } | ||
| 281 | + | ||
| 282 | + /// The DPB index of `RefPicListX[idx]`, `None` past the end. | ||
| 283 | + #[inline] | ||
| 284 | + pub(crate) fn get(&self, idx: usize) -> Option<usize> { | ||
| 285 | + (idx < self.len).then(|| usize::from(self.entries[idx])) | ||
| 286 | + } | ||
| 287 | + | ||
| 288 | + fn push(&mut self, idx: usize) { | ||
| 289 | + if self.len < self.entries.len() { | ||
| 290 | + self.entries[self.len] = idx as u8; | ||
| 291 | + self.len += 1; | ||
| 292 | + } | ||
| 293 | + } | ||
| 294 | +} | ||
| 295 | + | ||
| 296 | +/// The decoded picture buffer and the clause 8.2 state that spans pictures. | ||
| 297 | +pub(crate) struct Dpb { | ||
| 298 | + /// Stored pictures, in no particular order. | ||
| 299 | + pub frames: Vec<Picture>, | ||
| 300 | + /// Recycled picture buffers. | ||
| 301 | + free: Vec<Picture>, | ||
| 302 | + next_id: i32, | ||
| 303 | + /// `max_dec_frame_buffering`. | ||
| 304 | + max_frames: usize, | ||
| 305 | + /// `max_num_reorder_frames`. | ||
| 306 | + max_reorder: usize, | ||
| 307 | + /// `MaxLongTermFrameIdx`, `None` = "no long-term frame indices". | ||
| 308 | + max_long_term_idx: Option<u32>, | ||
| 309 | + // Picture order count state (8.2.1). | ||
| 310 | + prev_poc_msb: i32, | ||
| 311 | + prev_poc_lsb: i32, | ||
| 312 | + prev_frame_num: u32, | ||
| 313 | + prev_frame_num_offset: i32, | ||
| 314 | + prev_has_mmco5: bool, | ||
| 315 | + /// `PrevRefFrameNum` for the gap detection of 8.2.5.2. | ||
| 316 | + prev_ref_frame_num: u32, | ||
| 317 | + /// Set once a picture has been decoded since the last reset. | ||
| 318 | + started: bool, | ||
| 319 | + /// Everything stored before [`Dpb::last_id`] must be output before it. | ||
| 320 | + pending_flush: bool, | ||
| 321 | + /// Identity of the most recently stored picture. | ||
| 322 | + last_id: i32, | ||
| 323 | +} | ||
| 324 | + | ||
| 325 | +impl Default for Dpb { | ||
| 326 | + fn default() -> Dpb { | ||
| 327 | + Dpb { | ||
| 328 | + frames: Vec::new(), | ||
| 329 | + free: Vec::new(), | ||
| 330 | + next_id: 0, | ||
| 331 | + max_frames: 16, | ||
| 332 | + max_reorder: 16, | ||
| 333 | + max_long_term_idx: None, | ||
| 334 | + prev_poc_msb: 0, | ||
| 335 | + prev_poc_lsb: 0, | ||
| 336 | + prev_frame_num: 0, | ||
| 337 | + prev_frame_num_offset: 0, | ||
| 338 | + prev_has_mmco5: false, | ||
| 339 | + prev_ref_frame_num: 0, | ||
| 340 | + started: false, | ||
| 341 | + pending_flush: false, | ||
| 342 | + last_id: -1, | ||
| 343 | + } | ||
| 344 | + } | ||
| 345 | +} | ||
| 346 | + | ||
| 347 | +/// Output of the picture order count derivation (clause 8.2.1). | ||
| 348 | +#[derive(Clone, Copy, Debug, Default)] | ||
| 349 | +pub(crate) struct Poc { | ||
| 350 | + /// `PicOrderCnt( )` of the frame. | ||
| 351 | + pub value: i32, | ||
| 352 | + /// `FrameNumOffset`, predicted from by the next picture. | ||
| 353 | + pub frame_num_offset: i32, | ||
| 354 | + /// `PicOrderCntMsb` (POC type 0 only). | ||
| 355 | + pub msb: i32, | ||
| 356 | + /// `pic_order_cnt_lsb` (POC type 0 only). | ||
| 357 | + pub lsb: i32, | ||
| 358 | +} | ||
| 359 | + | ||
| 360 | +/// Everything about the current picture the DPB needs, gathered from the first | ||
| 361 | +/// slice header of that picture. | ||
| 362 | +#[derive(Clone, Copy, Debug)] | ||
| 363 | +pub(crate) struct PicInfo { | ||
| 364 | + pub is_idr: bool, | ||
| 365 | + pub is_reference: bool, | ||
| 366 | + pub frame_num: u32, | ||
| 367 | + pub pic_order_cnt_lsb: u32, | ||
| 368 | + pub delta_pic_order_cnt_bottom: i32, | ||
| 369 | + pub delta_pic_order_cnt: [i32; 2], | ||
| 370 | +} | ||
| 371 | + | ||
| 372 | +impl Dpb { | ||
| 373 | + /// Adopt the buffer limits of `sps` (Annex A / VUI), keeping whatever is | ||
| 374 | + /// already stored. | ||
| 375 | + pub(crate) fn configure(&mut self, sps: &Sps) { | ||
| 376 | + let level_frames = max_dpb_frames(sps); | ||
| 377 | + let (buffering, reorder) = match sps.vui.as_ref().and_then(|v| v.bitstream_restriction) { | ||
| 378 | + Some(r) => ( | ||
| 379 | + (r.max_dec_frame_buffering as usize).min(MAX_STORED - 1), | ||
| 380 | + (r.max_num_reorder_frames as usize).min(MAX_STORED - 1), | ||
| 381 | + ), | ||
| 382 | + // Without the VUI restriction the level limit is all we know. It | ||
| 383 | + // over-buffers a low-delay stream, which costs latency but never | ||
| 384 | + // order: pictures still leave smallest-POC-first. | ||
| 385 | + None => (level_frames, level_frames), | ||
| 386 | + }; | ||
| 387 | + self.max_frames = buffering.max(sps.max_num_ref_frames as usize).max(1); | ||
| 388 | + self.max_reorder = reorder.min(self.max_frames); | ||
| 389 | + } | ||
| 390 | + | ||
| 391 | + /// A picture buffer to decode into, off the free list when possible. | ||
| 392 | + pub(crate) fn take_picture(&mut self) -> Picture { | ||
| 393 | + let mut pic = self.free.pop().unwrap_or_default(); | ||
| 394 | + pic.id = self.next_id; | ||
| 395 | + self.next_id = self.next_id.wrapping_add(1); | ||
| 396 | + pic | ||
| 397 | + } | ||
| 398 | + | ||
| 399 | + /// Hand a picture buffer back for reuse. | ||
| 400 | + pub(crate) fn recycle(&mut self, pic: Picture) { | ||
| 401 | + if self.free.len() < MAX_STORED { | ||
| 402 | + self.free.push(pic); | ||
| 403 | + } | ||
| 404 | + } | ||
| 405 | + | ||
| 406 | + /// Drop every stored picture (seek / stream discontinuity). | ||
| 407 | + pub(crate) fn clear(&mut self) { | ||
| 408 | + while let Some(pic) = self.frames.pop() { | ||
| 409 | + self.recycle(pic); | ||
| 410 | + } | ||
| 411 | + self.max_long_term_idx = None; | ||
| 412 | + self.prev_poc_msb = 0; | ||
| 413 | + self.prev_poc_lsb = 0; | ||
| 414 | + self.prev_frame_num = 0; | ||
| 415 | + self.prev_frame_num_offset = 0; | ||
| 416 | + self.prev_has_mmco5 = false; | ||
| 417 | + self.prev_ref_frame_num = 0; | ||
| 418 | + self.started = false; | ||
| 419 | + self.pending_flush = false; | ||
| 420 | + self.last_id = -1; | ||
| 421 | + } | ||
| 422 | + | ||
| 423 | + /// `PicOrderCnt( )` of a picture about to be decoded (clause 8.2.1), | ||
| 424 | + /// together with the `FrameNumOffset` and `PicOrderCntMsb` the next | ||
| 425 | + /// picture predicts from. | ||
| 426 | + pub(crate) fn picture_order_count(&self, sps: &Sps, info: &PicInfo) -> Result<Poc> { | ||
| 427 | + match sps.pic_order_cnt_type { | ||
| 428 | + 0 => { | ||
| 429 | + let max_lsb = 1i32 << sps.log2_max_pic_order_cnt_lsb; | ||
| 430 | + let (prev_msb, prev_lsb) = if info.is_idr { | ||
| 431 | + (0, 0) | ||
| 432 | + } else { | ||
| 433 | + (self.prev_poc_msb, self.prev_poc_lsb) | ||
| 434 | + }; | ||
| 435 | + let lsb = info.pic_order_cnt_lsb as i32; | ||
| 436 | + let msb = if lsb < prev_lsb && prev_lsb - lsb >= max_lsb / 2 { | ||
| 437 | + prev_msb + max_lsb | ||
| 438 | + } else if lsb > prev_lsb && lsb - prev_lsb > max_lsb / 2 { | ||
| 439 | + prev_msb - max_lsb | ||
| 440 | + } else { | ||
| 441 | + prev_msb | ||
| 442 | + }; | ||
| 443 | + let top = msb + lsb; | ||
| 444 | + let bottom = top + info.delta_pic_order_cnt_bottom; | ||
| 445 | + Ok(Poc { | ||
| 446 | + value: top.min(bottom), | ||
| 447 | + frame_num_offset: 0, | ||
| 448 | + msb, | ||
| 449 | + lsb, | ||
| 450 | + }) | ||
| 451 | + } | ||
| 452 | + 1 => { | ||
| 453 | + let max_frame_num = 1i32 << sps.log2_max_frame_num; | ||
| 454 | + let offset = self.frame_num_offset(info, max_frame_num); | ||
| 455 | + let cycle_len = sps.offsets_for_ref_frame.len() as i32; | ||
| 456 | + let mut abs_frame_num = if cycle_len != 0 { | ||
| 457 | + offset + info.frame_num as i32 | ||
| 458 | + } else { | ||
| 459 | + 0 | ||
| 460 | + }; | ||
| 461 | + if !info.is_reference && abs_frame_num > 0 { | ||
| 462 | + abs_frame_num -= 1; | ||
| 463 | + } | ||
| 464 | + let mut expected = 0i32; | ||
| 465 | + if abs_frame_num > 0 { | ||
| 466 | + let expected_delta: i32 = sps.offsets_for_ref_frame.iter().sum(); | ||
| 467 | + let cycle_cnt = (abs_frame_num - 1) / cycle_len; | ||
| 468 | + let in_cycle = (abs_frame_num - 1) % cycle_len; | ||
| 469 | + expected = cycle_cnt.wrapping_mul(expected_delta); | ||
| 470 | + for i in 0..=in_cycle as usize { | ||
| 471 | + expected = expected.wrapping_add(sps.offsets_for_ref_frame[i]); | ||
| 472 | + } | ||
| 473 | + } | ||
| 474 | + if !info.is_reference { | ||
| 475 | + expected = expected.wrapping_add(sps.offset_for_non_ref_pic); | ||
| 476 | + } | ||
| 477 | + let top = expected.wrapping_add(info.delta_pic_order_cnt[0]); | ||
| 478 | + let bottom = top | ||
| 479 | + .wrapping_add(sps.offset_for_top_to_bottom_field) | ||
| 480 | + .wrapping_add(info.delta_pic_order_cnt[1]); | ||
| 481 | + Ok(Poc { | ||
| 482 | + value: top.min(bottom), | ||
| 483 | + frame_num_offset: offset, | ||
| 484 | + msb: 0, | ||
| 485 | + lsb: 0, | ||
| 486 | + }) | ||
| 487 | + } | ||
| 488 | + 2 => { | ||
| 489 | + let max_frame_num = 1i32 << sps.log2_max_frame_num; | ||
| 490 | + let offset = self.frame_num_offset(info, max_frame_num); | ||
| 491 | + let poc = if info.is_idr { | ||
| 492 | + 0 | ||
| 493 | + } else if !info.is_reference { | ||
| 494 | + 2 * (offset + info.frame_num as i32) - 1 | ||
| 495 | + } else { | ||
| 496 | + 2 * (offset + info.frame_num as i32) | ||
| 497 | + }; | ||
| 498 | + Ok(Poc { | ||
| 499 | + value: poc, | ||
| 500 | + frame_num_offset: offset, | ||
| 501 | + msb: 0, | ||
| 502 | + lsb: 0, | ||
| 503 | + }) | ||
| 504 | + } | ||
| 505 | + other => Err(Error::corrupt(format!("pic_order_cnt_type {other}"))), | ||
| 506 | + } | ||
| 507 | + } | ||
| 508 | + | ||
| 509 | + /// `FrameNumOffset` (Equations 8-6 and 8-11). | ||
| 510 | + fn frame_num_offset(&self, info: &PicInfo, max_frame_num: i32) -> i32 { | ||
| 511 | + if info.is_idr { | ||
| 512 | + return 0; | ||
| 513 | + } | ||
| 514 | + let prev = if self.prev_has_mmco5 { | ||
| 515 | + 0 | ||
| 516 | + } else { | ||
| 517 | + self.prev_frame_num_offset | ||
| 518 | + }; | ||
| 519 | + if self.prev_frame_num > info.frame_num { | ||
| 520 | + prev + max_frame_num | ||
| 521 | + } else { | ||
| 522 | + prev | ||
| 523 | + } | ||
| 524 | + } | ||
| 525 | + | ||
| 526 | + /// True when `frame_num` skips values, i.e. pictures are missing | ||
| 527 | + /// (clause 8.2.5.2). Editor seeks and lossy transports both produce this; | ||
| 528 | + /// it is a normal condition, not a corrupt stream. | ||
| 529 | + pub(crate) fn frame_num_gap(&self, sps: &Sps, frame_num: u32) -> bool { | ||
| 530 | + let max = 1u32 << sps.log2_max_frame_num; | ||
| 531 | + self.started | ||
| 532 | + && frame_num != self.prev_ref_frame_num | ||
| 533 | + && frame_num != (self.prev_ref_frame_num + 1) % max | ||
| 534 | + } | ||
| 535 | + | ||
| 536 | + /// Insert the "non-existing" frames of clause 8.2.5.2 for a frame_num gap, | ||
| 537 | + /// so that reference numbering stays aligned with the encoder's and the | ||
| 538 | + /// pictures that follow decode instead of being dropped. | ||
| 539 | + pub(crate) fn fill_frame_num_gap(&mut self, sps: &Sps, frame_num: u32) -> Result<()> { | ||
| 540 | + let max = 1u32 << sps.log2_max_frame_num; | ||
| 541 | + let mut unused = (self.prev_ref_frame_num + 1) % max; | ||
| 542 | + // A gap can be as wide as MaxFrameNum; every inferred frame costs a | ||
| 543 | + // sliding-window step, so bound the work at the buffer size. | ||
| 544 | + let mut budget = MAX_STORED; | ||
| 545 | + while unused != frame_num && budget > 0 { | ||
| 546 | + budget -= 1; | ||
| 547 | + let mut pic = self.take_picture(); | ||
| 548 | + pic.start(sps); | ||
| 549 | + // The samples are unspecified; the last reference picture is a far | ||
| 550 | + // better guess than grey when a later picture wrongly predicts | ||
| 551 | + // from the gap. | ||
| 552 | + match self.frames.iter().max_by_key(|p| p.frame_num_wrap) { | ||
| 553 | + Some(src) if src.y.data.len() == pic.y.data.len() => pic.copy_samples_from(src), | ||
| 554 | + _ => pic.fill_grey(), | ||
| 555 | + } | ||
| 556 | + pic.non_existing = true; | ||
| 557 | + pic.frame_num = unused; | ||
| 558 | + pic.output = false; | ||
| 559 | + pic.complete = true; | ||
| 560 | + let info = PicInfo { | ||
| 561 | + is_idr: false, | ||
| 562 | + is_reference: true, | ||
| 563 | + frame_num: unused, | ||
| 564 | + pic_order_cnt_lsb: 0, | ||
| 565 | + delta_pic_order_cnt_bottom: 0, | ||
| 566 | + delta_pic_order_cnt: [0; 2], | ||
| 567 | + }; | ||
| 568 | + // 8.2.5.2: picture order count is only derived for a non-existing | ||
| 569 | + // frame when pic_order_cnt_type is not 0. Under type 0 the frame | ||
| 570 | + // has no output order, and 8.2.4.2.3 keeps it out of the B lists. | ||
| 571 | + let poc = if sps.pic_order_cnt_type == 0 { | ||
| 572 | + Poc::default() | ||
| 573 | + } else { | ||
| 574 | + self.picture_order_count(sps, &info)? | ||
| 575 | + }; | ||
| 576 | + pic.poc = poc.value; | ||
| 577 | + pic.frame_num_offset = poc.frame_num_offset; | ||
| 578 | + pic.mark = Mark::Short; | ||
| 579 | + self.number_short_term(unused, sps); | ||
| 580 | + self.sliding_window(sps)?; | ||
| 581 | + pic.frame_num_wrap = unused as i32; | ||
| 582 | + pic.pic_num = unused as i32; | ||
| 583 | + self.frames.push(pic); | ||
| 584 | + self.prev_frame_num = unused; | ||
| 585 | + self.prev_frame_num_offset = poc.frame_num_offset; | ||
| 586 | + self.prev_has_mmco5 = false; | ||
| 587 | + self.prev_ref_frame_num = unused; | ||
| 588 | + unused = (unused + 1) % max; | ||
| 589 | + } | ||
| 590 | + Ok(()) | ||
| 591 | + } | ||
| 592 | + | ||
| 593 | + /// Recompute `FrameNumWrap` and `PicNum` for every stored reference | ||
| 594 | + /// picture against the current `frame_num` (clause 8.2.4.1). | ||
| 595 | + pub(crate) fn number_short_term(&mut self, frame_num: u32, sps: &Sps) { | ||
| 596 | + let max_frame_num = 1i32 << sps.log2_max_frame_num; | ||
| 597 | + for pic in &mut self.frames { | ||
| 598 | + match pic.mark { | ||
| 599 | + Mark::Short => { | ||
| 600 | + pic.frame_num_wrap = if pic.frame_num > frame_num { | ||
| 601 | + pic.frame_num as i32 - max_frame_num | ||
| 602 | + } else { | ||
| 603 | + pic.frame_num as i32 | ||
| 604 | + }; | ||
| 605 | + pic.pic_num = pic.frame_num_wrap; | ||
| 606 | + } | ||
| 607 | + Mark::Long => pic.pic_num = pic.long_term_frame_idx as i32, | ||
| 608 | + Mark::Unused => {} | ||
| 609 | + } | ||
| 610 | + } | ||
| 611 | + } | ||
| 612 | + | ||
| 613 | + /// Build `RefPicList0` and `RefPicList1` for one slice: initialisation | ||
| 614 | + /// (8.2.4.2.1 / 8.2.4.2.3) followed by modification (8.2.4.3). | ||
| 615 | + pub(crate) fn build_ref_lists( | ||
| 616 | + &self, | ||
| 617 | + slice_type: SliceType, | ||
| 618 | + curr_poc: i32, | ||
| 619 | + curr_pic_num: i32, | ||
| 620 | + max_pic_num: i32, | ||
| 621 | + num_l0: usize, | ||
| 622 | + num_l1: usize, | ||
| 623 | + mods: (&[RefPicListMod], &[RefPicListMod]), | ||
| 624 | + ) -> Result<[RefList; 2]> { | ||
| 625 | + let mut lists = [RefList::default(), RefList::default()]; | ||
| 626 | + // Short-term candidates, then long-term, both by index into `frames`. | ||
| 627 | + let mut short: [usize; MAX_STORED] = [0; MAX_STORED]; | ||
| 628 | + let mut n_short = 0usize; | ||
| 629 | + let mut long: [usize; MAX_STORED] = [0; MAX_STORED]; | ||
| 630 | + let mut n_long = 0usize; | ||
| 631 | + for (i, pic) in self.frames.iter().enumerate() { | ||
| 632 | + // A frame inferred for a frame_num gap has no output order, so it | ||
| 633 | + // cannot take part in the POC ordering a B list is built from | ||
| 634 | + // (8.2.4.2.3); it stays a legal P reference by PicNum. | ||
| 635 | + if pic.non_existing && slice_type == SliceType::B { | ||
| 636 | + continue; | ||
| 637 | + } | ||
| 638 | + match pic.mark { | ||
| 639 | + Mark::Short if n_short < MAX_STORED => { | ||
| 640 | + short[n_short] = i; | ||
| 641 | + n_short += 1; | ||
| 642 | + } | ||
| 643 | + Mark::Long if n_long < MAX_STORED => { | ||
| 644 | + long[n_long] = i; | ||
| 645 | + n_long += 1; | ||
| 646 | + } | ||
| 647 | + _ => {} | ||
| 648 | + } | ||
| 649 | + } | ||
| 650 | + let long = &mut long[..n_long]; | ||
| 651 | + long.sort_unstable_by_key(|&i| self.frames[i].long_term_frame_idx); | ||
| 652 | + | ||
| 653 | + if slice_type == SliceType::B { | ||
| 654 | + let short = &mut short[..n_short]; | ||
| 655 | + // List 0: earlier pictures by descending POC, then later ascending. | ||
| 656 | + short.sort_unstable_by_key(|&i| { | ||
| 657 | + let poc = self.frames[i].poc; | ||
| 658 | + if poc < curr_poc { | ||
| 659 | + (0i32, -poc) | ||
| 660 | + } else { | ||
| 661 | + (1, poc) | ||
| 662 | + } | ||
| 663 | + }); | ||
| 664 | + for &i in short.iter() { | ||
| 665 | + lists[0].push(i); | ||
| 666 | + } | ||
| 667 | + for &i in long.iter() { | ||
| 668 | + lists[0].push(i); | ||
| 669 | + } | ||
| 670 | + // List 1: later pictures by ascending POC, then earlier descending. | ||
| 671 | + short.sort_unstable_by_key(|&i| { | ||
| 672 | + let poc = self.frames[i].poc; | ||
| 673 | + if poc > curr_poc { | ||
| 674 | + (0i32, poc) | ||
| 675 | + } else { | ||
| 676 | + (1, -poc) | ||
| 677 | + } | ||
| 678 | + }); | ||
| 679 | + for &i in short.iter() { | ||
| 680 | + lists[1].push(i); | ||
| 681 | + } | ||
| 682 | + for &i in long.iter() { | ||
| 683 | + lists[1].push(i); | ||
| 684 | + } | ||
| 685 | + // 8.2.4.2.3 step 3. | ||
| 686 | + if lists[1].len > 1 && lists[1].entries[..lists[1].len] == lists[0].entries[..lists[0].len] | ||
| 687 | + { | ||
| 688 | + lists[1].entries.swap(0, 1); | ||
| 689 | + } | ||
| 690 | + } else { | ||
| 691 | + let short = &mut short[..n_short]; | ||
| 692 | + short.sort_unstable_by_key(|&i| -self.frames[i].pic_num); | ||
| 693 | + for &i in short.iter() { | ||
| 694 | + lists[0].push(i); | ||
| 695 | + } | ||
| 696 | + for &i in long.iter() { | ||
| 697 | + lists[0].push(i); | ||
| 698 | + } | ||
| 699 | + } | ||
| 700 | + | ||
| 701 | + let wanted = [num_l0, num_l1]; | ||
| 702 | + let mods = [mods.0, mods.1]; | ||
| 703 | + for x in 0..2 { | ||
| 704 | + if x == 1 && slice_type != SliceType::B { | ||
| 705 | + lists[1].len = 0; | ||
| 706 | + continue; | ||
| 707 | + } | ||
| 708 | + if lists[x].len == 0 { | ||
| 709 | + return Err(Error::corrupt("inter slice with an empty reference list")); | ||
| 710 | + } | ||
| 711 | + // 8.2.4.2: the initial list is truncated to the active count. A | ||
| 712 | + // list shorter than that leaves the tail unspecified, and a | ||
| 713 | + // conformant stream fills it by modification; repeating entry 0 | ||
| 714 | + // keeps every index in range meanwhile. | ||
| 715 | + let first = lists[x].entries[0]; | ||
| 716 | + while lists[x].len < wanted[x] { | ||
| 717 | + lists[x].push(usize::from(first)); | ||
| 718 | + } | ||
| 719 | + lists[x].len = wanted[x]; | ||
| 720 | + self.modify_list(&mut lists[x], mods[x], curr_pic_num, max_pic_num); | ||
| 721 | + } | ||
| 722 | + Ok(lists) | ||
| 723 | + } | ||
| 724 | + | ||
| 725 | + /// Reference picture list modification (clause 8.2.4.3), following the | ||
| 726 | + /// insert-and-compact of Equations 8-37 and 8-38 with the one-longer | ||
| 727 | + /// temporary list those equations use. | ||
| 728 | + /// | ||
| 729 | + /// Comparing DPB indices stands in for `PicNumF`/`LongTermPicNumF`: a | ||
| 730 | + /// picture appears in the buffer once, and the sentinel those functions | ||
| 731 | + /// return for a wrongly marked picture can never equal the target. | ||
| 732 | + fn modify_list( | ||
| 733 | + &self, | ||
| 734 | + list: &mut RefList, | ||
| 735 | + mods: &[RefPicListMod], | ||
| 736 | + curr_pic_num: i32, | ||
| 737 | + max_pic_num: i32, | ||
| 738 | + ) { | ||
| 739 | + if mods.is_empty() { | ||
| 740 | + return; | ||
| 741 | + } | ||
| 742 | + let active = list.len; | ||
| 743 | + let mut tmp = [0u8; 34]; | ||
| 744 | + tmp[..active].copy_from_slice(&list.entries[..active]); | ||
| 745 | + let mut pred = curr_pic_num; | ||
| 746 | + let mut ref_idx = 0usize; | ||
| 747 | + for op in mods { | ||
| 748 | + let target = match *op { | ||
| 749 | + RefPicListMod::ShortTerm { | ||
| 750 | + abs_diff_pic_num_minus1, | ||
| 751 | + add, | ||
| 752 | + } => { | ||
| 753 | + let diff = abs_diff_pic_num_minus1 as i32 + 1; | ||
| 754 | + let no_wrap = if add { | ||
| 755 | + if pred + diff >= max_pic_num { | ||
| 756 | + pred + diff - max_pic_num | ||
| 757 | + } else { | ||
| 758 | + pred + diff | ||
| 759 | + } | ||
| 760 | + } else if pred - diff < 0 { | ||
| 761 | + pred - diff + max_pic_num | ||
| 762 | + } else { | ||
| 763 | + pred - diff | ||
| 764 | + }; | ||
| 765 | + pred = no_wrap; | ||
| 766 | + let pic_num = if no_wrap > curr_pic_num { | ||
| 767 | + no_wrap - max_pic_num | ||
| 768 | + } else { | ||
| 769 | + no_wrap | ||
| 770 | + }; | ||
| 771 | + self.frames | ||
| 772 | + .iter() | ||
| 773 | + .position(|p| p.mark == Mark::Short && p.pic_num == pic_num) | ||
| 774 | + } | ||
| 775 | + RefPicListMod::LongTerm(num) => self | ||
| 776 | + .frames | ||
| 777 | + .iter() | ||
| 778 | + .position(|p| p.mark == Mark::Long && p.pic_num == num as i32), | ||
| 779 | + }; | ||
| 780 | + // A modification naming a picture the buffer never received points | ||
| 781 | + // at something that was lost; keeping the initial entry decodes a | ||
| 782 | + // seek or a dropped packet instead of failing the slice. | ||
| 783 | + let Some(target) = target else { continue }; | ||
| 784 | + if ref_idx >= active { | ||
| 785 | + break; | ||
| 786 | + } | ||
| 787 | + for c in (ref_idx + 1..=active).rev() { | ||
| 788 | + tmp[c] = tmp[c - 1]; | ||
| 789 | + } | ||
| 790 | + tmp[ref_idx] = target as u8; | ||
| 791 | + ref_idx += 1; | ||
| 792 | + let mut n = ref_idx; | ||
| 793 | + for c in ref_idx..=active { | ||
| 794 | + if usize::from(tmp[c]) != target { | ||
| 795 | + tmp[n] = tmp[c]; | ||
| 796 | + n += 1; | ||
| 797 | + } | ||
| 798 | + } | ||
| 799 | + } | ||
| 800 | + list.entries[..active].copy_from_slice(&tmp[..active]); | ||
| 801 | + list.len = active; | ||
| 802 | + } | ||
| 803 | + | ||
| 804 | + /// Store a decoded picture and apply the reference marking of 8.2.5. | ||
| 805 | + pub(crate) fn store( | ||
| 806 | + &mut self, | ||
| 807 | + mut pic: Picture, | ||
| 808 | + sps: &Sps, | ||
| 809 | + info: &PicInfo, | ||
| 810 | + marking: Option<&DecRefPicMarking>, | ||
| 811 | + ) -> Result<()> { | ||
| 812 | + let has_mmco5 = marking.is_some_and(|m| m.mmcos.iter().any(|c| c.op == 5)); | ||
| 813 | + pic.output = true; | ||
| 814 | + pic.complete = true; | ||
| 815 | + | ||
| 816 | + if info.is_idr { | ||
| 817 | + let no_output = marking.is_some_and(|m| m.no_output_of_prior_pics); | ||
| 818 | + self.drain_prior(no_output); | ||
| 819 | + pic.mark = Mark::Short; | ||
| 820 | + if marking.is_some_and(|m| m.long_term_reference) { | ||
| 821 | + pic.mark = Mark::Long; | ||
| 822 | + pic.long_term_frame_idx = 0; | ||
| 823 | + self.max_long_term_idx = Some(0); | ||
| 824 | + } else { | ||
| 825 | + self.max_long_term_idx = None; | ||
| 826 | + } | ||
| 827 | + } else if info.is_reference { | ||
| 828 | + let m = marking.expect("a reference picture carries dec_ref_pic_marking"); | ||
| 829 | + pic.mark = Mark::Short; | ||
| 830 | + if m.adaptive { | ||
| 831 | + self.apply_mmco(&mut pic, m, info)?; | ||
| 832 | + } else { | ||
| 833 | + self.sliding_window(sps)?; | ||
| 834 | + } | ||
| 835 | + } | ||
| 836 | + | ||
| 837 | + if has_mmco5 { | ||
| 838 | + // 8.2.1: an MMCO 5 restarts frame_num and picture order count at | ||
| 839 | + // this picture, so everything before it must leave first. | ||
| 840 | + pic.poc = 0; | ||
| 841 | + pic.frame_num = 0; | ||
| 842 | + pic.frame_num_offset = 0; | ||
| 843 | + pic.poc_msb = 0; | ||
| 844 | + pic.poc_lsb = 0; | ||
| 845 | + } | ||
| 846 | + | ||
| 847 | + self.prev_frame_num = pic.frame_num; | ||
| 848 | + self.prev_frame_num_offset = pic.frame_num_offset; | ||
| 849 | + self.prev_has_mmco5 = has_mmco5; | ||
| 850 | + if info.is_reference { | ||
| 851 | + self.prev_ref_frame_num = pic.frame_num; | ||
| 852 | + self.prev_poc_msb = pic.poc_msb; | ||
| 853 | + self.prev_poc_lsb = pic.poc_lsb; | ||
| 854 | + } | ||
| 855 | + self.started = true; | ||
| 856 | + // An IDR or an MMCO 5 restarts picture order count, so POC no longer | ||
| 857 | + // orders across the boundary: everything already in the buffer belongs | ||
| 858 | + // ahead of this picture and has to leave first. | ||
| 859 | + if (info.is_idr || has_mmco5) && self.frames.iter().any(|p| p.output) { | ||
| 860 | + self.pending_flush = true; | ||
| 861 | + } | ||
| 862 | + self.last_id = pic.id; | ||
| 863 | + | ||
| 864 | + if self.frames.len() >= MAX_STORED { | ||
| 865 | + // Every stored picture is either a reference or waiting to be | ||
| 866 | + // output, and both limits were enforced above; a stream that still | ||
| 867 | + // overflows is not conformant. | ||
| 868 | + return Err(Error::corrupt("decoded picture buffer overflow")); | ||
| 869 | + } | ||
| 870 | + self.frames.push(pic); | ||
| 871 | + Ok(()) | ||
| 872 | + } | ||
| 873 | + | ||
| 874 | + /// Output and remove every stored picture (IDR boundary or MMCO 5). | ||
| 875 | + fn drain_prior(&mut self, discard: bool) { | ||
| 876 | + for pic in &mut self.frames { | ||
| 877 | + pic.mark = Mark::Unused; | ||
| 878 | + if discard { | ||
| 879 | + pic.output = false; | ||
| 880 | + } | ||
| 881 | + } | ||
| 882 | + } | ||
| 883 | + | ||
| 884 | + /// Sliding window marking (clause 8.2.5.3). | ||
| 885 | + fn sliding_window(&mut self, sps: &Sps) -> Result<()> { | ||
| 886 | + let max_refs = (sps.max_num_ref_frames as usize).max(1); | ||
| 887 | + loop { | ||
| 888 | + let n = self | ||
| 889 | + .frames | ||
| 890 | + .iter() | ||
| 891 | + .filter(|p| p.mark != Mark::Unused) | ||
| 892 | + .count(); | ||
| 893 | + if n < max_refs { | ||
| 894 | + return Ok(()); | ||
| 895 | + } | ||
| 896 | + let Some(oldest) = self | ||
| 897 | + .frames | ||
| 898 | + .iter_mut() | ||
| 899 | + .filter(|p| p.mark == Mark::Short) | ||
| 900 | + .min_by_key(|p| p.frame_num_wrap) | ||
| 901 | + else { | ||
| 902 | + // Only long-term references left and the window is full: the | ||
| 903 | + // stream must free one by MMCO, so refusing here would break a | ||
| 904 | + // conformant stream. Leave the buffer as is. | ||
| 905 | + return Ok(()); | ||
| 906 | + }; | ||
| 907 | + oldest.mark = Mark::Unused; | ||
| 908 | + } | ||
| 909 | + } | ||
| 910 | + | ||
| 911 | + /// Adaptive marking (clause 8.2.5.4). | ||
| 912 | + fn apply_mmco(&mut self, pic: &mut Picture, m: &DecRefPicMarking, info: &PicInfo) -> Result<()> { | ||
| 913 | + let curr_pic_num = info.frame_num as i32; | ||
| 914 | + for op in &m.mmcos { | ||
| 915 | + match op.op { | ||
| 916 | + 1 => { | ||
| 917 | + let target = curr_pic_num - (op.arg1 as i32 + 1); | ||
| 918 | + if let Some(p) = self | ||
| 919 | + .frames | ||
| 920 | + .iter_mut() | ||
| 921 | + .find(|p| p.mark == Mark::Short && p.pic_num == target) | ||
| 922 | + { | ||
| 923 | + p.mark = Mark::Unused; | ||
| 924 | + } | ||
| 925 | + } | ||
| 926 | + 2 => { | ||
| 927 | + if let Some(p) = self | ||
| 928 | + .frames | ||
| 929 | + .iter_mut() | ||
| 930 | + .find(|p| p.mark == Mark::Long && p.pic_num == op.arg1 as i32) | ||
| 931 | + { | ||
| 932 | + p.mark = Mark::Unused; | ||
| 933 | + } | ||
| 934 | + } | ||
| 935 | + 3 => { | ||
| 936 | + let target = curr_pic_num - (op.arg1 as i32 + 1); | ||
| 937 | + let idx = op.arg2; | ||
| 938 | + for p in &mut self.frames { | ||
| 939 | + if p.mark == Mark::Long && p.long_term_frame_idx == idx { | ||
| 940 | + p.mark = Mark::Unused; | ||
| 941 | + } | ||
| 942 | + } | ||
| 943 | + if let Some(p) = self | ||
| 944 | + .frames | ||
| 945 | + .iter_mut() | ||
| 946 | + .find(|p| p.mark == Mark::Short && p.pic_num == target) | ||
| 947 | + { | ||
| 948 | + p.mark = Mark::Long; | ||
| 949 | + p.long_term_frame_idx = idx; | ||
| 950 | + p.pic_num = idx as i32; | ||
| 951 | + } | ||
| 952 | + } | ||
| 953 | + 4 => { | ||
| 954 | + self.max_long_term_idx = op.arg1.checked_sub(1); | ||
| 955 | + let limit = self.max_long_term_idx; | ||
| 956 | + for p in &mut self.frames { | ||
| 957 | + if p.mark == Mark::Long | ||
| 958 | + && limit.is_none_or(|max| p.long_term_frame_idx > max) | ||
| 959 | + { | ||
| 960 | + p.mark = Mark::Unused; | ||
| 961 | + } | ||
| 962 | + } | ||
| 963 | + } | ||
| 964 | + 5 => { | ||
| 965 | + for p in &mut self.frames { | ||
| 966 | + p.mark = Mark::Unused; | ||
| 967 | + } | ||
| 968 | + self.max_long_term_idx = None; | ||
| 969 | + } | ||
| 970 | + 6 => { | ||
| 971 | + let idx = op.arg1; | ||
| 972 | + for p in &mut self.frames { | ||
| 973 | + if p.mark == Mark::Long && p.long_term_frame_idx == idx { | ||
| 974 | + p.mark = Mark::Unused; | ||
| 975 | + } | ||
| 976 | + } | ||
| 977 | + pic.mark = Mark::Long; | ||
| 978 | + pic.long_term_frame_idx = idx; | ||
| 979 | + pic.pic_num = idx as i32; | ||
| 980 | + } | ||
| 981 | + other => { | ||
| 982 | + return Err(Error::corrupt(format!( | ||
| 983 | + "memory_management_control_operation {other}" | ||
| 984 | + ))); | ||
| 985 | + } | ||
| 986 | + } | ||
| 987 | + } | ||
| 988 | + Ok(()) | ||
| 989 | + } | ||
| 990 | + | ||
| 991 | + /// The next picture to output, or `None` while the buffer is still within | ||
| 992 | + /// its reordering and storage limits (the bumping process of C.4.5.3). | ||
| 993 | + /// | ||
| 994 | + /// `flush` empties the buffer, which is what end of stream and a seek do. | ||
| 995 | + pub(crate) fn next_output(&mut self, flush: bool) -> Option<usize> { | ||
| 996 | + if self.pending_flush { | ||
| 997 | + let last = self.last_id; | ||
| 998 | + let best = self | ||
| 999 | + .frames | ||
| 1000 | + .iter() | ||
| 1001 | + .enumerate() | ||
| 1002 | + .filter(|(_, p)| p.output && p.id != last) | ||
| 1003 | + .min_by_key(|(_, p)| p.poc) | ||
| 1004 | + .map(|(i, _)| i); | ||
| 1005 | + if best.is_some() { | ||
| 1006 | + return best; | ||
| 1007 | + } | ||
| 1008 | + self.pending_flush = false; | ||
| 1009 | + } | ||
| 1010 | + let pending = self.frames.iter().filter(|p| p.output).count(); | ||
| 1011 | + let stored = self.frames.iter().filter(|p| p.stored()).count(); | ||
| 1012 | + if !flush && pending <= self.max_reorder && stored <= self.max_frames { | ||
| 1013 | + return None; | ||
| 1014 | + } | ||
| 1015 | + let mut best: Option<usize> = None; | ||
| 1016 | + for (i, pic) in self.frames.iter().enumerate() { | ||
| 1017 | + if !pic.output { | ||
| 1018 | + continue; | ||
| 1019 | + } | ||
| 1020 | + if best.is_none_or(|b| pic.poc < self.frames[b].poc) { | ||
| 1021 | + best = Some(i); | ||
| 1022 | + } | ||
| 1023 | + } | ||
| 1024 | + best | ||
| 1025 | + } | ||
| 1026 | + | ||
| 1027 | + /// Mark picture `idx` as output and reclaim every slot that is now free. | ||
| 1028 | + pub(crate) fn released(&mut self, idx: usize) { | ||
| 1029 | + self.frames[idx].output = false; | ||
| 1030 | + let mut i = 0; | ||
| 1031 | + while i < self.frames.len() { | ||
| 1032 | + if self.frames[i].stored() { | ||
| 1033 | + i += 1; | ||
| 1034 | + continue; | ||
| 1035 | + } | ||
| 1036 | + let pic = self.frames.swap_remove(i); | ||
| 1037 | + self.recycle(pic); | ||
| 1038 | + } | ||
| 1039 | + } | ||
| 1040 | +} | ||
| 1041 | + | ||
| 1042 | +/// `MaxDpbFrames` from the level limits of Table A-1, the buffer size a stream | ||
| 1043 | +/// is allowed to assume when its VUI does not state one. | ||
| 1044 | +fn max_dpb_frames(sps: &Sps) -> usize { | ||
| 1045 | + let max_dpb_mbs = match sps.level_idc { | ||
| 1046 | + 0..=10 => 396, | ||
| 1047 | + 11 => { | ||
| 1048 | + // constraint_set3_flag distinguishes level 1b from level 1.1; both | ||
| 1049 | + // have the same MaxDpbMbs, so the flag does not change the answer. | ||
| 1050 | + 396 | ||
| 1051 | + } | ||
| 1052 | + 12..=20 => 2376, | ||
| 1053 | + 21 => 4752, | ||
| 1054 | + 22..=30 => 8100, | ||
| 1055 | + 31 => 18000, | ||
| 1056 | + 32 => 20480, | ||
| 1057 | + 33..=41 => 32768, | ||
| 1058 | + 42 => 34816, | ||
| 1059 | + 50 => 110400, | ||
| 1060 | + 51..=52 => 184320, | ||
| 1061 | + _ => 696320, | ||
| 1062 | + }; | ||
| 1063 | + let per_frame = (sps.mb_width as usize * sps.mb_height as usize).max(1); | ||
| 1064 | + (max_dpb_mbs / per_frame).clamp(1, 16) | ||
| 1065 | +} | ||
| 1066 | + | ||
| 1067 | +#[cfg(test)] | ||
| 1068 | +mod tests { | ||
| 1069 | + use super::*; | ||
| 1070 | + | ||
| 1071 | + fn plane(w: usize, h: usize) -> Plane8 { | ||
| 1072 | + let mut p = Plane8::default(); | ||
| 1073 | + p.resize(w, h, 4); | ||
| 1074 | + for y in 0..h { | ||
| 1075 | + for x in 0..w { | ||
| 1076 | + let at = p.at(x, y); | ||
| 1077 | + p.data[at] = (x + y * 10) as u8; | ||
| 1078 | + } | ||
| 1079 | + } | ||
| 1080 | + p | ||
| 1081 | + } | ||
| 1082 | + | ||
| 1083 | + /// Border replication makes an out-of-picture read equal the clipped | ||
| 1084 | + /// in-picture read, which is what [`crate::inter`] relies on. | ||
| 1085 | + #[test] | ||
| 1086 | + fn extend_borders_replicates_edges() { | ||
| 1087 | + let mut p = plane(6, 5); | ||
| 1088 | + p.extend_borders(); | ||
| 1089 | + let at = |x: i32, y: i32| -> u8 { | ||
| 1090 | + p.data[(p.origin as i32 + y * p.stride as i32 + x) as usize] | ||
| 1091 | + }; | ||
| 1092 | + for y in -4..9i32 { | ||
| 1093 | + for x in -4..10i32 { | ||
| 1094 | + let cx = x.clamp(0, 5) as usize; | ||
| 1095 | + let cy = y.clamp(0, 4) as usize; | ||
| 1096 | + assert_eq!(at(x, y), p.data[p.at(cx, cy)], "({x}, {y})"); | ||
| 1097 | + } | ||
| 1098 | + } | ||
| 1099 | + } | ||
| 1100 | + | ||
| 1101 | + fn sps_for(poc_type: u8) -> Sps { | ||
| 1102 | + use ec_core::BitWriter; | ||
| 1103 | + let mut w = BitWriter::new(); | ||
| 1104 | + w.write_bits(66, 8); | ||
| 1105 | + w.write_bits(0, 8); | ||
| 1106 | + w.write_bits(30, 8); | ||
| 1107 | + w.write_ue(0); // sps id | ||
| 1108 | + w.write_ue(4); // log2_max_frame_num_minus4 -> 8 | ||
| 1109 | + w.write_ue(u32::from(poc_type)); | ||
| 1110 | + match poc_type { | ||
| 1111 | + 0 => w.write_ue(4), // log2_max_pic_order_cnt_lsb_minus4 -> 8 | ||
| 1112 | + 1 => { | ||
| 1113 | + w.write_bit(false); // delta_pic_order_always_zero | ||
| 1114 | + w.write_se(0); | ||
| 1115 | + w.write_se(0); | ||
| 1116 | + w.write_ue(1); // one offset_for_ref_frame | ||
| 1117 | + w.write_se(2); | ||
| 1118 | + } | ||
| 1119 | + _ => {} | ||
| 1120 | + } | ||
| 1121 | + w.write_ue(2); // max_num_ref_frames | ||
| 1122 | + w.write_bit(false); | ||
| 1123 | + w.write_ue(10); | ||
| 1124 | + w.write_ue(8); | ||
| 1125 | + w.write_bit(true); // frame_mbs_only | ||
| 1126 | + w.write_bit(true); // direct_8x8_inference | ||
| 1127 | + w.write_bit(false); // no cropping | ||
| 1128 | + w.write_bit(false); // no vui | ||
| 1129 | + w.align_to_byte(); | ||
| 1130 | + Sps::parse(w.as_bytes()).unwrap() | ||
| 1131 | + } | ||
| 1132 | + | ||
| 1133 | + fn info(frame_num: u32, lsb: u32, is_ref: bool, is_idr: bool) -> PicInfo { | ||
| 1134 | + PicInfo { | ||
| 1135 | + is_idr, | ||
| 1136 | + is_reference: is_ref, | ||
| 1137 | + frame_num, | ||
| 1138 | + pic_order_cnt_lsb: lsb, | ||
| 1139 | + delta_pic_order_cnt_bottom: 0, | ||
| 1140 | + delta_pic_order_cnt: [0; 2], | ||
| 1141 | + } | ||
| 1142 | + } | ||
| 1143 | + | ||
| 1144 | + /// Picture order count type 0 wraps when pic_order_cnt_lsb rolls over. | ||
| 1145 | + #[test] | ||
| 1146 | + fn poc_type_0_tracks_the_msb_across_a_wrap() { | ||
| 1147 | + let sps = sps_for(0); | ||
| 1148 | + let mut dpb = Dpb::default(); | ||
| 1149 | + let mut expect = |i: PicInfo, want: i32| { | ||
| 1150 | + let poc = dpb.picture_order_count(&sps, &i).unwrap(); | ||
| 1151 | + assert_eq!(poc.value, want, "{i:?}"); | ||
| 1152 | + // Emulate the reference-picture bookkeeping of `store`. | ||
| 1153 | + if i.is_reference { | ||
| 1154 | + dpb.prev_poc_msb = poc.msb; | ||
| 1155 | + dpb.prev_poc_lsb = poc.lsb; | ||
| 1156 | + } | ||
| 1157 | + }; | ||
| 1158 | + expect(info(0, 0, true, true), 0); | ||
| 1159 | + expect(info(1, 100, true, false), 100); | ||
| 1160 | + expect(info(2, 200, true, false), 200); | ||
| 1161 | + // 200 -> 40 is more than half of MaxPicOrderCntLsb backwards, so it is | ||
| 1162 | + // read as a wrap forward rather than a jump back. | ||
| 1163 | + expect(info(3, 40, true, false), 296); | ||
| 1164 | + // A genuine step back stays a step back. | ||
| 1165 | + expect(info(4, 100, true, false), 356); | ||
| 1166 | + } | ||
| 1167 | + | ||
| 1168 | + /// Type 2 counts pictures in decode order, so a non-reference picture sits | ||
| 1169 | + /// just before the reference picture that follows it. | ||
| 1170 | + #[test] | ||
| 1171 | + fn poc_type_2_is_twice_the_frame_number() { | ||
| 1172 | + let sps = sps_for(2); | ||
| 1173 | + let dpb = Dpb::default(); | ||
| 1174 | + assert_eq!(dpb.picture_order_count(&sps, &info(0, 0, true, true)).unwrap().value, 0); | ||
| 1175 | + assert_eq!(dpb.picture_order_count(&sps, &info(3, 0, true, false)).unwrap().value, 6); | ||
| 1176 | + assert_eq!(dpb.picture_order_count(&sps, &info(3, 0, false, false)).unwrap().value, 5); | ||
| 1177 | + } | ||
| 1178 | + | ||
| 1179 | + /// Type 1 walks the offset_for_ref_frame cycle. | ||
| 1180 | + #[test] | ||
| 1181 | + fn poc_type_1_follows_the_offset_cycle() { | ||
| 1182 | + let sps = sps_for(1); | ||
| 1183 | + let dpb = Dpb::default(); | ||
| 1184 | + // One-entry cycle of +2: frame n has expectedPicOrderCnt 2n. | ||
| 1185 | + assert_eq!(dpb.picture_order_count(&sps, &info(0, 0, true, true)).unwrap().value, 0); | ||
| 1186 | + assert_eq!(dpb.picture_order_count(&sps, &info(1, 0, true, false)).unwrap().value, 2); | ||
| 1187 | + assert_eq!(dpb.picture_order_count(&sps, &info(4, 0, true, false)).unwrap().value, 8); | ||
| 1188 | + } | ||
| 1189 | + | ||
| 1190 | + fn push_ref(dpb: &mut Dpb, frame_num: u32, poc: i32, mark: Mark) { | ||
| 1191 | + let mut pic = dpb.take_picture(); | ||
| 1192 | + pic.frame_num = frame_num; | ||
| 1193 | + pic.frame_num_wrap = frame_num as i32; | ||
| 1194 | + pic.pic_num = frame_num as i32; | ||
| 1195 | + pic.poc = poc; | ||
| 1196 | + pic.mark = mark; | ||
| 1197 | + dpb.frames.push(pic); | ||
| 1198 | + } | ||
| 1199 | + | ||
| 1200 | + /// P list 0 is short-term by descending PicNum then long-term ascending. | ||
| 1201 | + #[test] | ||
| 1202 | + fn p_list_initialisation_orders_by_pic_num() { | ||
| 1203 | + let mut dpb = Dpb::default(); | ||
| 1204 | + push_ref(&mut dpb, 2, 4, Mark::Short); | ||
| 1205 | + push_ref(&mut dpb, 5, 10, Mark::Short); | ||
| 1206 | + push_ref(&mut dpb, 3, 6, Mark::Short); | ||
| 1207 | + let mut lt = dpb.take_picture(); | ||
| 1208 | + lt.mark = Mark::Long; | ||
| 1209 | + lt.long_term_frame_idx = 1; | ||
| 1210 | + lt.pic_num = 1; | ||
| 1211 | + dpb.frames.push(lt); | ||
| 1212 | + let lists = dpb | ||
| 1213 | + .build_ref_lists(SliceType::P, 12, 6, 256, 4, 0, (&[], &[])) | ||
| 1214 | + .unwrap(); | ||
| 1215 | + let nums: Vec<i32> = (0..lists[0].len()) | ||
| 1216 | + .map(|i| dpb.frames[lists[0].get(i).unwrap()].pic_num) | ||
| 1217 | + .collect(); | ||
| 1218 | + assert_eq!(nums, vec![5, 3, 2, 1]); | ||
| 1219 | + } | ||
| 1220 | + | ||
| 1221 | + /// B lists split around the current POC and mirror each other. | ||
| 1222 | + #[test] | ||
| 1223 | + fn b_list_initialisation_splits_around_the_current_poc() { | ||
| 1224 | + let mut dpb = Dpb::default(); | ||
| 1225 | + push_ref(&mut dpb, 0, 0, Mark::Short); | ||
| 1226 | + push_ref(&mut dpb, 1, 8, Mark::Short); | ||
| 1227 | + push_ref(&mut dpb, 2, 4, Mark::Short); | ||
| 1228 | + push_ref(&mut dpb, 3, 12, Mark::Short); | ||
| 1229 | + let lists = dpb | ||
| 1230 | + .build_ref_lists(SliceType::B, 6, 4, 256, 4, 4, (&[], &[])) | ||
| 1231 | + .unwrap(); | ||
| 1232 | + let poc = |l: &RefList| -> Vec<i32> { | ||
| 1233 | + (0..l.len()).map(|i| dpb.frames[l.get(i).unwrap()].poc).collect() | ||
| 1234 | + }; | ||
| 1235 | + assert_eq!(poc(&lists[0]), vec![4, 0, 8, 12]); | ||
| 1236 | + assert_eq!(poc(&lists[1]), vec![8, 12, 4, 0]); | ||
| 1237 | + } | ||
| 1238 | + | ||
| 1239 | + /// A single-entry list identical in both directions gets its first two | ||
| 1240 | + /// entries swapped (8.2.4.2.3 step 3 only fires above one entry). | ||
| 1241 | + #[test] | ||
| 1242 | + fn identical_b_lists_swap_the_first_two_entries() { | ||
| 1243 | + let mut dpb = Dpb::default(); | ||
| 1244 | + push_ref(&mut dpb, 0, 0, Mark::Short); | ||
| 1245 | + push_ref(&mut dpb, 1, 2, Mark::Short); | ||
| 1246 | + // Both references precede the current picture, so initialisation gives | ||
| 1247 | + // list 0 and list 1 the same descending-POC order. | ||
| 1248 | + let lists = dpb | ||
| 1249 | + .build_ref_lists(SliceType::B, 10, 2, 256, 2, 2, (&[], &[])) | ||
| 1250 | + .unwrap(); | ||
| 1251 | + let l0: Vec<i32> = (0..2).map(|i| dpb.frames[lists[0].get(i).unwrap()].poc).collect(); | ||
| 1252 | + let l1: Vec<i32> = (0..2).map(|i| dpb.frames[lists[1].get(i).unwrap()].poc).collect(); | ||
| 1253 | + assert_eq!(l0, vec![2, 0]); | ||
| 1254 | + assert_eq!(l1, vec![0, 2], "identical lists swap"); | ||
| 1255 | + } | ||
| 1256 | + | ||
| 1257 | + /// A short-term modification moves the named picture to the front. | ||
| 1258 | + #[test] | ||
| 1259 | + fn short_term_modification_reorders_the_list() { | ||
| 1260 | + let mut dpb = Dpb::default(); | ||
| 1261 | + push_ref(&mut dpb, 5, 10, Mark::Short); | ||
| 1262 | + push_ref(&mut dpb, 4, 8, Mark::Short); | ||
| 1263 | + push_ref(&mut dpb, 3, 6, Mark::Short); | ||
| 1264 | + // CurrPicNum 6, abs_diff 3 -> picNum 3, which is the last entry. | ||
| 1265 | + let mods = [RefPicListMod::ShortTerm { | ||
| 1266 | + abs_diff_pic_num_minus1: 2, | ||
| 1267 | + add: false, | ||
| 1268 | + }]; | ||
| 1269 | + let lists = dpb | ||
| 1270 | + .build_ref_lists(SliceType::P, 12, 6, 256, 3, 0, (&mods, &[])) | ||
| 1271 | + .unwrap(); | ||
| 1272 | + let nums: Vec<i32> = (0..3) | ||
| 1273 | + .map(|i| dpb.frames[lists[0].get(i).unwrap()].pic_num) | ||
| 1274 | + .collect(); | ||
| 1275 | + assert_eq!(nums, vec![3, 5, 4]); | ||
| 1276 | + } | ||
| 1277 | +} | ||
crates/ec-h264/src/entropy.rsmodified+137 -3
| @@ -20,7 +20,7 @@ use ec_core::error::{Error, Result}; | |||
| 20 | 20 | ||
| 21 | use crate::bits::BitCursor; | 21 | use crate::bits::BitCursor; |
| 22 | use crate::cabac::Cabac; | 22 | use crate::cabac::Cabac; |
| 23 | -use crate::tables::CBP_INTRA_420; | 23 | +use crate::tables::{CBP_INTER_420, CBP_INTRA_420}; |
| 24 | 24 | ||
| 25 | /// Macroblock state bits (`Picture::mb_flags`, and `MbInfo::flags` for a | 25 | /// Macroblock state bits (`Picture::mb_flags`, and `MbInfo::flags` for a |
| 26 | /// neighbour). CABAC context selection reads all of them. | 26 | /// neighbour). CABAC context selection reads all of them. |
| @@ -32,6 +32,12 @@ pub(crate) const FLAG_PCM: u8 = 2; | |||
| 32 | pub(crate) const FLAG_I16: u8 = 4; | 32 | pub(crate) const FLAG_I16: u8 = 4; |
| 33 | /// intra_chroma_pred_mode is not 0 (DC). | 33 | /// intra_chroma_pred_mode is not 0 (DC). |
| 34 | pub(crate) const FLAG_CHROMA_PRED: u8 = 8; | 34 | pub(crate) const FLAG_CHROMA_PRED: u8 = 8; |
| 35 | +/// The macroblock is inter coded. | ||
| 36 | +pub(crate) const FLAG_INTER: u8 = 16; | ||
| 37 | +/// mb_type is B_Skip or B_Direct_16x16 (9.3.3.1.1.3 at ctxIdxOffset 27). | ||
| 38 | +pub(crate) const FLAG_DIRECT: u8 = 32; | ||
| 39 | +/// mb_type is P_Skip or B_Skip (9.3.3.1.1.1). | ||
| 40 | +pub(crate) const FLAG_SKIP: u8 = 64; | ||
| 35 | 41 | ||
| 36 | /// Residual block class (spec Table 9-42, the 4:2:0 subset this decoder codes). | 42 | /// Residual block class (spec Table 9-42, the 4:2:0 subset this decoder codes). |
| 37 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] | 43 | #[derive(Clone, Copy, PartialEq, Eq, Debug)] |
| @@ -113,8 +119,136 @@ impl<'a> Entropy<'a> { | |||
| 113 | 119 | ||
| 114 | /// A CABAC reader: consumes the `cabac_alignment_one_bit`s and initialises | 120 | /// A CABAC reader: consumes the `cabac_alignment_one_bit`s and initialises |
| 115 | /// the context variables and the arithmetic decoding engine (clause 9.3.1). | 121 | /// the context variables and the arithmetic decoding engine (clause 9.3.1). |
| 116 | - pub(crate) fn cabac(rbsp: &'a [u8], header_bits: u64, slice_qp: i32) -> Result<Entropy<'a>> { | 122 | + /// `init_column` is 0 for I and SI slices, `cabac_init_idc + 1` otherwise. |
| 117 | - Ok(Entropy::Cabac(Cabac::new(rbsp, header_bits, slice_qp)?)) | 123 | + pub(crate) fn cabac( |
| 124 | + rbsp: &'a [u8], | ||
| 125 | + header_bits: u64, | ||
| 126 | + slice_qp: i32, | ||
| 127 | + init_column: usize, | ||
| 128 | + ) -> Result<Entropy<'a>> { | ||
| 129 | + Ok(Entropy::Cabac(Cabac::new( | ||
| 130 | + rbsp, | ||
| 131 | + header_bits, | ||
| 132 | + slice_qp, | ||
| 133 | + init_column, | ||
| 134 | + )?)) | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + /// True for the CABAC variant. | ||
| 138 | + #[inline] | ||
| 139 | + pub(crate) fn is_cabac(&self) -> bool { | ||
| 140 | + matches!(self, Entropy::Cabac(_)) | ||
| 141 | + } | ||
| 142 | + | ||
| 143 | + /// Declare whether the macroblock being parsed is intra coded, which | ||
| 144 | + /// CABAC needs for the coded_block_flag contexts of 9.3.3.1.1.9. | ||
| 145 | + #[inline] | ||
| 146 | + pub(crate) fn set_intra(&mut self, intra: bool) { | ||
| 147 | + if let Entropy::Cabac(c) = self { | ||
| 148 | + c.set_intra(intra); | ||
| 149 | + } | ||
| 150 | + } | ||
| 151 | + | ||
| 152 | + /// `mb_skip_run` (7.3.4), CAVLC only. | ||
| 153 | + pub(crate) fn mb_skip_run(&mut self) -> Result<u32> { | ||
| 154 | + match self { | ||
| 155 | + Entropy::Cavlc(r) => r.read_ue(), | ||
| 156 | + Entropy::Cabac(_) => Err(Error::corrupt("mb_skip_run in a CABAC slice")), | ||
| 157 | + } | ||
| 158 | + } | ||
| 159 | + | ||
| 160 | + /// `mb_skip_flag` (7.3.4), CABAC only; `inc` is condTermFlagA + | ||
| 161 | + /// condTermFlagB per 9.3.3.1.1.1. | ||
| 162 | + pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> Result<bool> { | ||
| 163 | + match self { | ||
| 164 | + Entropy::Cavlc(_) => Err(Error::corrupt("mb_skip_flag in a CAVLC slice")), | ||
| 165 | + Entropy::Cabac(c) => Ok(c.mb_skip_flag(b_slice, inc)), | ||
| 166 | + } | ||
| 167 | + } | ||
| 168 | + | ||
| 169 | + /// `mb_type` of a P or SP slice: 0..4, or 5 + the I-slice mb_type. | ||
| 170 | + pub(crate) fn mb_type_p(&mut self) -> Result<u32> { | ||
| 171 | + match self { | ||
| 172 | + Entropy::Cavlc(r) => { | ||
| 173 | + let t = r.read_ue()?; | ||
| 174 | + if t > 30 { | ||
| 175 | + return Err(Error::corrupt("P-slice mb_type > 30")); | ||
| 176 | + } | ||
| 177 | + Ok(t) | ||
| 178 | + } | ||
| 179 | + Entropy::Cabac(c) => c.mb_type_p(), | ||
| 180 | + } | ||
| 181 | + } | ||
| 182 | + | ||
| 183 | + /// `mb_type` of a B slice: 0..22, or 23 + the I-slice mb_type. | ||
| 184 | + pub(crate) fn mb_type_b(&mut self) -> Result<u32> { | ||
| 185 | + match self { | ||
| 186 | + Entropy::Cavlc(r) => { | ||
| 187 | + let t = r.read_ue()?; | ||
| 188 | + if t > 48 { | ||
| 189 | + return Err(Error::corrupt("B-slice mb_type > 48")); | ||
| 190 | + } | ||
| 191 | + Ok(t) | ||
| 192 | + } | ||
| 193 | + Entropy::Cabac(c) => c.mb_type_b(), | ||
| 194 | + } | ||
| 195 | + } | ||
| 196 | + | ||
| 197 | + /// `sub_mb_type[ ]` of a P (`b_slice` false) or B macroblock. | ||
| 198 | + pub(crate) fn sub_mb_type(&mut self, b_slice: bool) -> Result<u32> { | ||
| 199 | + let max = if b_slice { 12 } else { 3 }; | ||
| 200 | + match self { | ||
| 201 | + Entropy::Cavlc(r) => { | ||
| 202 | + let t = r.read_ue()?; | ||
| 203 | + if t > max { | ||
| 204 | + return Err(Error::corrupt("sub_mb_type out of range")); | ||
| 205 | + } | ||
| 206 | + Ok(t) | ||
| 207 | + } | ||
| 208 | + Entropy::Cabac(c) => Ok(if b_slice { | ||
| 209 | + c.sub_mb_type_b() | ||
| 210 | + } else { | ||
| 211 | + c.sub_mb_type_p() | ||
| 212 | + }), | ||
| 213 | + } | ||
| 214 | + } | ||
| 215 | + | ||
| 216 | + /// `ref_idx_lX` (7.3.5.1): te(v) over `0..=cmax` for CAVLC, unary with the | ||
| 217 | + /// neighbour context of 9.3.3.1.1.6 for CABAC. | ||
| 218 | + pub(crate) fn ref_idx(&mut self, cmax: u32, inc: usize) -> Result<u32> { | ||
| 219 | + let v = match self { | ||
| 220 | + // te(v), clause 9.1.1: a one-valued range is a single inverted bit. | ||
| 221 | + Entropy::Cavlc(r) if cmax == 1 => u32::from(!r.read_bit()?), | ||
| 222 | + Entropy::Cavlc(r) => r.read_ue()?, | ||
| 223 | + Entropy::Cabac(c) => c.ref_idx(inc)?, | ||
| 224 | + }; | ||
| 225 | + if v > cmax { | ||
| 226 | + return Err(Error::corrupt("ref_idx beyond num_ref_idx_active")); | ||
| 227 | + } | ||
| 228 | + Ok(v) | ||
| 229 | + } | ||
| 230 | + | ||
| 231 | + /// One `mvd_lX` component (7.3.5.1), in quarter luma samples. | ||
| 232 | + pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> { | ||
| 233 | + match self { | ||
| 234 | + Entropy::Cavlc(r) => r.read_se(), | ||
| 235 | + Entropy::Cabac(c) => c.mvd(comp, inc), | ||
| 236 | + } | ||
| 237 | + } | ||
| 238 | + | ||
| 239 | + /// `coded_block_pattern` of an inter macroblock, as | ||
| 240 | + /// `(CodedBlockPatternLuma, CodedBlockPatternChroma)`. | ||
| 241 | + pub(crate) fn coded_block_pattern_inter(&mut self) -> Result<(u8, u8)> { | ||
| 242 | + match self { | ||
| 243 | + Entropy::Cavlc(r) => { | ||
| 244 | + let code = r.read_ue()? as usize; | ||
| 245 | + let cbp = *CBP_INTER_420 | ||
| 246 | + .get(code) | ||
| 247 | + .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 47"))?; | ||
| 248 | + Ok((cbp & 15, cbp >> 4)) | ||
| 249 | + } | ||
| 250 | + Entropy::Cabac(c) => c.coded_block_pattern(), | ||
| 251 | + } | ||
| 118 | } | 252 | } |
| 119 | 253 | ||
| 120 | /// Publish the neighbourhood of the macroblock about to be parsed. | 254 | /// Publish the neighbourhood of the macroblock about to be parsed. |
crates/ec-h264/src/inter.rsadded+483 -0
| @@ -0,0 +1,483 @@ | |||
| 1 | +//! Inter prediction sample construction (spec 8.4.2): the quarter-sample luma | ||
| 2 | +//! interpolation of 8.4.2.2.1, the eighth-sample chroma interpolation of | ||
| 3 | +//! 8.4.2.2.2 and the weighted combination of 8.4.2.3. | ||
| 4 | +//! | ||
| 5 | +//! Reference planes are the same padded [`crate::decoder::Plane8`] the decoder | ||
| 6 | +//! writes into, with the borders replicated once per picture | ||
| 7 | +//! (`Plane8::extend_borders`). That turns the per-sample `Clip3` of Equations | ||
| 8 | +//! 8-239 and 8-240 into a single clamp of the block origin: any position the | ||
| 9 | +//! spec would clip to an edge sample lands on the replicated copy of that same | ||
| 10 | +//! edge sample, so the interpolation loop never bounds-checks and never | ||
| 11 | +//! branches per sample. The clamp bounds below are what makes that exact — | ||
| 12 | +//! see [`clamp_origin`]. | ||
| 13 | + | ||
| 14 | +/// A reference picture plane for motion compensation. | ||
| 15 | +pub(crate) struct RefPlane<'a> { | ||
| 16 | + /// The whole padded plane. | ||
| 17 | + pub data: &'a [u8], | ||
| 18 | + /// Row pitch. | ||
| 19 | + pub stride: usize, | ||
| 20 | + /// Index of picture sample (0, 0). | ||
| 21 | + pub origin: usize, | ||
| 22 | + /// Picture width in samples. | ||
| 23 | + pub width: usize, | ||
| 24 | + /// Picture height in samples. | ||
| 25 | + pub height: usize, | ||
| 26 | + /// Replicated border width on every side. | ||
| 27 | + pub pad: usize, | ||
| 28 | +} | ||
| 29 | + | ||
| 30 | +impl RefPlane<'_> { | ||
| 31 | + #[inline] | ||
| 32 | + fn at(&self, x: i32, y: i32) -> usize { | ||
| 33 | + (self.origin as isize + y as isize * self.stride as isize + x as isize) as usize | ||
| 34 | + } | ||
| 35 | +} | ||
| 36 | + | ||
| 37 | +/// Clamp a block origin so that every tap the interpolator reads stays inside | ||
| 38 | +/// the replicated border while producing the samples Equations 8-239/8-240 | ||
| 39 | +/// would have clipped to. | ||
| 40 | +/// | ||
| 41 | +/// `left`/`right` are the tap reach on each side (2 and 3 for the 6-tap luma | ||
| 42 | +/// filter, 0 and 1 for the bilinear chroma filter) and `size` the block extent. | ||
| 43 | +/// Once the block is completely outside the picture every tap resolves to the | ||
| 44 | +/// same edge sample, so clamping the origin to the last position where that is | ||
| 45 | +/// still true is exact rather than approximate. | ||
| 46 | +#[inline] | ||
| 47 | +fn clamp_origin(v: i32, size: usize, extent: usize, pad: usize, left: i32, right: i32) -> i32 { | ||
| 48 | + let lo = -(pad as i32) + left; | ||
| 49 | + let hi = extent as i32 + pad as i32 - right - size as i32; | ||
| 50 | + v.clamp(lo.min(hi), hi) | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +/// The 6-tap half-sample filter of Equations 8-241/8-242 over samples spaced | ||
| 54 | +/// `step` apart, centred between `p[0]` and `p[step]`. | ||
| 55 | +#[inline] | ||
| 56 | +fn tap6(data: &[u8], at: usize, step: usize) -> i32 { | ||
| 57 | + let s = |k: isize| i32::from(data[(at as isize + k * step as isize) as usize]); | ||
| 58 | + s(-2) - 5 * s(-1) + 20 * s(0) + 20 * s(1) - 5 * s(2) + s(3) | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// The same over already-filtered intermediate values (Equations 8-245/8-246). | ||
| 62 | +#[inline] | ||
| 63 | +fn tap6_i32(v: &[i32], at: usize, step: usize) -> i32 { | ||
| 64 | + let s = |k: isize| v[(at as isize + k * step as isize) as usize]; | ||
| 65 | + s(-2) - 5 * s(-1) + 20 * s(0) + 20 * s(1) - 5 * s(2) + s(3) | ||
| 66 | +} | ||
| 67 | + | ||
| 68 | +#[inline] | ||
| 69 | +fn clip8(v: i32) -> u8 { | ||
| 70 | + v.clamp(0, 255) as u8 | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +#[inline] | ||
| 74 | +fn avg(a: u8, b: u8) -> u8 { | ||
| 75 | + ((u32::from(a) + u32::from(b) + 1) >> 1) as u8 | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +/// Widest intermediate row the luma interpolator needs: a 16-wide partition | ||
| 79 | +/// plus the five taps of the horizontal filter. | ||
| 80 | +const TMP_W: usize = 16 + 5; | ||
| 81 | + | ||
| 82 | +/// Luma quarter-sample interpolation (8.4.2.2.1) of a `w` x `h` partition whose | ||
| 83 | +/// full-sample origin is `(x, y)` and whose motion vector is `mv` in quarter | ||
| 84 | +/// samples. Writes `w` x `h` prediction samples into `out` at pitch `w`. | ||
| 85 | +pub(crate) fn mc_luma(r: &RefPlane<'_>, x: i32, y: i32, mv: [i16; 2], w: usize, h: usize, out: &mut [u8]) { | ||
| 86 | + let (fx, fy) = ((mv[0] & 3) as usize, (mv[1] & 3) as usize); | ||
| 87 | + let xi = clamp_origin(x + (mv[0] as i32 >> 2), w, r.width, r.pad, 2, 3); | ||
| 88 | + let yi = clamp_origin(y + (mv[1] as i32 >> 2), h, r.height, r.pad, 2, 3); | ||
| 89 | + let stride = r.stride; | ||
| 90 | + let base = r.at(xi, yi); | ||
| 91 | + | ||
| 92 | + // Full sample: a straight copy. | ||
| 93 | + if fx == 0 && fy == 0 { | ||
| 94 | + for row in 0..h { | ||
| 95 | + let src = base + row * stride; | ||
| 96 | + out[row * w..row * w + w].copy_from_slice(&r.data[src..src + w]); | ||
| 97 | + } | ||
| 98 | + return; | ||
| 99 | + } | ||
| 100 | + | ||
| 101 | + // Half-sample rows ("b" of Equation 8-243) for rows yi..yi+h, plus one more | ||
| 102 | + // row when the quarter position also needs "s". | ||
| 103 | + let need_b = fx != 0 && fy != 2; | ||
| 104 | + let need_h = fy != 0 && fx != 2; | ||
| 105 | + let need_j = (fx == 2 && fy != 0) || (fy == 2 && fx != 0); | ||
| 106 | + | ||
| 107 | + let mut bb = [0u8; 16 * 17]; | ||
| 108 | + if need_b { | ||
| 109 | + // "s" is the same filter one row down, so row fy>>1 selects b or s. | ||
| 110 | + let row0 = yi + if fy == 3 { 1 } else { 0 }; | ||
| 111 | + for row in 0..h { | ||
| 112 | + let src = r.at(xi, row0 + row as i32); | ||
| 113 | + for col in 0..w { | ||
| 114 | + bb[row * w + col] = clip8((tap6(r.data, src + col, 1) + 16) >> 5); | ||
| 115 | + } | ||
| 116 | + } | ||
| 117 | + } | ||
| 118 | + let mut hh = [0u8; 16 * 17]; | ||
| 119 | + if need_h { | ||
| 120 | + // "m" is the same filter one column right, so column fx>>1 selects h or m. | ||
| 121 | + let col0 = xi + if fx == 3 { 1 } else { 0 }; | ||
| 122 | + for row in 0..h { | ||
| 123 | + let src = r.at(col0, yi + row as i32); | ||
| 124 | + for col in 0..w { | ||
| 125 | + hh[row * w + col] = clip8((tap6(r.data, src + col, stride) + 16) >> 5); | ||
| 126 | + } | ||
| 127 | + } | ||
| 128 | + } | ||
| 129 | + let mut jj = [0u8; 16 * 16]; | ||
| 130 | + if need_j { | ||
| 131 | + // Equation 8-246: filter horizontally into intermediates, then | ||
| 132 | + // vertically over those. The horizontal pass needs two rows above and | ||
| 133 | + // three below the partition. | ||
| 134 | + let mut inter = [0i32; TMP_W * (16 + 5)]; | ||
| 135 | + for row in 0..h + 5 { | ||
| 136 | + let src = r.at(xi, yi + row as i32 - 2); | ||
| 137 | + for col in 0..w { | ||
| 138 | + inter[row * TMP_W + col] = tap6(r.data, src + col, 1); | ||
| 139 | + } | ||
| 140 | + } | ||
| 141 | + for row in 0..h { | ||
| 142 | + for col in 0..w { | ||
| 143 | + let v = tap6_i32(&inter, (row + 2) * TMP_W + col, TMP_W); | ||
| 144 | + jj[row * w + col] = clip8((v + 512) >> 10); | ||
| 145 | + } | ||
| 146 | + } | ||
| 147 | + } | ||
| 148 | + | ||
| 149 | + for row in 0..h { | ||
| 150 | + for col in 0..w { | ||
| 151 | + let i = row * w + col; | ||
| 152 | + let g = |dx: i32, dy: i32| r.data[base + (row as i32 + dy) as usize * stride | ||
| 153 | + + (col as i32 + dx) as usize]; | ||
| 154 | + out[i] = match (fx, fy) { | ||
| 155 | + // Table 8-12, quarter positions on the integer rows/columns. | ||
| 156 | + (1, 0) => avg(g(0, 0), bb[i]), | ||
| 157 | + (2, 0) => bb[i], | ||
| 158 | + (3, 0) => avg(g(1, 0), bb[i]), | ||
| 159 | + (0, 1) => avg(g(0, 0), hh[i]), | ||
| 160 | + (0, 2) => hh[i], | ||
| 161 | + (0, 3) => avg(g(0, 1), hh[i]), | ||
| 162 | + // Centre column / row: mix with the centre sample j. | ||
| 163 | + (2, 1) | (2, 3) => avg(bb[i], jj[i]), | ||
| 164 | + (1, 2) | (3, 2) => avg(hh[i], jj[i]), | ||
| 165 | + (2, 2) => jj[i], | ||
| 166 | + // Diagonal quarter positions: the two nearest half samples. | ||
| 167 | + _ => avg(bb[i], hh[i]), | ||
| 168 | + }; | ||
| 169 | + } | ||
| 170 | + } | ||
| 171 | +} | ||
| 172 | + | ||
| 173 | +/// Chroma eighth-sample interpolation (Equation 8-270) of a `w` x `h` block. | ||
| 174 | +pub(crate) fn mc_chroma( | ||
| 175 | + r: &RefPlane<'_>, | ||
| 176 | + x: i32, | ||
| 177 | + y: i32, | ||
| 178 | + mv: [i16; 2], | ||
| 179 | + w: usize, | ||
| 180 | + h: usize, | ||
| 181 | + out: &mut [u8], | ||
| 182 | +) { | ||
| 183 | + let (fx, fy) = ((mv[0] & 7) as i32, (mv[1] & 7) as i32); | ||
| 184 | + let xi = clamp_origin(x + (mv[0] as i32 >> 3), w, r.width, r.pad, 0, 1); | ||
| 185 | + let yi = clamp_origin(y + (mv[1] as i32 >> 3), h, r.height, r.pad, 0, 1); | ||
| 186 | + let stride = r.stride; | ||
| 187 | + let base = r.at(xi, yi); | ||
| 188 | + let (wa, wb, wc, wd) = ( | ||
| 189 | + (8 - fx) * (8 - fy), | ||
| 190 | + fx * (8 - fy), | ||
| 191 | + (8 - fx) * fy, | ||
| 192 | + fx * fy, | ||
| 193 | + ); | ||
| 194 | + for row in 0..h { | ||
| 195 | + let src = base + row * stride; | ||
| 196 | + for col in 0..w { | ||
| 197 | + let a = i32::from(r.data[src + col]); | ||
| 198 | + let b = i32::from(r.data[src + col + 1]); | ||
| 199 | + let c = i32::from(r.data[src + col + stride]); | ||
| 200 | + let d = i32::from(r.data[src + col + stride + 1]); | ||
| 201 | + out[row * w + col] = ((wa * a + wb * b + wc * c + wd * d + 32) >> 6) as u8; | ||
| 202 | + } | ||
| 203 | + } | ||
| 204 | +} | ||
| 205 | + | ||
| 206 | +/// Weights of one component for one partition (spec 8.4.3), already resolved | ||
| 207 | +/// to the explicit/implicit/default case. | ||
| 208 | +#[derive(Clone, Copy, Debug, PartialEq, Eq)] | ||
| 209 | +pub(crate) struct Weights { | ||
| 210 | + /// `logWDC`. | ||
| 211 | + pub log_wd: i32, | ||
| 212 | + /// `w0C`, `w1C`. | ||
| 213 | + pub w: [i32; 2], | ||
| 214 | + /// `o0C`, `o1C`. | ||
| 215 | + pub o: [i32; 2], | ||
| 216 | +} | ||
| 217 | + | ||
| 218 | +impl Weights { | ||
| 219 | + /// The identity weighting, which reproduces 8.4.2.3.1 exactly. | ||
| 220 | + pub(crate) const DEFAULT: Weights = Weights { | ||
| 221 | + log_wd: 0, | ||
| 222 | + w: [1, 1], | ||
| 223 | + o: [0, 0], | ||
| 224 | + }; | ||
| 225 | + | ||
| 226 | + fn is_default(&self) -> bool { | ||
| 227 | + *self == Weights::DEFAULT | ||
| 228 | + } | ||
| 229 | +} | ||
| 230 | + | ||
| 231 | +/// Combine the list predictions of one partition into the final prediction | ||
| 232 | +/// (spec 8.4.2.3). `p0`/`p1` hold `n` samples each; the entry for a list that | ||
| 233 | +/// is not used is ignored. | ||
| 234 | +pub(crate) fn combine( | ||
| 235 | + out: &mut [u8], | ||
| 236 | + p0: &[u8], | ||
| 237 | + p1: &[u8], | ||
| 238 | + use0: bool, | ||
| 239 | + use1: bool, | ||
| 240 | + wt: &Weights, | ||
| 241 | + n: usize, | ||
| 242 | +) { | ||
| 243 | + if wt.is_default() { | ||
| 244 | + // 8.4.2.3.1. | ||
| 245 | + match (use0, use1) { | ||
| 246 | + (true, false) => out[..n].copy_from_slice(&p0[..n]), | ||
| 247 | + (false, true) => out[..n].copy_from_slice(&p1[..n]), | ||
| 248 | + _ => { | ||
| 249 | + for i in 0..n { | ||
| 250 | + out[i] = avg(p0[i], p1[i]); | ||
| 251 | + } | ||
| 252 | + } | ||
| 253 | + } | ||
| 254 | + return; | ||
| 255 | + } | ||
| 256 | + // 8.4.2.3.2. | ||
| 257 | + if use0 && use1 { | ||
| 258 | + let round = 1 << wt.log_wd; | ||
| 259 | + let off = (wt.o[0] + wt.o[1] + 1) >> 1; | ||
| 260 | + for i in 0..n { | ||
| 261 | + let v = (i32::from(p0[i]) * wt.w[0] + i32::from(p1[i]) * wt.w[1] + round) | ||
| 262 | + >> (wt.log_wd + 1); | ||
| 263 | + out[i] = clip8(v + off); | ||
| 264 | + } | ||
| 265 | + return; | ||
| 266 | + } | ||
| 267 | + let (src, k) = if use0 { (p0, 0) } else { (p1, 1) }; | ||
| 268 | + if wt.log_wd >= 1 { | ||
| 269 | + let round = 1 << (wt.log_wd - 1); | ||
| 270 | + for i in 0..n { | ||
| 271 | + out[i] = clip8(((i32::from(src[i]) * wt.w[k] + round) >> wt.log_wd) + wt.o[k]); | ||
| 272 | + } | ||
| 273 | + } else { | ||
| 274 | + for i in 0..n { | ||
| 275 | + out[i] = clip8(i32::from(src[i]) * wt.w[k] + wt.o[k]); | ||
| 276 | + } | ||
| 277 | + } | ||
| 278 | +} | ||
| 279 | + | ||
| 280 | +#[cfg(test)] | ||
| 281 | +mod tests { | ||
| 282 | + use super::*; | ||
| 283 | + | ||
| 284 | + /// A plane whose interior is a known ramp and whose borders are replicated, | ||
| 285 | + /// the way `Plane8::extend_borders` leaves them. | ||
| 286 | + fn ramp_plane(w: usize, h: usize, pad: usize) -> (Vec<u8>, usize, usize) { | ||
| 287 | + let stride = w + 2 * pad; | ||
| 288 | + let origin = pad * stride + pad; | ||
| 289 | + let mut data = vec![0u8; stride * (h + 2 * pad)]; | ||
| 290 | + for y in 0..h { | ||
| 291 | + for x in 0..w { | ||
| 292 | + data[origin + y * stride + x] = ((x * 3 + y * 7) % 251) as u8; | ||
| 293 | + } | ||
| 294 | + } | ||
| 295 | + for y in 0..h { | ||
| 296 | + let row = origin + y * stride; | ||
| 297 | + let (l, r) = (data[row], data[row + w - 1]); | ||
| 298 | + data[row - pad..row].fill(l); | ||
| 299 | + data[row + w..row + w + pad].fill(r); | ||
| 300 | + } | ||
| 301 | + for y in 0..pad { | ||
| 302 | + let top = origin - (y + 1) * stride - pad; | ||
| 303 | + let src = origin - pad; | ||
| 304 | + let (a, b) = data.split_at_mut(src); | ||
| 305 | + a[top..top + stride].copy_from_slice(&b[..stride]); | ||
| 306 | + let bot = origin + (h + y) * stride - pad; | ||
| 307 | + let src = origin + (h - 1) * stride - pad; | ||
| 308 | + let (a, b) = data.split_at_mut(bot); | ||
| 309 | + b[..stride].copy_from_slice(&a[src..src + stride]); | ||
| 310 | + } | ||
| 311 | + (data, stride, origin) | ||
| 312 | + } | ||
| 313 | + | ||
| 314 | + fn plane(data: &[u8], stride: usize, origin: usize, w: usize, h: usize, pad: usize) -> RefPlane<'_> { | ||
| 315 | + RefPlane { | ||
| 316 | + data, | ||
| 317 | + stride, | ||
| 318 | + origin, | ||
| 319 | + width: w, | ||
| 320 | + height: h, | ||
| 321 | + pad, | ||
| 322 | + } | ||
| 323 | + } | ||
| 324 | + | ||
| 325 | + /// The spec's clipped, per-sample definition of the same interpolation, | ||
| 326 | + /// written straight from Equations 8-239 to 8-261 with no padding tricks. | ||
| 327 | + fn spec_luma( | ||
| 328 | + pic: &[u8], | ||
| 329 | + stride: usize, | ||
| 330 | + origin: usize, | ||
| 331 | + w: usize, | ||
| 332 | + h: usize, | ||
| 333 | + x: i32, | ||
| 334 | + y: i32, | ||
| 335 | + mv: [i16; 2], | ||
| 336 | + pw: usize, | ||
| 337 | + ph: usize, | ||
| 338 | + out: &mut [u8], | ||
| 339 | + ) { | ||
| 340 | + let s = |px: i32, py: i32| -> i32 { | ||
| 341 | + let cx = px.clamp(0, w as i32 - 1) as usize; | ||
| 342 | + let cy = py.clamp(0, h as i32 - 1) as usize; | ||
| 343 | + i32::from(pic[origin + cy * stride + cx]) | ||
| 344 | + }; | ||
| 345 | + let hf = |px: i32, py: i32| { | ||
| 346 | + s(px - 2, py) - 5 * s(px - 1, py) + 20 * s(px, py) + 20 * s(px + 1, py) | ||
| 347 | + - 5 * s(px + 2, py) | ||
| 348 | + + s(px + 3, py) | ||
| 349 | + }; | ||
| 350 | + let vf = |px: i32, py: i32| { | ||
| 351 | + s(px, py - 2) - 5 * s(px, py - 1) + 20 * s(px, py) + 20 * s(px, py + 1) | ||
| 352 | + - 5 * s(px, py + 2) | ||
| 353 | + + s(px, py + 3) | ||
| 354 | + }; | ||
| 355 | + let j1 = |px: i32, py: i32| { | ||
| 356 | + let t = |k: i32| hf(px, py + k); | ||
| 357 | + t(-2) - 5 * t(-1) + 20 * t(0) + 20 * t(1) - 5 * t(2) + t(3) | ||
| 358 | + }; | ||
| 359 | + let (fx, fy) = ((mv[0] & 3) as i32, (mv[1] & 3) as i32); | ||
| 360 | + let (xi, yi) = (x + (mv[0] as i32 >> 2), y + (mv[1] as i32 >> 2)); | ||
| 361 | + for row in 0..ph { | ||
| 362 | + for col in 0..pw { | ||
| 363 | + let (px, py) = (xi + col as i32, yi + row as i32); | ||
| 364 | + let g = |dx: i32, dy: i32| s(px + dx, py + dy) as u8; | ||
| 365 | + let b = |dy: i32| clip8((hf(px, py + dy) + 16) >> 5); | ||
| 366 | + let hs = |dx: i32| clip8((vf(px + dx, py) + 16) >> 5); | ||
| 367 | + let j = clip8((j1(px, py) + 512) >> 10); | ||
| 368 | + out[row * pw + col] = match (fx, fy) { | ||
| 369 | + (0, 0) => g(0, 0), | ||
| 370 | + (1, 0) => avg(g(0, 0), b(0)), | ||
| 371 | + (2, 0) => b(0), | ||
| 372 | + (3, 0) => avg(g(1, 0), b(0)), | ||
| 373 | + (0, 1) => avg(g(0, 0), hs(0)), | ||
| 374 | + (0, 2) => hs(0), | ||
| 375 | + (0, 3) => avg(g(0, 1), hs(0)), | ||
| 376 | + (1, 1) => avg(b(0), hs(0)), | ||
| 377 | + (3, 1) => avg(b(0), hs(1)), | ||
| 378 | + (1, 3) => avg(hs(0), b(1)), | ||
| 379 | + (3, 3) => avg(hs(1), b(1)), | ||
| 380 | + (2, 1) => avg(b(0), j), | ||
| 381 | + (2, 3) => avg(b(1), j), | ||
| 382 | + (1, 2) => avg(hs(0), j), | ||
| 383 | + (3, 2) => avg(hs(1), j), | ||
| 384 | + _ => j, | ||
| 385 | + }; | ||
| 386 | + } | ||
| 387 | + } | ||
| 388 | + } | ||
| 389 | + | ||
| 390 | + /// Every fractional position, at interior positions and far outside the | ||
| 391 | + /// picture, agrees with the spec's clipped definition. | ||
| 392 | + #[test] | ||
| 393 | + fn luma_interpolation_matches_the_clipped_definition() { | ||
| 394 | + let (w, h, pad) = (48usize, 32usize, 32usize); | ||
| 395 | + let (data, stride, origin) = ramp_plane(w, h, pad); | ||
| 396 | + let r = plane(&data, stride, origin, w, h, pad); | ||
| 397 | + let mut ours = [0u8; 256]; | ||
| 398 | + let mut theirs = [0u8; 256]; | ||
| 399 | + for &(px, py) in &[(8i32, 8i32), (0, 0), (32, 16), (-40, -40), (60, 44), (44, 4)] { | ||
| 400 | + for fy in 0..4i16 { | ||
| 401 | + for fx in 0..4i16 { | ||
| 402 | + for &(pw, ph) in &[(16usize, 16usize), (8, 4), (4, 8), (4, 4)] { | ||
| 403 | + let mv = [fx - 20 * 4, fy + 12]; | ||
| 404 | + mc_luma(&r, px, py, mv, pw, ph, &mut ours); | ||
| 405 | + spec_luma( | ||
| 406 | + &data, stride, origin, w, h, px, py, mv, pw, ph, &mut theirs, | ||
| 407 | + ); | ||
| 408 | + assert_eq!( | ||
| 409 | + ours[..pw * ph], | ||
| 410 | + theirs[..pw * ph], | ||
| 411 | + "({px},{py}) frac ({fx},{fy}) {pw}x{ph}" | ||
| 412 | + ); | ||
| 413 | + } | ||
| 414 | + } | ||
| 415 | + } | ||
| 416 | + } | ||
| 417 | + } | ||
| 418 | + | ||
| 419 | + #[test] | ||
| 420 | + fn chroma_interpolation_matches_equation_8_270() { | ||
| 421 | + let (w, h, pad) = (24usize, 16usize, 16usize); | ||
| 422 | + let (data, stride, origin) = ramp_plane(w, h, pad); | ||
| 423 | + let r = plane(&data, stride, origin, w, h, pad); | ||
| 424 | + let mut ours = [0u8; 64]; | ||
| 425 | + for &(px, py) in &[(4i32, 4i32), (0, 0), (-30, -30), (30, 22)] { | ||
| 426 | + for fy in 0..8i16 { | ||
| 427 | + for fx in 0..8i16 { | ||
| 428 | + let mv = [fx, fy]; | ||
| 429 | + mc_chroma(&r, px, py, mv, 8, 8, &mut ours); | ||
| 430 | + for row in 0..8i32 { | ||
| 431 | + for col in 0..8i32 { | ||
| 432 | + let s = |dx: i32, dy: i32| -> i32 { | ||
| 433 | + let cx = (px + col + dx).clamp(0, w as i32 - 1) as usize; | ||
| 434 | + let cy = (py + row + dy).clamp(0, h as i32 - 1) as usize; | ||
| 435 | + i32::from(data[origin + cy * stride + cx]) | ||
| 436 | + }; | ||
| 437 | + let (fx, fy) = (i32::from(fx), i32::from(fy)); | ||
| 438 | + let want = ((8 - fx) * (8 - fy) * s(0, 0) | ||
| 439 | + + fx * (8 - fy) * s(1, 0) | ||
| 440 | + + (8 - fx) * fy * s(0, 1) | ||
| 441 | + + fx * fy * s(1, 1) | ||
| 442 | + + 32) | ||
| 443 | + >> 6; | ||
| 444 | + assert_eq!( | ||
| 445 | + i32::from(ours[(row * 8 + col) as usize]), | ||
| 446 | + want, | ||
| 447 | + "({px},{py}) frac ({fx},{fy}) at ({col},{row})" | ||
| 448 | + ); | ||
| 449 | + } | ||
| 450 | + } | ||
| 451 | + } | ||
| 452 | + } | ||
| 453 | + } | ||
| 454 | + } | ||
| 455 | + | ||
| 456 | + #[test] | ||
| 457 | + fn weighted_combination_follows_8_4_2_3() { | ||
| 458 | + let p0 = [100u8; 4]; | ||
| 459 | + let p1 = [200u8; 4]; | ||
| 460 | + let mut out = [0u8; 4]; | ||
| 461 | + combine(&mut out, &p0, &p1, true, true, &Weights::DEFAULT, 4); | ||
| 462 | + assert_eq!(out, [150; 4]); | ||
| 463 | + // Explicit, single list: ((100 * 2 + 2) >> 2) + 5 = 55. | ||
| 464 | + let w = Weights { | ||
| 465 | + log_wd: 2, | ||
| 466 | + w: [2, 3], | ||
| 467 | + o: [5, -5], | ||
| 468 | + }; | ||
| 469 | + combine(&mut out, &p0, &p1, true, false, &w, 4); | ||
| 470 | + assert_eq!(out, [55; 4]); | ||
| 471 | + // Explicit, both lists: ((100*2 + 200*3 + 4) >> 3) + ((5 - 5 + 1) >> 1). | ||
| 472 | + combine(&mut out, &p0, &p1, true, true, &w, 4); | ||
| 473 | + assert_eq!(out, [100; 4]); | ||
| 474 | + // logWD 0 skips the rounding term entirely. | ||
| 475 | + let w0 = Weights { | ||
| 476 | + log_wd: 0, | ||
| 477 | + w: [2, 1], | ||
| 478 | + o: [3, 0], | ||
| 479 | + }; | ||
| 480 | + combine(&mut out, &p0, &p1, true, false, &w0, 4); | ||
| 481 | + assert_eq!(out, [203; 4]); | ||
| 482 | + } | ||
| 483 | +} | ||
crates/ec-h264/src/lib.rsmodified+11 -5
| @@ -1,9 +1,12 @@ | |||
| 1 | //! H.264 software decoder. | 1 | //! H.264 software decoder. |
| 2 | //! | 2 | //! |
| 3 | -//! Current scope: CAVLC-coded I slices (Intra_4x4, Intra_16x16, I_PCM) of | 3 | +//! Current scope: I, P and B slices under both entropy coders (CAVLC and |
| 4 | -//! 8-bit 4:2:0 progressive streams, with the full in-loop deblocking filter, | 4 | +//! CABAC) of 8-bit 4:2:0 progressive streams — intra prediction, inter |
| 5 | -//! decoded bit-exactly against the JVT conformance suite. Everything outside | 5 | +//! prediction with the full decoded picture buffer of clause 8.2, weighted |
| 6 | -//! that scope returns a named [`Error::Unsupported`] — never wrong output. | 6 | +//! prediction, and the in-loop deblocking filter — decoded bit-exactly against |
| 7 | +//! the JVT conformance suite. Frames come out in display order. Everything | ||
| 8 | +//! outside that scope returns a named [`Error::Unsupported`] — never wrong | ||
| 9 | +//! output. | ||
| 7 | //! | 10 | //! |
| 8 | //! Implemented from Rec. ITU-T H.264 (V15, 08/2024) only; no third-party | 11 | //! Implemented from Rec. ITU-T H.264 (V15, 08/2024) only; no third-party |
| 9 | //! decoder source was consulted. | 12 | //! decoder source was consulted. |
| @@ -37,11 +40,14 @@ mod cavlc; | |||
| 37 | mod codec; | 40 | mod codec; |
| 38 | mod deblock; | 41 | mod deblock; |
| 39 | mod decoder; | 42 | mod decoder; |
| 43 | +mod dpb; | ||
| 40 | mod entropy; | 44 | mod entropy; |
| 45 | +mod inter; | ||
| 46 | +mod mv; | ||
| 41 | mod pred; | 47 | mod pred; |
| 42 | mod tables; | 48 | mod tables; |
| 43 | mod transform; | 49 | mod transform; |
| 44 | 50 | ||
| 45 | pub use codec::H264Decoder; | 51 | pub use codec::H264Decoder; |
| 46 | -pub use decoder::{Decoder, NalOutcome}; | 52 | +pub use decoder::{Decoder, NalOutcome, OutputOrder}; |
| 47 | pub use ec_core::error::{Error, Result}; | 53 | pub use ec_core::error::{Error, Result}; |
crates/ec-h264/src/mv.rsadded+448 -0
| @@ -0,0 +1,448 @@ | |||
| 1 | +//! Macroblock partitioning and motion vector derivation (spec 7.4.5, 8.4.1). | ||
| 2 | +//! | ||
| 3 | +//! Motion data lives in the picture's per-4x4-block arrays, written as each | ||
| 4 | +//! partition is derived. Neighbour derivation (8.4.1.3.2) then reads those same | ||
| 5 | +//! arrays, which is what makes "the partition inside this macroblock has not | ||
| 6 | +//! been decoded yet" expressible: a bitmask of the blocks written so far stands | ||
| 7 | +//! in for the availability rule of clause 6.4.11.7, exactly rather than | ||
| 8 | +//! approximately. | ||
| 9 | + | ||
| 10 | +use crate::dpb::{BLK_DIRECT, BLK_INTRA, BLK_SKIP, Picture}; | ||
| 11 | + | ||
| 12 | +/// Prediction mode of a macroblock or sub-macroblock partition (Table 7-13, | ||
| 13 | +/// 7-14, 7-17, 7-18). | ||
| 14 | +#[derive(Clone, Copy, PartialEq, Eq, Debug)] | ||
| 15 | +pub(crate) enum Pred { | ||
| 16 | + /// Pred_L0. | ||
| 17 | + L0, | ||
| 18 | + /// Pred_L1. | ||
| 19 | + L1, | ||
| 20 | + /// BiPred. | ||
| 21 | + Bi, | ||
| 22 | + /// Direct (B_Skip, B_Direct_16x16, B_Direct_8x8). | ||
| 23 | + Direct, | ||
| 24 | +} | ||
| 25 | + | ||
| 26 | +impl Pred { | ||
| 27 | + /// `(predFlagL0, predFlagL1)`; direct mode resolves later. | ||
| 28 | + #[inline] | ||
| 29 | + pub(crate) fn uses(self, list: usize) -> bool { | ||
| 30 | + match self { | ||
| 31 | + Pred::L0 => list == 0, | ||
| 32 | + Pred::L1 => list == 1, | ||
| 33 | + Pred::Bi => true, | ||
| 34 | + Pred::Direct => false, | ||
| 35 | + } | ||
| 36 | + } | ||
| 37 | +} | ||
| 38 | + | ||
| 39 | +/// The partitioning of one inter macroblock. | ||
| 40 | +#[derive(Clone, Copy, Debug)] | ||
| 41 | +pub(crate) struct MbShape { | ||
| 42 | + /// `NumMbPart( mb_type )`. | ||
| 43 | + pub parts: usize, | ||
| 44 | + /// `MbPartWidth`/`MbPartHeight` in 4x4 blocks. | ||
| 45 | + pub w: usize, | ||
| 46 | + pub h: usize, | ||
| 47 | + /// `MbPartPredMode` of each partition. | ||
| 48 | + pub pred: [Pred; 2], | ||
| 49 | + /// mb_type is P_8x8/P_8x8ref0/B_8x8: sub-macroblock types follow. | ||
| 50 | + pub sub: bool, | ||
| 51 | +} | ||
| 52 | + | ||
| 53 | +const fn shape(parts: usize, w: usize, h: usize, p0: Pred, p1: Pred) -> MbShape { | ||
| 54 | + MbShape { | ||
| 55 | + parts, | ||
| 56 | + w, | ||
| 57 | + h, | ||
| 58 | + pred: [p0, p1], | ||
| 59 | + sub: false, | ||
| 60 | + } | ||
| 61 | +} | ||
| 62 | + | ||
| 63 | +const SUB8X8: MbShape = MbShape { | ||
| 64 | + parts: 4, | ||
| 65 | + w: 2, | ||
| 66 | + h: 2, | ||
| 67 | + pred: [Pred::L0, Pred::L0], | ||
| 68 | + sub: true, | ||
| 69 | +}; | ||
| 70 | + | ||
| 71 | +/// Table 7-13, mb_type 0..4 of a P or SP slice. | ||
| 72 | +pub(crate) const P_SHAPES: [MbShape; 5] = [ | ||
| 73 | + shape(1, 4, 4, Pred::L0, Pred::L0), | ||
| 74 | + shape(2, 4, 2, Pred::L0, Pred::L0), | ||
| 75 | + shape(2, 2, 4, Pred::L0, Pred::L0), | ||
| 76 | + SUB8X8, | ||
| 77 | + SUB8X8, // P_8x8ref0: same partitioning, ref_idx inferred 0. | ||
| 78 | +]; | ||
| 79 | + | ||
| 80 | +/// Table 7-14, mb_type 0..22 of a B slice. | ||
| 81 | +pub(crate) const B_SHAPES: [MbShape; 23] = [ | ||
| 82 | + shape(1, 4, 4, Pred::Direct, Pred::Direct), | ||
| 83 | + shape(1, 4, 4, Pred::L0, Pred::L0), | ||
| 84 | + shape(1, 4, 4, Pred::L1, Pred::L1), | ||
| 85 | + shape(1, 4, 4, Pred::Bi, Pred::Bi), | ||
| 86 | + shape(2, 4, 2, Pred::L0, Pred::L0), | ||
| 87 | + shape(2, 2, 4, Pred::L0, Pred::L0), | ||
| 88 | + shape(2, 4, 2, Pred::L1, Pred::L1), | ||
| 89 | + shape(2, 2, 4, Pred::L1, Pred::L1), | ||
| 90 | + shape(2, 4, 2, Pred::L0, Pred::L1), | ||
| 91 | + shape(2, 2, 4, Pred::L0, Pred::L1), | ||
| 92 | + shape(2, 4, 2, Pred::L1, Pred::L0), | ||
| 93 | + shape(2, 2, 4, Pred::L1, Pred::L0), | ||
| 94 | + shape(2, 4, 2, Pred::L0, Pred::Bi), | ||
| 95 | + shape(2, 2, 4, Pred::L0, Pred::Bi), | ||
| 96 | + shape(2, 4, 2, Pred::L1, Pred::Bi), | ||
| 97 | + shape(2, 2, 4, Pred::L1, Pred::Bi), | ||
| 98 | + shape(2, 4, 2, Pred::Bi, Pred::L0), | ||
| 99 | + shape(2, 2, 4, Pred::Bi, Pred::L0), | ||
| 100 | + shape(2, 4, 2, Pred::Bi, Pred::L1), | ||
| 101 | + shape(2, 2, 4, Pred::Bi, Pred::L1), | ||
| 102 | + shape(2, 4, 2, Pred::Bi, Pred::Bi), | ||
| 103 | + shape(2, 2, 4, Pred::Bi, Pred::Bi), | ||
| 104 | + SUB8X8, | ||
| 105 | +]; | ||
| 106 | + | ||
| 107 | +/// The partitioning of one 8x8 sub-macroblock. | ||
| 108 | +#[derive(Clone, Copy, Debug)] | ||
| 109 | +pub(crate) struct SubShape { | ||
| 110 | + /// `NumSubMbPart( sub_mb_type )`. | ||
| 111 | + pub parts: usize, | ||
| 112 | + /// `SubMbPartWidth`/`SubMbPartHeight` in 4x4 blocks. | ||
| 113 | + pub w: usize, | ||
| 114 | + pub h: usize, | ||
| 115 | + /// `SubMbPredMode`. | ||
| 116 | + pub pred: Pred, | ||
| 117 | +} | ||
| 118 | + | ||
| 119 | +const fn sub(parts: usize, w: usize, h: usize, pred: Pred) -> SubShape { | ||
| 120 | + SubShape { parts, w, h, pred } | ||
| 121 | +} | ||
| 122 | + | ||
| 123 | +/// Table 7-17, sub_mb_type of a P macroblock. | ||
| 124 | +pub(crate) const P_SUB: [SubShape; 4] = [ | ||
| 125 | + sub(1, 2, 2, Pred::L0), | ||
| 126 | + sub(2, 2, 1, Pred::L0), | ||
| 127 | + sub(2, 1, 2, Pred::L0), | ||
| 128 | + sub(4, 1, 1, Pred::L0), | ||
| 129 | +]; | ||
| 130 | + | ||
| 131 | +/// Table 7-18, sub_mb_type of a B macroblock. | ||
| 132 | +pub(crate) const B_SUB: [SubShape; 13] = [ | ||
| 133 | + sub(4, 1, 1, Pred::Direct), | ||
| 134 | + sub(1, 2, 2, Pred::L0), | ||
| 135 | + sub(1, 2, 2, Pred::L1), | ||
| 136 | + sub(1, 2, 2, Pred::Bi), | ||
| 137 | + sub(2, 2, 1, Pred::L0), | ||
| 138 | + sub(2, 1, 2, Pred::L0), | ||
| 139 | + sub(2, 2, 1, Pred::L1), | ||
| 140 | + sub(2, 1, 2, Pred::L1), | ||
| 141 | + sub(2, 2, 1, Pred::Bi), | ||
| 142 | + sub(2, 1, 2, Pred::Bi), | ||
| 143 | + sub(4, 1, 1, Pred::L0), | ||
| 144 | + sub(4, 1, 1, Pred::L1), | ||
| 145 | + sub(4, 1, 1, Pred::Bi), | ||
| 146 | +]; | ||
| 147 | + | ||
| 148 | +/// Motion data of one neighbouring partition (8.4.1.3.2). | ||
| 149 | +#[derive(Clone, Copy, Debug, Default)] | ||
| 150 | +pub(crate) struct Nb { | ||
| 151 | + /// The partition exists and has been decoded (clause 6.4.11.7). | ||
| 152 | + pub avail: bool, | ||
| 153 | + pub mv: [i16; 2], | ||
| 154 | + /// -1 when the neighbour does not use this list, or is intra. | ||
| 155 | + pub ref_idx: i8, | ||
| 156 | +} | ||
| 157 | + | ||
| 158 | +/// Where the current macroblock's motion data is being written, and which of | ||
| 159 | +/// its 4x4 blocks already carry it. | ||
| 160 | +pub(crate) struct MvCtx { | ||
| 161 | + pub mb_x: usize, | ||
| 162 | + pub mb_y: usize, | ||
| 163 | + pub slice_id: u16, | ||
| 164 | + /// Bit `y * 4 + x` set once block (x, y) of this macroblock is derived. | ||
| 165 | + pub written: u16, | ||
| 166 | +} | ||
| 167 | + | ||
| 168 | +impl MvCtx { | ||
| 169 | + /// Motion data of the 4x4 block at picture block coordinates `(bx, by)`, | ||
| 170 | + /// for list `list`. | ||
| 171 | + pub(crate) fn at(&self, pic: &Picture, bx: i32, by: i32, list: usize) -> Nb { | ||
| 172 | + let w4 = (pic.mb_w * 4) as i32; | ||
| 173 | + let h4 = (pic.mb_h * 4) as i32; | ||
| 174 | + if bx < 0 || by < 0 || bx >= w4 || by >= h4 { | ||
| 175 | + return Nb::default(); | ||
| 176 | + } | ||
| 177 | + let (mbx, mby) = (bx as usize / 4, by as usize / 4); | ||
| 178 | + let addr = mby * pic.mb_w + mbx; | ||
| 179 | + if mbx == self.mb_x && mby == self.mb_y { | ||
| 180 | + let within = (by as usize % 4) * 4 + bx as usize % 4; | ||
| 181 | + if self.written & (1 << within) == 0 { | ||
| 182 | + return Nb::default(); | ||
| 183 | + } | ||
| 184 | + } else if pic.mb_slice[addr] != self.slice_id { | ||
| 185 | + return Nb::default(); | ||
| 186 | + } | ||
| 187 | + let idx = by as usize * pic.mb_w * 4 + bx as usize; | ||
| 188 | + if pic.blk[idx] & BLK_INTRA != 0 { | ||
| 189 | + // Available as a partition, but contributes no motion (8.4.1.3.2). | ||
| 190 | + return Nb { | ||
| 191 | + avail: true, | ||
| 192 | + mv: [0; 2], | ||
| 193 | + ref_idx: -1, | ||
| 194 | + }; | ||
| 195 | + } | ||
| 196 | + Nb { | ||
| 197 | + avail: true, | ||
| 198 | + mv: pic.mv[idx][list], | ||
| 199 | + ref_idx: pic.ref_idx[idx][list], | ||
| 200 | + } | ||
| 201 | + } | ||
| 202 | + | ||
| 203 | + /// Neighbours A, B and C of a partition whose top-left 4x4 block is at | ||
| 204 | + /// macroblock-relative `(px, py)` and whose `predPartWidth` is `pw` blocks | ||
| 205 | + /// (clause 6.4.11.7, with the C-to-D substitution of 8-214). | ||
| 206 | + pub(crate) fn neighbours(&self, pic: &Picture, px: usize, py: usize, pw: usize, list: usize) -> [Nb; 3] { | ||
| 207 | + let bx = (self.mb_x * 4 + px) as i32; | ||
| 208 | + let by = (self.mb_y * 4 + py) as i32; | ||
| 209 | + let a = self.at(pic, bx - 1, by, list); | ||
| 210 | + let b = self.at(pic, bx, by - 1, list); | ||
| 211 | + let mut c = self.at(pic, bx + pw as i32, by - 1, list); | ||
| 212 | + if !c.avail { | ||
| 213 | + c = self.at(pic, bx - 1, by - 1, list); | ||
| 214 | + } | ||
| 215 | + [a, b, c] | ||
| 216 | + } | ||
| 217 | +} | ||
| 218 | + | ||
| 219 | +#[inline] | ||
| 220 | +fn median(a: i16, b: i16, c: i16) -> i16 { | ||
| 221 | + a.max(b).min(a.min(b).max(c)) | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// Motion vector prediction (clause 8.4.1.3), including the directional | ||
| 225 | +/// segmentation shortcuts of Equations 8-203 to 8-206. | ||
| 226 | +/// | ||
| 227 | +/// `part_w`/`part_h` are `MbPartWidth`/`MbPartHeight` in 4x4 blocks and only | ||
| 228 | +/// select those shortcuts; `part` is the macroblock partition index. | ||
| 229 | +pub(crate) fn predict_mv(n: &[Nb; 3], ref_idx: i8, part_w: usize, part_h: usize, part: usize) -> [i16; 2] { | ||
| 230 | + let [a, mut b, mut c] = *n; | ||
| 231 | + match (part_w, part_h, part) { | ||
| 232 | + (4, 2, 0) if b.ref_idx == ref_idx => return b.mv, | ||
| 233 | + (4, 2, 1) if a.ref_idx == ref_idx => return a.mv, | ||
| 234 | + (2, 4, 0) if a.ref_idx == ref_idx => return a.mv, | ||
| 235 | + (2, 4, 1) if c.ref_idx == ref_idx => return c.mv, | ||
| 236 | + _ => {} | ||
| 237 | + } | ||
| 238 | + // 8.4.1.3.1 step 1. | ||
| 239 | + if !b.avail && !c.avail && a.avail { | ||
| 240 | + b = a; | ||
| 241 | + c = a; | ||
| 242 | + } | ||
| 243 | + let matches = u8::from(a.ref_idx == ref_idx) | ||
| 244 | + + u8::from(b.ref_idx == ref_idx) | ||
| 245 | + + u8::from(c.ref_idx == ref_idx); | ||
| 246 | + if matches == 1 { | ||
| 247 | + if a.ref_idx == ref_idx { | ||
| 248 | + return a.mv; | ||
| 249 | + } | ||
| 250 | + if b.ref_idx == ref_idx { | ||
| 251 | + return b.mv; | ||
| 252 | + } | ||
| 253 | + return c.mv; | ||
| 254 | + } | ||
| 255 | + [ | ||
| 256 | + median(a.mv[0], b.mv[0], c.mv[0]), | ||
| 257 | + median(a.mv[1], b.mv[1], c.mv[1]), | ||
| 258 | + ] | ||
| 259 | +} | ||
| 260 | + | ||
| 261 | +/// `MinPositive` (Equation 8-187). | ||
| 262 | +#[inline] | ||
| 263 | +pub(crate) fn min_positive(x: i8, y: i8) -> i8 { | ||
| 264 | + if x >= 0 && y >= 0 { x.min(y) } else { x.max(y) } | ||
| 265 | +} | ||
| 266 | + | ||
| 267 | +/// Record one 4x4 block's motion data into the picture arrays. | ||
| 268 | +#[allow(clippy::too_many_arguments)] | ||
| 269 | +pub(crate) fn write_block( | ||
| 270 | + pic: &mut Picture, | ||
| 271 | + ctx: &mut MvCtx, | ||
| 272 | + px: usize, | ||
| 273 | + py: usize, | ||
| 274 | + mv: [[i16; 2]; 2], | ||
| 275 | + ref_idx: [i8; 2], | ||
| 276 | + ref_id: [i32; 2], | ||
| 277 | + flags: u8, | ||
| 278 | +) { | ||
| 279 | + let bx = ctx.mb_x * 4 + px; | ||
| 280 | + let by = ctx.mb_y * 4 + py; | ||
| 281 | + let idx = by * pic.mb_w * 4 + bx; | ||
| 282 | + pic.mv[idx] = mv; | ||
| 283 | + pic.ref_idx[idx] = ref_idx; | ||
| 284 | + pic.ref_id[idx] = ref_id; | ||
| 285 | + pic.blk[idx] = flags; | ||
| 286 | + ctx.written |= 1 << (py * 4 + px); | ||
| 287 | +} | ||
| 288 | + | ||
| 289 | +/// Mark every 4x4 block of the current macroblock as intra, clearing the motion | ||
| 290 | +/// data an inter neighbour would otherwise read (8.4.1.3.2, 9.3.3.1.1.7). | ||
| 291 | +pub(crate) fn write_intra_mb(pic: &mut Picture, mb_x: usize, mb_y: usize) { | ||
| 292 | + let w4 = pic.mb_w * 4; | ||
| 293 | + for py in 0..4 { | ||
| 294 | + let base = (mb_y * 4 + py) * w4 + mb_x * 4; | ||
| 295 | + for idx in base..base + 4 { | ||
| 296 | + pic.mv[idx] = [[0; 2]; 2]; | ||
| 297 | + pic.ref_idx[idx] = [-1; 2]; | ||
| 298 | + pic.ref_id[idx] = [-1; 2]; | ||
| 299 | + pic.mvd_abs[idx] = [0; 4]; | ||
| 300 | + pic.blk[idx] = BLK_INTRA; | ||
| 301 | + } | ||
| 302 | + } | ||
| 303 | +} | ||
| 304 | + | ||
| 305 | +/// Record `Abs( mvd )` for one 4x4 block, saturated at the largest value the | ||
| 306 | +/// context thresholds of 9.3.3.1.1.7 can distinguish. | ||
| 307 | +#[inline] | ||
| 308 | +pub(crate) fn write_mvd(pic: &mut Picture, mb_x: usize, mb_y: usize, px: usize, py: usize, list: usize, mvd: [i16; 2]) { | ||
| 309 | + let idx = (mb_y * 4 + py) * pic.mb_w * 4 + mb_x * 4 + px; | ||
| 310 | + let e = &mut pic.mvd_abs[idx]; | ||
| 311 | + e[list * 2] = mvd[0].unsigned_abs().min(127) as u8; | ||
| 312 | + e[list * 2 + 1] = mvd[1].unsigned_abs().min(127) as u8; | ||
| 313 | +} | ||
| 314 | + | ||
| 315 | +/// `absMvdCompN` of the neighbouring partition at picture block coordinates | ||
| 316 | +/// `(bx, by)` (9.3.3.1.1.7): zero when the neighbour is unavailable, skipped, | ||
| 317 | +/// intra or direct coded. | ||
| 318 | +pub(crate) fn neighbour_mvd(pic: &Picture, ctx: &MvCtx, bx: i32, by: i32, list: usize) -> [u32; 2] { | ||
| 319 | + let w4 = (pic.mb_w * 4) as i32; | ||
| 320 | + let h4 = (pic.mb_h * 4) as i32; | ||
| 321 | + if bx < 0 || by < 0 || bx >= w4 || by >= h4 { | ||
| 322 | + return [0; 2]; | ||
| 323 | + } | ||
| 324 | + let (mbx, mby) = (bx as usize / 4, by as usize / 4); | ||
| 325 | + if mbx == ctx.mb_x && mby == ctx.mb_y { | ||
| 326 | + let within = (by as usize % 4) * 4 + bx as usize % 4; | ||
| 327 | + if ctx.written & (1 << within) == 0 { | ||
| 328 | + return [0; 2]; | ||
| 329 | + } | ||
| 330 | + } else if pic.mb_slice[mby * pic.mb_w + mbx] != ctx.slice_id { | ||
| 331 | + return [0; 2]; | ||
| 332 | + } | ||
| 333 | + let idx = by as usize * pic.mb_w * 4 + bx as usize; | ||
| 334 | + if pic.blk[idx] & (BLK_INTRA | BLK_SKIP | BLK_DIRECT) != 0 || pic.ref_idx[idx][list] < 0 { | ||
| 335 | + return [0; 2]; | ||
| 336 | + } | ||
| 337 | + let e = pic.mvd_abs[idx]; | ||
| 338 | + [u32::from(e[list * 2]), u32::from(e[list * 2 + 1])] | ||
| 339 | +} | ||
| 340 | + | ||
| 341 | +/// `condTermFlagN` for ref_idx_lX (9.3.3.1.1.6). | ||
| 342 | +pub(crate) fn ref_idx_cond(pic: &Picture, ctx: &MvCtx, bx: i32, by: i32, list: usize) -> usize { | ||
| 343 | + let w4 = (pic.mb_w * 4) as i32; | ||
| 344 | + let h4 = (pic.mb_h * 4) as i32; | ||
| 345 | + if bx < 0 || by < 0 || bx >= w4 || by >= h4 { | ||
| 346 | + return 0; | ||
| 347 | + } | ||
| 348 | + let (mbx, mby) = (bx as usize / 4, by as usize / 4); | ||
| 349 | + if mbx == ctx.mb_x && mby == ctx.mb_y { | ||
| 350 | + let within = (by as usize % 4) * 4 + bx as usize % 4; | ||
| 351 | + if ctx.written & (1 << within) == 0 { | ||
| 352 | + return 0; | ||
| 353 | + } | ||
| 354 | + } else if pic.mb_slice[mby * pic.mb_w + mbx] != ctx.slice_id { | ||
| 355 | + return 0; | ||
| 356 | + } | ||
| 357 | + let idx = by as usize * pic.mb_w * 4 + bx as usize; | ||
| 358 | + if pic.blk[idx] & (BLK_INTRA | BLK_SKIP | BLK_DIRECT) != 0 { | ||
| 359 | + return 0; | ||
| 360 | + } | ||
| 361 | + usize::from(pic.ref_idx[idx][list] > 0) | ||
| 362 | +} | ||
| 363 | + | ||
| 364 | +#[cfg(test)] | ||
| 365 | +mod tests { | ||
| 366 | + use super::*; | ||
| 367 | + | ||
| 368 | + fn nb(avail: bool, mv: [i16; 2], ref_idx: i8) -> Nb { | ||
| 369 | + Nb { | ||
| 370 | + avail, | ||
| 371 | + mv, | ||
| 372 | + ref_idx, | ||
| 373 | + } | ||
| 374 | + } | ||
| 375 | + | ||
| 376 | + /// With exactly one neighbour on the same reference picture, that | ||
| 377 | + /// neighbour's vector is the prediction (Equation 8-211). | ||
| 378 | + #[test] | ||
| 379 | + fn single_matching_reference_wins() { | ||
| 380 | + let n = [ | ||
| 381 | + nb(true, [4, 4], 1), | ||
| 382 | + nb(true, [8, 8], 0), | ||
| 383 | + nb(true, [12, 12], 2), | ||
| 384 | + ]; | ||
| 385 | + assert_eq!(predict_mv(&n, 0, 4, 4, 0), [8, 8]); | ||
| 386 | + } | ||
| 387 | + | ||
| 388 | + /// Otherwise the prediction is the component-wise median (8-212, 8-213). | ||
| 389 | + #[test] | ||
| 390 | + fn median_of_three_when_several_match() { | ||
| 391 | + let n = [ | ||
| 392 | + nb(true, [4, -8], 0), | ||
| 393 | + nb(true, [8, 2], 0), | ||
| 394 | + nb(true, [-2, 6], 1), | ||
| 395 | + ]; | ||
| 396 | + assert_eq!(predict_mv(&n, 0, 4, 4, 0), [4, 2]); | ||
| 397 | + } | ||
| 398 | + | ||
| 399 | + /// B and C unavailable with A available copies A into both, which turns the | ||
| 400 | + /// median into A (8-207 to 8-210). | ||
| 401 | + #[test] | ||
| 402 | + fn unavailable_b_and_c_fall_back_to_a() { | ||
| 403 | + let n = [nb(true, [6, -6], 3), nb(false, [0, 0], -1), nb(false, [0, 0], -1)]; | ||
| 404 | + assert_eq!(predict_mv(&n, 0, 4, 4, 0), [6, -6]); | ||
| 405 | + // With refIdx 3 the single-match rule fires first, same answer. | ||
| 406 | + assert_eq!(predict_mv(&n, 3, 4, 4, 0), [6, -6]); | ||
| 407 | + } | ||
| 408 | + | ||
| 409 | + /// The 16x8 and 8x16 shortcuts bypass the median entirely. | ||
| 410 | + #[test] | ||
| 411 | + fn directional_segmentation_shortcuts() { | ||
| 412 | + let n = [ | ||
| 413 | + nb(true, [1, 1], 0), | ||
| 414 | + nb(true, [2, 2], 0), | ||
| 415 | + nb(true, [3, 3], 0), | ||
| 416 | + ]; | ||
| 417 | + assert_eq!(predict_mv(&n, 0, 4, 2, 0), [2, 2], "16x8 part 0 takes B"); | ||
| 418 | + assert_eq!(predict_mv(&n, 0, 4, 2, 1), [1, 1], "16x8 part 1 takes A"); | ||
| 419 | + assert_eq!(predict_mv(&n, 0, 2, 4, 0), [1, 1], "8x16 part 0 takes A"); | ||
| 420 | + assert_eq!(predict_mv(&n, 0, 2, 4, 1), [3, 3], "8x16 part 1 takes C"); | ||
| 421 | + // A shortcut that does not match the reference index falls through. | ||
| 422 | + assert_eq!(predict_mv(&n, 1, 4, 2, 0), [2, 2], "median of 1,2,3"); | ||
| 423 | + } | ||
| 424 | + | ||
| 425 | + #[test] | ||
| 426 | + fn min_positive_prefers_the_non_negative() { | ||
| 427 | + assert_eq!(min_positive(2, 5), 2); | ||
| 428 | + assert_eq!(min_positive(-1, 5), 5); | ||
| 429 | + assert_eq!(min_positive(-1, -1), -1); | ||
| 430 | + assert_eq!(min_positive(0, -1), 0); | ||
| 431 | + } | ||
| 432 | + | ||
| 433 | + /// Every B macroblock type maps to the partition shape Table 7-14 states. | ||
| 434 | + #[test] | ||
| 435 | + fn b_shapes_match_table_7_14() { | ||
| 436 | + assert_eq!(B_SHAPES[0].pred[0], Pred::Direct); | ||
| 437 | + assert_eq!((B_SHAPES[3].parts, B_SHAPES[3].pred[0]), (1, Pred::Bi)); | ||
| 438 | + // The 16x8 / 8x16 pairs alternate, starting at mb_type 4. | ||
| 439 | + for t in 4..22 { | ||
| 440 | + let s = B_SHAPES[t]; | ||
| 441 | + assert_eq!(s.parts, 2, "mb_type {t}"); | ||
| 442 | + let (w, h) = if t % 2 == 0 { (4, 2) } else { (2, 4) }; | ||
| 443 | + assert_eq!((s.w, s.h), (w, h), "mb_type {t}"); | ||
| 444 | + } | ||
| 445 | + assert!(B_SHAPES[22].sub); | ||
| 446 | + assert!(P_SHAPES[3].sub && P_SHAPES[4].sub); | ||
| 447 | + } | ||
| 448 | +} | ||
crates/ec-h264/src/tables.rsmodified+14 -2
| @@ -468,6 +468,13 @@ pub const CBP_INTRA_420: [u8; 48] = [ | |||
| 468 | 35, 37, 42, 44, 1, 2, 4, 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41, | 468 | 35, 37, 42, 44, 1, 2, 4, 8, 17, 18, 20, 24, 6, 9, 22, 25, 32, 33, 34, 36, 40, 38, 41, |
| 469 | ]; | 469 | ]; |
| 470 | 470 | ||
| 471 | +/// Table 9-4 (a), Inter column: codeNum -> coded_block_pattern for | ||
| 472 | +/// ChromaArrayType 1 or 2. | ||
| 473 | +pub const CBP_INTER_420: [u8; 48] = [ | ||
| 474 | + 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, | ||
| 475 | + 36, 40, 39, 43, 45, 46, 17, 18, 20, 24, 19, 21, 26, 28, 23, 27, 29, 30, 22, 25, 38, 41, | ||
| 476 | +]; | ||
| 477 | + | ||
| 471 | /// Table 9-4 (b), Intra column: codeNum -> coded_block_pattern for | 478 | /// Table 9-4 (b), Intra column: codeNum -> coded_block_pattern for |
| 472 | /// ChromaArrayType 0 or 3. Unused until monochrome / 4:4:4 decode lands; | 479 | /// ChromaArrayType 0 or 3. Unused until monochrome / 4:4:4 decode lands; |
| 473 | /// kept beside its sibling so the spec table lives in one place. | 480 | /// kept beside its sibling so the spec table lives in one place. |
| @@ -510,14 +517,19 @@ pub const BETA: [u8; 52] = [ | |||
| 510 | ]; | 517 | ]; |
| 511 | 518 | ||
| 512 | /// Table 8-17: tC0' by [bS - 1][indexA]. | 519 | /// Table 8-17: tC0' by [bS - 1][indexA]. |
| 520 | +/// | ||
| 521 | +/// The bS 1 and 2 rows are unreachable from an intra-only decoder, so they went | ||
| 522 | +/// in transcribed but unexercised and both were wrong — a whole-row shift, the | ||
| 523 | +/// classic transcription defect. They are re-derived here from the printed | ||
| 524 | +/// table and now carry oracle coverage (inter edges reach every row). | ||
| 513 | pub const TC0: [[u8; 52]; 3] = [ | 525 | pub const TC0: [[u8; 52]; 3] = [ |
| 514 | [ | 526 | [ |
| 515 | 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, | 527 | 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, |
| 516 | - 1, 1, 1, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, | 528 | + 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 4, 5, 6, 6, 7, 8, 9, 10, 11, 13, |
| 517 | ], | 529 | ], |
| 518 | [ | 530 | [ |
| 519 | 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, | 531 | 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, |
| 520 | - 1, 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 8, 8, 10, 11, 12, 13, 15, | 532 | + 1, 2, 2, 2, 2, 3, 3, 3, 4, 4, 5, 5, 6, 7, 8, 8, 10, 11, 12, 13, 15, 17, |
| 521 | ], | 533 | ], |
| 522 | [ | 534 | [ |
| 523 | 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, | 535 | 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, |