forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

entropy.rs500 lines, 18.4 KiBHistoryRawDownload
1//! Entropy seat: the slice-data syntax reader the macroblock loop talks to.
2//!
3//! H.264 codes the same slice-data syntax two ways — CAVLC (clause 9.2) and
4//! CABAC (clause 9.3) — and the difference reaches every syntax element, not
5//! just the residual blocks. This enum is the single seam between them, so
6//! [`crate::decoder::decode_macroblock`] stays one fused parse-and-reconstruct
7//! loop instead of growing a second copy per entropy coder.
8//!
9//! Enum dispatch rather than a generic parameter: the variant is fixed for a
10//! whole slice, so every branch here is perfectly predicted, and one
11//! monomorphisation of the macroblock loop keeps the instruction cache (and the
12//! source) half the size. Measured: no change on the CAVLC ns/MB test.
13//!
14//! The seat deliberately takes *neighbour values*, never the picture: context
15//! derivation needs the neighbouring macroblocks' coefficient counts and coded
16//! block patterns, and passing those in as small copied values keeps the
17//! flat-array picture state private to the decoder module.
18
19use ec_core::error::{Error, Result};
20
21use crate::bits::BitCursor;
22use crate::cabac::Cabac;
23use crate::tables::{CBP_INTER_420, CBP_INTER_MONO, CBP_INTRA_420, CBP_INTRA_MONO};
24
25/// Macroblock state bits (`Picture::mb_flags`, and `MbInfo::flags` for a
26/// neighbour). CABAC context selection reads all of them.
27/// The macroblock has been decoded in this picture.
28pub(crate) const FLAG_DECODED: u8 = 1;
29/// mb_type is I_PCM.
30pub(crate) const FLAG_PCM: u8 = 2;
31/// mb_type is one of the Intra_16x16 types.
32pub(crate) const FLAG_I16: u8 = 4;
33/// intra_chroma_pred_mode is not 0 (DC).
34pub(crate) const FLAG_CHROMA_PRED: u8 = 8;
35/// The macroblock is inter coded.
36pub(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).
38pub(crate) const FLAG_DIRECT: u8 = 32;
39/// mb_type is P_Skip or B_Skip (9.3.3.1.1.1).
40pub(crate) const FLAG_SKIP: u8 = 64;
41/// transform_size_8x8_flag is 1: the luma residual is four 8x8 transform
42/// blocks, and an Intra_NxN macroblock predicts in 8x8 blocks (8.3.2).
43pub(crate) const FLAG_TRANS8X8: u8 = 128;
44
45/// Residual block class (spec Table 9-42, the 4:2:0 subset this decoder codes).
46#[derive(Clone, Copy, PartialEq, Eq, Debug)]
47pub(crate) enum BlockCat {
48 /// Intra16x16DCLevel, `ctxBlockCat` 0.
49 LumaDc,
50 /// Intra16x16ACLevel, `ctxBlockCat` 1.
51 LumaAc,
52 /// LumaLevel4x4, `ctxBlockCat` 2.
53 Luma4x4,
54 /// ChromaDCLevel of component `iCbCr`, `ctxBlockCat` 3.
55 ChromaDc(u8),
56 /// ChromaDCLevel of component `iCbCr` for 4:2:2 (2x4 DC, eight levels),
57 /// `ctxBlockCat` 3.
58 ChromaDc422(u8),
59 /// ChromaACLevel, `ctxBlockCat` 4.
60 ChromaAc,
61 /// LumaLevel8x8, `ctxBlockCat` 5: one 64-coefficient block under
62 /// transform_size_8x8_flag. CABAC codes it whole (no coded_block_flag for
63 /// 4:2:0); CAVLC never sees this category, it codes the block as four
64 /// interleaved `Luma4x4` blocks (7.3.5.3.1).
65 Luma8x8,
66}
67
68impl BlockCat {
69 /// `maxNumCoeff` (Table 9-42).
70 pub(crate) const fn max_num_coeff(self) -> usize {
71 match self {
72 BlockCat::LumaDc | BlockCat::Luma4x4 => 16,
73 BlockCat::LumaAc | BlockCat::ChromaAc => 15,
74 BlockCat::ChromaDc(_) => 4,
75 BlockCat::ChromaDc422(_) => 8,
76 BlockCat::Luma8x8 => 64,
77 }
78 }
79
80 /// `ctxBlockCat` (Table 9-42).
81 pub(crate) const fn ctx_block_cat(self) -> usize {
82 match self {
83 BlockCat::LumaDc => 0,
84 BlockCat::LumaAc => 1,
85 BlockCat::Luma4x4 => 2,
86 BlockCat::ChromaDc(_) | BlockCat::ChromaDc422(_) => 3,
87 BlockCat::ChromaAc => 4,
88 BlockCat::Luma8x8 => 5,
89 }
90 }
91}
92
93/// What a context-adaptive reader needs to know about one neighbouring
94/// macroblock.
95#[derive(Clone, Copy)]
96pub(crate) struct MbInfo {
97 /// The `FLAG_*` bits above.
98 pub flags: u8,
99 /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4`.
100 pub cbp: u8,
101 /// coded_block_flag of the DC blocks: bit 0 luma, bit 1 Cb, bit 2 Cr.
102 pub dc_cbf: u8,
103}
104
105/// Neighbourhood of the macroblock about to be parsed: left (A) and above (B)
106/// per clause 6.4.11.1, `None` when outside the picture or in another slice.
107#[derive(Clone, Copy, Default)]
108pub(crate) struct MbCtx {
109 pub a: Option<MbInfo>,
110 pub b: Option<MbInfo>,
111 /// ctxIdxInc for the first mb_qp_delta bin (clause 9.3.3.1.1.5), derived by
112 /// the caller from the previous macroblock in decoding order.
113 pub qp_delta_inc: u8,
114 /// The macroblock is a field macroblock (a field picture, or a field
115 /// macroblock of an MBAFF frame): field-coded significance contexts.
116 pub field: bool,
117 /// MBAFF frames only: the left neighbour of the lower 8x8 luma blocks can
118 /// be a different macroblock from the one beside the upper blocks, and the
119 /// 8x8 block of the neighbour that is adjacent differs with it.
120 pub mbaff_a: Option<MbaffA>,
121}
122
123/// See [`MbCtx::mbaff_a`].
124#[derive(Clone, Copy)]
125pub(crate) struct MbaffA {
126 /// The macroblock left of luma row 8.
127 pub lower: Option<MbInfo>,
128 /// The 8x8 block index inside the neighbour that bins 0 (upper) and 2
129 /// (lower) of coded_block_pattern read.
130 pub blk: [u8; 2],
131}
132
133/// The slice-data syntax reader.
134///
135/// The CABAC variant is much the larger of the two (it carries 436 context
136/// variables), and stays inline on purpose: one of these lives per slice on the
137/// stack, so boxing it would trade a compile-time size warning for a heap
138/// allocation in a decode loop that is otherwise allocation free.
139#[allow(clippy::large_enum_variant)]
140pub(crate) enum Entropy<'a> {
141 Cavlc(BitCursor<'a>),
142 Cabac(Cabac<'a>),
143}
144
145impl<'a> Entropy<'a> {
146 /// A CAVLC reader over `rbsp`, positioned just past the slice header.
147 pub(crate) fn cavlc(rbsp: &'a [u8], header_bits: u64) -> Entropy<'a> {
148 Entropy::Cavlc(BitCursor::new(rbsp, header_bits))
149 }
150
151 /// A CABAC reader: consumes the `cabac_alignment_one_bit`s and initialises
152 /// the context variables and the arithmetic decoding engine (clause 9.3.1).
153 /// `init_column` is 0 for I and SI slices, `cabac_init_idc + 1` otherwise.
154 pub(crate) fn cabac(
155 rbsp: &'a [u8],
156 header_bits: u64,
157 slice_qp: i32,
158 init_column: usize,
159 ) -> Result<Entropy<'a>> {
160 Ok(Entropy::Cabac(Cabac::new(
161 rbsp,
162 header_bits,
163 slice_qp,
164 init_column,
165 )?))
166 }
167
168 /// True for the CABAC variant.
169 #[inline]
170 pub(crate) fn is_cabac(&self) -> bool {
171 matches!(self, Entropy::Cabac(_))
172 }
173
174 /// Declare whether the macroblock being parsed is intra coded, which
175 /// CABAC needs for the coded_block_flag contexts of 9.3.3.1.1.9.
176 #[inline]
177 pub(crate) fn set_intra(&mut self, intra: bool) {
178 if let Entropy::Cabac(c) = self {
179 c.set_intra(intra);
180 }
181 }
182
183 /// `mb_skip_run` (7.3.4), CAVLC only.
184 pub(crate) fn mb_skip_run(&mut self) -> Result<u32> {
185 match self {
186 Entropy::Cavlc(r) => r.read_ue(),
187 Entropy::Cabac(_) => Err(Error::corrupt("mb_skip_run in a CABAC slice")),
188 }
189 }
190
191 /// `mb_skip_flag` (7.3.4), CABAC only; `inc` is condTermFlagA +
192 /// condTermFlagB per 9.3.3.1.1.1.
193 pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> Result<bool> {
194 match self {
195 Entropy::Cavlc(_) => Err(Error::corrupt("mb_skip_flag in a CAVLC slice")),
196 Entropy::Cabac(c) => Ok(c.mb_skip_flag(b_slice, inc)),
197 }
198 }
199
200 /// `mb_field_decoding_flag` (7.3.4); `inc` is the CABAC context increment.
201 pub(crate) fn mb_field_flag(&mut self, inc: usize) -> Result<bool> {
202 match self {
203 Entropy::Cavlc(r) => r.read_bit(),
204 Entropy::Cabac(c) => Ok(c.mb_field_decoding_flag(inc)),
205 }
206 }
207
208 /// The next CAVLC bit without consuming it (the field flag of the bottom
209 /// macroblock when the top one is skipped); `false` for CABAC.
210 pub(crate) fn peek_bit(&mut self) -> bool {
211 match self {
212 Entropy::Cavlc(r) => r.peek16() & 0x8000 != 0,
213 Entropy::Cabac(_) => false,
214 }
215 }
216
217 /// `mb_type` of a P or SP slice: 0..4, or 5 + the I-slice mb_type.
218 pub(crate) fn mb_type_p(&mut self) -> Result<u32> {
219 match self {
220 Entropy::Cavlc(r) => {
221 let t = r.read_ue()?;
222 if t > 30 {
223 return Err(Error::corrupt("P-slice mb_type > 30"));
224 }
225 Ok(t)
226 }
227 Entropy::Cabac(c) => c.mb_type_p(),
228 }
229 }
230
231 /// `mb_type` of a B slice: 0..22, or 23 + the I-slice mb_type.
232 pub(crate) fn mb_type_b(&mut self) -> Result<u32> {
233 match self {
234 Entropy::Cavlc(r) => {
235 let t = r.read_ue()?;
236 if t > 48 {
237 return Err(Error::corrupt("B-slice mb_type > 48"));
238 }
239 Ok(t)
240 }
241 Entropy::Cabac(c) => c.mb_type_b(),
242 }
243 }
244
245 /// `sub_mb_type[ ]` of a P (`b_slice` false) or B macroblock.
246 pub(crate) fn sub_mb_type(&mut self, b_slice: bool) -> Result<u32> {
247 let max = if b_slice { 12 } else { 3 };
248 match self {
249 Entropy::Cavlc(r) => {
250 let t = r.read_ue()?;
251 if t > max {
252 return Err(Error::corrupt("sub_mb_type out of range"));
253 }
254 Ok(t)
255 }
256 Entropy::Cabac(c) => Ok(if b_slice {
257 c.sub_mb_type_b()
258 } else {
259 c.sub_mb_type_p()
260 }),
261 }
262 }
263
264 /// `ref_idx_lX` (7.3.5.1): te(v) over `0..=cmax` for CAVLC, unary with the
265 /// neighbour context of 9.3.3.1.1.6 for CABAC.
266 pub(crate) fn ref_idx(&mut self, cmax: u32, inc: usize) -> Result<u32> {
267 let v = match self {
268 // te(v), clause 9.1.1: a one-valued range is a single inverted bit.
269 Entropy::Cavlc(r) if cmax == 1 => u32::from(!r.read_bit()?),
270 Entropy::Cavlc(r) => r.read_ue()?,
271 Entropy::Cabac(c) => c.ref_idx(inc)?,
272 };
273 if v > cmax {
274 return Err(Error::corrupt("ref_idx beyond num_ref_idx_active"));
275 }
276 Ok(v)
277 }
278
279 /// One `mvd_lX` component (7.3.5.1), in quarter luma samples.
280 pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> {
281 match self {
282 Entropy::Cavlc(r) => r.read_se(),
283 Entropy::Cabac(c) => c.mvd(comp, inc),
284 }
285 }
286
287 /// `coded_block_pattern` of an inter macroblock, as
288 /// `(CodedBlockPatternLuma, CodedBlockPatternChroma)`.
289 ///
290 /// `has_chroma` is ChromaArrayType 1 or 2: the pattern then has a chroma
291 /// part; for 0 and 3 (Table 9-4 b) it is the luma nibble alone.
292 pub(crate) fn coded_block_pattern_inter(&mut self, has_chroma: bool) -> Result<(u8, u8)> {
293 match self {
294 Entropy::Cavlc(r) => {
295 let code = r.read_ue()? as usize;
296 if !has_chroma {
297 let cbp = *CBP_INTER_MONO
298 .get(code)
299 .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 15"))?;
300 return Ok((cbp, 0));
301 }
302 let cbp = *CBP_INTER_420
303 .get(code)
304 .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 47"))?;
305 Ok((cbp & 15, cbp >> 4))
306 }
307 Entropy::Cabac(c) => c.coded_block_pattern(has_chroma),
308 }
309 }
310
311 /// Publish the neighbourhood of the macroblock about to be parsed.
312 #[inline]
313 pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) {
314 if let Entropy::Cabac(c) = self {
315 c.begin_mb(ctx);
316 }
317 }
318
319 /// `mb_type` of an I slice: 0 (I_NxN), 1..24 (Intra_16x16), 25 (I_PCM).
320 pub(crate) fn mb_type_i(&mut self) -> Result<u32> {
321 match self {
322 Entropy::Cavlc(r) => {
323 let t = r.read_ue()?;
324 if t > 25 {
325 return Err(Error::corrupt("I-slice mb_type > 25"));
326 }
327 Ok(t)
328 }
329 Entropy::Cabac(c) => c.mb_type_i(),
330 }
331 }
332
333 /// `transform_size_8x8_flag` (7.3.5).
334 pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {
335 match self {
336 Entropy::Cavlc(r) => r.read_bit(),
337 Entropy::Cabac(c) => c.transform_size_8x8_flag(),
338 }
339 }
340
341 /// One 4x4 intra prediction mode: `None` selects the predicted mode,
342 /// `Some(rem)` the `rem_intra4x4_pred_mode` value (7.3.5.1).
343 #[inline]
344 pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> {
345 match self {
346 Entropy::Cavlc(r) => {
347 if r.read_bit()? {
348 Ok(None)
349 } else {
350 Ok(Some(r.read_bits(3)? as u8))
351 }
352 }
353 Entropy::Cabac(c) => c.intra4x4_pred_mode(),
354 }
355 }
356
357 /// `intra_chroma_pred_mode` (7.3.5.1), 0..3.
358 pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> {
359 match self {
360 Entropy::Cavlc(r) => {
361 let m = r.read_ue()?;
362 if m > 3 {
363 return Err(Error::corrupt("intra_chroma_pred_mode > 3"));
364 }
365 Ok(m as u8)
366 }
367 Entropy::Cabac(c) => c.intra_chroma_pred_mode(),
368 }
369 }
370
371 /// `coded_block_pattern` of an Intra_4x4 macroblock, as
372 /// `(CodedBlockPatternLuma, CodedBlockPatternChroma)`.
373 pub(crate) fn coded_block_pattern_intra(&mut self, has_chroma: bool) -> Result<(u8, u8)> {
374 match self {
375 Entropy::Cavlc(r) => {
376 // me(v), clause 9.1.2 Table 9-4.
377 let code = r.read_ue()? as usize;
378 if !has_chroma {
379 let cbp = *CBP_INTRA_MONO
380 .get(code)
381 .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 15"))?;
382 return Ok((cbp, 0));
383 }
384 let cbp = *CBP_INTRA_420
385 .get(code)
386 .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 47"))?;
387 Ok((cbp & 15, cbp >> 4))
388 }
389 Entropy::Cabac(c) => c.coded_block_pattern(has_chroma),
390 }
391 }
392
393 /// `mb_qp_delta` (7.4.5), already range checked.
394 pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {
395 let delta = match self {
396 Entropy::Cavlc(r) => r.read_se()?,
397 Entropy::Cabac(c) => c.mb_qp_delta()?,
398 };
399 // The widest range any supported bit depth allows; the caller narrows it
400 // to the picture's QpBdOffset.
401 if !(-32..=31).contains(&delta) {
402 return Err(Error::corrupt("mb_qp_delta outside [-26, 25]"));
403 }
404 Ok(delta)
405 }
406
407 /// Decode one residual block into `coeff[0..cat.max_num_coeff()]` in scan
408 /// order, returning the number of non-zero coefficients.
409 ///
410 /// `na`/`nb` are the same counts for the left and above neighbouring blocks
411 /// of the same class, `None` when that neighbour is unavailable. CAVLC
412 /// averages them into nC (9.2.1); CABAC turns them into the
413 /// coded_block_flag context increment (9.3.3.1.1.9).
414 #[inline]
415 pub(crate) fn residual_block(
416 &mut self,
417 coeff: &mut [i32; 16],
418 cat: BlockCat,
419 na: Option<u8>,
420 nb: Option<u8>,
421 ) -> Result<u8> {
422 self.residual_block_c(coeff, cat, 0, na, nb)
423 }
424
425 /// [`Entropy::residual_block`] for colour component `comp` of a 4:4:4
426 /// macroblock (0 Y, 1 Cb, 2 Cr): the Cb and Cr residual is coded like luma
427 /// but with context sets of its own.
428 #[inline]
429 pub(crate) fn residual_block_c(
430 &mut self,
431 coeff: &mut [i32; 16],
432 cat: BlockCat,
433 comp: u8,
434 na: Option<u8>,
435 nb: Option<u8>,
436 ) -> Result<u8> {
437 match self {
438 Entropy::Cavlc(r) => {
439 let nc = if matches!(cat, BlockCat::ChromaDc(_)) {
440 -1
441 } else if matches!(cat, BlockCat::ChromaDc422(_)) {
442 -2
443 } else {
444 match (na, nb) {
445 (Some(a), Some(b)) => (i32::from(a) + i32::from(b) + 1) >> 1,
446 (Some(a), None) => i32::from(a),
447 (None, Some(b)) => i32::from(b),
448 (None, None) => 0,
449 }
450 };
451 crate::cavlc::residual_block(r, coeff, cat.max_num_coeff(), nc)
452 }
453 Entropy::Cabac(c) => c.residual_block(coeff, cat, comp, na, nb),
454 }
455 }
456
457 /// Decode one 8x8 luma residual block into `coeff[0..64]` in scan order,
458 /// returning the number of non-zero coefficients. CABAC only: a CAVLC 8x8
459 /// block is coded as four interleaved 4x4 blocks (7.3.5.3.1), which the
460 /// caller reads through [`Entropy::residual_block`].
461 ///
462 /// `comp` is the colour component, and `cbf` the neighbouring blocks' counts
463 /// when coded_block_flag is sent for the 8x8 class (ChromaArrayType 3).
464 pub(crate) fn residual_block_8x8(
465 &mut self,
466 coeff: &mut [i32; 64],
467 comp: u8,
468 cbf: Option<(Option<u8>, Option<u8>)>,
469 ) -> Result<u8> {
470 match self {
471 Entropy::Cavlc(_) => Err(Error::corrupt("8x8 residual block read from a CAVLC slice")),
472 Entropy::Cabac(c) => c.residual_block_8x8(coeff, comp, cbf),
473 }
474 }
475
476 /// The raw bytes of an I_PCM macroblock (256 luma plus the chroma samples), after
477 /// alignment. A CABAC reader restarts its arithmetic engine afterwards
478 /// (clause 9.3.1.2).
479 pub(crate) fn pcm_block(&mut self, bd: u32, samples: usize) -> Result<&'a [u8]> {
480 // `samples` samples of `bd` bits: 256 luma plus the chroma ones (384
481 // for 4:2:0, 256 for monochrome, 768 for 4:4:4).
482 let n = samples / 8 * bd as usize;
483 match self {
484 Entropy::Cavlc(r) => {
485 r.align_to_byte();
486 r.read_bytes(n)
487 }
488 Entropy::Cabac(c) => c.pcm_block(bd, samples),
489 }
490 }
491
492 /// True while the slice has another macroblock: `more_rbsp_data()` for
493 /// CAVLC, `!end_of_slice_flag` for CABAC.
494 pub(crate) fn more_macroblocks(&mut self) -> Result<bool> {
495 match self {
496 Entropy::Cavlc(r) => Ok(r.more_rbsp_data()),
497 Entropy::Cabac(c) => c.more_macroblocks(),
498 }
499 }
500}