forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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