Debian Codegraph @

src/tree.rs

raw symbols SCIP
1 use std::fmt;
2 use std::num::NonZeroU8;
3 use std::ops::Range;
4
5 use crate::{Bitstream, DecodeFailed};
6
7 /// The canonical tree cannot be used to decode elements. Instead, it behaves like a builder for
8 /// instances of the actual tree that can decode elements efficiently.
9 #[derive(Debug)]
10 pub struct CanonicalTree {
11 // > Each tree element can have a path length of [0, 16], where a zero path length indicates
12 // > that the element has a zero frequency and is not present in the tree.
13 //
14 // We represent them as `u8` due to their very short range.
15 path_lengths: Vec<u8>,
16 }
17
18 pub struct Tree {
19 path_lengths: Vec<u8>,
20 largest_length: NonZeroU8,
21 huffman_tree: Vec<u16>,
22 }
23
24 impl CanonicalTree {
25 pub fn new(count: usize) -> Self {
26 Self {
27 // > In the case of the very first such tree, the delta is calculated against a tree
28 // > in which all elements have a zero path length.
29 path_lengths: vec![0; count],
30 }
31 }
32
33 /// Create a new `Tree` instance from this cast that can be used to decode elements. If the
34 /// resulting tree is empty (all path lengths are 0), then `Ok(None)` is returned.
35 ///
36 /// This method transforms the canonical Huffman tree into a different structure that can
37 /// be used to better decode elements.
38 // > an LZXD decoder uses only the path lengths of the Huffman tree to reconstruct the
39 // > identical tree,
40 pub fn create_instance_allow_empty(&self) -> Result<Option<Tree>, DecodeFailed> {
41 // The ideas implemented by this method are heavily inspired from LeonBlade's xnbcli
42 // on GitHub.
43 //
44 // The path lengths contains the bit indices or zero if its not present, so find the
45 // highest path length to determine how big our tree needs to be.
46 let largest_length =
47 match NonZeroU8::new(*self.path_lengths.iter().max().expect("empty path lengths")) {
48 Some(x) => x,
49 // N.B: If all the path lengths are zero, then the tree is empty (which is allowed).
50 None => return Ok(None),
51 };
52 let mut huffman_tree = vec![0; 1 << largest_length.get()];
53
54 // > a zero path length indicates that the element has a zero frequency and is not
55 // > present in the tree. Tree elements are output in sequential order starting with the
56 // > first element
57 //
58 // We start at the MSB, 1, and write the tree elements in sequential order from index 0.
59 let mut pos = 0;
60 for bit in 1..=largest_length.get() {
61 let amount = 1 << (largest_length.get() - bit);
62
63 // The codes correspond with the indices of the path length (because
64 // `path_lengths[code]` is its path length).
65 for code in 0..self.path_lengths.len() {
66 // As soon as a code's path length matches with our bit index write the code as
67 // many times as the bit index itself represents.
68 if self.path_lengths[code] == bit {
69 huffman_tree
70 .get_mut(pos..pos + amount)
71 .ok_or(DecodeFailed::InvalidPathLengths)?
72 .iter_mut()
73 .for_each(|x| *x = code as u16);
74
75 pos += amount;
76 }
77 }
78 }
79
80 // If we didn't fill the entire table, the path lengths were wrong.
81 if pos != huffman_tree.len() {
82 Err(DecodeFailed::InvalidPathLengths)?;
83 }
84
85 Ok(Some(Tree {
86 path_lengths: self.path_lengths.clone(),
87 largest_length,
88 huffman_tree,
89 }))
90 }
91
92 /// Create a new `Tree` instance from this cast that can be used to decode elements.
93 ///
94 /// This method transforms the canonical Huffman tree into a different structure that can
95 /// be used to better decode elements.
96 // > an LZXD decoder uses only the path lengths of the Huffman tree to reconstruct the
97 // > identical tree,
98 pub fn create_instance(&self) -> Result<Tree, DecodeFailed> {
99 self.create_instance_allow_empty()?
100 .ok_or(DecodeFailed::EmptyTree)
101 }
102
103 // Note: the tree already exists and is used to apply the deltas.
104 pub fn update_range_with_pretree(
105 &mut self,
106 bitstream: &mut Bitstream,
107 range: Range<usize>,
108 ) -> Result<(), DecodeFailed> {
109 // > Each of the 17 possible values of (len[x] - prev_len[x]) mod 17, plus three
110 // > additional codes used for run-length encoding, are not output directly as 5-bit
111 // > numbers but are instead encoded via a Huffman tree called the pretree. The pretree
112 // > is generated dynamically according to the frequencies of the 20 allowable tree
113 // > codes. The structure of the pretree is encoded in a total of 80 bits by using 4 bits
114 // > to output the path length of each of the 20 pretree elements. Once again, a zero
115 // > path length indicates a zero-frequency element.
116 let pretree = {
117 let mut path_lengths = Vec::with_capacity(20);
118 for _ in 0..20 {
119 path_lengths.push(bitstream.read_bits(4)? as u8)
120 }
121
122 Tree::from_path_lengths(path_lengths)?
123 };
124
125 // > Tree elements are output in sequential order starting with the first element.
126 let mut i = range.start;
127 while i < range.end {
128 // > The "real" tree is then encoded using the pretree Huffman codes.
129 let code = pretree.decode_element(bitstream)?;
130
131 // > Elements can be encoded in one of two ways: if several consecutive elements have
132 // > the same path length, run-length encoding is employed; otherwise, the element is
133 // > output by encoding the difference between the current path length and the
134 // > previous path length of the tree, mod 17.
135 match code {
136 0..=16 => {
137 self.path_lengths[i] = (17 + self.path_lengths[i] - code as u8) % 17;
138 i += 1;
139 }
140 // > Codes 17, 18, and 19 are used to represent consecutive elements that have the
141 // > same path length.
142 17 => {
143 let zeros = bitstream.read_bits(4)?;
144 self.path_lengths
145 .get_mut(i..i + zeros as usize + 4)
146 .ok_or(DecodeFailed::InvalidPretreeRle)?
147 .iter_mut()
148 .for_each(|x| *x = 0);
149 i += zeros as usize + 4;
150 }
151 18 => {
152 let zeros = bitstream.read_bits(5)?;
153 self.path_lengths
154 .get_mut(i..i + zeros as usize + 20)
155 .ok_or(DecodeFailed::InvalidPretreeRle)?
156 .iter_mut()
157 .for_each(|x| *x = 0);
158 i += zeros as usize + 20;
159 }
160 19 => {
161 let same = bitstream.read_bits(1)?;
162 // "Decode new code" is used to parse the next code from the bitstream, which
163 // has a value range of [0, 16].
164 let code = pretree.decode_element(bitstream)?;
165 if code > 16 {
166 return Err(DecodeFailed::InvalidPretreeElement(code))?;
167 }
168
169 let value = (17 + self.path_lengths[i] - code as u8) % 17;
170 self.path_lengths
171 .get_mut(i..i + same as usize + 4)
172 .ok_or(DecodeFailed::InvalidPretreeRle)?
173 .iter_mut()
174 .for_each(|x| *x = value);
175 i += same as usize + 4;
176 }
177 _ => return Err(DecodeFailed::InvalidPretreeElement(code)),
178 };
179 }
180
181 Ok(())
182 }
183 }
184
185 impl Tree {
186 /// Create a new usable tree instance directly from known path lengths.
187 pub fn from_path_lengths(path_lengths: Vec<u8>) -> Result<Self, DecodeFailed> {
188 CanonicalTree { path_lengths }.create_instance()
189 }
190
191 pub fn decode_element(&self, bitstream: &mut Bitstream) -> Result<u16, DecodeFailed> {
192 // Perform the inverse translation, peeking as many bits as our tree is…
193 let code = self.huffman_tree[bitstream.peek_bits(self.largest_length.get()) as usize];
194
195 // …and advancing the stream for as many bits this code actually takes (read to seek).
196 bitstream.read_bits(self.path_lengths[code as usize])?;
197
198 Ok(code)
199 }
200 }
201
202 impl fmt::Debug for Tree {
203 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
204 f.debug_struct("Tree")
205 .field("path_lengths", &self.path_lengths.len())
206 .field("largest_length", &self.largest_length)
207 .finish()
208 }
209 }
210
211 #[cfg(test)]
212 mod tests {
213 use super::*;
214
215 #[test]
216 fn decode_simple_table() {
217 // Based on some aligned offset tree
218 let tree = Tree::from_path_lengths(vec![6, 5, 1, 3, 4, 6, 2, 0]).unwrap();
219 let value_count = vec![(2, 32), (6, 16), (3, 8), (4, 4), (1, 2), (0, 1), (5, 1)];
220
221 let mut i = 0;
222 for (value, count) in value_count.into_iter() {
223 (0..count).for_each(|_| {
224 assert_eq!(tree.huffman_tree[i], value);
225 i += 1;
226 })
227 }
228 }
229
230 #[test]
231 fn decode_complex_table() {
232 // Based on the pretree of some length tree
233 let tree = Tree::from_path_lengths(vec![
234 1, 0, 0, 0, 0, 7, 3, 3, 4, 4, 5, 5, 5, 7, 8, 8, 0, 7, 0, 0,
235 ])
236 .unwrap();
237 let value_count = vec![
238 (0, 128),
239 (6, 32),
240 (7, 32),
241 (8, 16),
242 (9, 16),
243 (10, 8),
244 (11, 8),
245 (12, 8),
246 (5, 2),
247 (13, 2),
248 (17, 2),
249 (14, 1),
250 (15, 1),
251 ];
252
253 let mut i = 0;
254 for (value, count) in value_count.into_iter() {
255 (0..count).for_each(|_| {
256 assert_eq!(tree.huffman_tree[i], value);
257 i += 1;
258 })
259 }
260 }
261
262 #[test]
263 fn decode_elements() {
264 let tree = Tree::from_path_lengths(vec![6, 5, 1, 3, 4, 6, 2, 0]).unwrap();
265
266 let buffer = [0x5b, 0xda, 0x3f, 0xf8];
267 let mut bitstream = Bitstream::new(&buffer);
268 bitstream.read_bits(11).unwrap();
269 assert_eq!(tree.decode_element(&mut bitstream), Ok(3));
270 assert_eq!(tree.decode_element(&mut bitstream), Ok(5));
271 assert_eq!(tree.decode_element(&mut bitstream), Ok(6));
272 assert_eq!(tree.decode_element(&mut bitstream), Ok(2));
273 }
274 }