forge
Explore
Log in

Don't you dare go Hollow

Integer transforms, quantiser and the CABAC coder

Browse files at this commit

990d3ac834b35f8b8e1d8144d1bebee332a92f1eAhmet Kaan GümüşParent: 0d07f18
  • feat
    • integer transforms, quantiser and the CABAC coder
Show full message
feat(h265): integer transforms, quantiser and the CABAC coder

The inverse transform and the dequantiser are the normative ones, so the
encoder's reconstruction is what a decoder produces. Only the first 16
columns of the 32x32 matrix are typed in; the rest follow from the
matrix's own symmetry, and tests check both the printed second half and
orthogonality, because a mistyped column is the classic defect here.

The CABAC coder can run in counting mode - identical context updates, no
bytes kept - which is how rate-distortion decisions are priced at the
rate they actually cost. A spec-derived decoder in the tests reads back
what the encoder writes.
crates/ec-h265/Cargo.tomladded+11 -0
@@ -0,0 +1,11 @@
1+[package]
2+name = "ec-h265"
3+description = "Intra-only HEVC (H.265) encoder with wavefront-parallel encoding inside one call."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core.workspace = true
11+ec-h265-syntax.workspace = true
crates/ec-h265/src/cabac.rsadded+597 -0
@@ -0,0 +1,597 @@
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+/// Number of context variables this encoder keeps.
11+pub const NUM_CONTEXTS: usize = ctx::TOTAL;
12+
13+/// Context index layout: one named base per syntax element, I-slice only.
14+pub mod ctx {
15+ /// `split_cu_flag`, 3 contexts.
16+ pub const SPLIT_CU: usize = 0;
17+ /// `part_mode`, 1 context in an I slice.
18+ pub const PART_MODE: usize = SPLIT_CU + 3;
19+ /// `prev_intra_luma_pred_flag`.
20+ pub const PREV_INTRA_LUMA_PRED: usize = PART_MODE + 1;
21+ /// `intra_chroma_pred_mode`.
22+ pub const INTRA_CHROMA_PRED_MODE: usize = PREV_INTRA_LUMA_PRED + 1;
23+ /// `split_transform_flag`, 3 contexts.
24+ pub const SPLIT_TRANSFORM: usize = INTRA_CHROMA_PRED_MODE + 1;
25+ /// `cbf_luma`, 2 contexts.
26+ pub const CBF_LUMA: usize = SPLIT_TRANSFORM + 3;
27+ /// `cbf_cb` / `cbf_cr`, 4 contexts.
28+ pub const CBF_CHROMA: usize = CBF_LUMA + 2;
29+ /// `last_sig_coeff_x_prefix`, 18 contexts.
30+ pub const LAST_X: usize = CBF_CHROMA + 4;
31+ /// `last_sig_coeff_y_prefix`, 18 contexts.
32+ pub const LAST_Y: usize = LAST_X + 18;
33+ /// `coded_sub_block_flag`, 4 contexts.
34+ pub const CODED_SUB_BLOCK: usize = LAST_Y + 18;
35+ /// `sig_coeff_flag`, 44 contexts (42 transform + 2 transform-skip).
36+ pub const SIG_COEFF: usize = CODED_SUB_BLOCK + 4;
37+ /// `coeff_abs_level_greater1_flag`, 24 contexts.
38+ pub const GREATER1: usize = SIG_COEFF + 44;
39+ /// `coeff_abs_level_greater2_flag`, 6 contexts.
40+ pub const GREATER2: usize = GREATER1 + 24;
41+ /// Total context count.
42+ pub const TOTAL: usize = GREATER2 + 6;
43+}
44+
45+/// `initValue` for every context, initType 0 (I slices), Tables 9-7 to 9-31.
46+#[rustfmt::skip]
47+const INIT_VALUES: [u8; ctx::TOTAL] = [
48+ // split_cu_flag (Table 9-7)
49+ 139, 141, 157,
50+ // part_mode (Table 9-11)
51+ 184,
52+ // prev_intra_luma_pred_flag (Table 9-12)
53+ 184,
54+ // intra_chroma_pred_mode (Table 9-13)
55+ 63,
56+ // split_transform_flag (Table 9-20)
57+ 153, 138, 138,
58+ // cbf_luma (Table 9-21)
59+ 111, 141,
60+ // cbf_cb / cbf_cr (Table 9-22)
61+ 94, 138, 182, 154,
62+ // last_sig_coeff_x_prefix (Table 9-26)
63+ 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63,
64+ // last_sig_coeff_y_prefix (Table 9-27)
65+ 110, 110, 124, 125, 140, 153, 125, 127, 140, 109, 111, 143, 127, 111, 79, 108, 123, 63,
66+ // coded_sub_block_flag (Table 9-28)
67+ 91, 171, 134, 141,
68+ // sig_coeff_flag (Table 9-29), ctxIdx 0..41 then the two transform-skip ones
69+ 111, 111, 125, 110, 110, 94, 124, 108, 124, 107, 125, 141, 179, 153, 125, 107,
70+ 125, 141, 179, 153, 125, 107, 125, 141, 179, 153, 125, 140, 139, 182, 182, 152,
71+ 136, 152, 136, 153, 136, 139, 111, 136, 139, 111,
72+ 141, 111,
73+ // coeff_abs_level_greater1_flag (Table 9-30)
74+ 140, 92, 137, 138, 140, 152, 138, 139, 153, 74, 149, 92, 139, 107, 122, 152,
75+ 140, 179, 166, 182, 140, 227, 122, 197,
76+ // coeff_abs_level_greater2_flag (Table 9-31)
77+ 138, 153, 136, 167, 152, 152,
78+];
79+
80+/// `rangeTabLps[pStateIdx][qRangeIdx]` (Table 9-52).
81+#[rustfmt::skip]
82+const RANGE_TAB_LPS: [[u8; 4]; 64] = [
83+ [128, 176, 208, 240], [128, 167, 197, 227], [128, 158, 187, 216], [123, 150, 178, 205],
84+ [116, 142, 169, 195], [111, 135, 160, 185], [105, 128, 152, 175], [100, 122, 144, 166],
85+ [95, 116, 137, 158], [90, 110, 130, 150], [85, 104, 123, 142], [81, 99, 117, 135],
86+ [77, 94, 111, 128], [73, 89, 105, 122], [69, 85, 100, 116], [66, 80, 95, 110],
87+ [62, 76, 90, 104], [59, 72, 86, 99], [56, 69, 81, 94], [53, 65, 77, 89],
88+ [51, 62, 73, 85], [48, 59, 69, 80], [46, 56, 66, 76], [43, 53, 63, 72],
89+ [41, 50, 59, 69], [39, 48, 56, 65], [37, 45, 54, 62], [35, 43, 51, 59],
90+ [33, 41, 48, 56], [32, 39, 46, 53], [30, 37, 43, 50], [29, 35, 41, 48],
91+ [27, 33, 39, 45], [26, 31, 37, 43], [24, 30, 35, 41], [23, 28, 33, 39],
92+ [22, 27, 32, 37], [21, 26, 30, 35], [20, 24, 29, 33], [19, 23, 27, 31],
93+ [18, 22, 26, 30], [17, 21, 25, 28], [16, 20, 23, 27], [15, 19, 22, 25],
94+ [14, 18, 21, 24], [14, 17, 20, 23], [13, 16, 19, 22], [12, 15, 18, 21],
95+ [12, 14, 17, 20], [11, 14, 16, 19], [11, 13, 15, 18], [10, 12, 15, 17],
96+ [10, 12, 14, 16], [9, 11, 13, 15], [9, 11, 12, 14], [8, 10, 12, 14],
97+ [8, 9, 11, 13], [7, 9, 11, 12], [7, 9, 10, 12], [7, 8, 10, 11],
98+ [6, 8, 9, 11], [6, 7, 9, 10], [6, 7, 8, 9], [2, 2, 2, 2],
99+];
100+
101+/// `transIdxLps[pStateIdx]` (Table 9-53).
102+#[rustfmt::skip]
103+const TRANS_IDX_LPS: [u8; 64] = [
104+ 0, 0, 1, 2, 2, 4, 4, 5, 6, 7, 8, 9, 9, 11, 11, 12,
105+ 13, 13, 15, 15, 16, 16, 18, 18, 19, 19, 21, 21, 22, 22, 23, 24,
106+ 24, 25, 26, 26, 27, 27, 28, 29, 29, 30, 30, 30, 31, 32, 32, 33,
107+ 33, 33, 34, 34, 35, 35, 35, 36, 36, 36, 37, 37, 37, 38, 38, 63,
108+];
109+
110+/// `transIdxMps[pStateIdx]` (Table 9-53).
111+#[rustfmt::skip]
112+const TRANS_IDX_MPS: [u8; 64] = [
113+ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14, 15, 16,
114+ 17, 18, 19, 20, 21, 22, 23, 24, 25, 26, 27, 28, 29, 30, 31, 32,
115+ 33, 34, 35, 36, 37, 38, 39, 40, 41, 42, 43, 44, 45, 46, 47, 48,
116+ 49, 50, 51, 52, 53, 54, 55, 56, 57, 58, 59, 60, 61, 62, 62, 63,
117+];
118+
119+/// The context variables, `pStateIdx << 1 | valMps` per entry.
120+#[derive(Clone, PartialEq, Eq, Debug)]
121+pub struct Contexts {
122+ state: [u8; ctx::TOTAL],
123+}
124+
125+impl Contexts {
126+ /// Initialise every context for an I slice at `slice_qp` (9.3.2.2).
127+ pub fn new(slice_qp: i32) -> Contexts {
128+ let qp = slice_qp.clamp(0, 51);
129+ let mut state = [0u8; ctx::TOTAL];
130+ for (i, &init_value) in INIT_VALUES.iter().enumerate() {
131+ let slope_idx = (init_value >> 4) as i32;
132+ let offset_idx = (init_value & 15) as i32;
133+ let m = slope_idx * 5 - 45;
134+ let n = (offset_idx << 3) - 16;
135+ let pre_ctx_state = (((m * qp) >> 4) + n).clamp(1, 126);
136+ let val_mps = i32::from(pre_ctx_state > 63);
137+ let p_state = if val_mps == 1 {
138+ pre_ctx_state - 64
139+ } else {
140+ 63 - pre_ctx_state
141+ };
142+ state[i] = ((p_state as u8) << 1) | val_mps as u8;
143+ }
144+ Contexts { state }
145+ }
146+}
147+
148+/// A rollback point for [`CabacEncoder`].
149+///
150+/// A plain [`CabacEncoder::snapshot`] rewinds by truncation, which is all a
151+/// trial-and-discard needs. A [`CabacEncoder::snapshot_since`] also carries the
152+/// bytes written since an earlier point, which is what a trial-and-*keep* needs:
153+/// a second trial overwrites the first one's bytes in place, so rewinding to a
154+/// length alone would leave the loser's bytes in the winner's positions.
155+#[derive(Clone)]
156+pub struct CabacState {
157+ low: u32,
158+ range: u32,
159+ bits_outstanding: u32,
160+ first_bit: bool,
161+ bits: u64,
162+ out_len: usize,
163+ tail_base: usize,
164+ tail: Vec<u8>,
165+ partial: u8,
166+ partial_bits: u8,
167+ contexts: Contexts,
168+}
169+
170+/// The CABAC encoding engine (9.3.5).
171+#[derive(Clone)]
172+pub struct CabacEncoder {
173+ low: u32,
174+ range: u32,
175+ bits_outstanding: u32,
176+ first_bit: bool,
177+ /// Bits written, counted whether or not they are kept.
178+ bits: u64,
179+ /// `None` while estimating a rate rather than producing a bitstream.
180+ out: Option<Vec<u8>>,
181+ /// While set, bins are coded and counted but no bytes are kept — what a
182+ /// rate-distortion trial wants, since its bytes are about to be thrown away.
183+ counting: bool,
184+ partial: u8,
185+ partial_bits: u8,
186+ /// Context variables, public to the modules that index them by name.
187+ pub contexts: Contexts,
188+}
189+
190+impl CabacEncoder {
191+ /// A fresh engine writing into its own buffer.
192+ pub fn new(contexts: Contexts) -> CabacEncoder {
193+ CabacEncoder {
194+ low: 0,
195+ range: 510,
196+ bits_outstanding: 0,
197+ first_bit: true,
198+ bits: 0,
199+ out: Some(Vec::new()),
200+ counting: false,
201+ partial: 0,
202+ partial_bits: 0,
203+ contexts,
204+ }
205+ }
206+
207+ /// An engine that counts bits and writes nothing — the rate half of every
208+ /// rate-distortion decision.
209+ pub fn counter(contexts: Contexts) -> CabacEncoder {
210+ let mut enc = CabacEncoder::new(contexts);
211+ enc.out = None;
212+ enc
213+ }
214+
215+ /// Bits produced so far, including the ones a counting engine discards.
216+ pub fn bit_count(&self) -> u64 {
217+ self.bits
218+ }
219+
220+ /// Code bins without keeping their bytes; the counter still runs.
221+ pub fn set_counting(&mut self, counting: bool) {
222+ self.counting = counting;
223+ }
224+
225+ fn write_bit(&mut self, bit: u32) {
226+ self.bits += 1;
227+ if self.counting {
228+ return;
229+ }
230+ if let Some(out) = &mut self.out {
231+ self.partial = (self.partial << 1) | (bit as u8);
232+ self.partial_bits += 1;
233+ if self.partial_bits == 8 {
234+ out.push(self.partial);
235+ self.partial = 0;
236+ self.partial_bits = 0;
237+ }
238+ }
239+ }
240+
241+ fn put_bit(&mut self, bit: u32) {
242+ if self.first_bit {
243+ self.first_bit = false;
244+ } else {
245+ self.write_bit(bit);
246+ }
247+ while self.bits_outstanding > 0 {
248+ self.write_bit(1 - bit);
249+ self.bits_outstanding -= 1;
250+ }
251+ }
252+
253+ fn renorm(&mut self) {
254+ while self.range < 256 {
255+ if self.low < 256 {
256+ self.put_bit(0);
257+ } else if self.low >= 512 {
258+ self.low -= 512;
259+ self.put_bit(1);
260+ } else {
261+ self.low -= 256;
262+ self.bits_outstanding += 1;
263+ }
264+ self.range <<= 1;
265+ self.low <<= 1;
266+ }
267+ }
268+
269+ /// Take a snapshot the encoder can be rolled back to.
270+ ///
271+ /// This is what makes exact rate measurement affordable: a trial encode runs
272+ /// into the real coder, its bits are read off the counter, and the coder is
273+ /// put back. The cost is one 129-byte context copy, not a copy of the
274+ /// substream written so far.
275+ pub fn snapshot(&self) -> CabacState {
276+ let out_len = self.out.as_ref().map_or(0, |o| o.len());
277+ CabacState {
278+ low: self.low,
279+ range: self.range,
280+ bits_outstanding: self.bits_outstanding,
281+ first_bit: self.first_bit,
282+ bits: self.bits,
283+ out_len,
284+ tail_base: out_len,
285+ tail: Vec::new(),
286+ partial: self.partial,
287+ partial_bits: self.partial_bits,
288+ contexts: self.contexts.clone(),
289+ }
290+ }
291+
292+ /// A snapshot that also carries the bytes written since `base`, so that
293+ /// restoring it puts those bytes back after a competing trial overwrote
294+ /// them.
295+ pub fn snapshot_since(&self, base: &CabacState) -> CabacState {
296+ let mut state = self.snapshot();
297+ state.tail_base = base.out_len;
298+ if let Some(out) = &self.out {
299+ state.tail = out[base.out_len..].to_vec();
300+ }
301+ state
302+ }
303+
304+ /// Roll back to a snapshot.
305+ pub fn restore(&mut self, state: &CabacState) {
306+ self.low = state.low;
307+ self.range = state.range;
308+ self.bits_outstanding = state.bits_outstanding;
309+ self.first_bit = state.first_bit;
310+ self.bits = state.bits;
311+ self.partial = state.partial;
312+ self.partial_bits = state.partial_bits;
313+ self.contexts.clone_from(&state.contexts);
314+ if let Some(out) = &mut self.out {
315+ out.truncate(state.tail_base);
316+ out.extend_from_slice(&state.tail);
317+ debug_assert_eq!(out.len(), state.out_len);
318+ }
319+ }
320+
321+ /// Encode one context-coded bin (9.3.5.3).
322+ #[inline]
323+ pub fn encode_bin(&mut self, ctx_idx: usize, bin: u32) {
324+ let state = self.contexts.state[ctx_idx];
325+ let p_state = (state >> 1) as usize;
326+ let val_mps = u32::from(state & 1);
327+ let q_range_idx = ((self.range >> 6) & 3) as usize;
328+ let lps_range = u32::from(RANGE_TAB_LPS[p_state][q_range_idx]);
329+ self.range -= lps_range;
330+ if bin != val_mps {
331+ self.low += self.range;
332+ self.range = lps_range;
333+ let new_mps = if p_state == 0 { 1 - val_mps } else { val_mps };
334+ self.contexts.state[ctx_idx] = (TRANS_IDX_LPS[p_state] << 1) | new_mps as u8;
335+ } else {
336+ self.contexts.state[ctx_idx] = (TRANS_IDX_MPS[p_state] << 1) | val_mps as u8;
337+ }
338+ self.renorm();
339+ }
340+
341+ /// Encode one bypass bin (9.3.5.5).
342+ #[inline]
343+ pub fn encode_bypass(&mut self, bin: u32) {
344+ self.low <<= 1;
345+ if bin != 0 {
346+ self.low += self.range;
347+ }
348+ if self.low >= 1024 {
349+ self.put_bit(1);
350+ self.low -= 1024;
351+ } else if self.low < 512 {
352+ self.put_bit(0);
353+ } else {
354+ self.low -= 512;
355+ self.bits_outstanding += 1;
356+ }
357+ }
358+
359+ /// Encode `count` bypass bins from the low bits of `value`, most
360+ /// significant first.
361+ pub fn encode_bypass_bits(&mut self, value: u32, count: u32) {
362+ for i in (0..count).rev() {
363+ self.encode_bypass((value >> i) & 1);
364+ }
365+ }
366+
367+ /// Encode a terminating bin: `end_of_slice_segment_flag` or
368+ /// `end_of_subset_one_bit` (9.3.5.6). A one flushes the engine.
369+ pub fn encode_terminate(&mut self, bin: u32) {
370+ self.range -= 2;
371+ if bin != 0 {
372+ self.low += self.range;
373+ self.flush();
374+ } else {
375+ self.renorm();
376+ }
377+ }
378+
379+ fn flush(&mut self) {
380+ self.range = 2;
381+ self.renorm();
382+ self.put_bit((self.low >> 9) & 1);
383+ // The last two bits, the low one always set: it is the
384+ // rbsp_stop_one_bit or the alignment_bit_equal_to_one.
385+ self.write_bit((self.low >> 8) & 1);
386+ self.write_bit(1);
387+ }
388+
389+ /// Finish a substream: pad the last byte with zeros and hand back the bytes.
390+ ///
391+ /// Only valid after [`CabacEncoder::encode_terminate`] with a one bin, which
392+ /// is where the flush happened.
393+ pub fn finish(mut self) -> Vec<u8> {
394+ let mut out = self.out.take().unwrap_or_default();
395+ if self.partial_bits > 0 {
396+ out.push(self.partial << (8 - self.partial_bits));
397+ }
398+ out
399+ }
400+}
401+
402+#[cfg(test)]
403+mod tests {
404+ use super::*;
405+
406+ #[test]
407+ fn context_init_matches_the_worked_formula() {
408+ // initValue 154 is the "no slope" entry: m = 0, n = 64, so every QP
409+ // lands on preCtxState 64, valMps 1, pStateIdx 0.
410+ let init_value: u8 = 154;
411+ let m = (init_value >> 4) as i32 * 5 - 45;
412+ let n = (((init_value & 15) as i32) << 3) - 16;
413+ assert_eq!((m, n), (0, 64));
414+ // And a real one: split_cu_flag ctx 0 (139) at QP 30.
415+ let ctxs = Contexts::new(30);
416+ let m = (139u8 >> 4) as i32 * 5 - 45;
417+ let n = (((139u8 & 15) as i32) << 3) - 16;
418+ let pre = (((m * 30) >> 4) + n).clamp(1, 126);
419+ let expect = if pre > 63 {
420+ (((pre - 64) as u8) << 1) | 1
421+ } else {
422+ ((63 - pre) as u8) << 1
423+ };
424+ assert_eq!(ctxs.state[ctx::SPLIT_CU], expect);
425+ }
426+
427+ #[test]
428+ fn state_tables_are_consistent() {
429+ // Every LPS transition moves towards the uncertain end, every MPS
430+ // transition towards the certain one, and state 63 is absorbing.
431+ for s in 0..64usize {
432+ assert!(TRANS_IDX_LPS[s] as usize <= s);
433+ assert!(TRANS_IDX_MPS[s] as usize >= s);
434+ assert!(TRANS_IDX_MPS[s] < 64 && TRANS_IDX_LPS[s] < 64);
435+ // rangeTabLps shrinks as the state gets more certain.
436+ if s > 0 {
437+ for q in 0..4 {
438+ assert!(RANGE_TAB_LPS[s][q] <= RANGE_TAB_LPS[s - 1][q]);
439+ }
440+ }
441+ }
442+ assert_eq!(TRANS_IDX_LPS[63], 63);
443+ assert_eq!(TRANS_IDX_MPS[63], 63);
444+ }
445+
446+ #[test]
447+ fn counting_engine_tracks_the_writing_engine() {
448+ let mut writer = CabacEncoder::new(Contexts::new(30));
449+ let mut counter = CabacEncoder::counter(Contexts::new(30));
450+ for i in 0..500u32 {
451+ let bin = (i * 7 % 5) & 1;
452+ writer.encode_bin(ctx::SIG_COEFF + (i as usize % 44), bin);
453+ counter.encode_bin(ctx::SIG_COEFF + (i as usize % 44), bin);
454+ writer.encode_bypass(bin);
455+ counter.encode_bypass(bin);
456+ }
457+ assert_eq!(writer.bit_count(), counter.bit_count());
458+ assert_eq!(writer.contexts, counter.contexts);
459+ }
460+
461+ /// The decoding engine of 9.3.4.3, written from the normative flowcharts,
462+ /// as an oracle for the encoder above.
463+ struct RefDecoder<'a> {
464+ data: &'a [u8],
465+ bit: usize,
466+ range: u32,
467+ offset: u32,
468+ contexts: Contexts,
469+ }
470+
471+ impl<'a> RefDecoder<'a> {
472+ fn new(data: &'a [u8], contexts: Contexts) -> RefDecoder<'a> {
473+ let mut d = RefDecoder {
474+ data,
475+ bit: 0,
476+ range: 510,
477+ offset: 0,
478+ contexts,
479+ };
480+ for _ in 0..9 {
481+ d.offset = (d.offset << 1) | d.read_bit();
482+ }
483+ d
484+ }
485+
486+ fn read_bit(&mut self) -> u32 {
487+ let byte = self.data.get(self.bit / 8).copied().unwrap_or(0);
488+ let bit = u32::from((byte >> (7 - (self.bit % 8))) & 1);
489+ self.bit += 1;
490+ bit
491+ }
492+
493+ fn decode_bin(&mut self, ctx_idx: usize) -> u32 {
494+ let state = self.contexts.state[ctx_idx];
495+ let p_state = (state >> 1) as usize;
496+ let val_mps = u32::from(state & 1);
497+ let q = ((self.range >> 6) & 3) as usize;
498+ let lps = u32::from(RANGE_TAB_LPS[p_state][q]);
499+ self.range -= lps;
500+ let bin;
501+ if self.offset >= self.range {
502+ bin = 1 - val_mps;
503+ self.offset -= self.range;
504+ self.range = lps;
505+ let new_mps = if p_state == 0 { 1 - val_mps } else { val_mps };
506+ self.contexts.state[ctx_idx] = (TRANS_IDX_LPS[p_state] << 1) | new_mps as u8;
507+ } else {
508+ bin = val_mps;
509+ self.contexts.state[ctx_idx] = (TRANS_IDX_MPS[p_state] << 1) | val_mps as u8;
510+ }
511+ while self.range < 256 {
512+ self.range <<= 1;
513+ self.offset = (self.offset << 1) | self.read_bit();
514+ }
515+ bin
516+ }
517+
518+ fn decode_bypass(&mut self) -> u32 {
519+ self.offset = (self.offset << 1) | self.read_bit();
520+ if self.offset >= self.range {
521+ self.offset -= self.range;
522+ 1
523+ } else {
524+ 0
525+ }
526+ }
527+
528+ fn decode_terminate(&mut self) -> u32 {
529+ self.range -= 2;
530+ if self.offset >= self.range {
531+ 1
532+ } else {
533+ while self.range < 256 {
534+ self.range <<= 1;
535+ self.offset = (self.offset << 1) | self.read_bit();
536+ }
537+ 0
538+ }
539+ }
540+ }
541+
542+ #[test]
543+ fn the_spec_decoder_reads_back_what_the_encoder_wrote() {
544+ // A long mixed sequence: context bins across many contexts, bypass bins,
545+ // and the terminating bin that flushes. If the engine's carry handling
546+ // or state transitions were wrong, this diverges within a few bins —
547+ // which is exactly the failure a real decoder shows as a broken picture.
548+ let mut plan: Vec<(usize, u32, u8)> = Vec::new(); // (ctx or 0, bin, kind)
549+ let mut seed = 12345u32;
550+ let mut rand = move || {
551+ seed = seed.wrapping_mul(1103515245).wrapping_add(12345);
552+ (seed >> 16) & 0x7fff
553+ };
554+ for i in 0..3000 {
555+ let kind = if i % 7 == 3 { 1 } else { 0 };
556+ let ctx = (rand() as usize) % ctx::TOTAL;
557+ let bin = if i % 5 == 0 { 1 } else { rand() & 1 };
558+ plan.push((ctx, bin, kind));
559+ }
560+ let mut enc = CabacEncoder::new(Contexts::new(32));
561+ for &(ctx_idx, bin, kind) in &plan {
562+ if kind == 0 {
563+ enc.encode_bin(ctx_idx, bin);
564+ } else {
565+ enc.encode_bypass(bin);
566+ }
567+ }
568+ enc.encode_terminate(1);
569+ let bytes = enc.finish();
570+
571+ let mut dec = RefDecoder::new(&bytes, Contexts::new(32));
572+ for (i, &(ctx_idx, bin, kind)) in plan.iter().enumerate() {
573+ let got = if kind == 0 {
574+ dec.decode_bin(ctx_idx)
575+ } else {
576+ dec.decode_bypass()
577+ };
578+ assert_eq!(got, bin, "bin {i} (ctx {ctx_idx}, kind {kind})");
579+ }
580+ assert_eq!(dec.decode_terminate(), 1, "terminating bin");
581+ }
582+
583+ #[test]
584+ fn a_skewed_symbol_stream_compresses() {
585+ // 4000 zeros through one adapting context must cost far less than 4000
586+ // bits — the property that makes the engine an arithmetic coder at all.
587+ let mut enc = CabacEncoder::new(Contexts::new(30));
588+ for _ in 0..4000 {
589+ enc.encode_bin(ctx::SIG_COEFF, 0);
590+ }
591+ enc.encode_terminate(1);
592+ let bits = enc.bit_count();
593+ let bytes = enc.finish();
594+ assert!(bits < 400, "{bits} bits for 4000 skewed bins");
595+ assert!(!bytes.is_empty());
596+ }
597+}
crates/ec-h265/src/lib.rsadded+7 -0
@@ -0,0 +1,7 @@
1+//! Intra-only HEVC encoder.
2+#![forbid(unsafe_code)]
3+#![warn(missing_docs)]
4+
5+pub mod cabac;
6+pub mod residual;
7+pub mod transform;
crates/ec-h265/src/residual.rsadded+510 -0
@@ -0,0 +1,510 @@
1+//! `residual_coding()` (7.3.8.11) and the scan orders it walks (6.5.3 - 6.5.5).
2+
3+use crate::cabac::{CabacEncoder, ctx};
4+use std::sync::LazyLock;
5+
6+/// Scan orders: `SCANS[log2BlockSize][scanIdx][pos] = (x, y)`.
7+///
8+/// Built once rather than typed in — the diagonal scan is four lines of the
9+/// spec's own pseudo-code, and generating it cannot go wrong the way a
10+/// transcribed 64-entry table can.
11+static SCANS: LazyLock<[[Vec<(u8, u8)>; 3]; 4]> = LazyLock::new(|| {
12+ std::array::from_fn(|log2_size| {
13+ let size = 1usize << log2_size;
14+ std::array::from_fn(|scan_idx| match scan_idx {
15+ 1 => (0..size * size)
16+ .map(|i| ((i % size) as u8, (i / size) as u8))
17+ .collect(),
18+ 2 => (0..size * size)
19+ .map(|i| ((i / size) as u8, (i % size) as u8))
20+ .collect(),
21+ _ => {
22+ // 6.5.3, up-right diagonal.
23+ let mut out = Vec::with_capacity(size * size);
24+ let (mut x, mut y) = (0usize, 0usize);
25+ loop {
26+ loop {
27+ if x < size && y < size {
28+ out.push((x as u8, y as u8));
29+ }
30+ if y == 0 {
31+ break;
32+ }
33+ y -= 1;
34+ x += 1;
35+ }
36+ y = x + 1;
37+ x = 0;
38+ if out.len() >= size * size {
39+ break;
40+ }
41+ }
42+ out
43+ }
44+ })
45+ })
46+});
47+
48+/// `ctxIdxMap[i]` for 4x4 blocks (Table 9-50); index 15 is never queried
49+/// because that position is always the last significant one.
50+const CTX_IDX_MAP: [usize; 16] = [0, 1, 4, 5, 2, 3, 4, 5, 6, 6, 8, 8, 7, 7, 8, 8];
51+
52+/// The scan order for one block size and scan index.
53+pub fn scan(log2_size: u32, scan_idx: usize) -> &'static [(u8, u8)] {
54+ &SCANS[log2_size as usize][scan_idx]
55+}
56+
57+/// Truncated-Rice + EGk binarization of `coeff_abs_level_remaining` (9.3.3.11).
58+fn encode_remaining(enc: &mut CabacEncoder, value: u32, rice: u32) {
59+ let c_max = 4 << rice;
60+ if value < c_max {
61+ let prefix = value >> rice;
62+ for _ in 0..prefix {
63+ enc.encode_bypass(1);
64+ }
65+ enc.encode_bypass(0);
66+ if rice > 0 {
67+ enc.encode_bypass_bits(value & ((1 << rice) - 1), rice);
68+ }
69+ } else {
70+ for _ in 0..4 {
71+ enc.encode_bypass(1);
72+ }
73+ let mut rest = value - c_max;
74+ let mut k = rice + 1;
75+ loop {
76+ if rest >= (1 << k) {
77+ enc.encode_bypass(1);
78+ rest -= 1 << k;
79+ k += 1;
80+ } else {
81+ enc.encode_bypass(0);
82+ enc.encode_bypass_bits(rest, k);
83+ break;
84+ }
85+ }
86+ }
87+}
88+
89+/// `last_sig_coeff_*_prefix` for a coordinate, and its suffix bit count.
90+fn last_prefix(coord: u32) -> (u32, u32) {
91+ if coord < 4 {
92+ (coord, 0)
93+ } else {
94+ let log2 = 31 - coord.leading_zeros();
95+ let prefix = 2 * log2 + ((coord >> (log2 - 1)) & 1);
96+ (prefix, (prefix >> 1) - 1)
97+ }
98+}
99+
100+/// Encode one transform block's levels.
101+///
102+/// `levels` is row-major `n x n` with `levels[y * n + x]`, `c_idx` is 0 for luma
103+/// and 1/2 for chroma, and at least one level must be non-zero (the caller codes
104+/// a `cbf` of zero instead).
105+pub fn encode_residual(
106+ enc: &mut CabacEncoder,
107+ levels: &[i32],
108+ log2_size: u32,
109+ c_idx: usize,
110+ scan_idx: usize,
111+) {
112+ let n = 1usize << log2_size;
113+ let sub_wide = n >> 2;
114+ let sub_scan = scan(log2_size - 2, scan_idx);
115+ let pos_scan = scan(2, scan_idx);
116+ let chroma = c_idx > 0;
117+
118+ // The last significant coefficient in scan order.
119+ let mut last_sub = 0usize;
120+ let mut last_pos = 0usize;
121+ 'outer: for i in (0..sub_scan.len()).rev() {
122+ let (xs, ys) = sub_scan[i];
123+ for p in (0..16).rev() {
124+ let (xp, yp) = pos_scan[p];
125+ let xc = (xs as usize) * 4 + xp as usize;
126+ let yc = (ys as usize) * 4 + yp as usize;
127+ if levels[yc * n + xc] != 0 {
128+ last_sub = i;
129+ last_pos = p;
130+ break 'outer;
131+ }
132+ }
133+ }
134+ let (last_xs, last_ys) = sub_scan[last_sub];
135+ let (last_xp, last_yp) = pos_scan[last_pos];
136+ let mut last_x = (last_xs as u32) * 4 + last_xp as u32;
137+ let mut last_y = (last_ys as u32) * 4 + last_yp as u32;
138+ if scan_idx == 2 {
139+ std::mem::swap(&mut last_x, &mut last_y);
140+ }
141+
142+ // last_sig_coeff_x/y prefix and suffix (9.3.4.2.3 for the contexts).
143+ let (offset, shift) = if c_idx == 0 {
144+ (
145+ 3 * (log2_size - 2) + ((log2_size - 1) >> 2),
146+ (log2_size + 1) >> 2,
147+ )
148+ } else {
149+ (15, log2_size - 2)
150+ };
151+ let c_max = (log2_size << 1) - 1;
152+ let (x_prefix, x_suffix_bits) = last_prefix(last_x);
153+ let (y_prefix, y_suffix_bits) = last_prefix(last_y);
154+ for (prefix, base) in [(x_prefix, ctx::LAST_X), (y_prefix, ctx::LAST_Y)] {
155+ for bin in 0..prefix {
156+ enc.encode_bin(base + ((bin >> shift) + offset) as usize, 1);
157+ }
158+ if prefix < c_max {
159+ enc.encode_bin(base + ((prefix >> shift) + offset) as usize, 0);
160+ }
161+ }
162+ if x_suffix_bits > 0 {
163+ let base = (1 << x_suffix_bits) * (2 + (x_prefix & 1));
164+ enc.encode_bypass_bits(last_x - base, x_suffix_bits);
165+ }
166+ if y_suffix_bits > 0 {
167+ let base = (1 << y_suffix_bits) * (2 + (y_prefix & 1));
168+ enc.encode_bypass_bits(last_y - base, y_suffix_bits);
169+ }
170+
171+ let mut csbf = [false; 64];
172+ csbf[last_ys as usize * sub_wide + last_xs as usize] = true;
173+ // The DC sub-block is always coded (7.4.9.11 inference).
174+ let (dc_xs, dc_ys) = sub_scan[0];
175+ csbf[dc_ys as usize * sub_wide + dc_xs as usize] = true;
176+ // Mark every sub-block that holds a level, so the neighbour contexts below
177+ // see the same flags the decoder will.
178+ for &(xs, ys) in sub_scan.iter().take(last_sub) {
179+ let (xs, ys) = (xs as usize, ys as usize);
180+ let mut any = false;
181+ for row in 0..4 {
182+ let base = (ys * 4 + row) * n + xs * 4;
183+ if levels[base..base + 4].iter().any(|&v| v != 0) {
184+ any = true;
185+ break;
186+ }
187+ }
188+ if any {
189+ csbf[ys * sub_wide + xs] = true;
190+ }
191+ }
192+
193+ let mut greater1_ctx = 1u32;
194+ for i in (0..=last_sub).rev() {
195+ let (xs, ys) = sub_scan[i];
196+ let (xs, ys) = (xs as usize, ys as usize);
197+ let coded = csbf[ys * sub_wide + xs];
198+ let mut infer_dc_sig = false;
199+ if i < last_sub && i > 0 {
200+ let mut csbf_ctx = 0;
201+ if xs < sub_wide - 1 && csbf[ys * sub_wide + xs + 1] {
202+ csbf_ctx += 1;
203+ }
204+ if ys < sub_wide - 1 && csbf[(ys + 1) * sub_wide + xs] {
205+ csbf_ctx += 1;
206+ }
207+ let inc = if chroma {
208+ 2 + csbf_ctx.min(1)
209+ } else {
210+ csbf_ctx.min(1)
211+ };
212+ enc.encode_bin(ctx::CODED_SUB_BLOCK + inc, u32::from(coded));
213+ infer_dc_sig = true;
214+ }
215+ if !coded {
216+ continue;
217+ }
218+
219+ // sig_coeff_flag over the sub-block, high scan position first.
220+ let mut significant = [false; 16];
221+ if i == last_sub {
222+ significant[last_pos] = true;
223+ }
224+ let first = if i == last_sub { last_pos as i32 - 1 } else { 15 };
225+ let mut scan_pos = first;
226+ while scan_pos >= 0 {
227+ let p = scan_pos as usize;
228+ scan_pos -= 1;
229+ let (xp, yp) = pos_scan[p];
230+ let xc = xs * 4 + xp as usize;
231+ let yc = ys * 4 + yp as usize;
232+ let sig = levels[yc * n + xc] != 0;
233+ if p > 0 || !infer_dc_sig {
234+ let inc = sig_ctx_inc(xc, yc, xs, ys, sub_wide, &csbf, log2_size, c_idx, scan_idx);
235+ enc.encode_bin(ctx::SIG_COEFF + inc, u32::from(sig));
236+ }
237+ significant[p] = sig;
238+ if sig {
239+ infer_dc_sig = false;
240+ }
241+ }
242+ if infer_dc_sig {
243+ // The flag was not coded because it is inferred to be one.
244+ significant[0] = true;
245+ }
246+
247+ let mut order = [0usize; 16];
248+ let mut order_len = 0;
249+ for p in (0..16).rev() {
250+ if significant[p] {
251+ order[order_len] = p;
252+ order_len += 1;
253+ }
254+ }
255+ let order = &order[..order_len];
256+ if order.is_empty() {
257+ continue;
258+ }
259+
260+ // coeff_abs_level_greater1_flag, first eight only (9.3.4.2.6).
261+ let mut ctx_set = if i == 0 || chroma { 0 } else { 2 };
262+ if greater1_ctx == 0 {
263+ ctx_set += 1;
264+ }
265+ greater1_ctx = 1;
266+ let mut last_greater1 = None;
267+ let mut greater1 = [false; 16];
268+ for &p in order.iter().take(8) {
269+ let (xp, yp) = pos_scan[p];
270+ let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
271+ let flag = level > 1;
272+ let inc = ctx_set * 4 + greater1_ctx.min(3) + if chroma { 16 } else { 0 };
273+ enc.encode_bin(ctx::GREATER1 + inc as usize, u32::from(flag));
274+ greater1[p] = flag;
275+ if flag {
276+ if last_greater1.is_none() {
277+ last_greater1 = Some(p);
278+ }
279+ greater1_ctx = 0;
280+ } else if greater1_ctx > 0 {
281+ greater1_ctx += 1;
282+ }
283+ }
284+
285+ // coeff_abs_level_greater2_flag for the first greater-than-one level.
286+ let mut greater2 = false;
287+ if let Some(p) = last_greater1 {
288+ let (xp, yp) = pos_scan[p];
289+ let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
290+ greater2 = level > 2;
291+ let inc = ctx_set + if chroma { 4 } else { 0 };
292+ enc.encode_bin(ctx::GREATER2 + inc as usize, u32::from(greater2));
293+ }
294+
295+ // Signs, then the remaining magnitudes. Sign data hiding is off, so
296+ // every significant coefficient carries its own sign bit.
297+ for &p in order {
298+ let (xp, yp) = pos_scan[p];
299+ let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize];
300+ enc.encode_bypass(u32::from(level < 0));
301+ }
302+ let mut rice = 0u32;
303+ let mut num_sig = 0usize;
304+ for &p in order {
305+ let (xp, yp) = pos_scan[p];
306+ let level = levels[(ys * 4 + yp as usize) * n + xs * 4 + xp as usize].unsigned_abs();
307+ let coded_greater1 = num_sig < 8;
308+ let base_level = 1
309+ + u32::from(coded_greater1 && greater1[p])
310+ + u32::from(last_greater1 == Some(p) && greater2);
311+ let threshold = if num_sig < 8 {
312+ if last_greater1 == Some(p) { 3 } else { 2 }
313+ } else {
314+ 1
315+ };
316+ if base_level == threshold {
317+ let remaining = level - base_level;
318+ encode_remaining(enc, remaining, rice);
319+ rice = (rice + u32::from(level > (3 << rice))).min(4);
320+ }
321+ num_sig += 1;
322+ }
323+ }
324+}
325+
326+/// `ctxInc` for `sig_coeff_flag` (9.3.4.2.5).
327+#[allow(clippy::too_many_arguments)]
328+fn sig_ctx_inc(
329+ xc: usize,
330+ yc: usize,
331+ xs: usize,
332+ ys: usize,
333+ sub_wide: usize,
334+ csbf: &[bool],
335+ log2_size: u32,
336+ c_idx: usize,
337+ scan_idx: usize,
338+) -> usize {
339+ let mut sig_ctx;
340+ if log2_size == 2 {
341+ sig_ctx = CTX_IDX_MAP[(yc << 2) + xc];
342+ } else if xc + yc == 0 {
343+ sig_ctx = 0;
344+ } else {
345+ let mut prev_csbf = 0usize;
346+ if xs < sub_wide - 1 && csbf[ys * sub_wide + xs + 1] {
347+ prev_csbf += 1;
348+ }
349+ if ys < sub_wide - 1 && csbf[(ys + 1) * sub_wide + xs] {
350+ prev_csbf += 2;
351+ }
352+ let (xp, yp) = (xc & 3, yc & 3);
353+ sig_ctx = match prev_csbf {
354+ 0 => {
355+ if xp + yp == 0 {
356+ 2
357+ } else if xp + yp < 3 {
358+ 1
359+ } else {
360+ 0
361+ }
362+ }
363+ 1 => {
364+ if yp == 0 {
365+ 2
366+ } else if yp == 1 {
367+ 1
368+ } else {
369+ 0
370+ }
371+ }
372+ 2 => {
373+ if xp == 0 {
374+ 2
375+ } else if xp == 1 {
376+ 1
377+ } else {
378+ 0
379+ }
380+ }
381+ _ => 2,
382+ };
383+ if c_idx == 0 {
384+ if xs + ys > 0 {
385+ sig_ctx += 3;
386+ }
387+ if log2_size == 3 {
388+ sig_ctx += if scan_idx == 0 { 9 } else { 15 };
389+ } else {
390+ sig_ctx += 21;
391+ }
392+ } else if log2_size == 3 {
393+ sig_ctx += 9;
394+ } else {
395+ sig_ctx += 12;
396+ }
397+ }
398+ if c_idx == 0 { sig_ctx } else { 27 + sig_ctx }
399+}
400+
401+#[cfg(test)]
402+mod tests {
403+ use super::*;
404+ use crate::cabac::Contexts;
405+
406+ #[test]
407+ fn diagonal_scan_matches_the_spec_walk() {
408+ // 4x4 up-right diagonal, from 6.5.3.
409+ let expect: Vec<(u8, u8)> = vec![
410+ (0, 0),
411+ (0, 1),
412+ (1, 0),
413+ (0, 2),
414+ (1, 1),
415+ (2, 0),
416+ (0, 3),
417+ (1, 2),
418+ (2, 1),
419+ (3, 0),
420+ (1, 3),
421+ (2, 2),
422+ (3, 1),
423+ (2, 3),
424+ (3, 2),
425+ (3, 3),
426+ ];
427+ assert_eq!(scan(2, 0), &expect[..]);
428+ // Horizontal and vertical are the plain raster orders.
429+ assert_eq!(scan(2, 1)[..4], [(0, 0), (1, 0), (2, 0), (3, 0)]);
430+ assert_eq!(scan(2, 2)[..4], [(0, 0), (0, 1), (0, 2), (0, 3)]);
431+ // Every size is a permutation of its block.
432+ for log2 in 0..4u32 {
433+ for idx in 0..3 {
434+ let s = scan(log2, idx);
435+ let size = 1usize << log2;
436+ assert_eq!(s.len(), size * size);
437+ let mut seen = vec![false; size * size];
438+ for &(x, y) in s {
439+ let slot = y as usize * size + x as usize;
440+ assert!(!seen[slot]);
441+ seen[slot] = true;
442+ }
443+ }
444+ }
445+ }
446+
447+ #[test]
448+ fn last_position_binarization_inverts_the_spec_formula() {
449+ for coord in 0..32u32 {
450+ let (prefix, suffix_bits) = last_prefix(coord);
451+ let decoded = if suffix_bits == 0 {
452+ prefix
453+ } else {
454+ let base = (1 << ((prefix >> 1) - 1)) * (2 + (prefix & 1));
455+ let suffix = coord - base;
456+ assert!(suffix < (1 << suffix_bits), "coord {coord}");
457+ base + suffix
458+ };
459+ assert_eq!(decoded, coord);
460+ assert!(prefix <= 9, "coord {coord} prefix {prefix}");
461+ }
462+ }
463+
464+ #[test]
465+ fn residual_coding_costs_less_for_sparser_blocks() {
466+ // Not a bit-exactness check — that is the ffmpeg conformance test — but
467+ // the invariant that makes rate-distortion decisions meaningful: fewer
468+ // and smaller levels must cost fewer bits.
469+ let mut sparse = vec![0i32; 64];
470+ sparse[0] = 1;
471+ let mut dense = vec![0i32; 64];
472+ for (i, v) in dense.iter_mut().enumerate() {
473+ *v = ((i % 7) as i32) - 3;
474+ }
475+ let mut costs = Vec::new();
476+ for levels in [&sparse, &dense] {
477+ let mut enc = CabacEncoder::counter(Contexts::new(30));
478+ encode_residual(&mut enc, levels, 3, 0, 0);
479+ costs.push(enc.bit_count());
480+ }
481+ assert!(costs[0] < costs[1], "{costs:?}");
482+ assert!(costs[0] > 0);
483+ }
484+
485+ #[test]
486+ fn every_block_size_and_scan_codes_without_panicking() {
487+ for log2 in 2..=5u32 {
488+ let n = 1usize << log2;
489+ for scan_idx in 0..3 {
490+ for c_idx in [0usize, 1] {
491+ let mut levels = vec![0i32; n * n];
492+ for (i, v) in levels.iter_mut().enumerate() {
493+ *v = match i % 11 {
494+ 0 => 0,
495+ 1 => 1,
496+ 2 => -2,
497+ 3 => 3,
498+ 4 => -17,
499+ 5 => 400,
500+ _ => 0,
501+ };
502+ }
503+ let mut enc = CabacEncoder::counter(Contexts::new(27));
504+ encode_residual(&mut enc, &levels, log2, c_idx, scan_idx);
505+ assert!(enc.bit_count() > 0);
506+ }
507+ }
508+ }
509+ }
510+}
crates/ec-h265/src/transform.rsadded+454 -0
@@ -0,0 +1,454 @@
1+//! The integer transforms and the quantizer (8.6.2 - 8.6.4).
2+//!
3+//! The *inverse* path here is normative: a decoder does exactly this, so the
4+//! encoder's reconstruction runs the same code and is bit-identical to what any
5+//! conformant decoder produces. The forward path and the quantizer are the
6+//! encoder's own choice; what makes them correct is that they invert the
7+//! normative path — which is what [`tests::round_trip_recovers_flat_blocks`]
8+//! and the ffmpeg conformance test in `tests/` check.
9+//!
10+//! One transcription safeguard is worth naming: only the first 16 columns of the
11+//! 32x32 matrix are typed in. The rest follow from `M[m][31 - n] = (-1)^m M[m][n]`,
12+//! which the spec's own second half satisfies, and a test asserts that half back
13+//! entry by entry. A wrong column is the classic defect in this kind of table
14+//! (it cost this family a week in H.264), so the table is checked against
15+//! orthogonality as well as against the printed values.
16+
17+/// Columns 0..15 of `transMatrix` (8-319), rows 0..31.
18+///
19+/// The size-N transform uses rows `k * (32 / N)` and columns `0..N`.
20+#[rustfmt::skip]
21+const TRANS_MATRIX_HALF: [[i32; 16]; 32] = [
22+ [64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64, 64],
23+ [90, 90, 88, 85, 82, 78, 73, 67, 61, 54, 46, 38, 31, 22, 13, 4],
24+ [90, 87, 80, 70, 57, 43, 25, 9, -9, -25, -43, -57, -70, -80, -87, -90],
25+ [90, 82, 67, 46, 22, -4, -31, -54, -73, -85, -90, -88, -78, -61, -38, -13],
26+ [89, 75, 50, 18, -18, -50, -75, -89, -89, -75, -50, -18, 18, 50, 75, 89],
27+ [88, 67, 31, -13, -54, -82, -90, -78, -46, -4, 38, 73, 90, 85, 61, 22],
28+ [87, 57, 9, -43, -80, -90, -70, -25, 25, 70, 90, 80, 43, -9, -57, -87],
29+ [85, 46, -13, -67, -90, -73, -22, 38, 82, 88, 54, -4, -61, -90, -78, -31],
30+ [83, 36, -36, -83, -83, -36, 36, 83, 83, 36, -36, -83, -83, -36, 36, 83],
31+ [82, 22, -54, -90, -61, 13, 78, 85, 31, -46, -90, -67, 4, 73, 88, 38],
32+ [80, 9, -70, -87, -25, 57, 90, 43, -43, -90, -57, 25, 87, 70, -9, -80],
33+ [78, -4, -82, -73, 13, 85, 67, -22, -88, -61, 31, 90, 54, -38, -90, -46],
34+ [75, -18, -89, -50, 50, 89, 18, -75, -75, 18, 89, 50, -50, -89, -18, 75],
35+ [73, -31, -90, -22, 78, 67, -38, -90, -13, 82, 61, -46, -88, -4, 85, 54],
36+ [70, -43, -87, 9, 90, 25, -80, -57, 57, 80, -25, -90, -9, 87, 43, -70],
37+ [67, -54, -78, 38, 85, -22, -90, 4, 90, 13, -88, -31, 82, 46, -73, -61],
38+ [64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64, 64, -64, -64, 64],
39+ [61, -73, -46, 82, 31, -88, -13, 90, -4, -90, 22, 85, -38, -78, 54, 67],
40+ [57, -80, -25, 90, -9, -87, 43, 70, -70, -43, 87, 9, -90, 25, 80, -57],
41+ [54, -85, -4, 88, -46, -61, 82, 13, -90, 38, 67, -78, -22, 90, -31, -73],
42+ [50, -89, 18, 75, -75, -18, 89, -50, -50, 89, -18, -75, 75, 18, -89, 50],
43+ [46, -90, 38, 54, -90, 31, 61, -88, 22, 67, -85, 13, 73, -82, 4, 78],
44+ [43, -90, 57, 25, -87, 70, 9, -80, 80, -9, -70, 87, -25, -57, 90, -43],
45+ [38, -88, 73, -4, -67, 90, -46, -31, 85, -78, 13, 61, -90, 54, 22, -82],
46+ [36, -83, 83, -36, -36, 83, -83, 36, 36, -83, 83, -36, -36, 83, -83, 36],
47+ [31, -78, 90, -61, 4, 54, -88, 82, -38, -22, 73, -90, 67, -13, -46, 85],
48+ [25, -70, 90, -80, 43, 9, -57, 87, -87, 57, -9, -43, 80, -90, 70, -25],
49+ [22, -61, 85, -90, 73, -38, -4, 46, -78, 90, -82, 54, -13, -31, 67, -88],
50+ [18, -50, 75, -89, 89, -75, 50, -18, -18, 50, -75, 89, -89, 75, -50, 18],
51+ [13, -38, 61, -78, 88, -90, 85, -73, 54, -31, 4, 22, -46, 67, -82, 90],
52+ [9, -25, 43, -57, 70, -80, 87, -90, 90, -87, 80, -70, 57, -43, 25, -9],
53+ [4, -13, 22, -31, 38, -46, 54, -61, 67, -73, 78, -82, 85, -88, 90, -90],
54+];
55+
56+/// `transMatrix` for `trType = 1`: the 4x4 DST used for luma intra 4x4 blocks
57+/// (8-316).
58+#[rustfmt::skip]
59+const DST_MATRIX: [[i32; 4]; 4] = [
60+ [29, 55, 74, 84],
61+ [74, 74, 0, -74],
62+ [84, -29, -74, 55],
63+ [55, -84, 74, -29],
64+];
65+
66+/// `M[m][n]` of the 32-point matrix, mirrored out of the stored half.
67+#[inline]
68+fn m32(row: usize, col: usize) -> i32 {
69+ if col < 16 {
70+ TRANS_MATRIX_HALF[row][col]
71+ } else if row % 2 == 0 {
72+ TRANS_MATRIX_HALF[row][31 - col]
73+ } else {
74+ -TRANS_MATRIX_HALF[row][31 - col]
75+ }
76+}
77+
78+/// `levelScale[k]`, 8.6.3.
79+const LEVEL_SCALE: [i32; 6] = [40, 45, 51, 57, 64, 72];
80+
81+/// The quantizer's reciprocal of [`LEVEL_SCALE`], `round(2^20 / levelScale)`.
82+///
83+/// Derived rather than transcribed: the product of the two is 2^20 to within a
84+/// count, which is the whole design of the HEVC quantizer, and
85+/// [`tests::quant_scale_is_the_reciprocal`] holds it to that.
86+const QUANT_SCALE: [i32; 6] = [26_214, 23_302, 20_560, 18_396, 16_384, 14_564];
87+
88+/// Largest and smallest coefficient a Main-profile decoder may hold (`CoeffMin`,
89+/// `CoeffMax` for `extended_precision_processing_flag = 0`).
90+const COEFF_MIN: i32 = -32_768;
91+const COEFF_MAX: i32 = 32_767;
92+
93+/// One-dimensional inverse transform, `y[i] = sum_j M[j][i] * x[j]`.
94+///
95+/// Split even/odd once per level: the even rows of the size-N matrix *are* the
96+/// size-N/2 matrix, so the recursion costs ~N^2/3 multiplies where the plain
97+/// product costs N^2.
98+fn inverse_1d(n: usize, src: &[i32], dst: &mut [i32]) {
99+ if n == 1 {
100+ dst[0] = 64 * src[0];
101+ return;
102+ }
103+ let half = n / 2;
104+ let stride = 32 / n;
105+ let mut even_src = [0i32; 16];
106+ for j in 0..half {
107+ even_src[j] = src[2 * j];
108+ }
109+ let mut even = [0i32; 16];
110+ inverse_1d(half, &even_src[..half], &mut even[..half]);
111+ for x in 0..half {
112+ let mut odd = 0i32;
113+ for j in 0..half {
114+ odd += m32((2 * j + 1) * stride, x) * src[2 * j + 1];
115+ }
116+ dst[x] = even[x] + odd;
117+ dst[n - 1 - x] = even[x] - odd;
118+ }
119+}
120+
121+/// One-dimensional forward transform, `c[k] = sum_x M[k][x] * src[x]`.
122+fn forward_1d(n: usize, src: &[i32], dst: &mut [i32]) {
123+ if n == 1 {
124+ dst[0] = 64 * src[0];
125+ return;
126+ }
127+ let half = n / 2;
128+ let stride = 32 / n;
129+ let mut sums = [0i32; 16];
130+ let mut diffs = [0i32; 16];
131+ for x in 0..half {
132+ sums[x] = src[x] + src[n - 1 - x];
133+ diffs[x] = src[x] - src[n - 1 - x];
134+ }
135+ let mut even = [0i32; 16];
136+ forward_1d(half, &sums[..half], &mut even[..half]);
137+ for j in 0..half {
138+ dst[2 * j] = even[j];
139+ let mut odd = 0i32;
140+ for x in 0..half {
141+ odd += m32((2 * j + 1) * stride, x) * diffs[x];
142+ }
143+ dst[2 * j + 1] = odd;
144+ }
145+}
146+
147+/// Forward 4x4 DST (the inverse of the normative `trType = 1` transform).
148+fn forward_dst4(src: &[i32; 4], dst: &mut [i32; 4]) {
149+ for (k, out) in dst.iter_mut().enumerate() {
150+ *out = (0..4).map(|x| DST_MATRIX[k][x] * src[x]).sum();
151+ }
152+}
153+
154+/// Inverse 4x4 DST, `y[i] = sum_j M[j][i] * x[j]` (8-315).
155+fn inverse_dst4(src: &[i32; 4], dst: &mut [i32; 4]) {
156+ for (i, out) in dst.iter_mut().enumerate() {
157+ *out = (0..4).map(|j| DST_MATRIX[j][i] * src[j]).sum();
158+ }
159+}
160+
161+/// True when a block takes the DST: luma, intra, 4x4 (8.6.4.1).
162+pub fn uses_dst(size: usize, is_luma: bool) -> bool {
163+ is_luma && size == 4
164+}
165+
166+/// Forward transform of an `n x n` residual block into coefficients.
167+///
168+/// `residual` and `coeffs` are both row-major `n x n`; `coeffs[v * n + k]` is
169+/// vertical frequency `v`, horizontal frequency `k`, which is the order the
170+/// scans and the residual coder index.
171+pub fn forward_transform(residual: &[i32], coeffs: &mut [i32], n: usize, dst_type: bool) {
172+ let log2n = n.trailing_zeros() as i32;
173+ // 8-bit input: shift1 = log2N + bitDepth - 9, shift2 = log2N + 6. Together
174+ // they leave the DC at 128 x the mean residual whatever the block size,
175+ // which is what the dequantiser's shift assumes.
176+ let shift1 = log2n - 1;
177+ let shift2 = log2n + 6;
178+ let round1 = 1 << (shift1 - 1);
179+ let round2 = 1 << (shift2 - 1);
180+ let mut tmp = [0i32; 32 * 32];
181+ let mut row = [0i32; 32];
182+ let mut out = [0i32; 32];
183+ for y in 0..n {
184+ row[..n].copy_from_slice(&residual[y * n..y * n + n]);
185+ if dst_type {
186+ let mut src4 = [0i32; 4];
187+ src4.copy_from_slice(&row[..4]);
188+ let mut dst4 = [0i32; 4];
189+ forward_dst4(&src4, &mut dst4);
190+ out[..4].copy_from_slice(&dst4);
191+ } else {
192+ forward_1d(n, &row[..n], &mut out[..n]);
193+ }
194+ // Transposed store: the second pass then runs over what were columns.
195+ for (k, &value) in out[..n].iter().enumerate() {
196+ tmp[k * n + y] = (value + round1) >> shift1;
197+ }
198+ }
199+ for k in 0..n {
200+ row[..n].copy_from_slice(&tmp[k * n..k * n + n]);
201+ if dst_type {
202+ let mut src4 = [0i32; 4];
203+ src4.copy_from_slice(&row[..4]);
204+ let mut dst4 = [0i32; 4];
205+ forward_dst4(&src4, &mut dst4);
206+ out[..4].copy_from_slice(&dst4);
207+ } else {
208+ forward_1d(n, &row[..n], &mut out[..n]);
209+ }
210+ for (v, &value) in out[..n].iter().enumerate() {
211+ coeffs[v * n + k] = (value + round2) >> shift2;
212+ }
213+ }
214+}
215+
216+/// Inverse transform of scaled coefficients into residual samples, exactly as
217+/// clause 8.6.4 specifies including its intermediate clipping.
218+pub fn inverse_transform(scaled: &[i32], residual: &mut [i32], n: usize, dst_type: bool) {
219+ let mut e = [0i32; 32 * 32];
220+ let mut col = [0i32; 32];
221+ let mut out = [0i32; 32];
222+ // Stage 1: every column, i.e. along the vertical frequency index.
223+ for k in 0..n {
224+ for y in 0..n {
225+ col[y] = scaled[y * n + k];
226+ }
227+ if dst_type {
228+ let mut src4 = [0i32; 4];
229+ src4.copy_from_slice(&col[..4]);
230+ let mut dst4 = [0i32; 4];
231+ inverse_dst4(&src4, &mut dst4);
232+ out[..4].copy_from_slice(&dst4);
233+ } else {
234+ inverse_1d(n, &col[..n], &mut out[..n]);
235+ }
236+ for y in 0..n {
237+ e[y * n + k] = ((out[y] + 64) >> 7).clamp(COEFF_MIN, COEFF_MAX);
238+ }
239+ }
240+ // Stage 2: every row, then the bit-depth shift (8-299).
241+ const BD_SHIFT: i32 = 12; // 20 - bitDepth, 8-bit
242+ let round = 1 << (BD_SHIFT - 1);
243+ for y in 0..n {
244+ col[..n].copy_from_slice(&e[y * n..y * n + n]);
245+ if dst_type {
246+ let mut src4 = [0i32; 4];
247+ src4.copy_from_slice(&col[..4]);
248+ let mut dst4 = [0i32; 4];
249+ inverse_dst4(&src4, &mut dst4);
250+ out[..4].copy_from_slice(&dst4);
251+ } else {
252+ inverse_1d(n, &col[..n], &mut out[..n]);
253+ }
254+ for x in 0..n {
255+ residual[y * n + x] = (out[x] + round) >> BD_SHIFT;
256+ }
257+ }
258+}
259+
260+/// Quantise coefficients in place, returning the number of non-zero levels.
261+///
262+/// The rounding offset is a third of a step, which is the intra bias every
263+/// encoder in this class uses: it costs a little distortion at the rounding
264+/// boundary and buys back more in rate.
265+pub fn quantize(coeffs: &[i32], levels: &mut [i32], n: usize, qp: i32) -> usize {
266+ let log2n = n.trailing_zeros() as i32;
267+ let qbits = 21 + qp / 6 - log2n;
268+ let scale = QUANT_SCALE[(qp % 6) as usize] as i64;
269+ let offset = (1i64 << qbits) / 3;
270+ let mut nonzero = 0;
271+ for (i, &c) in coeffs[..n * n].iter().enumerate() {
272+ let magnitude = ((c.unsigned_abs() as i64 * scale + offset) >> qbits) as i32;
273+ let level = magnitude.min(COEFF_MAX);
274+ levels[i] = if c < 0 { -level } else { level };
275+ if level != 0 {
276+ nonzero += 1;
277+ }
278+ }
279+ nonzero
280+}
281+
282+/// Scale levels back into coefficients, exactly as clause 8.6.3 specifies.
283+pub fn dequantize(levels: &[i32], scaled: &mut [i32], n: usize, qp: i32) {
284+ let log2n = n.trailing_zeros() as i32;
285+ let bd_shift = log2n + 3; // bitDepth + Log2(nTbS) + 10 - 15, 8-bit
286+ let round = 1i64 << (bd_shift - 1);
287+ let scale = (16 * LEVEL_SCALE[(qp % 6) as usize]) as i64;
288+ let shift = qp / 6;
289+ for (i, &level) in levels[..n * n].iter().enumerate() {
290+ let value = (((level as i64 * scale) << shift) + round) >> bd_shift;
291+ scaled[i] = value.clamp(COEFF_MIN as i64, COEFF_MAX as i64) as i32;
292+ }
293+}
294+
295+/// The chroma QP a luma QP maps to for 4:2:0 (Table 8-10), before any offset.
296+pub fn chroma_qp(qp_luma: i32, offset: i32) -> i32 {
297+ let qpi = (qp_luma + offset).clamp(0, 57);
298+ if qpi < 30 {
299+ qpi
300+ } else if qpi > 43 {
301+ qpi - 6
302+ } else {
303+ const TABLE: [i32; 14] = [29, 30, 31, 32, 33, 33, 34, 34, 35, 35, 36, 36, 37, 37];
304+ TABLE[(qpi - 30) as usize]
305+ }
306+}
307+
308+#[cfg(test)]
309+mod tests {
310+ use super::*;
311+
312+ #[test]
313+ fn mirrored_half_matches_the_spec_second_table() {
314+ // Spot values from transMatrixCol16to31 (8-321): row, column, value.
315+ let spec: &[(usize, usize, i32)] = &[
316+ (0, 16, 64),
317+ (0, 31, 64),
318+ (1, 16, -4),
319+ (1, 31, -90),
320+ (2, 16, -90),
321+ (2, 31, 90),
322+ (3, 16, 13),
323+ (3, 23, 73),
324+ (4, 16, 89),
325+ (8, 16, 83),
326+ (16, 16, 64),
327+ (16, 17, -64),
328+ (31, 16, 90),
329+ (31, 31, -4),
330+ (30, 16, -9),
331+ (29, 31, -13),
332+ ];
333+ for &(row, col, value) in spec {
334+ assert_eq!(m32(row, col), value, "M[{row}][{col}]");
335+ }
336+ }
337+
338+ #[test]
339+ fn matrix_rows_are_orthogonal() {
340+ // Every size's rows: orthogonal, and all of equal norm. A single mistyped
341+ // entry breaks both.
342+ for log2n in 2..=5u32 {
343+ let n = 1usize << log2n;
344+ let stride = 32 / n;
345+ let norm: i32 = (0..n).map(|x| m32(0, x) * m32(0, x)).sum();
346+ for a in 0..n {
347+ let self_dot: i32 = (0..n).map(|x| m32(a * stride, x) * m32(a * stride, x)).sum();
348+ // 64^2 * n is exact for the DC row; the others are within the
349+ // rounding the integer matrix carries.
350+ assert!(
351+ (self_dot - norm).abs() * 200 < norm,
352+ "row {a} of {n}: norm {self_dot} vs {norm}"
353+ );
354+ for b in a + 1..n {
355+ let dot: i32 = (0..n)
356+ .map(|x| m32(a * stride, x) * m32(b * stride, x))
357+ .sum();
358+ assert!(dot.abs() * 100 < norm, "rows {a},{b} of {n}: dot {dot}");
359+ }
360+ }
361+ }
362+ }
363+
364+ #[test]
365+ fn quant_scale_is_the_reciprocal() {
366+ for k in 0..6 {
367+ let product = QUANT_SCALE[k] as i64 * LEVEL_SCALE[k] as i64;
368+ assert!((product - (1 << 20)).abs() < 64, "k={k}: {product}");
369+ assert_eq!(QUANT_SCALE[k], ((1 << 20) as f64 / LEVEL_SCALE[k] as f64).round() as i32);
370+ }
371+ }
372+
373+ fn round_trip(residual: &[i32], n: usize, qp: i32, dst: bool) -> Vec<i32> {
374+ let mut coeffs = vec![0i32; n * n];
375+ forward_transform(residual, &mut coeffs, n, dst);
376+ let mut levels = vec![0i32; n * n];
377+ quantize(&coeffs, &mut levels, n, qp);
378+ let mut scaled = vec![0i32; n * n];
379+ dequantize(&levels, &mut scaled, n, qp);
380+ let mut out = vec![0i32; n * n];
381+ inverse_transform(&scaled, &mut out, n, dst);
382+ out
383+ }
384+
385+ #[test]
386+ fn round_trip_recovers_flat_blocks() {
387+ // A constant residual stays constant at any QP — only the DC level
388+ // survives — and at low QP it comes back to its own value. At QP 40 one
389+ // level step *is* 16 samples, so accuracy is asserted where accuracy is
390+ // on offer and flatness everywhere.
391+ for &n in &[4usize, 8, 16, 32] {
392+ for &qp in &[0i32, 12, 22, 27, 40, 51] {
393+ let residual = vec![20i32; n * n];
394+ let out = round_trip(&residual, n, qp, false);
395+ assert!(out.iter().all(|&v| v == out[0]), "n={n} qp={qp}: {out:?}");
396+ if qp <= 22 {
397+ assert!((out[0] - 20).abs() <= 2, "n={n} qp={qp}: {}", out[0]);
398+ }
399+ }
400+ }
401+ }
402+
403+ #[test]
404+ fn round_trip_is_near_lossless_at_low_qp() {
405+ // A textured block at QP 4 comes back within a sample or two; this is
406+ // what proves the forward transform is the inverse of the normative one
407+ // rather than merely self-consistent.
408+ for &n in &[4usize, 8, 16, 32] {
409+ for dst in [false, true] {
410+ if dst && n != 4 {
411+ continue;
412+ }
413+ let residual: Vec<i32> = (0..n * n)
414+ .map(|i| (((i * 37) % 61) as i32) - 30)
415+ .collect();
416+ let out = round_trip(&residual, n, 4, dst);
417+ let worst = residual
418+ .iter()
419+ .zip(&out)
420+ .map(|(a, b)| (a - b).abs())
421+ .max()
422+ .unwrap();
423+ assert!(worst <= 3, "n={n} dst={dst}: worst {worst}");
424+ }
425+ }
426+ }
427+
428+ #[test]
429+ fn dc_only_coefficient_is_flat_after_inverse() {
430+ // The spec's inverse of a DC-only block is a constant; a transposed
431+ // matrix index would tilt it.
432+ for &n in &[4usize, 8, 16, 32] {
433+ let mut scaled = vec![0i32; n * n];
434+ scaled[0] = 4096;
435+ let mut out = vec![0i32; n * n];
436+ inverse_transform(&scaled, &mut out, n, false);
437+ assert!(out.iter().all(|&v| v == out[0]), "n={n}: {out:?}");
438+ // 4096 / 128: the two-stage inverse divides by 2^7 after the first
439+ // pass and 2^12 after the second, against 64 x 64 of matrix gain.
440+ assert_eq!(out[0], 32);
441+ }
442+ }
443+
444+ #[test]
445+ fn chroma_qp_table() {
446+ assert_eq!(chroma_qp(29, 0), 29);
447+ assert_eq!(chroma_qp(30, 0), 29);
448+ assert_eq!(chroma_qp(35, 0), 33);
449+ assert_eq!(chroma_qp(43, 0), 37);
450+ assert_eq!(chroma_qp(44, 0), 38);
451+ assert_eq!(chroma_qp(51, 0), 45);
452+ assert_eq!(chroma_qp(30, -2), 28);
453+ }
454+}