forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB00c1b3fTahinli2 months ago1999 commits

huffman.rs85 lines, 2.6 KiBHistoryRawDownload
1//! Prefix-code decoding for the spectral and scalefactor codebooks.
2//!
3//! Every codebook is a complete prefix code (Kraft sum exactly 1, asserted in
4//! the tests), so a binary tree walk is total: no bit pattern falls off the
5//! tree, and the only failure a stream can produce is running out of bits.
6
7use ec_core::{BitReader, Error, Result};
8
9/// A codebook as a walkable binary tree. `nodes[i]` holds the two children of
10/// node `i`; a non-negative child is another node, a negative one is the leaf
11/// `-(index + 1)`.
12#[derive(Debug, Clone)]
13pub struct Tree {
14 nodes: Vec<[i32; 2]>,
15}
16
17impl Tree {
18 /// Builds the tree from `(length, code)` by symbol index.
19 ///
20 /// # Panics
21 /// If two symbols share a prefix, which would mean a corrupt table.
22 pub fn new(codes: &[(u8, u32)]) -> Tree {
23 let mut nodes = vec![[0i32; 2]];
24 for (symbol, &(len, code)) in codes.iter().enumerate() {
25 let mut at = 0usize;
26 for depth in (0..len).rev() {
27 let bit = ((code >> depth) & 1) as usize;
28 let last = depth == 0;
29 if last {
30 assert_eq!(nodes[at][bit], 0, "codebook prefix collision");
31 nodes[at][bit] = -(symbol as i32 + 1);
32 } else if nodes[at][bit] == 0 {
33 nodes.push([0i32; 2]);
34 let next = nodes.len() as i32 - 1;
35 nodes[at][bit] = next;
36 at = next as usize;
37 } else {
38 at = nodes[at][bit] as usize;
39 }
40 }
41 }
42 Tree { nodes }
43 }
44
45 /// Reads one symbol index.
46 pub fn decode(&self, r: &mut BitReader<'_>) -> Result<usize> {
47 let mut at = 0usize;
48 loop {
49 let bit = usize::from(r.read_bit()?);
50 let next = self.nodes[at][bit];
51 if next < 0 {
52 return Ok((-next - 1) as usize);
53 }
54 if next == 0 {
55 return Err(Error::corrupt("aac: undefined Huffman code"));
56 }
57 at = next as usize;
58 }
59 }
60}
61
62/// The eleven spectral trees plus the scalefactor tree, built once per decoder.
63#[derive(Debug, Clone)]
64pub struct Books {
65 pub spectral: Vec<Tree>,
66 pub scalefactor: Tree,
67}
68
69impl Books {
70 pub fn new() -> Books {
71 Books {
72 spectral: crate::tables::CODEBOOKS
73 .iter()
74 .map(|cb| Tree::new(cb.codes))
75 .collect(),
76 scalefactor: Tree::new(crate::tables::SCALEFACTOR_CODES),
77 }
78 }
79}
80
81impl Default for Books {
82 fn default() -> Books {
83 Books::new()
84 }
85}