forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8dbd683Tahinli3 months ago856 commits

cabac.rs1000 lines, 34.9 KiBHistoryRawDownload
1//! CABAC slice-data parsing (spec clause 9.3): arithmetic decoding engine,
2//! context variables, binarizations and context selection.
3//!
4//! Scope is what a frame-coded 4:2:0 8-bit stream needs, I, P and B, with or
5//! without the High-profile 8x8 transform; every other tool the decoder refuses
6//! by name before reaching this module, so the contexts, block categories and
7//! initialisation columns that only field or 4:4:4 coding reads are absent
8//! rather than transcribed untested.
9//!
10//! The engine keeps codIRange and codIOffset in `u32` with the spec's exact
11//! integer steps — no probability floats, no shortcuts — and reads its bits
12//! from the same [`BitCursor`] the CAVLC path uses. Past the end of the RBSP the
13//! cursor is treated as zero-filled: a conformant stream never depends on those
14//! bits (the last one read is the rbsp_stop_one_bit), and the macroblock loop,
15//! not the bit supply, is what bounds a truncated one.
16
17use ec_core::error::{Error, Result};
18
19use crate::bits::BitCursor;
20use crate::cabac_tables::{
21 INIT_11_59, INIT_60_69, INIT_70_275, INIT_399_401, INIT_402_435, INIT_MB_TYPE_I, LAST_8X8,
22 RANGE_LPS, SIG_8X8_FRAME, TRANS_LPS, TRANS_MPS,
23};
24use crate::entropy::{
25 BlockCat, FLAG_CHROMA_PRED, FLAG_DIRECT, FLAG_I16, FLAG_INTER, FLAG_PCM, FLAG_TRANS8X8, MbCtx,
26 MbInfo,
27};
28
29/// Highest ctxIdx this decoder can address, plus one (426..435 is
30/// coeff_abs_level_minus1 of the 8x8 luma category, the last range a
31/// frame-coded 4:2:0 slice reaches; 436 and up are the field-coded and 4:4:4
32/// categories this decoder refuses by name).
33pub(crate) const NUM_CTX: usize = 436;
34
35/// ctxIdx 276 (end_of_slice_flag and the I_PCM bin of mb_type) is decoded by
36/// DecodeTerminate and has no adapting state.
37const CTX_TERMINATE: usize = 276;
38
39/// Table 9-40, `ctxIdxBlockCatOffset` for the five 4:2:0 block categories.
40pub(crate) const CBF_CAT_OFF: [usize; 5] = [0, 4, 8, 12, 16];
41pub(crate) const SIG_CAT_OFF: [usize; 5] = [0, 15, 29, 44, 47];
42pub(crate) const ABS_CAT_OFF: [usize; 5] = [0, 10, 20, 30, 39];
43
44/// ctxIdxOffset values of Table 9-34 used here.
45pub(crate) const OFF_MB_TYPE: usize = 3;
46pub(crate) const OFF_SKIP_P: usize = 11;
47pub(crate) const OFF_MB_TYPE_P: usize = 14;
48pub(crate) const OFF_SUB_TYPE_P: usize = 21;
49const OFF_SKIP_B: usize = 24;
50const OFF_MB_TYPE_B: usize = 27;
51const OFF_SUB_TYPE_B: usize = 36;
52pub(crate) const OFF_MVD: [usize; 2] = [40, 47];
53const OFF_REF_IDX: usize = 54;
54pub(crate) const OFF_QP_DELTA: usize = 60;
55pub(crate) const OFF_CHROMA_PRED: usize = 64;
56pub(crate) const OFF_PREV_I4: usize = 68;
57pub(crate) const OFF_REM_I4: usize = 69;
58pub(crate) const OFF_CBP_LUMA: usize = 73;
59pub(crate) const OFF_CBP_CHROMA: usize = 77;
60pub(crate) const OFF_CBF: usize = 85;
61pub(crate) const OFF_SIG: usize = 105;
62pub(crate) const OFF_LAST: usize = 166;
63pub(crate) const OFF_ABS: usize = 227;
64pub(crate) const OFF_TRANSFORM_8X8: usize = 399;
65/// significant_coeff_flag / last_significant_coeff_flag / coeff_abs_level_minus1
66/// of ctxBlockCat 5 (frame coded), Table 9-34.
67pub(crate) const OFF_SIG_8X8: usize = 402;
68pub(crate) const OFF_LAST_8X8: usize = 417;
69pub(crate) const OFF_ABS_8X8: usize = 426;
70
71/// The ctxIdx values the Intra_16x16 part of an mb_type bin string uses, in
72/// bin order: `[b0, CodedBlockPatternLuma, chroma bin 0, chroma bin 1,
73/// prediction mode bin 0, prediction mode bin 1]`.
74///
75/// Table 9-39 lists these per binIdx, but the chroma element is one or two bins
76/// long, which shifts the prediction-mode bins; resolving the table to fixed
77/// ctxIdx values here is what makes the two spellings (I slice at ctxIdxOffset
78/// 3, intra suffix at 17 or 32) one piece of code.
79pub(crate) const I_MB_TYPE_CTX: [usize; 6] = [3, 6, 7, 8, 9, 10];
80pub(crate) const I_SUFFIX_CTX_P: [usize; 6] = [17, 18, 19, 19, 20, 20];
81const I_SUFFIX_CTX_B: [usize; 6] = [32, 33, 34, 34, 35, 35];
82
83/// Where a slice's bits went, in 1/256ths of a bit, by syntax class. The
84/// arithmetic decoder spends fractional bits per element, so the sub-bit
85/// resolution is the point: a class is charged the movement of
86/// `bit_position * 256 + log2(codIRange)` across its own reads. Both our
87/// streams and any other encoder's are parsed by this decoder, which is what
88/// makes the two accounts comparable.
89#[derive(Clone, Copy, Default, Debug)]
90pub struct BitAccount {
91 pub skip: u64,
92 pub mb_type: u64,
93 pub mv: u64,
94 pub ref_idx: u64,
95 pub cbp_qp: u64,
96 pub intra_mode: u64,
97 pub residual_luma: u64,
98 pub residual_chroma: u64,
99}
100
101impl BitAccount {
102 /// Every class summed, in 1/256ths of a bit.
103 pub fn total(&self) -> u64 {
104 self.skip
105 + self.mb_type
106 + self.mv
107 + self.ref_idx
108 + self.cbp_qp
109 + self.intra_mode
110 + self.residual_luma
111 + self.residual_chroma
112 }
113
114 pub(crate) fn add(&mut self, other: &BitAccount) {
115 self.skip += other.skip;
116 self.mb_type += other.mb_type;
117 self.mv += other.mv;
118 self.ref_idx += other.ref_idx;
119 self.cbp_qp += other.cbp_qp;
120 self.intra_mode += other.intra_mode;
121 self.residual_luma += other.residual_luma;
122 self.residual_chroma += other.residual_chroma;
123 }
124}
125
126pub(crate) struct Cabac<'a> {
127 r: BitCursor<'a>,
128 /// codIRange (9.3.3.2).
129 range: u32,
130 /// codIOffset (9.3.3.2).
131 offset: u32,
132 /// Context variables: `pStateIdx << 1 | valMPS`, indexed by ctxIdx.
133 state: [u8; NUM_CTX],
134 /// Neighbourhood of the macroblock being parsed.
135 ctx: MbCtx,
136 /// CodedBlockPatternLuma bins decoded so far in this macroblock, for the
137 /// within-macroblock neighbours of clause 9.3.3.1.1.4.
138 cbp_luma_bins: u8,
139 /// The macroblock being parsed is intra coded, which flips the
140 /// coded_block_flag context of an unavailable neighbour (9.3.3.1.1.9).
141 cur_intra: bool,
142 /// Bits spent so far, by syntax class.
143 account: BitAccount,
144}
145
146impl<'a> Cabac<'a> {
147 /// Start CABAC parsing at `header_bits`: `cabac_alignment_one_bit`s, then
148 /// the context and engine initialisation of clause 9.3.1.
149 ///
150 /// `init_column` selects the initialisation column: 0 for I and SI slices,
151 /// `cabac_init_idc + 1` otherwise.
152 pub(crate) fn new(
153 rbsp: &'a [u8],
154 header_bits: u64,
155 slice_qp: i32,
156 init_column: usize,
157 ) -> Result<Cabac<'a>> {
158 let mut r = BitCursor::new(rbsp, header_bits);
159 // cabac_alignment_one_bit (7.3.4): the stuffing bits are all 1, which
160 // a corrupt-stream check would only duplicate; skipping to the byte
161 // boundary is the whole effect.
162 r.align_to_byte();
163 let mut c = Cabac {
164 r,
165 range: 510,
166 offset: 0,
167 state: [63 << 1; NUM_CTX],
168 ctx: MbCtx::default(),
169 cbp_luma_bins: 0,
170 cur_intra: true,
171 account: BitAccount::default(),
172 };
173 c.state = init_contexts(slice_qp, init_column.min(3));
174 c.init_engine()?;
175 Ok(c)
176 }
177
178 /// 9.3.1.2: codIRange = 510, codIOffset = read_bits(9).
179 fn init_engine(&mut self) -> Result<()> {
180 self.range = 510;
181 self.offset = self.r.read_bits(9)?;
182 if self.offset >= 510 {
183 return Err(Error::corrupt("CABAC codIOffset initialised to 510 or 511"));
184 }
185 Ok(())
186 }
187
188 /// One bit of slice data; zero past the end (see the module note).
189 #[inline]
190 fn bit(&mut self) -> u32 {
191 u32::from(self.r.read_bit().unwrap_or(false))
192 }
193
194 /// 9.3.3.2.2 RenormD.
195 #[inline]
196 fn renorm(&mut self) {
197 while self.range < 256 {
198 self.range <<= 1;
199 self.offset = (self.offset << 1) | self.bit();
200 }
201 }
202
203 /// 9.3.3.2.1 DecodeDecision, with the state transition of 9.3.3.2.1.1.
204 #[inline]
205 fn decision(&mut self, ctx_idx: usize) -> bool {
206 let s = self.state[ctx_idx];
207 let p = usize::from(s >> 1);
208 let mps = s & 1;
209 let lps = u32::from(RANGE_LPS[p][((self.range >> 6) & 3) as usize]);
210 self.range -= lps;
211 let bin;
212 if self.offset >= self.range {
213 bin = mps ^ 1;
214 self.offset -= self.range;
215 self.range = lps;
216 // Crossing state 0 swaps the most probable symbol.
217 let mps = if p == 0 { mps ^ 1 } else { mps };
218 self.state[ctx_idx] = (TRANS_LPS[p] << 1) | mps;
219 } else {
220 bin = mps;
221 self.state[ctx_idx] = (TRANS_MPS[p] << 1) | mps;
222 }
223 self.renorm();
224 bin != 0
225 }
226
227 /// 9.3.3.2.3 DecodeBypass.
228 #[inline]
229 fn bypass(&mut self) -> bool {
230 self.offset = (self.offset << 1) | self.bit();
231 if self.offset >= self.range {
232 self.offset -= self.range;
233 true
234 } else {
235 false
236 }
237 }
238
239 /// 9.3.3.2.4 DecodeTerminate.
240 #[inline]
241 fn terminate(&mut self) -> bool {
242 self.range -= 2;
243 if self.offset >= self.range {
244 true
245 } else {
246 self.renorm();
247 false
248 }
249 }
250
251 pub(crate) fn begin_mb(&mut self, ctx: &MbCtx) {
252 self.ctx = *ctx;
253 self.cbp_luma_bins = 0;
254 self.cur_intra = true;
255 }
256
257 /// Declare whether the macroblock being parsed is intra coded
258 /// (9.3.3.1.1.9 reads it for every coded_block_flag).
259 /// The decoder's position in 1/256ths of a bit: the bits already read plus
260 /// what the arithmetic engine's interval says it is holding.
261 fn mark(&self) -> u64 {
262 self.r.bit_position() * 256 + u64::from(self.range.leading_zeros())
263 }
264
265 pub(crate) fn account(&self) -> BitAccount {
266 self.account
267 }
268
269 pub(crate) fn mb_type_i(&mut self) -> Result<u32> {
270 let m = self.mark();
271 let out = self.mb_type_i_inner();
272 self.account.mb_type += self.mark() - m;
273 out
274 }
275
276 pub(crate) fn mb_type_p(&mut self) -> Result<u32> {
277 let m = self.mark();
278 let out = self.mb_type_p_inner();
279 self.account.mb_type += self.mark() - m;
280 out
281 }
282
283 pub(crate) fn mb_type_b(&mut self) -> Result<u32> {
284 let m = self.mark();
285 let out = self.mb_type_b_inner();
286 self.account.mb_type += self.mark() - m;
287 out
288 }
289
290 pub(crate) fn sub_mb_type_p(&mut self) -> u32 {
291 let m = self.mark();
292 let out = self.sub_mb_type_p_inner();
293 self.account.mb_type += self.mark() - m;
294 out
295 }
296
297 pub(crate) fn sub_mb_type_b(&mut self) -> u32 {
298 let m = self.mark();
299 let out = self.sub_mb_type_b_inner();
300 self.account.mb_type += self.mark() - m;
301 out
302 }
303
304 pub(crate) fn mb_skip_flag(&mut self, b_slice: bool, inc: usize) -> bool {
305 let m = self.mark();
306 let out = self.mb_skip_flag_inner(b_slice, inc);
307 self.account.skip += self.mark() - m;
308 out
309 }
310
311 pub(crate) fn ref_idx(&mut self, inc: usize) -> Result<u32> {
312 let m = self.mark();
313 let out = self.ref_idx_inner(inc);
314 self.account.ref_idx += self.mark() - m;
315 out
316 }
317
318 pub(crate) fn mvd(&mut self, comp: usize, inc: usize) -> Result<i32> {
319 let m = self.mark();
320 let out = self.mvd_inner(comp, inc);
321 self.account.mv += self.mark() - m;
322 out
323 }
324
325 pub(crate) fn transform_size_8x8_flag(&mut self) -> Result<bool> {
326 let m = self.mark();
327 let out = self.transform_size_8x8_flag_inner();
328 self.account.cbp_qp += self.mark() - m;
329 out
330 }
331
332 pub(crate) fn coded_block_pattern(&mut self) -> Result<(u8, u8)> {
333 let m = self.mark();
334 let out = self.coded_block_pattern_inner();
335 self.account.cbp_qp += self.mark() - m;
336 out
337 }
338
339 pub(crate) fn mb_qp_delta(&mut self) -> Result<i32> {
340 let m = self.mark();
341 let out = self.mb_qp_delta_inner();
342 self.account.cbp_qp += self.mark() - m;
343 out
344 }
345
346 pub(crate) fn intra4x4_pred_mode(&mut self) -> Result<Option<u8>> {
347 let m = self.mark();
348 let out = self.intra4x4_pred_mode_inner();
349 self.account.intra_mode += self.mark() - m;
350 out
351 }
352
353 pub(crate) fn intra_chroma_pred_mode(&mut self) -> Result<u8> {
354 let m = self.mark();
355 let out = self.intra_chroma_pred_mode_inner();
356 self.account.intra_mode += self.mark() - m;
357 out
358 }
359
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 let m = self.mark();
368 let out = self.residual_block_inner(coeff, cat, na, nb);
369 let spent = self.mark() - m;
370 match cat {
371 BlockCat::ChromaDc(_) | BlockCat::ChromaAc => self.account.residual_chroma += spent,
372 _ => self.account.residual_luma += spent,
373 }
374 out
375 }
376
377 pub(crate) fn set_intra(&mut self, intra: bool) {
378 self.cur_intra = intra;
379 }
380
381 /// 9.3.3.1.1.3: condTermFlagA + condTermFlagB for mb_type. At ctxIdxOffset
382 /// 3 a neighbour counts unless it is I_NxN; at 27 (B slices) unless it is
383 /// B_Skip or B_Direct_16x16.
384 fn mb_type_inc(&self, offset: usize) -> usize {
385 let cond = |n: Option<MbInfo>| match n {
386 None => 0,
387 Some(i) if offset == OFF_MB_TYPE => usize::from(i.flags & (FLAG_I16 | FLAG_PCM) != 0),
388 Some(i) => usize::from(i.flags & FLAG_DIRECT == 0),
389 };
390 cond(self.ctx.a) + cond(self.ctx.b)
391 }
392
393 /// mb_type of an I slice (Table 9-36).
394 fn mb_type_i_inner(&mut self) -> Result<u32> {
395 let mut ctx = I_MB_TYPE_CTX;
396 ctx[0] = OFF_MB_TYPE + self.mb_type_inc(OFF_MB_TYPE);
397 self.mb_type_intra(&ctx)
398 }
399
400 /// The Intra part of an mb_type bin string (Table 9-36), whose `ctx` is
401 /// resolved by [`I_MB_TYPE_CTX`]. `ctx[0]` has already had its neighbour
402 /// increment applied where the offset uses one.
403 fn mb_type_intra(&mut self, ctx: &[usize; 6]) -> Result<u32> {
404 if !self.decision(ctx[0]) {
405 return Ok(0); // I_NxN
406 }
407 if self.terminate() {
408 return Ok(25); // I_PCM
409 }
410 let cbp_luma = u32::from(self.decision(ctx[1]));
411 let chroma = if !self.decision(ctx[2]) {
412 0
413 } else if self.decision(ctx[3]) {
414 2
415 } else {
416 1
417 };
418 let mode = u32::from(self.decision(ctx[4])) * 2 + u32::from(self.decision(ctx[5]));
419 Ok(1 + mode + chroma * 4 + cbp_luma * 12)
420 }
421
422 /// mb_skip_flag (9.3.3.1.1.1); `inc` is condTermFlagA + condTermFlagB.
423 fn mb_skip_flag_inner(&mut self, b_slice: bool, inc: usize) -> bool {
424 let off = if b_slice { OFF_SKIP_B } else { OFF_SKIP_P };
425 self.decision(off + inc)
426 }
427
428 /// mb_type of a P or SP slice (Table 9-37): values 0..3, or 5 + the I-slice
429 /// mb_type for an intra macroblock.
430 fn mb_type_p_inner(&mut self) -> Result<u32> {
431 if self.decision(OFF_MB_TYPE_P) {
432 return Ok(5 + self.mb_type_intra(&I_SUFFIX_CTX_P)?);
433 }
434 let b1 = self.decision(OFF_MB_TYPE_P + 1);
435 // Table 9-41: binIdx 2 takes ctxIdxInc 2 when b1 is not 1, else 3.
436 let b2 = self.decision(OFF_MB_TYPE_P + if b1 { 3 } else { 2 });
437 Ok(match (b1, b2) {
438 (false, false) => 0, // P_L0_16x16
439 (false, true) => 3, // P_8x8
440 (true, true) => 1, // P_L0_L0_16x8
441 (true, false) => 2, // P_L0_L0_8x16
442 })
443 }
444
445 /// mb_type of a B slice (Table 9-37): values 0..22, or 23 + the I-slice
446 /// mb_type for an intra macroblock.
447 fn mb_type_b_inner(&mut self) -> Result<u32> {
448 if !self.decision(OFF_MB_TYPE_B + self.mb_type_inc(OFF_MB_TYPE_B)) {
449 return Ok(0); // B_Direct_16x16
450 }
451 if !self.decision(OFF_MB_TYPE_B + 3) {
452 // "10x": B_L0_16x16 or B_L1_16x16. binIdx 2 with b1 == 0 takes 5.
453 return Ok(1 + u32::from(self.decision(OFF_MB_TYPE_B + 5)));
454 }
455 let tail = OFF_MB_TYPE_B + 5;
456 if !self.decision(OFF_MB_TYPE_B + 4) {
457 // "110" + three bins: 3..10.
458 let mut v = 0u32;
459 for _ in 0..3 {
460 v = v * 2 + u32::from(self.decision(tail));
461 }
462 return Ok(3 + v);
463 }
464 if !self.decision(tail) {
465 // "1110" + three bins: 12..19.
466 let mut v = 0u32;
467 for _ in 0..3 {
468 v = v * 2 + u32::from(self.decision(tail));
469 }
470 return Ok(12 + v);
471 }
472 if self.decision(tail) {
473 // "11111": B_L1_L0_8x16 or B_8x8.
474 return Ok(if self.decision(tail) { 22 } else { 11 });
475 }
476 if self.decision(tail) {
477 // "111101": the intra prefix.
478 return Ok(23 + self.mb_type_intra(&I_SUFFIX_CTX_B)?);
479 }
480 // "111100" + one bin: B_Bi_Bi_16x8 or B_Bi_Bi_8x16.
481 Ok(20 + u32::from(self.decision(tail)))
482 }
483
484 /// sub_mb_type of a P macroblock (Table 9-38).
485 fn sub_mb_type_p_inner(&mut self) -> u32 {
486 if self.decision(OFF_SUB_TYPE_P) {
487 return 0;
488 }
489 if !self.decision(OFF_SUB_TYPE_P + 1) {
490 return 1;
491 }
492 if self.decision(OFF_SUB_TYPE_P + 2) {
493 2
494 } else {
495 3
496 }
497 }
498
499 /// sub_mb_type of a B macroblock (Table 9-38).
500 fn sub_mb_type_b_inner(&mut self) -> u32 {
501 if !self.decision(OFF_SUB_TYPE_B) {
502 return 0; // B_Direct_8x8
503 }
504 let tail = OFF_SUB_TYPE_B + 3;
505 if !self.decision(OFF_SUB_TYPE_B + 1) {
506 return 1 + u32::from(self.decision(tail));
507 }
508 if !self.decision(OFF_SUB_TYPE_B + 2) {
509 let v = u32::from(self.decision(tail)) * 2 + u32::from(self.decision(tail));
510 return 3 + v;
511 }
512 if !self.decision(tail) {
513 let v = u32::from(self.decision(tail)) * 2 + u32::from(self.decision(tail));
514 return 7 + v;
515 }
516 11 + u32::from(self.decision(tail))
517 }
518
519 /// ref_idx_lX: unary, with the neighbour increment of 9.3.3.1.1.6 on the
520 /// first bin (Table 9-39 row 54).
521 fn ref_idx_inner(&mut self, inc: usize) -> Result<u32> {
522 if !self.decision(OFF_REF_IDX + inc) {
523 return Ok(0);
524 }
525 if !self.decision(OFF_REF_IDX + 4) {
526 return Ok(1);
527 }
528 let mut v = 2u32;
529 while self.decision(OFF_REF_IDX + 5) {
530 v += 1;
531 if v > 32 {
532 return Err(Error::corrupt("ref_idx bin string too long"));
533 }
534 }
535 Ok(v)
536 }
537
538 /// mvd_lX component `comp` (0 horizontal, 1 vertical): UEG3 with
539 /// signedValFlag 1 and uCoff 9 (clause 9.3.2.3), `inc` from 9.3.3.1.1.7.
540 fn mvd_inner(&mut self, comp: usize, inc: usize) -> Result<i32> {
541 let off = OFF_MVD[comp];
542 if !self.decision(off + inc) {
543 return Ok(0);
544 }
545 let mut prefix = 1u32;
546 // Table 9-39: binIdx 1..4 take 3..6, binIdx 5 and beyond take 6.
547 while prefix < 9 {
548 let ctx = off + (2 + prefix as usize).min(6);
549 if !self.decision(ctx) {
550 break;
551 }
552 prefix += 1;
553 }
554 let abs = if prefix < 9 {
555 prefix
556 } else {
557 9 + self.ueg_suffix(3)?
558 };
559 let value = i32::try_from(abs).map_err(|_| Error::corrupt("mvd out of range"))?;
560 Ok(if self.bypass() { -value } else { value })
561 }
562
563 /// transform_size_8x8_flag (9.3.3.1.1.10): a neighbour counts when it is
564 /// available and carried the flag itself.
565 fn transform_size_8x8_flag_inner(&mut self) -> Result<bool> {
566 let cond = |n: Option<MbInfo>| match n {
567 None => 0,
568 Some(i) => usize::from(i.flags & FLAG_TRANS8X8 != 0),
569 };
570 let inc = cond(self.ctx.a) + cond(self.ctx.b);
571 Ok(self.decision(OFF_TRANSFORM_8X8 + inc))
572 }
573
574 /// prev_intra4x4_pred_mode_flag, then rem_intra4x4_pred_mode as FL cMax=7
575 /// with binIdx 0 the least significant bit.
576 fn intra4x4_pred_mode_inner(&mut self) -> Result<Option<u8>> {
577 if self.decision(OFF_PREV_I4) {
578 return Ok(None);
579 }
580 let mut rem = 0u8;
581 for bit in 0..3 {
582 rem |= u8::from(self.decision(OFF_REM_I4)) << bit;
583 }
584 Ok(Some(rem))
585 }
586
587 /// intra_chroma_pred_mode: TU cMax=3, ctxIdxInc from 9.3.3.1.1.8.
588 fn intra_chroma_pred_mode_inner(&mut self) -> Result<u8> {
589 let cond = |n: Option<MbInfo>| match n {
590 None => 0,
591 Some(i) => usize::from(
592 i.flags & (FLAG_PCM | FLAG_INTER) == 0 && i.flags & FLAG_CHROMA_PRED != 0,
593 ),
594 };
595 let inc = cond(self.ctx.a) + cond(self.ctx.b);
596 if !self.decision(OFF_CHROMA_PRED + inc) {
597 return Ok(0);
598 }
599 if !self.decision(OFF_CHROMA_PRED + 3) {
600 return Ok(1);
601 }
602 Ok(if self.decision(OFF_CHROMA_PRED + 3) {
603 3
604 } else {
605 2
606 })
607 }
608
609 /// coded_block_pattern (9.3.2.6): FL cMax=15 luma prefix, TU cMax=2 chroma
610 /// suffix, both with the neighbour contexts of 9.3.3.1.1.4.
611 fn coded_block_pattern_inner(&mut self) -> Result<(u8, u8)> {
612 for bin in 0..4u8 {
613 // 6.4.11.2: the 8x8 block left of / above block `bin`, which for
614 // blocks 1, 2 and 3 can be inside this macroblock.
615 let (a, b) = match bin {
616 0 => (
617 self.cbp_luma_neighbour(self.ctx.a, 1),
618 self.cbp_luma_neighbour(self.ctx.b, 2),
619 ),
620 1 => (self.cbp_luma_own(0), self.cbp_luma_neighbour(self.ctx.b, 3)),
621 2 => (self.cbp_luma_neighbour(self.ctx.a, 3), self.cbp_luma_own(0)),
622 _ => (self.cbp_luma_own(2), self.cbp_luma_own(1)),
623 };
624 if self.decision(OFF_CBP_LUMA + a + 2 * b) {
625 self.cbp_luma_bins |= 1 << bin;
626 }
627 }
628 let luma = self.cbp_luma_bins;
629 let chroma_cond = |n: Option<MbInfo>, bin: u8| match n {
630 None => 0,
631 Some(i) if i.flags & FLAG_PCM != 0 => 1,
632 Some(i) => {
633 let c = i.cbp >> 4;
634 usize::from(if bin == 0 { c != 0 } else { c == 2 })
635 }
636 };
637 let inc0 = chroma_cond(self.ctx.a, 0) + 2 * chroma_cond(self.ctx.b, 0);
638 let chroma = if !self.decision(OFF_CBP_CHROMA + inc0) {
639 0
640 } else {
641 let inc1 = chroma_cond(self.ctx.a, 1) + 2 * chroma_cond(self.ctx.b, 1) + 4;
642 if self.decision(OFF_CBP_CHROMA + inc1) {
643 2
644 } else {
645 1
646 }
647 };
648 Ok((luma, chroma))
649 }
650
651 /// condTermFlagN for a coded_block_pattern luma bin whose neighbouring 8x8
652 /// block lies in another macroblock: set when that block has no coefficients.
653 fn cbp_luma_neighbour(&self, n: Option<MbInfo>, blk: u8) -> usize {
654 match n {
655 None => 0,
656 Some(i) if i.flags & FLAG_PCM != 0 => 0,
657 Some(i) => usize::from(i.cbp & (1 << blk) == 0),
658 }
659 }
660
661 /// The same for a neighbouring 8x8 block inside this macroblock, read from
662 /// the bins already decoded.
663 fn cbp_luma_own(&self, blk: u8) -> usize {
664 usize::from(self.cbp_luma_bins & (1 << blk) == 0)
665 }
666
667 /// mb_qp_delta: unary bin string of the Table 9-3 mapped value.
668 fn mb_qp_delta_inner(&mut self) -> Result<i32> {
669 let mut k = 0i32;
670 while self.decision(OFF_QP_DELTA + qp_delta_inc(k, usize::from(self.ctx.qp_delta_inc))) {
671 k += 1;
672 if k > 52 {
673 return Err(Error::corrupt("mb_qp_delta bin string too long"));
674 }
675 }
676 Ok(if k % 2 == 1 { (k + 1) / 2 } else { -(k / 2) })
677 }
678
679 /// residual_block_cabac (7.3.5.3.3) for one block, in scan order.
680 fn residual_block_inner(
681 &mut self,
682 coeff: &mut [i32; 16],
683 cat: BlockCat,
684 na: Option<u8>,
685 nb: Option<u8>,
686 ) -> Result<u8> {
687 *coeff = [0; 16];
688 let cat_i = cat.ctx_block_cat();
689 let max = cat.max_num_coeff();
690
691 // coded_block_flag (9.3.3.1.1.9). An unavailable neighbour counts as
692 // set for an intra macroblock and clear for an inter one; the caller
693 // has already folded I_PCM (all coefficients present) and P_Skip /
694 // B_Skip (none) into the neighbouring counts.
695 let intra = self.cur_intra;
696 let cond = |n: Option<u8>| match n {
697 None => usize::from(intra),
698 Some(v) => usize::from(v != 0),
699 };
700 let (a, b) = match cat {
701 // The DC blocks' neighbours are per macroblock, not per 4x4 block.
702 BlockCat::LumaDc => (self.dc_cbf(self.ctx.a, 0), self.dc_cbf(self.ctx.b, 0)),
703 BlockCat::ChromaDc(c) => (
704 self.dc_cbf(self.ctx.a, 1 + c),
705 self.dc_cbf(self.ctx.b, 1 + c),
706 ),
707 _ => (cond(na), cond(nb)),
708 };
709 if !self.decision(OFF_CBF + CBF_CAT_OFF[cat_i] + a + 2 * b) {
710 return Ok(0);
711 }
712
713 // Significance map: significant_coeff_flag / last_significant_coeff_flag
714 // over scanning positions 0..maxNumCoeff-1.
715 let sig_base = OFF_SIG + SIG_CAT_OFF[cat_i];
716 let last_base = OFF_LAST + SIG_CAT_OFF[cat_i];
717 let mut sig = [false; 16];
718 let mut num = max;
719 let mut i = 0;
720 while i + 1 < num {
721 let inc = sig_inc(cat, i);
722 if self.decision(sig_base + inc) {
723 sig[i] = true;
724 if self.decision(last_base + inc) {
725 num = i + 1;
726 }
727 }
728 i += 1;
729 }
730 sig[num - 1] = true;
731
732 self.decode_levels(coeff, &sig, num, OFF_ABS + ABS_CAT_OFF[cat_i], cat_i == 3)
733 }
734
735 /// residual_block_cabac for a luma 8x8 block (ctxBlockCat 5).
736 ///
737 /// There is no coded_block_flag here: with ChromaArrayType other than 3,
738 /// 7.3.5.3.3 sends the flag only when maxNumCoeff differs from 64, so the
739 /// coded_block_pattern bit that selected this block is the whole signal and
740 /// the flag is inferred to be 1.
741 pub(crate) fn residual_block_8x8(&mut self, coeff: &mut [i32; 64]) -> Result<u8> {
742 let m = self.mark();
743 let out = self.residual_block_8x8_inner(coeff);
744 self.account.residual_luma += self.mark() - m;
745 out
746 }
747
748 fn residual_block_8x8_inner(&mut self, coeff: &mut [i32; 64]) -> Result<u8> {
749 *coeff = [0; 64];
750 let mut sig = [false; 64];
751 let mut num = 64;
752 let mut i = 0;
753 while i + 1 < num {
754 if self.decision(OFF_SIG_8X8 + usize::from(SIG_8X8_FRAME[i])) {
755 sig[i] = true;
756 if self.decision(OFF_LAST_8X8 + usize::from(LAST_8X8[i])) {
757 num = i + 1;
758 }
759 }
760 i += 1;
761 }
762 sig[num - 1] = true;
763 self.decode_levels(coeff, &sig, num, OFF_ABS_8X8, false)
764 }
765
766 /// coeff_abs_level_minus1 and coeff_sign_flag over a decoded significance
767 /// map, highest scanning position first (9.3.3.1.3 counters). Returns the
768 /// number of levels written.
769 fn decode_levels(
770 &mut self,
771 coeff: &mut [i32],
772 sig: &[bool],
773 num: usize,
774 abs_base: usize,
775 chroma_dc: bool,
776 ) -> Result<u8> {
777 let mut num_eq1 = 0u32;
778 let mut num_gt1 = 0u32;
779 let mut total = 0u8;
780 for pos in (0..num).rev() {
781 if !sig[pos] {
782 continue;
783 }
784 let inc0 = if num_gt1 != 0 {
785 0
786 } else {
787 4.min(1 + num_eq1) as usize
788 };
789 let inc1 = 5 + (4 - u32::from(chroma_dc)).min(num_gt1) as usize;
790 // Prefix: TU with cMax = uCoff = 14.
791 let mut prefix = 0u32;
792 while prefix < 14 {
793 let ctx_idx = abs_base + if prefix == 0 { inc0 } else { inc1 };
794 if !self.decision(ctx_idx) {
795 break;
796 }
797 prefix += 1;
798 }
799 let abs_minus1 = if prefix < 14 {
800 prefix
801 } else {
802 14 + self.ueg_suffix(0)?
803 };
804 let level = i64::from(abs_minus1) + 1;
805 let level = if self.bypass() { -level } else { level };
806 coeff[pos] = i32::try_from(level)
807 .map_err(|_| Error::corrupt("coefficient level out of range"))?;
808 if abs_minus1 == 0 {
809 num_eq1 += 1;
810 } else {
811 num_gt1 += 1;
812 }
813 total += 1;
814 }
815 Ok(total)
816 }
817
818 /// The bypass-coded k-th order Exp-Golomb suffix of a UEGk bin string
819 /// (clause 9.3.2.3): k = 0 for coeff_abs_level_minus1, 3 for mvd.
820 fn ueg_suffix(&mut self, k0: u32) -> Result<u32> {
821 let mut k = k0;
822 let mut value = 0u32;
823 while self.bypass() {
824 value += 1 << k;
825 k += 1;
826 if k > 30 {
827 return Err(Error::corrupt("UEG0 suffix prefix too long"));
828 }
829 }
830 while k > 0 {
831 k -= 1;
832 value += u32::from(self.bypass()) << k;
833 }
834 Ok(value)
835 }
836
837 /// condTermFlagN for a DC block: bit `which` of the neighbour's DC
838 /// coded_block_flags, with I_PCM counting as coded. An unavailable
839 /// neighbour counts as set only for an intra macroblock (9.3.3.1.1.9) —
840 /// the chroma DC block of an inter macroblock at the picture edge reads
841 /// the opposite value.
842 fn dc_cbf(&self, n: Option<MbInfo>, which: u8) -> usize {
843 match n {
844 None => usize::from(self.cur_intra),
845 Some(i) if i.flags & FLAG_PCM != 0 => 1,
846 Some(i) => usize::from(i.dc_cbf & (1 << which) != 0),
847 }
848 }
849
850 /// The 384 raw bytes of an I_PCM macroblock. The arithmetic engine restarts
851 /// afterwards (9.3.1.2); the context variables survive.
852 pub(crate) fn pcm_block(&mut self) -> Result<&'a [u8]> {
853 self.r.align_to_byte();
854 let bytes = self.r.read_bytes(384)?;
855 self.init_engine()?;
856 Ok(bytes)
857 }
858
859 /// The raw engine, for the encoder's round-trip test.
860 #[cfg(test)]
861 pub(crate) fn decision_for_test(&mut self, ctx_idx: usize) -> bool {
862 self.decision(ctx_idx)
863 }
864
865 /// The raw bypass engine, for the encoder's round-trip test.
866 #[cfg(test)]
867 pub(crate) fn bypass_for_test(&mut self) -> bool {
868 self.bypass()
869 }
870
871 /// end_of_slice_flag (ctxIdx 276, DecodeTerminate).
872 pub(crate) fn more_macroblocks(&mut self) -> Result<bool> {
873 debug_assert_eq!(CTX_TERMINATE, 276);
874 Ok(!self.terminate())
875 }
876}
877
878/// 9.3.1.1: pStateIdx and valMPS of every context from the (m, n) table
879/// entries and SliceQPY. Shared with the encoder, which has to start from the
880/// same state or the two arithmetic coders diverge on the first bin.
881pub(crate) fn init_contexts(slice_qp: i32, column: usize) -> [u8; NUM_CTX] {
882 let qp = slice_qp.clamp(0, 51);
883 let mut state = [63u8 << 1; NUM_CTX];
884 let mut set = |idx: usize, (m, n): (i8, i8)| {
885 let pre = (((i32::from(m) * qp) >> 4) + i32::from(n)).clamp(1, 126);
886 state[idx] = if pre <= 63 {
887 ((63 - pre) as u8) << 1
888 } else {
889 (((pre - 64) as u8) << 1) | 1
890 };
891 };
892 for (i, &mn) in INIT_MB_TYPE_I.iter().enumerate() {
893 set(i, mn);
894 }
895 for (i, &mn) in INIT_11_59.iter().enumerate() {
896 set(11 + i, mn[column]);
897 }
898 for (i, &mn) in INIT_60_69.iter().enumerate() {
899 set(60 + i, mn);
900 }
901 for (i, &mn) in INIT_70_275.iter().enumerate() {
902 set(70 + i, mn[column]);
903 }
904 for (i, &mn) in INIT_399_401.iter().enumerate() {
905 set(OFF_TRANSFORM_8X8 + i, mn[column]);
906 }
907 for (i, &mn) in INIT_402_435.iter().enumerate() {
908 set(OFF_SIG_8X8 + i, mn[column]);
909 }
910 state
911}
912
913/// ctxIdxInc for mb_qp_delta bin `k` (Table 9-39 row 60).
914#[inline]
915pub(crate) fn qp_delta_inc(k: i32, first: usize) -> usize {
916 match k {
917 0 => first,
918 1 => 2,
919 _ => 3,
920 }
921}
922
923/// ctxIdxInc for significant_coeff_flag / last_significant_coeff_flag at
924/// scanning position `i` (9.3.3.1.3, frame coded, no 8x8 categories).
925#[inline]
926pub(crate) fn sig_inc(cat: BlockCat, i: usize) -> usize {
927 match cat {
928 // ChromaDC with ChromaArrayType 1: Min( levelListIdx / NumC8x8, 2 ).
929 BlockCat::ChromaDc(_) => i.min(2),
930 _ => i,
931 }
932}
933
934#[cfg(test)]
935mod tests {
936 use super::*;
937
938 /// The engine tables are transcribed by hand-checked script; these are the
939 /// structural invariants clause 9.3 states about them, so a shifted row or
940 /// a dropped column cannot pass silently.
941 #[test]
942 fn engine_tables_have_their_stated_shape() {
943 // Table 9-44 first and last rows (9.3.3.2.1): state 0 is p(LPS) = 0.5,
944 // state 63 is the near-deterministic one.
945 assert_eq!(RANGE_LPS[0], [128, 176, 208, 240]);
946 assert_eq!(RANGE_LPS[63], [2, 2, 2, 2]);
947 for (p, row) in RANGE_LPS.iter().enumerate() {
948 // Each row rises with qCodIRangeIdx and falls with the state index.
949 assert!(
950 row.windows(2).all(|w| w[0] <= w[1]),
951 "row {p} not monotonic"
952 );
953 if p > 0 {
954 assert!(
955 row[3] <= RANGE_LPS[p - 1][3],
956 "row {p} above its predecessor"
957 );
958 }
959 }
960 // Table 9-45: MPS transitions step up one state until the two sticky
961 // states at the top, LPS transitions never move up.
962 for (p, &next) in TRANS_MPS.iter().enumerate().take(62) {
963 assert_eq!(next, p as u8 + 1);
964 }
965 assert_eq!((TRANS_MPS[62], TRANS_MPS[63]), (62, 63));
966 for (p, &next) in TRANS_LPS.iter().enumerate() {
967 assert!(usize::from(next) <= p, "LPS transition {p} moves up");
968 }
969 assert_eq!(TRANS_LPS[63], 63);
970 assert_eq!(TRANS_LPS[0], 0);
971 }
972
973 /// 9.3.1.1 worked through by hand for two entries.
974 #[test]
975 fn context_initialisation_matches_equation_9_5() {
976 let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 26, 0).unwrap();
977 // ctxIdx 0, (m, n) = (20, -15): preCtxState = ((20*26) >> 4) - 15 = 17,
978 // so pStateIdx = 63 - 17 = 46 and valMPS = 0.
979 assert_eq!(c.state[0], 46 << 1);
980 // ctxIdx 60, (m, n) = (0, 41): preCtxState = 41 -> pStateIdx 22, MPS 0.
981 assert_eq!(c.state[60], 22 << 1);
982 // Clip3(1, 126, ...) at a low QP: ctxIdx 6, (m, n) = (-28, 127) at
983 // QP 0 gives 127, clipped to 126 -> pStateIdx 62, valMPS 1.
984 let c = Cabac::new(&[0x55, 0, 0, 0, 0], 0, 0, 0).unwrap();
985 assert_eq!(c.state[6], (62 << 1) | 1);
986 }
987
988 /// The initialisation of 9.3.1.2 reads exactly nine bits after the
989 /// alignment bits, and every context lands in range.
990 #[test]
991 fn engine_initialisation_reads_nine_bits() {
992 // Header ends mid byte: the alignment bits carry to the boundary, then
993 // 0b1010_1010_1 is codIOffset.
994 let data = [0xFF, 0b1010_1010, 0b1000_0000, 0, 0];
995 let c = Cabac::new(&data, 3, 30, 0).unwrap();
996 assert_eq!(c.range, 510);
997 assert_eq!(c.offset, 0b1_0101_0101);
998 assert!(c.state.iter().all(|&s| s >> 1 < 64));
999 }
1000}