forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB03dc6e9Tahinli3 months ago178 commits

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