Skip to main content

threers_codec/decode/
cabac.rs

1//! The CABAC arithmetic decoding engine (H.264 §9.3.3.2, H.265 §9.3.4.3).
2//!
3//! The two standards specify the same engine — the same `rangeTabLPS`, state
4//! transitions and renormalisation — and differ only in how a context's state
5//! is initialised, which is what [`Ctx::h264`] and [`Ctx::hevc`] are for.
6//!
7//! This follows the specification's 9-bit `codIOffset` formulation literally,
8//! reading renormalisation bits straight from a [`BitReader`]. That keeps the
9//! reader's position equal to the number of bits the specification says have
10//! been consumed, which is what PCM samples, WPP substreams and tile entry
11//! points need: after a terminating bin the next byte-aligned position is
12//! exactly where the following data starts.
13
14use super::bits::BitReader;
15use crate::hevc::tables::{RANGE_TAB_LPS, TRANS_IDX_LPS, TRANS_IDX_MPS};
16
17/// One context variable: probability state and most probable symbol.
18#[derive(Clone, Copy, Default, Debug, PartialEq, Eq)]
19pub struct Ctx {
20    /// Probability state index, 0 to 62 (`pStateIdx`).
21    pub state: u8,
22    /// The most probable symbol, 0 or 1 (`valMps`).
23    pub mps: u8,
24}
25
26impl Ctx {
27    fn from_pre(pre: i32) -> Ctx {
28        if pre <= 63 {
29            Ctx {
30                state: (63 - pre) as u8,
31                mps: 0,
32            }
33        } else {
34            Ctx {
35                state: (pre - 64) as u8,
36                mps: 1,
37            }
38        }
39    }
40
41    /// H.264 §9.3.1.1: from the `(m, n)` pair and `SliceQPY`.
42    pub fn h264(m: i8, n: i8, qp: i32) -> Ctx {
43        let pre = (((m as i32) * qp.clamp(0, 51)) >> 4) + n as i32;
44        Ctx::from_pre(pre.clamp(1, 126))
45    }
46
47    /// H.265 §9.3.2.2: from the 8-bit `initValue` and `SliceQpY`.
48    pub fn hevc(init: u8, qp: i32) -> Ctx {
49        let slope = (init >> 4) as i32 * 5 - 45;
50        let offset = (((init & 15) as i32) << 3) - 16;
51        let pre = ((slope * qp.clamp(0, 51)) >> 4) + offset;
52        Ctx::from_pre(pre.clamp(1, 126))
53    }
54}
55
56/// The arithmetic decoder.
57pub struct Cabac<'a> {
58    r: BitReader<'a>,
59    range: u32,
60    offset: u32,
61}
62
63impl<'a> Cabac<'a> {
64    /// Start decoding at byte `start` of `data` (§9.3.1.2 / §9.3.2.5).
65    pub fn new(data: &'a [u8], start: usize) -> Self {
66        let mut r = BitReader::new(data);
67        r.set_pos(start * 8);
68        let offset = r.u(9);
69        Cabac {
70            r,
71            range: 510,
72            offset,
73        }
74    }
75
76    /// Re-initialise at byte `start` — after PCM samples, or at the start of
77    /// a WPP row or tile.
78    pub fn restart(&mut self, start: usize) {
79        self.r.set_pos(start * 8);
80        self.range = 510;
81        self.offset = self.r.u(9);
82    }
83
84    /// Whether the decoder has read past the end of its data — a truncated
85    /// or corrupt slice.
86    pub fn overrun(&self) -> bool {
87        self.r.bits_left() < -64
88    }
89
90    /// The byte at which data following a terminating bin begins: the bits
91    /// consumed so far rounded up to a byte.
92    pub fn aligned_byte_pos(&self) -> usize {
93        self.r.byte_pos()
94    }
95
96    /// The slice data being decoded.
97    pub fn data(&self) -> &'a [u8] {
98        self.r.data()
99    }
100
101    /// Decode one context-coded bin and adapt `ctx`.
102    #[inline(always)]
103    pub fn decision(&mut self, ctx: &mut Ctx) -> u32 {
104        let q = ((self.range >> 6) & 3) as usize;
105        let lps = RANGE_TAB_LPS[ctx.state as usize][q] as u32;
106        self.range -= lps;
107        let bin;
108        if self.offset >= self.range {
109            bin = 1 - ctx.mps as u32;
110            self.offset -= self.range;
111            self.range = lps;
112            if ctx.state == 0 {
113                ctx.mps = 1 - ctx.mps;
114            }
115            ctx.state = TRANS_IDX_LPS[ctx.state as usize];
116        } else {
117            bin = ctx.mps as u32;
118            ctx.state = TRANS_IDX_MPS[ctx.state as usize];
119        }
120        if self.range < 256 {
121            let n = self.range.leading_zeros() - 23;
122            self.range <<= n;
123            self.offset = (self.offset << n) | self.r.u(n);
124        }
125        bin
126    }
127
128    /// Decode one bypass bin.
129    #[inline(always)]
130    pub fn bypass(&mut self) -> u32 {
131        self.offset = (self.offset << 1) | self.r.u(1);
132        if self.offset >= self.range {
133            self.offset -= self.range;
134            1
135        } else {
136            0
137        }
138    }
139
140    /// `n` bypass bins, first one most significant.
141    #[inline]
142    pub fn bypass_bits(&mut self, n: u32) -> u32 {
143        let mut v = 0;
144        for _ in 0..n {
145            v = (v << 1) | self.bypass();
146        }
147        v
148    }
149
150    /// A terminating bin (`end_of_slice_flag`, `pcm_flag`, ...).
151    pub fn terminate(&mut self) -> u32 {
152        self.range -= 2;
153        if self.offset >= self.range {
154            1
155        } else {
156            if self.range < 256 {
157                let n = self.range.leading_zeros() - 23;
158                self.range <<= n;
159                self.offset = (self.offset << n) | self.r.u(n);
160            }
161            0
162        }
163    }
164}
165
166#[cfg(test)]
167mod tests {
168    use super::*;
169    use crate::hevc::cabac::{CabacEncoder, CtxModel};
170
171    /// Decode what the crate's own encoder wrote, decisions, bypass and a
172    /// terminate, and land exactly on the byte that follows.
173    #[test]
174    fn decodes_the_encoders_output() {
175        let mut enc = CabacEncoder::new();
176        let mut ectx = [CtxModel::from_state(0, 0); 4];
177        let mut seq = Vec::new();
178        let mut x = 12345u32;
179        for i in 0..5000 {
180            x = x.wrapping_mul(1103515245).wrapping_add(12345);
181            let c = (i % 4) as usize;
182            let bias = [1, 3, 7, 15][c];
183            let bit = ((x >> 16) & bias == 0) as u32;
184            seq.push((c, bit, i % 7 == 0));
185            if i % 7 == 0 {
186                enc.encode_bypass(bit);
187            } else {
188                enc.encode_bin(&mut ectx[c], bit);
189            }
190        }
191        enc.encode_terminate(1);
192        let mut bytes = enc.finish();
193        let tail = bytes.len();
194        bytes.extend_from_slice(&[0xAB, 0xCD]);
195
196        let mut dec = Cabac::new(&bytes, 0);
197        let mut dctx = [Ctx { state: 0, mps: 0 }; 4];
198        for &(c, bit, by) in &seq {
199            let got = if by {
200                dec.bypass()
201            } else {
202                dec.decision(&mut dctx[c])
203            };
204            assert_eq!(got, bit);
205        }
206        assert_eq!(dec.terminate(), 1);
207        assert_eq!(dec.aligned_byte_pos(), tail);
208    }
209}