forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

cabac.rs739 lines, 27.3 KiBHistoryRawDownload
1//! The CABAC arithmetic coder and its context variables (clause 9.3).
2//!
3//! Two things live here that are usually separate: the encoder that writes bins,
4//! and the same encoder in *counting* mode, which runs the identical context
5//! updates but throws the bytes away and keeps the bit count. Rate-distortion
6//! decisions are made against that count, so the rate a decision is judged by is
7//! the rate it actually costs — no bit-estimate table to drift out of step with
8//! the coder.
9//!
10//! A third mode, *estimating*, exists purely for RDOQ's own trial-costing
11//! instrument (`rdoq_enc`): it skips the range/renorm arithmetic and instead
12//! looks up a per-context fractional-bit cost from [`ENTROPY_BITS`], the
13//! x265/HM `entropyBits`-table idiom. The committing encoder never uses it.
14
15use std::sync::LazyLock;
16
17/// Number of context variables this encoder keeps.
18pub const NUM_CONTEXTS: usize = ctx::TOTAL;
19
20/// Context index layout: one named base per syntax element, I-slice only.
21pub mod ctx {
22 /// `split_cu_flag`, 3 contexts.
23 pub const SPLIT_CU: usize = 0;
24 /// `part_mode`, 1 context in an I slice.
25 pub const PART_MODE: usize = SPLIT_CU + 3;
26 /// `prev_intra_luma_pred_flag`.
27 pub const PREV_INTRA_LUMA_PRED: usize = PART_MODE + 1;
28 /// `intra_chroma_pred_mode`.
29 pub const INTRA_CHROMA_PRED_MODE: usize = PREV_INTRA_LUMA_PRED + 1;
30 /// `split_transform_flag`, 3 contexts.
31 pub const SPLIT_TRANSFORM: usize = INTRA_CHROMA_PRED_MODE + 1;
32 /// `cbf_luma`, 2 contexts.
33 pub const CBF_LUMA: usize = SPLIT_TRANSFORM + 3;
34 /// `cbf_cb` / `cbf_cr`, 4 contexts.
35 pub const CBF_CHROMA: usize = CBF_LUMA + 2;
36 /// `transform_skip_flag`, 2 contexts (luma, chroma).
37 pub const TRANSFORM_SKIP: usize = CBF_CHROMA + 4;
38 /// `last_sig_coeff_x_prefix`, 18 contexts.
39 pub const LAST_X: usize = TRANSFORM_SKIP + 2;
40 /// `last_sig_coeff_y_prefix`, 18 contexts.
41 pub const LAST_Y: usize = LAST_X + 18;
42 /// `coded_sub_block_flag`, 4 contexts.
43 pub const CODED_SUB_BLOCK: usize = LAST_Y + 18;
44 /// `sig_coeff_flag`, 44 contexts (42 transform + 2 transform-skip).
45 pub const SIG_COEFF: usize = CODED_SUB_BLOCK + 4;
46 /// `coeff_abs_level_greater1_flag`, 24 contexts.
47 pub const GREATER1: usize = SIG_COEFF + 44;
48 /// `coeff_abs_level_greater2_flag`, 6 contexts.
49 pub const GREATER2: usize = GREATER1 + 24;
50 /// Total context count.
51 pub const TOTAL: usize = GREATER2 + 6;
52}
53
54/// `initValue` for every context, initType 0 (I slices), Tables 9-7 to 9-31.
55#[rustfmt::skip]
56const INIT_VALUES: [u8; ctx::TOTAL] = [
57 // split_cu_flag (Table 9-7)
58 139, 141, 157,
59 // part_mode (Table 9-11)
60 184,
61 // prev_intra_luma_pred_flag (Table 9-12)
62 184,
63 // intra_chroma_pred_mode (Table 9-13)
64 63,
65 // split_transform_flag (Table 9-20)
66 153, 138, 138,
67 // cbf_luma (Table 9-21)
68 111, 141,
69 // cbf_cb / cbf_cr (Table 9-22)
70 94, 138, 182, 154,
71 // transform_skip_flag (Table 9-25)
72 139, 139,
73 // last_sig_coeff_x_prefix (Table 9-26)
74 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63,
75 // last_sig_coeff_y_prefix (Table 9-27)
76 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63,
77 // coded_sub_block_flag (Table 9-28)
78 91, 171, 134, 141,
79 // sig_coeff_flag (Table 9-29), ctxIdx 0..41 then the two transform-skip ones
80 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107,
81 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 140, 139, 182, 182, 152,
82 136, 152, 136, 153, 136, 139, 111, 136, 139, 111,
83 141, 111,
84 // coeff_abs_level_greater1_flag (Table 9-30)
85 140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152,
86 140, 179, 166, 182, 140, 227, 122, 197,
87 // coeff_abs_level_greater2_flag (Table 9-31)
88 138, 153, 136, 167, 152, 152,
89];
90
91/// `rangeTabLps[pStateIdx][qRangeIdx]` (Table 9-52).
92#[rustfmt::skip]
93const RANGE_TAB_LPS: [[u8; 4]; 64] = [
94 [128, 176, 208, 240], [128, 167, 197, 227], [128, 158, 187, 216], [123, 150, 178, 205],
95 [116, 142, 169, 195], [111, 135, 160, 185], [105, 128, 152, 175], [100, 122, 144, 166],
96 [95, 116, 137, 158], [90, 110, 130, 150], [85, 104, 123, 142], [81, 99, 117, 135],
97 [77, 94, 111, 128], [73, 89, 105, 122], [69, 85, 100, 116], [66, 80, 95, 110],
98 [62, 76, 90, 104], [59, 72, 86, 99], [56, 69, 81, 94], [53, 65, 77, 89],
99 [51, 62, 73, 85], [48, 59, 69, 80], [46, 56, 66, 76], [43, 53, 63, 72],
100 [41, 50, 59, 69], [39, 48, 56, 65], [37, 45, 54, 62], [35, 43, 51, 59],
101 [33, 41, 48, 56], [32, 39, 46, 53], [30, 37, 43, 50], [29, 35, 41, 48],
102 [27, 33, 39, 45], [26, 31, 37, 43], [24, 30, 35, 41], [23, 28, 33, 39],
103 [22, 27, 32, 37], [21, 26, 30, 35], [20, 24, 29, 33], [19, 23, 27, 31],
104 [18, 22, 26, 30], [17, 21, 25, 28], [16, 20, 23, 27], [15, 19, 22, 25],
105 [14, 18, 21, 24], [14, 17, 20, 23], [13, 16, 19, 22], [12, 15, 18, 21],
106 [12, 14, 17, 20], [11, 14, 16, 19], [11, 13, 15, 18], [10, 12, 15, 17],
107 [10, 12, 14, 16], [9, 11, 13, 15], [9, 11, 12, 14], [8, 10, 12, 14],
108 [8, 9, 11, 13], [7, 9, 11, 12], [7, 9, 10, 12], [7, 8, 10, 11],
109 [6, 8, 9, 11], [6, 7, 9, 10], [6, 7, 8, 9], [2, 2, 2, 2],
110];
111
112/// `transIdxLps[pStateIdx]` (Table 9-53).
113#[rustfmt::skip]
114const TRANS_IDX_LPS: [u8; 64] = [
115 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12,
116 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24,
117 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33,
118 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63,
119];
120
121/// `transIdxMps[pStateIdx]` (Table 9-53).
122#[rustfmt::skip]
123const TRANS_IDX_MPS: [u8; 64] = [
124 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
125 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
126 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
127 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63,
128];
129
130/// `ENTROPY_BITS[pStateIdx] = [bits if the bin matches valMps, bits if it
131/// doesn't]`, the fractional-bit cost of a context-coded bin under its
132/// context's current probability state — RDOQ's estimating mode reads this
133/// instead of replaying the exact range-narrowing arithmetic per trial.
134///
135/// HEVC's 64 probability states follow the same geometric decay as H.264's
136/// (Marpe et al.): `pLPS(pStateIdx) = 0.5 * ALPHA^pStateIdx`, `ALPHA =
137/// 0.9493`, running from 0.5 at state 0 down to the ~0.01875 floor at state
138/// 63 that `RANGE_TAB_LPS`'s last row (all `2`s) also converges to. Bits are
139/// `-log2` of the matching/mismatching probability, x265/HM's `entropyBits`
140/// idiom — an entropy estimate, not the coder's own count, so RDOQ under
141/// this mode ranks candidates instead of pricing them exactly.
142static ENTROPY_BITS: LazyLock<[[f64; 2]; 64]> = LazyLock::new(|| {
143 const ALPHA: f64 = 0.9493;
144 std::array::from_fn(|p_state| {
145 let p_lps = 0.5 * ALPHA.powi(p_state as i32);
146 [-(1.0 - p_lps).log2(), -p_lps.log2()]
147 })
148});
149
150/// The context variables, `pStateIdx << 1 | valMps` per entry.
151#[derive(Clone, PartialEq, Eq, Debug)]
152pub struct Contexts {
153 state: [u8; ctx::TOTAL],
154}
155
156impl Contexts {
157 /// Initialise every context for an I slice at `slice_qp` (9.3.2.2).
158 pub fn new(slice_qp: i32) -> Contexts {
159 let qp = slice_qp.clamp(0, 51);
160 let mut state = [0u8; ctx::TOTAL];
161 for (i, &init_value) in INIT_VALUES.iter().enumerate() {
162 let slope_idx = (init_value >> 4) as i32;
163 let offset_idx = (init_value & 15) as i32;
164 let m = slope_idx * 5 - 45;
165 let n = (offset_idx << 3) - 16;
166 let pre_ctx_state = (((m * qp) >> 4) + n).clamp(1, 126);
167 let val_mps = i32::from(pre_ctx_state > 63);
168 let p_state = if val_mps == 1 {
169 pre_ctx_state - 64
170 } else {
171 63 - pre_ctx_state
172 };
173 state[i] = ((p_state as u8) << 1) | val_mps as u8;
174 }
175 Contexts { state }
176 }
177}
178
179/// A rollback point for [`CabacEncoder`].
180///
181/// A plain [`CabacEncoder::snapshot`] rewinds by truncation, which is all a
182/// trial-and-discard needs. A [`CabacEncoder::snapshot_since`] also carries the
183/// bytes written since an earlier point, which is what a trial-and-*keep* needs:
184/// a second trial overwrites the first one's bytes in place, so rewinding to a
185/// length alone would leave the loser's bytes in the winner's positions.
186#[derive(Clone)]
187pub struct CabacState {
188 low: u32,
189 range: u32,
190 bits_outstanding: u32,
191 first_bit: bool,
192 bits: u64,
193 out_len: usize,
194 tail_base: usize,
195 tail: Vec<u8>,
196 partial: u8,
197 partial_bits: u8,
198 contexts: Contexts,
199 /// [`CabacEncoder::est_bits`] at snapshot time, restored alongside it.
200 est_bits: f64,
201}
202
203/// The CABAC encoding engine (9.3.5).
204#[derive(Clone)]
205pub struct CabacEncoder {
206 low: u32,
207 range: u32,
208 bits_outstanding: u32,
209 first_bit: bool,
210 /// Bits written, counted whether or not they are kept.
211 bits: u64,
212 /// `None` while estimating a rate rather than producing a bitstream.
213 out: Option<Vec<u8>>,
214 /// While set, bins are coded and counted but no bytes are kept — what a
215 /// rate-distortion trial wants, since its bytes are about to be thrown away.
216 counting: bool,
217 partial: u8,
218 partial_bits: u8,
219 /// Context variables, public to the modules that index them by name.
220 pub contexts: Contexts,
221 /// While set, `encode_bin`/`encode_bypass*` skip the range/renorm
222 /// arithmetic entirely and instead accumulate [`ENTROPY_BITS`]-table
223 /// lookups into `est_bits` — RDOQ's trial-costing instrument only; the
224 /// committing encoder never sets this. `low`/`range`/`bits_outstanding`
225 /// are left untouched while this is set, so a `restore()` back to a
226 /// snapshot taken before estimating began is exact.
227 estimating: bool,
228 /// Fractional bits accumulated while `estimating`; read by
229 /// [`CabacEncoder::bit_count_f64`].
230 est_bits: f64,
231}
232
233impl CabacEncoder {
234 /// A fresh engine writing into its own buffer.
235 pub fn new(contexts: Contexts) -> CabacEncoder {
236 CabacEncoder {
237 low: 0,
238 range: 510,
239 bits_outstanding: 0,
240 first_bit: true,
241 bits: 0,
242 out: Some(Vec::new()),
243 counting: false,
244 partial: 0,
245 partial_bits: 0,
246 contexts,
247 estimating: false,
248 est_bits: 0.0,
249 }
250 }
251
252 /// An engine that counts bits and writes nothing — the rate half of every
253 /// rate-distortion decision.
254 pub fn counter(contexts: Contexts) -> CabacEncoder {
255 let mut enc = CabacEncoder::new(contexts);
256 enc.out = None;
257 enc
258 }
259
260 /// Bits produced so far, including the ones a counting engine discards.
261 /// In `estimating` mode this is stale (the estimating path never
262 /// increments it) — read [`CabacEncoder::bit_count_f64`] instead.
263 pub fn bit_count(&self) -> u64 {
264 self.bits
265 }
266
267 /// [`CabacEncoder::bit_count`], but fractional and estimating-mode-aware:
268 /// the exact bit count as `f64` normally, or the accumulated
269 /// [`ENTROPY_BITS`] estimate while `estimating` is set.
270 pub fn bit_count_f64(&self) -> f64 {
271 if self.estimating {
272 self.est_bits
273 } else {
274 self.bits as f64
275 }
276 }
277
278 /// Switch between exact range/renorm costing and the estimated
279 /// per-context fracbits table. See the `estimating` field.
280 pub fn set_estimating(&mut self, estimating: bool) {
281 self.estimating = estimating;
282 }
283
284 /// Code bins without keeping their bytes; the counter still runs.
285 pub fn set_counting(&mut self, counting: bool) {
286 self.counting = counting;
287 }
288
289 fn write_bit(&mut self, bit: u32) {
290 self.bits += 1;
291 if self.counting {
292 return;
293 }
294 if let Some(out) = &mut self.out {
295 self.partial = (self.partial << 1) | (bit as u8);
296 self.partial_bits += 1;
297 if self.partial_bits == 8 {
298 out.push(self.partial);
299 self.partial = 0;
300 self.partial_bits = 0;
301 }
302 }
303 }
304
305 fn put_bit(&mut self, bit: u32) {
306 if self.first_bit {
307 self.first_bit = false;
308 } else {
309 self.write_bit(bit);
310 }
311 while self.bits_outstanding > 0 {
312 self.write_bit(1 - bit);
313 self.bits_outstanding -= 1;
314 }
315 }
316
317 fn renorm(&mut self) {
318 while self.range < 256 {
319 if self.low < 256 {
320 self.put_bit(0);
321 } else if self.low >= 512 {
322 self.low -= 512;
323 self.put_bit(1);
324 } else {
325 self.low -= 256;
326 self.bits_outstanding += 1;
327 }
328 self.range <<= 1;
329 self.low <<= 1;
330 }
331 }
332
333 /// Take a snapshot the encoder can be rolled back to.
334 ///
335 /// This is what makes exact rate measurement affordable: a trial encode runs
336 /// into the real coder, its bits are read off the counter, and the coder is
337 /// put back. The cost is one 129-byte context copy, not a copy of the
338 /// substream written so far.
339 pub fn snapshot(&self) -> CabacState {
340 let out_len = self.out.as_ref().map_or(0, |o| o.len());
341 CabacState {
342 low: self.low,
343 range: self.range,
344 bits_outstanding: self.bits_outstanding,
345 first_bit: self.first_bit,
346 bits: self.bits,
347 out_len,
348 tail_base: out_len,
349 tail: Vec::new(),
350 partial: self.partial,
351 partial_bits: self.partial_bits,
352 contexts: self.contexts.clone(),
353 est_bits: self.est_bits,
354 }
355 }
356
357 /// A snapshot that also carries the bytes written since `base`, so that
358 /// restoring it puts those bytes back after a competing trial overwrote
359 /// them.
360 pub fn snapshot_since(&self, base: &CabacState) -> CabacState {
361 let mut state = self.snapshot();
362 state.tail_base = base.out_len;
363 if let Some(out) = &self.out {
364 state.tail = out[base.out_len..].to_vec();
365 }
366 state
367 }
368
369 /// Roll back to a snapshot.
370 pub fn restore(&mut self, state: &CabacState) {
371 self.low = state.low;
372 self.range = state.range;
373 self.bits_outstanding = state.bits_outstanding;
374 self.first_bit = state.first_bit;
375 self.bits = state.bits;
376 self.partial = state.partial;
377 self.partial_bits = state.partial_bits;
378 self.contexts.clone_from(&state.contexts);
379 self.est_bits = state.est_bits;
380 if let Some(out) = &mut self.out {
381 out.truncate(state.tail_base);
382 out.extend_from_slice(&state.tail);
383 debug_assert_eq!(out.len(), state.out_len);
384 }
385 }
386
387 /// Encode one context-coded bin (9.3.5.3).
388 #[inline]
389 pub fn encode_bin(&mut self, ctx_idx: usize, bin: u32) {
390 let state = self.contexts.state[ctx_idx];
391 let p_state = (state >> 1) as usize;
392 let val_mps = u32::from(state & 1);
393 if self.estimating {
394 self.est_bits += ENTROPY_BITS[p_state][usize::from(bin != val_mps)];
395 self.contexts.state[ctx_idx] = if bin != val_mps {
396 let new_mps = if p_state == 0 { 1 - val_mps } else { val_mps };
397 (TRANS_IDX_LPS[p_state] << 1) | new_mps as u8
398 } else {
399 (TRANS_IDX_MPS[p_state] << 1) | val_mps as u8
400 };
401 return;
402 }
403 let q_range_idx = ((self.range >> 6) & 3) as usize;
404 let lps_range = u32::from(RANGE_TAB_LPS[p_state][q_range_idx]);
405 self.range -= lps_range;
406 if bin != val_mps {
407 self.low += self.range;
408 self.range = lps_range;
409 let new_mps = if p_state == 0 { 1 - val_mps } else { val_mps };
410 self.contexts.state[ctx_idx] = (TRANS_IDX_LPS[p_state] << 1) | new_mps as u8;
411 } else {
412 self.contexts.state[ctx_idx] = (TRANS_IDX_MPS[p_state] << 1) | val_mps as u8;
413 }
414 self.renorm();
415 }
416
417 /// Encode one bypass bin (9.3.5.5).
418 #[inline]
419 pub fn encode_bypass(&mut self, bin: u32) {
420 if self.estimating {
421 // Bypass bins are uncontexted and uniform-probability: the real
422 // coder's carry propagation can occasionally defer more than one
423 // output bit to a later call, but the standard entropy estimate
424 // (x265/HM alike) is exactly one bit per bypass bin.
425 self.est_bits += 1.0;
426 return;
427 }
428 self.low <<= 1;
429 if bin != 0 {
430 self.low += self.range;
431 }
432 if self.low >= 1024 {
433 self.put_bit(1);
434 self.low -= 1024;
435 } else if self.low < 512 {
436 self.put_bit(0);
437 } else {
438 self.low -= 512;
439 self.bits_outstanding += 1;
440 }
441 }
442
443 /// Encode `count` bypass bins from the low bits of `value`, most
444 /// significant first.
445 pub fn encode_bypass_bits(&mut self, value: u32, count: u32) {
446 for i in (0..count).rev() {
447 self.encode_bypass((value >> i) & 1);
448 }
449 }
450
451 /// Encode a terminating bin: `end_of_slice_segment_flag` or
452 /// `end_of_subset_one_bit` (9.3.5.6). A one flushes the engine.
453 pub fn encode_terminate(&mut self, bin: u32) {
454 self.range -= 2;
455 if bin != 0 {
456 self.low += self.range;
457 self.flush();
458 } else {
459 self.renorm();
460 }
461 }
462
463 fn flush(&mut self) {
464 self.range = 2;
465 self.renorm();
466 self.put_bit((self.low >> 9) & 1);
467 // The last two bits, the low one always set: it is the
468 // rbsp_stop_one_bit or the alignment_bit_equal_to_one.
469 self.write_bit((self.low >> 8) & 1);
470 self.write_bit(1);
471 }
472
473 /// Finish a substream: pad the last byte with zeros and hand back the bytes.
474 ///
475 /// Only valid after [`CabacEncoder::encode_terminate`] with a one bin, which
476 /// is where the flush happened.
477 pub fn finish(mut self) -> Vec<u8> {
478 let mut out = self.out.take().unwrap_or_default();
479 if self.partial_bits > 0 {
480 out.push(self.partial << (8 - self.partial_bits));
481 }
482 out
483 }
484}
485
486/// The CABAC decoding engine (9.3.4.3.2), the mirror image of
487/// [`CabacEncoder`]: same context tables, same `RANGE_TAB_LPS` /
488/// `TRANS_IDX_LPS` / `TRANS_IDX_MPS`, so a context updates identically on
489/// both sides and a decoded bin is exactly the bin the encoder wrote.
490///
491/// Reads bits MSB-first from `data` starting at bit 0; a read past the end of
492/// `data` returns zero, the standard convention for the handful of bits a
493/// CABAC engine may read past a substream's real end while renormalising
494/// around its final terminating bin.
495pub struct CabacDecoder<'a> {
496 data: &'a [u8],
497 bit: usize,
498 range: u32,
499 offset: u32,
500 /// Context variables, public for the same reason [`CabacEncoder::contexts`] is.
501 pub contexts: Contexts,
502}
503
504impl<'a> CabacDecoder<'a> {
505 /// A fresh engine reading `data` from its first bit (9.3.2.5 init).
506 pub fn new(data: &'a [u8], contexts: Contexts) -> CabacDecoder<'a> {
507 let mut d = CabacDecoder {
508 data,
509 bit: 0,
510 range: 510,
511 offset: 0,
512 contexts,
513 };
514 for _ in 0..9 {
515 d.offset = (d.offset << 1) | d.read_bit();
516 }
517 d
518 }
519
520 fn read_bit(&mut self) -> u32 {
521 let byte = self.data.get(self.bit / 8).copied().unwrap_or(0);
522 let bit = u32::from((byte >> (7 - (self.bit % 8))) & 1);
523 self.bit += 1;
524 bit
525 }
526
527 /// Decode one context-coded bin (9.3.4.3.2.2).
528 pub fn decode_bin(&mut self, ctx_idx: usize) -> u32 {
529 let state = self.contexts.state[ctx_idx];
530 let p_state = (state >> 1) as usize;
531 let val_mps = u32::from(state & 1);
532 let q = ((self.range >> 6) & 3) as usize;
533 let lps = u32::from(RANGE_TAB_LPS[p_state][q]);
534 self.range -= lps;
535 let bin;
536 if self.offset >= self.range {
537 bin = 1 - val_mps;
538 self.offset -= self.range;
539 self.range = lps;
540 let new_mps = if p_state == 0 { 1 - val_mps } else { val_mps };
541 self.contexts.state[ctx_idx] = (TRANS_IDX_LPS[p_state] << 1) | new_mps as u8;
542 } else {
543 bin = val_mps;
544 self.contexts.state[ctx_idx] = (TRANS_IDX_MPS[p_state] << 1) | val_mps as u8;
545 }
546 while self.range < 256 {
547 self.range <<= 1;
548 self.offset = (self.offset << 1) | self.read_bit();
549 }
550 bin
551 }
552
553 /// Decode one bypass bin (9.3.4.3.4).
554 pub fn decode_bypass(&mut self) -> u32 {
555 self.offset = (self.offset << 1) | self.read_bit();
556 if self.offset >= self.range {
557 self.offset -= self.range;
558 1
559 } else {
560 0
561 }
562 }
563
564 /// Decode `count` bypass bins into one value, most significant first.
565 pub fn decode_bypass_bits(&mut self, count: u32) -> u32 {
566 let mut v = 0;
567 for _ in 0..count {
568 v = (v << 1) | self.decode_bypass();
569 }
570 v
571 }
572
573 /// Decode a terminating bin: `end_of_slice_segment_flag` or
574 /// `end_of_subset_one_bit` (9.3.4.3.5).
575 pub fn decode_terminate(&mut self) -> u32 {
576 self.range -= 2;
577 if self.offset >= self.range {
578 1
579 } else {
580 while self.range < 256 {
581 self.range <<= 1;
582 self.offset = (self.offset << 1) | self.read_bit();
583 }
584 0
585 }
586 }
587
588 /// Byte offset, from the start of `data`, of the substream after a
589 /// `decode_terminate() == 1`: the encoder's flush always pads to a byte
590 /// boundary here, so the next WPP row's substream starts exactly there.
591 pub fn byte_position_aligned(&self) -> usize {
592 self.bit.div_ceil(8)
593 }
594}
595
596#[cfg(test)]
597mod tests {
598 use super::*;
599
600 #[test]
601 fn decoder_inverts_the_encoder_bin_by_bin() {
602 // Every context-coded and bypass bin the encoder can write, decoded
603 // back through the same context table, must reproduce the exact
604 // sequence: this is what makes a CABAC decoder a mirror rather than a
605 // second implementation that might disagree with the first.
606 let bins: Vec<(usize, u32)> = (0..NUM_CONTEXTS)
607 .flat_map(|ctx| [(ctx, 0u32), (ctx, 1), (ctx, 0), (ctx, 1), (ctx, 1)])
608 .collect();
609 let mut enc = CabacEncoder::new(Contexts::new(27));
610 for &(ctx, bin) in &bins {
611 enc.encode_bin(ctx, bin);
612 }
613 for i in 0..37u32 {
614 enc.encode_bypass(i & 1);
615 }
616 enc.encode_terminate(1);
617 let bytes = enc.finish();
618
619 let mut dec = CabacDecoder::new(&bytes, Contexts::new(27));
620 for &(ctx, bin) in &bins {
621 assert_eq!(dec.decode_bin(ctx), bin);
622 }
623 for i in 0..37u32 {
624 assert_eq!(dec.decode_bypass(), i & 1);
625 }
626 assert_eq!(dec.decode_terminate(), 1);
627 }
628
629 #[test]
630 fn context_init_matches_the_worked_formula() {
631 // initValue 154 is the "no slope" entry: m = 0, n = 64, so every QP
632 // lands on preCtxState 64, valMps 1, pStateIdx 0.
633 let init_value: u8 = 154;
634 let m = (init_value >> 4) as i32 * 5 - 45;
635 let n = (((init_value & 15) as i32) << 3) - 16;
636 assert_eq!((m, n), (0, 64));
637 // And a real one: split_cu_flag ctx 0 (139) at QP 30.
638 let ctxs = Contexts::new(30);
639 let m = (139u8 >> 4) as i32 * 5 - 45;
640 let n = (((139u8 & 15) as i32) << 3) - 16;
641 let pre = (((m * 30) >> 4) + n).clamp(1, 126);
642 let expect = if pre > 63 {
643 (((pre - 64) as u8) << 1) | 1
644 } else {
645 ((63 - pre) as u8) << 1
646 };
647 assert_eq!(ctxs.state[ctx::SPLIT_CU], expect);
648 }
649
650 #[test]
651 fn state_tables_are_consistent() {
652 // Every LPS transition moves towards the uncertain end, every MPS
653 // transition towards the certain one, and state 63 is absorbing.
654 for s in 0..64usize {
655 assert!(TRANS_IDX_LPS[s] as usize <= s);
656 assert!(TRANS_IDX_MPS[s] as usize >= s);
657 assert!(TRANS_IDX_MPS[s] < 64 && TRANS_IDX_LPS[s] < 64);
658 // rangeTabLps shrinks as the state gets more certain.
659 if s > 0 {
660 for (q, &value) in RANGE_TAB_LPS[s].iter().enumerate() {
661 assert!(value <= RANGE_TAB_LPS[s - 1][q]);
662 }
663 }
664 }
665 assert_eq!(TRANS_IDX_LPS[63], 63);
666 assert_eq!(TRANS_IDX_MPS[63], 63);
667 }
668
669 #[test]
670 fn counting_engine_tracks_the_writing_engine() {
671 let mut writer = CabacEncoder::new(Contexts::new(30));
672 let mut counter = CabacEncoder::counter(Contexts::new(30));
673 for i in 0..500u32 {
674 let bin = (i * 7 % 5) & 1;
675 writer.encode_bin(ctx::SIG_COEFF + (i as usize % 44), bin);
676 counter.encode_bin(ctx::SIG_COEFF + (i as usize % 44), bin);
677 writer.encode_bypass(bin);
678 counter.encode_bypass(bin);
679 }
680 assert_eq!(writer.bit_count(), counter.bit_count());
681 assert_eq!(writer.contexts, counter.contexts);
682 }
683
684 #[test]
685 fn the_spec_decoder_reads_back_what_the_encoder_wrote() {
686 // A long mixed sequence: context bins across many contexts, bypass bins,
687 // and the terminating bin that flushes. If the engine's carry handling
688 // or state transitions were wrong, this diverges within a few bins —
689 // which is exactly the failure a real decoder shows as a broken picture.
690 let mut plan: Vec<(usize, u32, u8)> = Vec::new(); // (ctx or 0, bin, kind)
691 let mut seed = 12345u32;
692 let mut rand = move || {
693 seed = seed.wrapping_mul(1103515245).wrapping_add(12345);
694 (seed >> 16) & 0x7fff
695 };
696 for i in 0..3000 {
697 let kind = if i % 7 == 3 { 1 } else { 0 };
698 let ctx = (rand() as usize) % ctx::TOTAL;
699 let bin = if i % 5 == 0 { 1 } else { rand() & 1 };
700 plan.push((ctx, bin, kind));
701 }
702 let mut enc = CabacEncoder::new(Contexts::new(32));
703 for &(ctx_idx, bin, kind) in &plan {
704 if kind == 0 {
705 enc.encode_bin(ctx_idx, bin);
706 } else {
707 enc.encode_bypass(bin);
708 }
709 }
710 enc.encode_terminate(1);
711 let bytes = enc.finish();
712
713 let mut dec = CabacDecoder::new(&bytes, Contexts::new(32));
714 for (i, &(ctx_idx, bin, kind)) in plan.iter().enumerate() {
715 let got = if kind == 0 {
716 dec.decode_bin(ctx_idx)
717 } else {
718 dec.decode_bypass()
719 };
720 assert_eq!(got, bin, "bin {i} (ctx {ctx_idx}, kind {kind})");
721 }
722 assert_eq!(dec.decode_terminate(), 1, "terminating bin");
723 }
724
725 #[test]
726 fn a_skewed_symbol_stream_compresses() {
727 // 4000 zeros through one adapting context must cost far less than 4000
728 // bits — the property that makes the engine an arithmetic coder at all.
729 let mut enc = CabacEncoder::new(Contexts::new(30));
730 for _ in 0..4000 {
731 enc.encode_bin(ctx::SIG_COEFF, 0);
732 }
733 enc.encode_terminate(1);
734 let bits = enc.bit_count();
735 let bytes = enc.finish();
736 assert!(bits < 400, "{bits} bits for 4000 skewed bins");
737 assert!(!bytes.is_empty());
738 }
739}