forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

entropy.rs417 lines, 14.9 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_INTRA_420};
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 /// ChromaACLevel, `ctxBlockCat` 4.
57 ChromaAc,
58 /// LumaLevel8x8, `ctxBlockCat` 5: one 64-coefficient block under
59 /// transform_size_8x8_flag. CABAC codes it whole (no coded_block_flag for
60 /// 4:2:0); CAVLC never sees this category, it codes the block as four
61 /// interleaved `Luma4x4` blocks (7.3.5.3.1).
62 Luma8x8,
63}
64
65impl BlockCat {
66 /// `maxNumCoeff` (Table 9-42).
67 pub(crate) const fn max_num_coeff(self) -> usize {
68 match self {
69 BlockCat::LumaDc | BlockCat::Luma4x4 => 16,
70 BlockCat::LumaAc | BlockCat::ChromaAc => 15,
71 BlockCat::ChromaDc(_) => 4,
72 BlockCat::Luma8x8 => 64,
73 }
74 }
75
76 /// `ctxBlockCat` (Table 9-42).
77 pub(crate) const fn ctx_block_cat(self) -> usize {
78 match self {
79 BlockCat::LumaDc => 0,
80 BlockCat::LumaAc => 1,
81 BlockCat::Luma4x4 => 2,
82 BlockCat::ChromaDc(_) => 3,
83 BlockCat::ChromaAc => 4,
84 BlockCat::Luma8x8 => 5,
85 }
86 }
87}
88
89/// What a context-adaptive reader needs to know about one neighbouring
90/// macroblock.
91#[derive(Clone, Copy)]
92pub(crate) struct MbInfo {
93 /// The `FLAG_*` bits above.
94 pub flags: u8,
95 /// `CodedBlockPatternLuma | CodedBlockPatternChroma << 4`.
96 pub cbp: u8,
97 /// coded_block_flag of the DC blocks: bit 0 luma, bit 1 Cb, bit 2 Cr.
98 pub dc_cbf: u8,
99}
100
101/// Neighbourhood of the macroblock about to be parsed: left (A) and above (B)
102/// per clause 6.4.11.1, `None` when outside the picture or in another slice.
103#[derive(Clone, Copy, Default)]
104pub(crate) struct MbCtx {
105 pub a: Option<MbInfo>,
106 pub b: Option<MbInfo>,
107 /// ctxIdxInc for the first mb_qp_delta bin (clause 9.3.3.1.1.5), derived by
108 /// the caller from the previous macroblock in decoding order.
109 pub qp_delta_inc: u8,
110}
111
112/// The slice-data syntax reader.
113///
114/// The CABAC variant is much the larger of the two (it carries 436 context
115/// variables), and stays inline on purpose: one of these lives per slice on the
116/// stack, so boxing it would trade a compile-time size warning for a heap
117/// allocation in a decode loop that is otherwise allocation free.
118#[allow(clippy::large_enum_variant)]
119pub(crate) enum Entropy<'a> {
120 Cavlc(BitCursor<'a>),
121 Cabac(Cabac<'a>),
122}
123
124impl<'a> Entropy<'a> {
125 /// A CAVLC reader over `rbsp`, positioned just past the slice header.
126 pub(crate) fn cavlc(rbsp: &'a [u8], header_bits: u64) -> Entropy<'a> {
127 Entropy::Cavlc(BitCursor::new(rbsp, header_bits))
128 }
129
130 /// A CABAC reader: consumes the `cabac_alignment_one_bit`s and initialises
131 /// the context variables and the arithmetic decoding engine (clause 9.3.1).
132 /// `init_column` is 0 for I and SI slices, `cabac_init_idc + 1` otherwise.
133 pub(crate) fn cabac(
134 rbsp: &'a [u8],
135 header_bits: u64,
136 slice_qp: i32,
137 init_column: usize,
138 ) -> Result<Entropy<'a>> {
139 Ok(Entropy::Cabac(Cabac::new(
140 rbsp,
141 header_bits,
142 slice_qp,
143 init_column,
144 )?))
145 }
146
147 /// True for the CABAC variant.
148 #[inline]
149 pub(crate) fn is_cabac(&self) -> bool {
150 matches!(self, Entropy::Cabac(_))
151 }
152
153 /// Declare whether the macroblock being parsed is intra coded, which
154 /// CABAC needs for the coded_block_flag contexts of 9.3.3.1.1.9.
155 #[inline]
156 pub(crate) fn set_intra(&mut self, intra: bool) {
157 if let Entropy::Cabac(c) = self {
158 c.set_intra(intra);
159 }
160 }
161
162 /// `mb_skip_run` (7.3.4), CAVLC only.
163 pub(crate) fn mb_skip_run(&mut self) -> Result<u32> {
164 match self {
165 Entropy::Cavlc(r) => r.read_ue(),
166 Entropy::Cabac(_) => Err(Error::corrupt("mb_skip_run in a CABAC slice")),
167 }
168 }
169
170 /// `mb_skip_flag` (7.3.4), CABAC only; `inc` is condTermFlagA +
171 /// condTermFlagB per 9.3.3.1.1.1.
172 pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> Result<bool> {
173 match self {
174 Entropy::Cavlc(_) => Err(Error::corrupt("mb_skip_flag in a CAVLC slice")),
175 Entropy::Cabac(c) => Ok(c.mb_skip_flag(b_slice, inc)),
176 }
177 }
178
179 /// `mb_type` of a P or SP slice: 0..4, or 5 + the I-slice mb_type.
180 pub(crate) fn mb_type_p(&mut self) -> Result<u32> {
181 match self {
182 Entropy::Cavlc(r) => {
183 let t = r.read_ue()?;
184 if t > 30 {
185 return Err(Error::corrupt("P-slice mb_type > 30"));
186 }
187 Ok(t)
188 }
189 Entropy::Cabac(c) => c.mb_type_p(),
190 }
191 }
192
193 /// `mb_type` of a B slice: 0..22, or 23 + the I-slice mb_type.
194 pub(crate) fn mb_type_b(&mut self) -> Result<u32> {
195 match self {
196 Entropy::Cavlc(r) => {
197 let t = r.read_ue()?;
198 if t > 48 {
199 return Err(Error::corrupt("B-slice mb_type > 48"));
200 }
201 Ok(t)
202 }
203 Entropy::Cabac(c) => c.mb_type_b(),
204 }
205 }
206
207 /// `sub_mb_type[ ]` of a P (`b_slice` false) or B macroblock.
208 pub(crate) fn sub_mb_type(&mut self, b_slice: bool) -> Result<u32> {
209 let max = if b_slice { 12 } else { 3 };
210 match self {
211 Entropy::Cavlc(r) => {
212 let t = r.read_ue()?;
213 if t > max {
214 return Err(Error::corrupt("sub_mb_type out of range"));
215 }
216 Ok(t)
217 }
218 Entropy::Cabac(c) => Ok(if b_slice {
219 c.sub_mb_type_b()
220 } else {
221 c.sub_mb_type_p()
222 }),
223 }
224 }
225
226 /// `ref_idx_lX` (7.3.5.1): te(v) over `0..=cmax` for CAVLC, unary with the
227 /// neighbour context of 9.3.3.1.1.6 for CABAC.
228 pub(crate) fn ref_idx(&mut self, cmax: u32, inc: usize) -> Result<u32> {
229 let v = match self {
230 // te(v), clause 9.1.1: a one-valued range is a single inverted bit.
231 Entropy::Cavlc(r) if cmax == 1 => u32::from(!r.read_bit()?),
232 Entropy::Cavlc(r) => r.read_ue()?,
233 Entropy::Cabac(c) => c.ref_idx(inc)?,
234 };
235 if v > cmax {
236 return Err(Error::corrupt("ref_idx beyond num_ref_idx_active"));
237 }
238 Ok(v)
239 }
240
241 /// One `mvd_lX` component (7.3.5.1), in quarter luma samples.
242 pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> {
243 match self {
244 Entropy::Cavlc(r) => r.read_se(),
245 Entropy::Cabac(c) => c.mvd(comp, inc),
246 }
247 }
248
249 /// `coded_block_pattern` of an inter macroblock, as
250 /// `(CodedBlockPatternLuma, CodedBlockPatternChroma)`.
251 pub(crate) fn coded_block_pattern_inter(&mut self) -> Result<(u8, u8)> {
252 match self {
253 Entropy::Cavlc(r) => {
254 let code = r.read_ue()? as usize;
255 let cbp = *CBP_INTER_420
256 .get(code)
257 .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 47"))?;
258 Ok((cbp & 15, cbp >> 4))
259 }
260 Entropy::Cabac(c) => c.coded_block_pattern(),
261 }
262 }
263
264 /// Publish the neighbourhood of the macroblock about to be parsed.
265 #[inline]
266 pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) {
267 if let Entropy::Cabac(c) = self {
268 c.begin_mb(ctx);
269 }
270 }
271
272 /// `mb_type` of an I slice: 0 (I_NxN), 1..24 (Intra_16x16), 25 (I_PCM).
273 pub(crate) fn mb_type_i(&mut self) -> Result<u32> {
274 match self {
275 Entropy::Cavlc(r) => {
276 let t = r.read_ue()?;
277 if t > 25 {
278 return Err(Error::corrupt("I-slice mb_type > 25"));
279 }
280 Ok(t)
281 }
282 Entropy::Cabac(c) => c.mb_type_i(),
283 }
284 }
285
286 /// `transform_size_8x8_flag` (7.3.5).
287 pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {
288 match self {
289 Entropy::Cavlc(r) => r.read_bit(),
290 Entropy::Cabac(c) => c.transform_size_8x8_flag(),
291 }
292 }
293
294 /// One 4x4 intra prediction mode: `None` selects the predicted mode,
295 /// `Some(rem)` the `rem_intra4x4_pred_mode` value (7.3.5.1).
296 #[inline]
297 pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> {
298 match self {
299 Entropy::Cavlc(r) => {
300 if r.read_bit()? {
301 Ok(None)
302 } else {
303 Ok(Some(r.read_bits(3)? as u8))
304 }
305 }
306 Entropy::Cabac(c) => c.intra4x4_pred_mode(),
307 }
308 }
309
310 /// `intra_chroma_pred_mode` (7.3.5.1), 0..3.
311 pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> {
312 match self {
313 Entropy::Cavlc(r) => {
314 let m = r.read_ue()?;
315 if m > 3 {
316 return Err(Error::corrupt("intra_chroma_pred_mode > 3"));
317 }
318 Ok(m as u8)
319 }
320 Entropy::Cabac(c) => c.intra_chroma_pred_mode(),
321 }
322 }
323
324 /// `coded_block_pattern` of an Intra_4x4 macroblock, as
325 /// `(CodedBlockPatternLuma, CodedBlockPatternChroma)`.
326 pub(crate) fn coded_block_pattern_intra(&mut self) -> Result<(u8, u8)> {
327 match self {
328 Entropy::Cavlc(r) => {
329 // me(v), clause 9.1.2 Table 9-4.
330 let code = r.read_ue()? as usize;
331 let cbp = *CBP_INTRA_420
332 .get(code)
333 .ok_or_else(|| Error::corrupt("coded_block_pattern codeNum > 47"))?;
334 Ok((cbp & 15, cbp >> 4))
335 }
336 Entropy::Cabac(c) => c.coded_block_pattern(),
337 }
338 }
339
340 /// `mb_qp_delta` (7.4.5), already range checked.
341 pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {
342 let delta = match self {
343 Entropy::Cavlc(r) => r.read_se()?,
344 Entropy::Cabac(c) => c.mb_qp_delta()?,
345 };
346 if !(-26..=25).contains(&delta) {
347 return Err(Error::corrupt("mb_qp_delta outside [-26, 25]"));
348 }
349 Ok(delta)
350 }
351
352 /// Decode one residual block into `coeff[0..cat.max_num_coeff()]` in scan
353 /// order, returning the number of non-zero coefficients.
354 ///
355 /// `na`/`nb` are the same counts for the left and above neighbouring blocks
356 /// of the same class, `None` when that neighbour is unavailable. CAVLC
357 /// averages them into nC (9.2.1); CABAC turns them into the
358 /// coded_block_flag context increment (9.3.3.1.1.9).
359 #[inline]
360 pub(crate) fn residual_block(
361 &mut self,
362 coeff: &mut [i32; 16],
363 cat: BlockCat,
364 na: Option<u8>,
365 nb: Option<u8>,
366 ) -> Result<u8> {
367 match self {
368 Entropy::Cavlc(r) => {
369 let nc = if matches!(cat, BlockCat::ChromaDc(_)) {
370 -1
371 } else {
372 match (na, nb) {
373 (Some(a), Some(b)) => (i32::from(a) + i32::from(b) + 1) >> 1,
374 (Some(a), None) => i32::from(a),
375 (None, Some(b)) => i32::from(b),
376 (None, None) => 0,
377 }
378 };
379 crate::cavlc::residual_block(r, coeff, cat.max_num_coeff(), nc)
380 }
381 Entropy::Cabac(c) => c.residual_block(coeff, cat, na, nb),
382 }
383 }
384
385 /// Decode one 8x8 luma residual block into `coeff[0..64]` in scan order,
386 /// returning the number of non-zero coefficients. CABAC only: a CAVLC 8x8
387 /// block is coded as four interleaved 4x4 blocks (7.3.5.3.1), which the
388 /// caller reads through [`Entropy::residual_block`].
389 pub(crate) fn residual_block_8x8(&mut self, coeff: &mut [i32; 64]) -> Result<u8> {
390 match self {
391 Entropy::Cavlc(_) => Err(Error::corrupt("8x8 residual block read from a CAVLC slice")),
392 Entropy::Cabac(c) => c.residual_block_8x8(coeff),
393 }
394 }
395
396 /// The 384 raw bytes of an I_PCM macroblock (256 luma, 2x64 chroma), after
397 /// alignment. A CABAC reader restarts its arithmetic engine afterwards
398 /// (clause 9.3.1.2).
399 pub(crate) fn pcm_block(&mut self) -> Result<&'a [u8]> {
400 match self {
401 Entropy::Cavlc(r) => {
402 r.align_to_byte();
403 r.read_bytes(384)
404 }
405 Entropy::Cabac(c) => c.pcm_block(),
406 }
407 }
408
409 /// True while the slice has another macroblock: `more_rbsp_data()` for
410 /// CAVLC, `!end_of_slice_flag` for CABAC.
411 pub(crate) fn more_macroblocks(&mut self) -> Result<bool> {
412 match self {
413 Entropy::Cavlc(r) => Ok(r.more_rbsp_data()),
414 Entropy::Cabac(c) => c.more_macroblocks(),
415 }
416 }
417}