forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

cabac.rs950 lines, 36.7 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. Intra elements
21/// come first (their indices predate the inter tables), inter elements follow.
22pub mod ctx {
23 /// `split_cu_flag`, 3 contexts.
24 pub const SPLIT_CU: usize = 0;
25 /// `part_mode`, 4 contexts (intra uses the first; inter uses all four).
26 pub const PART_MODE: usize = SPLIT_CU + 3;
27 /// `prev_intra_luma_pred_flag`.
28 pub const PREV_INTRA_LUMA_PRED: usize = PART_MODE + 4;
29 /// `intra_chroma_pred_mode`.
30 pub const INTRA_CHROMA_PRED_MODE: usize = PREV_INTRA_LUMA_PRED + 1;
31 /// `split_transform_flag`, 3 contexts.
32 pub const SPLIT_TRANSFORM: usize = INTRA_CHROMA_PRED_MODE + 1;
33 /// `cbf_luma`, 2 contexts.
34 pub const CBF_LUMA: usize = SPLIT_TRANSFORM + 3;
35 /// `cbf_cb` / `cbf_cr`, 5 contexts (indexed by trafoDepth).
36 pub const CBF_CHROMA: usize = CBF_LUMA + 2;
37 /// `transform_skip_flag`, 2 contexts (luma, chroma).
38 pub const TRANSFORM_SKIP: usize = CBF_CHROMA + 5;
39 /// `last_sig_coeff_x_prefix`, 18 contexts.
40 pub const LAST_X: usize = TRANSFORM_SKIP + 2;
41 /// `last_sig_coeff_y_prefix`, 18 contexts.
42 pub const LAST_Y: usize = LAST_X + 18;
43 /// `coded_sub_block_flag`, 4 contexts.
44 pub const CODED_SUB_BLOCK: usize = LAST_Y + 18;
45 /// `sig_coeff_flag`, 44 contexts (42 transform + 2 transform-skip).
46 pub const SIG_COEFF: usize = CODED_SUB_BLOCK + 4;
47 /// `coeff_abs_level_greater1_flag`, 24 contexts.
48 pub const GREATER1: usize = SIG_COEFF + 44;
49 /// `coeff_abs_level_greater2_flag`, 6 contexts.
50 pub const GREATER2: usize = GREATER1 + 24;
51 /// `cu_skip_flag`, 3 contexts.
52 pub const CU_SKIP: usize = GREATER2 + 6;
53 /// `pred_mode_flag`, 1 context.
54 pub const PRED_MODE: usize = CU_SKIP + 3;
55 /// `merge_flag`, 1 context.
56 pub const MERGE_FLAG: usize = PRED_MODE + 1;
57 /// `merge_idx`, 1 context (the first bin; the rest are bypass).
58 pub const MERGE_IDX: usize = MERGE_FLAG + 1;
59 /// `inter_pred_idc`, 5 contexts (0..3 by CtDepth, 4 for the 8x4/4x8 case).
60 pub const INTER_PRED_IDC: usize = MERGE_IDX + 1;
61 /// `ref_idx_lX`, 2 contexts (the first two bins; the rest are bypass).
62 pub const REF_IDX: usize = INTER_PRED_IDC + 5;
63 /// `mvp_lX_flag`, 1 context.
64 pub const MVP_FLAG: usize = REF_IDX + 2;
65 /// `abs_mvd_greater0_flag`, 1 context.
66 pub const ABS_MVD_GT0: usize = MVP_FLAG + 1;
67 /// `abs_mvd_greater1_flag`, 1 context.
68 pub const ABS_MVD_GT1: usize = ABS_MVD_GT0 + 1;
69 /// `rqt_root_cbf`, 1 context.
70 pub const RQT_ROOT_CBF: usize = ABS_MVD_GT1 + 1;
71 /// `cu_qp_delta_abs`, 2 contexts (first bin; bins 1..4).
72 pub const CU_QP_DELTA_ABS: usize = RQT_ROOT_CBF + 1;
73 /// `sao_merge_left_flag` / `sao_merge_up_flag`, 1 context.
74 pub const SAO_MERGE: usize = CU_QP_DELTA_ABS + 2;
75 /// `sao_type_idx_luma` / `sao_type_idx_chroma`, 1 context.
76 pub const SAO_TYPE_IDX: usize = SAO_MERGE + 1;
77 /// Total context count.
78 /// `cu_transquant_bypass_flag`, 1 context.
79 pub const CU_TRANSQUANT_BYPASS: usize = SAO_TYPE_IDX + 1;
80 /// `cu_chroma_qp_offset_flag`, 1 context.
81 pub const CU_CHROMA_QP_OFFSET_FLAG: usize = CU_TRANSQUANT_BYPASS + 1;
82 /// `cu_chroma_qp_offset_idx`, 1 context (every bin).
83 pub const CU_CHROMA_QP_OFFSET_IDX: usize = CU_CHROMA_QP_OFFSET_FLAG + 1;
84 /// `explicit_rdpcm_flag`, 2 contexts (luma, chroma).
85 pub const EXPLICIT_RDPCM_FLAG: usize = CU_CHROMA_QP_OFFSET_IDX + 1;
86 /// `explicit_rdpcm_dir_flag`, 2 contexts (luma, chroma).
87 pub const EXPLICIT_RDPCM_DIR: usize = EXPLICIT_RDPCM_FLAG + 2;
88 /// `log2_res_scale_abs_plus1`, 8 contexts (`4 * c + binIdx`).
89 pub const LOG2_RES_SCALE_ABS: usize = EXPLICIT_RDPCM_DIR + 2;
90 /// `res_scale_sign_flag`, 2 contexts (one per chroma component).
91 pub const RES_SCALE_SIGN: usize = LOG2_RES_SCALE_ABS + 8;
92 /// Number of context slots.
93 pub const TOTAL: usize = RES_SCALE_SIGN + 2;
94}
95
96/// The `initValue`s of one syntax element for each initType (Tables 9-5 to 9-37).
97/// Rows are in [`ctx`] layout order; `t0` is I slices, `t1` and `t2` are P and B
98/// slices (initType 1 and 2, swapped by `cabac_init_flag`). Elements that do not
99/// occur in I slices carry the 154 filler in `t0`, which no I-slice bin reads.
100struct InitRow {
101 t0: &'static [u8],
102 t1: &'static [u8],
103 t2: &'static [u8],
104}
105
106#[rustfmt::skip]
107const INIT_ROWS: &[InitRow] = &[
108 // split_cu_flag (9-7)
109 InitRow { t0: &[139, 141, 157], t1: &[107, 139, 126], t2: &[107, 139, 126] },
110 // part_mode (9-11): initType 0 has one context
111 InitRow { t0: &[184, 154, 154, 154], t1: &[154, 139, 154, 154], t2: &[154, 139, 154, 154] },
112 // prev_intra_luma_pred_flag (9-12)
113 InitRow { t0: &[184], t1: &[154], t2: &[183] },
114 // intra_chroma_pred_mode (9-13)
115 InitRow { t0: &[63], t1: &[152], t2: &[152] },
116 // split_transform_flag (9-20)
117 InitRow { t0: &[153, 138, 138], t1: &[124, 138, 94], t2: &[224, 167, 122] },
118 // cbf_luma (9-21)
119 InitRow { t0: &[111, 141], t1: &[153, 111], t2: &[153, 111] },
120 // cbf_cb / cbf_cr (9-22); the fifth context is 154 in every initType
121 InitRow { t0: &[94, 138, 182, 154, 154], t1: &[149, 107, 167, 154, 154], t2: &[149, 92, 167, 154, 154] },
122 // transform_skip_flag (9-25)
123 InitRow { t0: &[139, 139], t1: &[139, 139], t2: &[139, 139] },
124 // last_sig_coeff_x_prefix (9-26)
125 InitRow {
126 t0: &[110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63],
127 t1: &[125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108],
128 t2: &[125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93],
129 },
130 // last_sig_coeff_y_prefix (9-27)
131 InitRow {
132 t0: &[110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63],
133 t1: &[125, 110, 94, 110, 95, 79, 125, 111, 110, 78, 110, 111, 111, 95, 94, 108, 123, 108],
134 t2: &[125, 110, 124, 110, 95, 94, 125, 111, 111, 79, 125, 126, 111, 111, 79, 108, 123, 93],
135 },
136 // coded_sub_block_flag (9-28)
137 InitRow { t0: &[91, 171, 134, 141], t1: &[121, 140, 61, 154], t2: &[121, 140, 61, 154] },
138 // sig_coeff_flag (9-29): 42 transform contexts, then the two transform-skip ones
139 InitRow {
140 t0: &[
141 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107,
142 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 140, 139, 182, 182, 152,
143 136, 152, 136, 153, 136, 139, 111, 136, 139, 111, 141, 111,
144 ],
145 t1: &[
146 155, 154, 139, 153, 139, 123, 123, 63, 153, 166, 183, 140, 136, 153, 154, 166,
147 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170, 153, 123, 123, 107,
148 121, 107, 121, 167, 151, 183, 140, 151, 183, 140, 140, 140,
149 ],
150 t2: &[
151 170, 154, 139, 153, 139, 123, 123, 63, 124, 166, 183, 140, 136, 153, 154, 166,
152 183, 140, 136, 153, 154, 166, 183, 140, 136, 153, 154, 170, 153, 138, 138, 122,
153 121, 122, 121, 167, 151, 183, 140, 151, 183, 140, 140, 140,
154 ],
155 },
156 // coeff_abs_level_greater1_flag (9-30)
157 InitRow {
158 t0: &[
159 140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152,
160 140, 179, 166, 182, 140, 227, 122, 197,
161 ],
162 t1: &[
163 154, 196, 196, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 137,
164 169, 194, 166, 167, 154, 167, 137, 182,
165 ],
166 t2: &[
167 154, 196, 167, 167, 154, 152, 167, 182, 182, 134, 149, 136, 153, 121, 136, 122,
168 169, 208, 166, 167, 154, 152, 167, 182,
169 ],
170 },
171 // coeff_abs_level_greater2_flag (9-31)
172 InitRow { t0: &[138, 153, 136, 167, 152, 152], t1: &[107, 167, 91, 122, 107, 167], t2: &[107, 167, 91, 107, 107, 167] },
173 // cu_skip_flag (9-9): no I-slice value
174 InitRow { t0: &[154, 154, 154], t1: &[197, 185, 201], t2: &[197, 185, 201] },
175 // pred_mode_flag (9-10)
176 InitRow { t0: &[154], t1: &[149], t2: &[134] },
177 // merge_flag (9-15)
178 InitRow { t0: &[154], t1: &[110], t2: &[154] },
179 // merge_idx (9-16)
180 InitRow { t0: &[154], t1: &[122], t2: &[137] },
181 // inter_pred_idc (9-17)
182 InitRow { t0: &[154, 154, 154, 154, 154], t1: &[95, 79, 63, 31, 31], t2: &[95, 79, 63, 31, 31] },
183 // ref_idx_lX (9-18)
184 InitRow { t0: &[154, 154], t1: &[153, 153], t2: &[153, 153] },
185 // mvp_lX_flag (9-19)
186 InitRow { t0: &[154], t1: &[168], t2: &[168] },
187 // abs_mvd_greater0_flag (9-23)
188 InitRow { t0: &[154], t1: &[140], t2: &[169] },
189 // abs_mvd_greater1_flag (9-23)
190 InitRow { t0: &[154], t1: &[198], t2: &[198] },
191 // rqt_root_cbf (9-14)
192 InitRow { t0: &[154], t1: &[79], t2: &[79] },
193 // cu_qp_delta_abs (9-24)
194 InitRow { t0: &[154, 154], t1: &[154, 154], t2: &[154, 154] },
195 // sao_merge_left_flag / sao_merge_up_flag (9-5)
196 InitRow { t0: &[153], t1: &[153], t2: &[153] },
197 // sao_type_idx_luma / sao_type_idx_chroma (9-6)
198 InitRow { t0: &[200], t1: &[185], t2: &[160] },
199 // cu_transquant_bypass_flag (9-22)
200 InitRow { t0: &[154], t1: &[154], t2: &[154] },
201 // cu_chroma_qp_offset_flag (9-38)
202 InitRow { t0: &[154], t1: &[154], t2: &[154] },
203 // cu_chroma_qp_offset_idx (9-39)
204 InitRow { t0: &[154], t1: &[154], t2: &[154] },
205 // explicit_rdpcm_flag (9-40)
206 InitRow { t0: &[139, 139], t1: &[139, 139], t2: &[139, 139] },
207 // explicit_rdpcm_dir_flag (9-41)
208 InitRow { t0: &[139, 139], t1: &[139, 139], t2: &[139, 139] },
209 // log2_res_scale_abs_plus1 (9-42)
210 InitRow { t0: &[154; 8], t1: &[154; 8], t2: &[154; 8] },
211 // res_scale_sign_flag (9-43)
212 InitRow { t0: &[154, 154], t1: &[154, 154], t2: &[154, 154] },
213];
214
215/// `rangeTabLps[pStateIdx][qRangeIdx]` (Table 9-52).
216#[rustfmt::skip]
217const RANGE_TAB_LPS: [[u8; 4]; 64] = [
218 [128, 176, 208, 240], [128, 167, 197, 227], [128, 158, 187, 216], [123, 150, 178, 205],
219 [116, 142, 169, 195], [111, 135, 160, 185], [105, 128, 152, 175], [100, 122, 144, 166],
220 [95, 116, 137, 158], [90, 110, 130, 150], [85, 104, 123, 142], [81, 99, 117, 135],
221 [77, 94, 111, 128], [73, 89, 105, 122], [69, 85, 100, 116], [66, 80, 95, 110],
222 [62, 76, 90, 104], [59, 72, 86, 99], [56, 69, 81, 94], [53, 65, 77, 89],
223 [51, 62, 73, 85], [48, 59, 69, 80], [46, 56, 66, 76], [43, 53, 63, 72],
224 [41, 50, 59, 69], [39, 48, 56, 65], [37, 45, 54, 62], [35, 43, 51, 59],
225 [33, 41, 48, 56], [32, 39, 46, 53], [30, 37, 43, 50], [29, 35, 41, 48],
226 [27, 33, 39, 45], [26, 31, 37, 43], [24, 30, 35, 41], [23, 28, 33, 39],
227 [22, 27, 32, 37], [21, 26, 30, 35], [20, 24, 29, 33], [19, 23, 27, 31],
228 [18, 22, 26, 30], [17, 21, 25, 28], [16, 20, 23, 27], [15, 19, 22, 25],
229 [14, 18, 21, 24], [14, 17, 20, 23], [13, 16, 19, 22], [12, 15, 18, 21],
230 [12, 14, 17, 20], [11, 14, 16, 19], [11, 13, 15, 18], [10, 12, 15, 17],
231 [10, 12, 14, 16], [9, 11, 13, 15], [9, 11, 12, 14], [8, 10, 12, 14],
232 [8, 9, 11, 13], [7, 9, 11, 12], [7, 9, 10, 12], [7, 8, 10, 11],
233 [6, 8, 9, 11], [6, 7, 9, 10], [6, 7, 8, 9], [2, 2, 2, 2],
234];
235
236/// `transIdxLps[pStateIdx]` (Table 9-53).
237#[rustfmt::skip]
238const TRANS_IDX_LPS: [u8; 64] = [
239 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12,
240 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24,
241 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33,
242 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63,
243];
244
245/// `transIdxMps[pStateIdx]` (Table 9-53).
246#[rustfmt::skip]
247const TRANS_IDX_MPS: [u8; 64] = [
248 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
249 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
250 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
251 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63,
252];
253
254/// `ENTROPY_BITS[pStateIdx] = [bits if the bin matches valMps, bits if it
255/// doesn't]`, the fractional-bit cost of a context-coded bin under its
256/// context's current probability state — RDOQ's estimating mode reads this
257/// instead of replaying the exact range-narrowing arithmetic per trial.
258///
259/// HEVC's 64 probability states follow the same geometric decay as H.264's
260/// (Marpe et al.): `pLPS(pStateIdx) = 0.5 * ALPHA^pStateIdx`, `ALPHA =
261/// 0.9493`, running from 0.5 at state 0 down to the ~0.01875 floor at state
262/// 63 that `RANGE_TAB_LPS`'s last row (all `2`s) also converges to. Bits are
263/// `-log2` of the matching/mismatching probability, x265/HM's `entropyBits`
264/// idiom — an entropy estimate, not the coder's own count, so RDOQ under
265/// this mode ranks candidates instead of pricing them exactly.
266static ENTROPY_BITS: LazyLock<[[f64; 2]; 64]> = LazyLock::new(|| {
267 const ALPHA: f64 = 0.9493;
268 std::array::from_fn(|p_state| {
269 let p_lps = 0.5 * ALPHA.powi(p_state as i32);
270 [-(1.0 - p_lps).log2(), -p_lps.log2()]
271 })
272});
273
274/// The context variables, `pStateIdx << 1 | valMps` per entry.
275#[derive(Clone, PartialEq, Eq, Debug)]
276pub struct Contexts {
277 state: [u8; ctx::TOTAL],
278 /// `StatCoeff[0..4]` of persistent Rice adaptation (9.3.2.4); stored and restored with
279 /// the contexts at wavefront and dependent-slice-segment boundaries.
280 pub stat_coeff: [u8; 4],
281}
282
283impl Contexts {
284 /// Initialise every context for an I slice at `slice_qp` (9.3.2.2).
285 pub fn new(slice_qp: i32) -> Contexts {
286 Contexts::for_init_type(slice_qp, 0)
287 }
288
289 /// Initialise every context for `init_type` (0 for I slices, 1 and 2 for
290 /// P and B slices, Table 9-4) at `slice_qp` (9.3.2.2, equations 9-4 to 9-6).
291 pub fn for_init_type(slice_qp: i32, init_type: u8) -> Contexts {
292 let qp = slice_qp.clamp(0, 51);
293 let mut state = [0u8; ctx::TOTAL];
294 let mut k = 0usize;
295 for row in INIT_ROWS {
296 let values = match init_type {
297 0 => row.t0,
298 1 => row.t1,
299 _ => row.t2,
300 };
301 for &init_value in values {
302 if k >= ctx::TOTAL {
303 break;
304 }
305 let slope_idx = (init_value >> 4) as i32;
306 let offset_idx = (init_value & 15) as i32;
307 let m = slope_idx * 5 - 45;
308 let n = (offset_idx << 3) - 16;
309 let pre_ctx_state = (((m * qp) >> 4) + n).clamp(1, 126);
310 let val_mps = i32::from(pre_ctx_state > 63);
311 let p_state = if val_mps == 1 {
312 pre_ctx_state - 64
313 } else {
314 63 - pre_ctx_state
315 };
316 state[k] = ((p_state as u8) << 1) | val_mps as u8;
317 k += 1;
318 }
319 }
320 Contexts {
321 state,
322 stat_coeff: [0; 4],
323 }
324 }
325}
326
327/// A rollback point for [`CabacEncoder`].
328///
329/// A plain [`CabacEncoder::snapshot`] rewinds by truncation, which is all a
330/// trial-and-discard needs. A [`CabacEncoder::snapshot_since`] also carries the
331/// bytes written since an earlier point, which is what a trial-and-*keep* needs:
332/// a second trial overwrites the first one's bytes in place, so rewinding to a
333/// length alone would leave the loser's bytes in the winner's positions.
334#[derive(Clone)]
335pub struct CabacState {
336 low: u32,
337 range: u32,
338 bits_outstanding: u32,
339 first_bit: bool,
340 bits: u64,
341 out_len: usize,
342 tail_base: usize,
343 tail: Vec<u8>,
344 partial: u8,
345 partial_bits: u8,
346 contexts: Contexts,
347 /// [`CabacEncoder::est_bits`] at snapshot time, restored alongside it.
348 est_bits: f64,
349}
350
351/// The CABAC encoding engine (9.3.5).
352#[derive(Clone)]
353pub struct CabacEncoder {
354 low: u32,
355 range: u32,
356 bits_outstanding: u32,
357 first_bit: bool,
358 /// Bits written, counted whether or not they are kept.
359 bits: u64,
360 /// `None` while estimating a rate rather than producing a bitstream.
361 out: Option<Vec<u8>>,
362 /// While set, bins are coded and counted but no bytes are kept — what a
363 /// rate-distortion trial wants, since its bytes are about to be thrown away.
364 counting: bool,
365 partial: u8,
366 partial_bits: u8,
367 /// Context variables, public to the modules that index them by name.
368 pub contexts: Contexts,
369 /// While set, `encode_bin`/`encode_bypass*` skip the range/renorm
370 /// arithmetic entirely and instead accumulate [`ENTROPY_BITS`]-table
371 /// lookups into `est_bits` — RDOQ's trial-costing instrument only; the
372 /// committing encoder never sets this. `low`/`range`/`bits_outstanding`
373 /// are left untouched while this is set, so a `restore()` back to a
374 /// snapshot taken before estimating began is exact.
375 estimating: bool,
376 /// Fractional bits accumulated while `estimating`; read by
377 /// [`CabacEncoder::bit_count_f64`].
378 est_bits: f64,
379}
380
381impl CabacEncoder {
382 /// A fresh engine writing into its own buffer.
383 pub fn new(contexts: Contexts) -> CabacEncoder {
384 CabacEncoder {
385 low: 0,
386 range: 510,
387 bits_outstanding: 0,
388 first_bit: true,
389 bits: 0,
390 out: Some(Vec::new()),
391 counting: false,
392 partial: 0,
393 partial_bits: 0,
394 contexts,
395 estimating: false,
396 est_bits: 0.0,
397 }
398 }
399
400 /// An engine that counts bits and writes nothing — the rate half of every
401 /// rate-distortion decision.
402 pub fn counter(contexts: Contexts) -> CabacEncoder {
403 let mut enc = CabacEncoder::new(contexts);
404 enc.out = None;
405 enc
406 }
407
408 /// Bits produced so far, including the ones a counting engine discards.
409 /// In `estimating` mode this is stale (the estimating path never
410 /// increments it) — read [`CabacEncoder::bit_count_f64`] instead.
411 pub fn bit_count(&self) -> u64 {
412 self.bits
413 }
414
415 /// [`CabacEncoder::bit_count`], but fractional and estimating-mode-aware:
416 /// the exact bit count as `f64` normally, or the accumulated
417 /// [`ENTROPY_BITS`] estimate while `estimating` is set.
418 pub fn bit_count_f64(&self) -> f64 {
419 if self.estimating {
420 self.est_bits
421 } else {
422 self.bits as f64
423 }
424 }
425
426 /// Whether the engine is in `estimating` mode.
427 pub fn is_estimating(&self) -> bool {
428 self.estimating
429 }
430
431 /// Add `bits` to the estimating-mode total (a caller's own closed-form estimate).
432 pub fn add_estimated_bits(&mut self, bits: f64) {
433 self.est_bits += bits;
434 }
435
436 /// Switch between exact range/renorm costing and the estimated
437 /// per-context fracbits table. See the `estimating` field.
438 pub fn set_estimating(&mut self, estimating: bool) {
439 self.estimating = estimating;
440 }
441
442 /// Code bins without keeping their bytes; the counter still runs.
443 pub fn set_counting(&mut self, counting: bool) {
444 self.counting = counting;
445 }
446
447 fn write_bit(&mut self, bit: u32) {
448 self.bits += 1;
449 if self.counting {
450 return;
451 }
452 if let Some(out) = &mut self.out {
453 self.partial = (self.partial << 1) | (bit as u8);
454 self.partial_bits += 1;
455 if self.partial_bits == 8 {
456 out.push(self.partial);
457 self.partial = 0;
458 self.partial_bits = 0;
459 }
460 }
461 }
462
463 fn put_bit(&mut self, bit: u32) {
464 if self.first_bit {
465 self.first_bit = false;
466 } else {
467 self.write_bit(bit);
468 }
469 while self.bits_outstanding > 0 {
470 self.write_bit(1 - bit);
471 self.bits_outstanding -= 1;
472 }
473 }
474
475 fn renorm(&mut self) {
476 while self.range < 256 {
477 if self.low < 256 {
478 self.put_bit(0);
479 } else if self.low >= 512 {
480 self.low -= 512;
481 self.put_bit(1);
482 } else {
483 self.low -= 256;
484 self.bits_outstanding += 1;
485 }
486 self.range <<= 1;
487 self.low <<= 1;
488 }
489 }
490
491 /// Take a snapshot the encoder can be rolled back to.
492 ///
493 /// This is what makes exact rate measurement affordable: a trial encode runs
494 /// into the real coder, its bits are read off the counter, and the coder is
495 /// put back. The cost is one 129-byte context copy, not a copy of the
496 /// substream written so far.
497 pub fn snapshot(&self) -> CabacState {
498 let out_len = self.out.as_ref().map_or(0, |o| o.len());
499 CabacState {
500 low: self.low,
501 range: self.range,
502 bits_outstanding: self.bits_outstanding,
503 first_bit: self.first_bit,
504 bits: self.bits,
505 out_len,
506 tail_base: out_len,
507 tail: Vec::new(),
508 partial: self.partial,
509 partial_bits: self.partial_bits,
510 contexts: self.contexts.clone(),
511 est_bits: self.est_bits,
512 }
513 }
514
515 /// A snapshot that also carries the bytes written since `base`, so that
516 /// restoring it puts those bytes back after a competing trial overwrote
517 /// them.
518 pub fn snapshot_since(&self, base: &CabacState) -> CabacState {
519 let mut state = self.snapshot();
520 state.tail_base = base.out_len;
521 if let Some(out) = &self.out {
522 state.tail = out[base.out_len..].to_vec();
523 }
524 state
525 }
526
527 /// Roll back to a snapshot.
528 pub fn restore(&mut self, state: &CabacState) {
529 self.low = state.low;
530 self.range = state.range;
531 self.bits_outstanding = state.bits_outstanding;
532 self.first_bit = state.first_bit;
533 self.bits = state.bits;
534 self.partial = state.partial;
535 self.partial_bits = state.partial_bits;
536 self.contexts.clone_from(&state.contexts);
537 self.est_bits = state.est_bits;
538 if let Some(out) = &mut self.out {
539 out.truncate(state.tail_base);
540 out.extend_from_slice(&state.tail);
541 debug_assert_eq!(out.len(), state.out_len);
542 }
543 }
544
545 /// Encode one context-coded bin (9.3.5.3).
546 #[inline]
547 pub fn encode_bin(&mut self, ctx_idx: usize, bin: u32) {
548 let state = self.contexts.state[ctx_idx];
549 let p_state = (state >> 1) as usize;
550 let val_mps = u32::from(state & 1);
551 if self.estimating {
552 self.est_bits += ENTROPY_BITS[p_state][usize::from(bin != val_mps)];
553 self.contexts.state[ctx_idx] = if bin != val_mps {
554 let new_mps = if p_state == 0 { 1 - val_mps } else { val_mps };
555 (TRANS_IDX_LPS[p_state] << 1) | new_mps as u8
556 } else {
557 (TRANS_IDX_MPS[p_state] << 1) | val_mps as u8
558 };
559 return;
560 }
561 let q_range_idx = ((self.range >> 6) & 3) as usize;
562 let lps_range = u32::from(RANGE_TAB_LPS[p_state][q_range_idx]);
563 self.range -= lps_range;
564 if bin != val_mps {
565 self.low += self.range;
566 self.range = lps_range;
567 let new_mps = if p_state == 0 { 1 - val_mps } else { val_mps };
568 self.contexts.state[ctx_idx] = (TRANS_IDX_LPS[p_state] << 1) | new_mps as u8;
569 } else {
570 self.contexts.state[ctx_idx] = (TRANS_IDX_MPS[p_state] << 1) | val_mps as u8;
571 }
572 self.renorm();
573 }
574
575 /// Encode one bypass bin (9.3.5.5).
576 #[inline]
577 pub fn encode_bypass(&mut self, bin: u32) {
578 if self.estimating {
579 // Bypass bins are uncontexted and uniform-probability: the real
580 // coder's carry propagation can occasionally defer more than one
581 // output bit to a later call, but the standard entropy estimate
582 // (x265/HM alike) is exactly one bit per bypass bin.
583 self.est_bits += 1.0;
584 return;
585 }
586 self.low <<= 1;
587 if bin != 0 {
588 self.low += self.range;
589 }
590 if self.low >= 1024 {
591 self.put_bit(1);
592 self.low -= 1024;
593 } else if self.low < 512 {
594 self.put_bit(0);
595 } else {
596 self.low -= 512;
597 self.bits_outstanding += 1;
598 }
599 }
600
601 /// Encode `count` bypass bins from the low bits of `value`, most
602 /// significant first.
603 pub fn encode_bypass_bits(&mut self, value: u32, count: u32) {
604 for i in (0..count).rev() {
605 self.encode_bypass((value >> i) & 1);
606 }
607 }
608
609 /// Encode a terminating bin: `end_of_slice_segment_flag` or
610 /// `end_of_subset_one_bit` (9.3.5.6). A one flushes the engine.
611 pub fn encode_terminate(&mut self, bin: u32) {
612 self.range -= 2;
613 if bin != 0 {
614 self.low += self.range;
615 self.flush();
616 } else {
617 self.renorm();
618 }
619 }
620
621 fn flush(&mut self) {
622 self.range = 2;
623 self.renorm();
624 self.put_bit((self.low >> 9) & 1);
625 // The last two bits, the low one always set: it is the
626 // rbsp_stop_one_bit or the alignment_bit_equal_to_one.
627 self.write_bit((self.low >> 8) & 1);
628 self.write_bit(1);
629 }
630
631 /// Finish a substream: pad the last byte with zeros and hand back the bytes.
632 ///
633 /// Only valid after [`CabacEncoder::encode_terminate`] with a one bin, which
634 /// is where the flush happened.
635 pub fn finish(mut self) -> Vec<u8> {
636 let mut out = self.out.take().unwrap_or_default();
637 if self.partial_bits > 0 {
638 out.push(self.partial << (8 - self.partial_bits));
639 }
640 out
641 }
642}
643
644/// The CABAC decoding engine (9.3.4.3.2), the mirror image of
645/// [`CabacEncoder`]: same context tables, same `RANGE_TAB_LPS` /
646/// `TRANS_IDX_LPS` / `TRANS_IDX_MPS`, so a context updates identically on
647/// both sides and a decoded bin is exactly the bin the encoder wrote.
648///
649/// Reads bits MSB-first from `data` starting at bit 0; a read past the end of
650/// `data` returns zero, the standard convention for the handful of bits a
651/// CABAC engine may read past a substream's real end while renormalising
652/// around its final terminating bin.
653pub struct CabacDecoder<'a> {
654 data: &'a [u8],
655 bit: usize,
656 range: u32,
657 offset: u32,
658 /// Context variables, public for the same reason [`CabacEncoder::contexts`] is.
659 pub contexts: Contexts,
660}
661
662impl<'a> CabacDecoder<'a> {
663 /// A fresh engine reading `data` from its first bit (9.3.2.5 init).
664 pub fn new(data: &'a [u8], contexts: Contexts) -> CabacDecoder<'a> {
665 let mut d = CabacDecoder {
666 data,
667 bit: 0,
668 range: 510,
669 offset: 0,
670 contexts,
671 };
672 for _ in 0..9 {
673 d.offset = (d.offset << 1) | d.read_bit();
674 }
675 d
676 }
677
678 fn read_bit(&mut self) -> u32 {
679 let byte = self.data.get(self.bit / 8).copied().unwrap_or(0);
680 let bit = u32::from((byte >> (7 - (self.bit % 8))) & 1);
681 self.bit += 1;
682 bit
683 }
684
685 /// Decode one context-coded bin (9.3.4.3.2.2).
686 pub fn decode_bin(&mut self, ctx_idx: usize) -> u32 {
687 let state = self.contexts.state[ctx_idx];
688 let p_state = (state >> 1) as usize;
689 let val_mps = u32::from(state & 1);
690 let q = ((self.range >> 6) & 3) as usize;
691 let lps = u32::from(RANGE_TAB_LPS[p_state][q]);
692 self.range -= lps;
693 let bin;
694 if self.offset >= self.range {
695 bin = 1 - val_mps;
696 self.offset -= self.range;
697 self.range = lps;
698 let new_mps = if p_state == 0 { 1 - val_mps } else { val_mps };
699 self.contexts.state[ctx_idx] = (TRANS_IDX_LPS[p_state] << 1) | new_mps as u8;
700 } else {
701 bin = val_mps;
702 self.contexts.state[ctx_idx] = (TRANS_IDX_MPS[p_state] << 1) | val_mps as u8;
703 }
704 while self.range < 256 {
705 self.range <<= 1;
706 self.offset = (self.offset << 1) | self.read_bit();
707 }
708 bin
709 }
710
711 /// Decode one bypass bin (9.3.4.3.4).
712 pub fn decode_bypass(&mut self) -> u32 {
713 self.offset = (self.offset << 1) | self.read_bit();
714 if self.offset >= self.range {
715 self.offset -= self.range;
716 1
717 } else {
718 0
719 }
720 }
721
722 /// Decode `count` bypass bins into one value, most significant first.
723 pub fn decode_bypass_bits(&mut self, count: u32) -> u32 {
724 let mut v = 0;
725 for _ in 0..count {
726 v = (v << 1) | self.decode_bypass();
727 }
728 v
729 }
730
731 /// Decode a terminating bin: `end_of_slice_segment_flag` or
732 /// `end_of_subset_one_bit` (9.3.4.3.5).
733 pub fn decode_terminate(&mut self) -> u32 {
734 self.range -= 2;
735 if self.offset >= self.range {
736 1
737 } else {
738 while self.range < 256 {
739 self.range <<= 1;
740 self.offset = (self.offset << 1) | self.read_bit();
741 }
742 0
743 }
744 }
745
746 /// Byte offset, from the start of `data`, of the substream after a
747 /// `decode_terminate() == 1`: the encoder's flush always pads to a byte
748 /// boundary here, so the next WPP row's substream starts exactly there.
749 pub fn byte_position_aligned(&self) -> usize {
750 self.bit.div_ceil(8)
751 }
752
753 /// Bits of the slice data read so far, including the bits read ahead by the
754 /// 9-bit offset register (9.3.2.5).
755 pub fn bits_read(&self) -> usize {
756 self.bit
757 }
758
759 /// The slice data this engine reads.
760 pub fn data(&self) -> &'a [u8] {
761 self.data
762 }
763
764 /// Restart the arithmetic decoder at byte `byte` of the data (9.3.2.5 after
765 /// PCM samples): the offset is read again, the contexts are kept.
766 pub fn restart_at_byte(&mut self, byte: usize) {
767 self.bit = byte * 8;
768 self.range = 510;
769 self.offset = 0;
770 for _ in 0..9 {
771 self.offset = (self.offset << 1) | self.read_bit();
772 }
773 }
774}
775
776#[cfg(test)]
777mod tests {
778 use super::*;
779
780 #[test]
781 fn decoder_inverts_the_encoder_bin_by_bin() {
782 // Every context-coded and bypass bin the encoder can write, decoded
783 // back through the same context table, must reproduce the exact
784 // sequence: this is what makes a CABAC decoder a mirror rather than a
785 // second implementation that might disagree with the first.
786 let bins: Vec<(usize, u32)> = (0..NUM_CONTEXTS)
787 .flat_map(|ctx| [(ctx, 0u32), (ctx, 1), (ctx, 0), (ctx, 1), (ctx, 1)])
788 .collect();
789 let mut enc = CabacEncoder::new(Contexts::new(27));
790 for &(ctx, bin) in &bins {
791 enc.encode_bin(ctx, bin);
792 }
793 for i in 0..37u32 {
794 enc.encode_bypass(i & 1);
795 }
796 enc.encode_terminate(1);
797 let bytes = enc.finish();
798
799 let mut dec = CabacDecoder::new(&bytes, Contexts::new(27));
800 for &(ctx, bin) in &bins {
801 assert_eq!(dec.decode_bin(ctx), bin);
802 }
803 for i in 0..37u32 {
804 assert_eq!(dec.decode_bypass(), i & 1);
805 }
806 assert_eq!(dec.decode_terminate(), 1);
807 }
808
809 #[test]
810 fn context_init_matches_the_worked_formula() {
811 // initValue 154 is the "no slope" entry: m = 0, n = 64, so every QP
812 // lands on preCtxState 64, valMps 1, pStateIdx 0.
813 let init_value: u8 = 154;
814 let m = (init_value >> 4) as i32 * 5 - 45;
815 let n = (((init_value & 15) as i32) << 3) - 16;
816 assert_eq!((m, n), (0, 64));
817 // And a real one: split_cu_flag ctx 0 (139) at QP 30.
818 let ctxs = Contexts::new(30);
819 let m = (139u8 >> 4) as i32 * 5 - 45;
820 let n = (((139u8 & 15) as i32) << 3) - 16;
821 let pre = (((m * 30) >> 4) + n).clamp(1, 126);
822 let expect = if pre > 63 {
823 (((pre - 64) as u8) << 1) | 1
824 } else {
825 ((63 - pre) as u8) << 1
826 };
827 assert_eq!(ctxs.state[ctx::SPLIT_CU], expect);
828 }
829
830 #[test]
831 fn state_tables_are_consistent() {
832 // Every LPS transition moves towards the uncertain end, every MPS
833 // transition towards the certain one, and state 63 is absorbing.
834 for s in 0..64usize {
835 assert!(TRANS_IDX_LPS[s] as usize <= s);
836 assert!(TRANS_IDX_MPS[s] as usize >= s);
837 assert!(TRANS_IDX_MPS[s] < 64 && TRANS_IDX_LPS[s] < 64);
838 // rangeTabLps shrinks as the state gets more certain.
839 if s > 0 {
840 for (q, &value) in RANGE_TAB_LPS[s].iter().enumerate() {
841 assert!(value <= RANGE_TAB_LPS[s - 1][q]);
842 }
843 }
844 }
845 assert_eq!(TRANS_IDX_LPS[63], 63);
846 assert_eq!(TRANS_IDX_MPS[63], 63);
847 }
848
849 #[test]
850 fn counting_engine_tracks_the_writing_engine() {
851 let mut writer = CabacEncoder::new(Contexts::new(30));
852 let mut counter = CabacEncoder::counter(Contexts::new(30));
853 for i in 0..500u32 {
854 let bin = (i * 7 % 5) & 1;
855 writer.encode_bin(ctx::SIG_COEFF + (i as usize % 44), bin);
856 counter.encode_bin(ctx::SIG_COEFF + (i as usize % 44), bin);
857 writer.encode_bypass(bin);
858 counter.encode_bypass(bin);
859 }
860 assert_eq!(writer.bit_count(), counter.bit_count());
861 assert_eq!(writer.contexts, counter.contexts);
862 }
863
864 #[test]
865 fn the_spec_decoder_reads_back_what_the_encoder_wrote() {
866 // A long mixed sequence: context bins across many contexts, bypass bins,
867 // and the terminating bin that flushes. If the engine's carry handling
868 // or state transitions were wrong, this diverges within a few bins —
869 // which is exactly the failure a real decoder shows as a broken picture.
870 let mut plan: Vec<(usize, u32, u8)> = Vec::new(); // (ctx or 0, bin, kind)
871 let mut seed = 12345u32;
872 let mut rand = move || {
873 seed = seed.wrapping_mul(1103515245).wrapping_add(12345);
874 (seed >> 16) & 0x7fff
875 };
876 for i in 0..3000 {
877 let kind = if i % 7 == 3 { 1 } else { 0 };
878 let ctx = (rand() as usize) % ctx::TOTAL;
879 let bin = if i % 5 == 0 { 1 } else { rand() & 1 };
880 plan.push((ctx, bin, kind));
881 }
882 let mut enc = CabacEncoder::new(Contexts::new(32));
883 for &(ctx_idx, bin, kind) in &plan {
884 if kind == 0 {
885 enc.encode_bin(ctx_idx, bin);
886 } else {
887 enc.encode_bypass(bin);
888 }
889 }
890 enc.encode_terminate(1);
891 let bytes = enc.finish();
892
893 let mut dec = CabacDecoder::new(&bytes, Contexts::new(32));
894 for (i, &(ctx_idx, bin, kind)) in plan.iter().enumerate() {
895 let got = if kind == 0 {
896 dec.decode_bin(ctx_idx)
897 } else {
898 dec.decode_bypass()
899 };
900 assert_eq!(got, bin, "bin {i} (ctx {ctx_idx}, kind {kind})");
901 }
902 assert_eq!(dec.decode_terminate(), 1, "terminating bin");
903 }
904
905 #[test]
906 fn a_skewed_symbol_stream_compresses() {
907 // 4000 zeros through one adapting context must cost far less than 4000
908 // bits — the property that makes the engine an arithmetic coder at all.
909 let mut enc = CabacEncoder::new(Contexts::new(30));
910 for _ in 0..4000 {
911 enc.encode_bin(ctx::SIG_COEFF, 0);
912 }
913 enc.encode_terminate(1);
914 let bits = enc.bit_count();
915 let bytes = enc.finish();
916 assert!(bits < 400, "{bits} bits for 4000 skewed bins");
917 assert!(!bytes.is_empty());
918 }
919}
920
921#[cfg(test)]
922mod init_table_tests {
923 use super::*;
924
925 /// Every syntax element's init row covers exactly its contexts, in all three
926 /// initTypes, so `Contexts::for_init_type` never reads past a row.
927 #[test]
928 fn init_rows_cover_every_context_for_each_init_type() {
929 let total: usize = INIT_ROWS.iter().map(|r| r.t0.len()).sum();
930 assert_eq!(total, ctx::TOTAL);
931 for row in INIT_ROWS {
932 assert_eq!(row.t0.len(), row.t1.len());
933 assert_eq!(row.t0.len(), row.t2.len());
934 }
935 }
936
937 /// initType 0 reproduces the I-slice states the intra path has always used.
938 #[test]
939 fn init_type_zero_is_the_intra_table() {
940 assert_eq!(Contexts::new(30), Contexts::for_init_type(30, 0));
941 assert_ne!(
942 Contexts::for_init_type(30, 0),
943 Contexts::for_init_type(30, 1)
944 );
945 assert_ne!(
946 Contexts::for_init_type(30, 1),
947 Contexts::for_init_type(30, 2)
948 );
949 }
950}