forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBddf43e8Tahinli2 months ago3186 commits

codebook.rs506 lines, 17.8 KiBHistoryRawDownload
1//! Codebooks: Huffman lengths in, entry numbers and VQ vectors out.
2//!
3//! Three things make a Vorbis codebook more than a Huffman table. The lengths
4//! themselves come in three encodings (flat, sparse, ordered-by-length). The
5//! codeword assignment is canonical but stated as "the next free codeword of
6//! this length", which is the same thing read from the other end. And a book
7//! may carry a *lookup*: entry numbers index a vector of quantised values,
8//! either by taking `dimensions` digits of the entry number in base
9//! `lookup_values` (type 1, the packing that makes a 2^24-vector book fit in a
10//! few hundred bytes) or by indexing the list directly (type 2). Both are
11//! expanded once at parse time, so decode is a tree walk and a slice.
12
13use ec_core::{Error, Result};
14
15use crate::bits::{Bits, BitsOut};
16
17/// One parsed codebook.
18#[derive(Debug, Clone)]
19pub struct Codebook {
20 /// Values per entry: 1 for a scalar book, more for a VQ book.
21 pub dimensions: usize,
22 /// Codeword tree, walked one bit at a time.
23 tree: Vec<Node>,
24 /// `entries * dimensions` values, empty when `lookup_type` is 0.
25 values: Vec<f32>,
26}
27
28impl Codebook {
29 /// Parse one codebook from a setup header (§3.2.1).
30 pub fn parse(bits: &mut Bits) -> Result<Codebook> {
31 if bits.read(24) != 0x0056_4342 {
32 return Err(Error::corrupt("codebook sync pattern"));
33 }
34 let dimensions = bits.read(16) as usize;
35 let entries = bits.read(24) as usize;
36 if bits.eop() {
37 return Err(Error::corrupt("codebook header truncated"));
38 }
39 if dimensions == 0 || entries == 0 {
40 return Err(Error::corrupt("empty codebook"));
41 }
42 // A book cannot be larger than the packet that describes it: every
43 // length costs at least one bit, so this is the OOM guard on a header
44 // that claims 2^24 entries in twenty bytes.
45 if entries as u64 > bits.remaining() + 64 {
46 return Err(Error::corrupt("codebook claims more entries than bits"));
47 }
48
49 let mut lengths = vec![0u8; entries];
50 if bits.bit() {
51 // Ordered: lengths are non-decreasing, stated as run lengths.
52 let mut entry = 0usize;
53 let mut length = bits.read(5) + 1;
54 while entry < entries {
55 if length > 32 {
56 return Err(Error::corrupt("ordered codebook overran 32 bits"));
57 }
58 let bits_needed = ilog((entries - entry) as u32);
59 let run = bits.read(bits_needed) as usize;
60 if entry + run > entries {
61 return Err(Error::corrupt("ordered codebook run past the end"));
62 }
63 lengths[entry..entry + run].fill(length as u8);
64 entry += run;
65 length += 1;
66 if bits.eop() {
67 return Err(Error::corrupt("ordered codebook truncated"));
68 }
69 }
70 } else {
71 let sparse = bits.bit();
72 for length in lengths.iter_mut() {
73 if sparse && !bits.bit() {
74 continue;
75 }
76 *length = (bits.read(5) + 1) as u8;
77 }
78 if bits.eop() {
79 return Err(Error::corrupt("codebook lengths truncated"));
80 }
81 }
82
83 let (tree, _) = assign_codes(&lengths)?;
84
85 let lookup_type = bits.read(4);
86 let values = match lookup_type {
87 0 => Vec::new(),
88 1 | 2 => {
89 let minimum = bits.float32();
90 let delta = bits.float32();
91 let value_bits = bits.read(4) + 1;
92 let sequence_p = bits.bit();
93 let lookup_values = match lookup_type {
94 1 => lookup1_values(entries, dimensions),
95 _ => entries * dimensions,
96 };
97 if bits.eop() || lookup_values as u64 > bits.remaining() + 64 {
98 return Err(Error::corrupt("codebook lookup truncated"));
99 }
100 let multiplicands: Vec<f32> = (0..lookup_values)
101 .map(|_| bits.read(value_bits) as f32)
102 .collect();
103 expand_lookup(
104 lookup_type,
105 entries,
106 dimensions,
107 minimum,
108 delta,
109 sequence_p,
110 &multiplicands,
111 )?
112 }
113 other => {
114 return Err(Error::unsupported(
115 format!("codebook lookup type {other}"),
116 "Vorbis I defines 0, 1 and 2",
117 ));
118 }
119 };
120 if bits.eop() {
121 return Err(Error::corrupt("codebook truncated"));
122 }
123
124 Ok(Codebook {
125 dimensions,
126 tree,
127 values,
128 })
129 }
130
131 /// True when entries carry VQ values, i.e. the book can fill a residue or
132 /// floor-0 vector rather than only naming a number.
133 pub fn has_values(&self) -> bool {
134 !self.values.is_empty()
135 }
136
137 /// Read one codeword; [`None`] at end of packet or on an undefined path.
138 pub fn decode_scalar(&self, bits: &mut Bits) -> Option<u32> {
139 let mut node = 0usize;
140 loop {
141 let child = self.tree[node].child[usize::from(bits.bit())];
142 if bits.eop() {
143 return None;
144 }
145 match child {
146 0 => return None,
147 c if c < 0 => return Some((-c - 1) as u32),
148 c => node = c as usize,
149 }
150 }
151 }
152
153 /// Read one codeword and answer its value vector; [`None`] as above.
154 pub fn decode_vector(&self, bits: &mut Bits) -> Option<&[f32]> {
155 let entry = self.decode_scalar(bits)? as usize;
156 self.vector(entry)
157 }
158
159 /// The value vector of `entry`, when this book has values.
160 pub fn vector(&self, entry: usize) -> Option<&[f32]> {
161 let start = entry.checked_mul(self.dimensions)?;
162 self.values.get(start..start + self.dimensions)
163 }
164}
165
166/// Greatest `m` with `m^dimensions <= entries` (§9.2.3), computed without
167/// `powf` so the boundary case never lands on the wrong side.
168pub fn lookup1_values(entries: usize, dimensions: usize) -> usize {
169 let mut value = 1usize;
170 loop {
171 let mut product = 1usize;
172 let mut overflow = false;
173 for _ in 0..dimensions {
174 match product.checked_mul(value + 1) {
175 Some(p) if p <= entries => product = p,
176 _ => {
177 overflow = true;
178 break;
179 }
180 }
181 }
182 if overflow {
183 return value;
184 }
185 value += 1;
186 }
187}
188
189/// Turn multiplicands into one value vector per entry (§3.2.1 "VQ lookup").
190fn expand_lookup(
191 lookup_type: u32,
192 entries: usize,
193 dimensions: usize,
194 minimum: f32,
195 delta: f32,
196 sequence_p: bool,
197 multiplicands: &[f32],
198) -> Result<Vec<f32>> {
199 let total = entries
200 .checked_mul(dimensions)
201 .filter(|n| *n <= 1 << 24)
202 .ok_or_else(|| Error::corrupt("codebook value table too large"))?;
203 let mut values = vec![0.0f32; total];
204 let lookup_values = multiplicands.len();
205 for entry in 0..entries {
206 let mut last = 0.0f32;
207 let mut divisor = 1usize;
208 for i in 0..dimensions {
209 let offset = match lookup_type {
210 1 => (entry / divisor) % lookup_values.max(1),
211 _ => entry * dimensions + i,
212 };
213 let value = multiplicands.get(offset).copied().unwrap_or(0.0) * delta + minimum + last;
214 values[entry * dimensions + i] = value;
215 if sequence_p {
216 last = value;
217 }
218 divisor = divisor.saturating_mul(lookup_values.max(1));
219 }
220 }
221 Ok(values)
222}
223
224/// `ilog` of §9.2.1: the position of the highest set bit, zero for zero.
225pub fn ilog(mut value: u32) -> u32 {
226 let mut bits = 0;
227 while value > 0 {
228 bits += 1;
229 value >>= 1;
230 }
231 bits
232}
233
234/// Codeword assignment (§3.2.1) as a walkable tree, plus the codeword each
235/// entry got.
236///
237/// The rule is *not* the classic sorted-canonical one: entries are walked in
238/// their own order and each takes the first codeword of its length that is
239/// still free — so a book whose lengths are not already non-decreasing gets a
240/// different assignment than sorting by length would give. (A Laplacian residue
241/// book, short codes in the middle and long ones at both ends, is exactly that
242/// case; getting it wrong desynchronises every packet while still consuming a
243/// plausible number of bits.)
244///
245/// An under-populated tree is accepted rather than refused: single-entry books
246/// are legal, and streams in the wild (the Xiph `one-entry-codebook` vector
247/// among them) lean on the same leniency. What is refused is an *over*-full
248/// tree, where an entry has no codeword left to take.
249fn assign_codes(lengths: &[u8]) -> Result<(Vec<Node>, Vec<u32>)> {
250 let mut nodes = vec![Node::default()];
251 let mut codes = vec![0u32; lengths.len()];
252 for (entry, &length) in lengths.iter().enumerate() {
253 if length == 0 {
254 continue;
255 }
256 if length > 32 {
257 return Err(Error::corrupt("codebook codeword longer than 32 bits"));
258 }
259 let mut node = 0usize;
260 let mut code = 0u32;
261 let mut path: Vec<usize> = Vec::with_capacity(usize::from(length));
262 for step in 0..length {
263 // Depth still to go *below* the branch about to be taken.
264 let below = length - step - 1;
265 let branch = (0..2)
266 .find(|&bit| free_depth(nodes[node].child[bit], &nodes) <= below)
267 .ok_or_else(|| Error::corrupt("codebook is over-full"))?;
268 code = (code << 1) | branch as u32;
269 path.push(node);
270 match below {
271 0 => nodes[node].child[branch] = -((entry as i32) + 1),
272 _ => {
273 if nodes[node].child[branch] == 0 {
274 nodes.push(Node::default());
275 nodes[node].child[branch] = (nodes.len() - 1) as i32;
276 }
277 node = nodes[node].child[branch] as usize;
278 }
279 }
280 }
281 // Free depths shrink from the leaf back up to the root.
282 for &node in path.iter().rev() {
283 let left = free_depth(nodes[node].child[0], &nodes);
284 let right = free_depth(nodes[node].child[1], &nodes);
285 nodes[node].free = left.min(right).saturating_add(1);
286 }
287 codes[entry] = code;
288 }
289 Ok((nodes, codes))
290}
291
292/// One node of the codeword tree.
293#[derive(Debug, Clone, Copy)]
294pub struct Node {
295 /// Per branch: 0 free, positive a child index, negative the leaf
296 /// `-(entry + 1)`.
297 child: [i32; 2],
298 /// Shallowest free slot in this subtree, 255 when there is none.
299 free: u8,
300}
301
302impl Default for Node {
303 fn default() -> Node {
304 // A fresh node has two free branches, so a codeword can end one step
305 // below it.
306 Node {
307 child: [0, 0],
308 free: 1,
309 }
310 }
311}
312
313/// How far below `slot` the shallowest free slot sits; 255 when full.
314fn free_depth(slot: i32, nodes: &[Node]) -> u8 {
315 match slot {
316 0 => 0,
317 s if s < 0 => 255,
318 s => nodes[s as usize].free,
319 }
320}
321
322/// A codebook the encoder designed, kept in the shape the setup-header writer
323/// and the packet writer both need: lengths to state, codewords to emit.
324#[derive(Debug, Clone)]
325pub struct CodebookSpec {
326 /// Values per entry.
327 pub dimensions: usize,
328 /// Codeword length per entry, all non-zero (no sparse books written).
329 pub lengths: Vec<u8>,
330 /// Codeword per entry, MSB-first in `lengths[i]` bits.
331 pub codes: Vec<u32>,
332 /// Quantised values per entry when the book carries a lookup, empty for a
333 /// pure symbol book.
334 pub values: Vec<f32>,
335}
336
337impl CodebookSpec {
338 /// Build a book over `weights` (one per entry, a relative frequency).
339 ///
340 /// Huffman over the weights, then the canonical assignment the decoder
341 /// rebuilds from lengths alone. Every entry gets a codeword — a zero weight
342 /// becomes a long one rather than an absent one, because the encoder must
343 /// always have *something* to emit for a symbol it can produce.
344 pub fn huffman(weights: &[f64], values: Vec<f32>) -> CodebookSpec {
345 let lengths = huffman_lengths(weights);
346 // The decoder's own rule, run forwards: same order, same choices.
347 let (_, codes) = assign_codes(&lengths).expect("a Kraft-complete book always assigns");
348 CodebookSpec {
349 dimensions: 1,
350 lengths,
351 codes,
352 values,
353 }
354 }
355
356 /// Number of entries.
357 pub fn entries(&self) -> usize {
358 self.lengths.len()
359 }
360
361 /// Emit the codeword for `entry`.
362 pub fn write(&self, out: &mut BitsOut, entry: usize) {
363 let length = u32::from(self.lengths[entry]);
364 let code = self.codes[entry];
365 // The stream is LSB-first but a codeword reads MSB-first, so the bits
366 // go out one at a time from the top.
367 for depth in (0..length).rev() {
368 out.bit((code >> depth) & 1 != 0);
369 }
370 }
371}
372
373/// Huffman code lengths for `weights`, capped at 24 bits.
374///
375/// The cap is enforced by flattening: a weight small enough to earn a 25-bit
376/// codeword is raised until it does not. With at most a few hundred entries and
377/// weights within a few decades of each other the cap never binds, and when it
378/// does the cost is a fraction of a bit on the rarest symbol.
379fn huffman_lengths(weights: &[f64]) -> Vec<u8> {
380 let n = weights.len();
381 assert!(n > 0, "a codebook needs at least one entry");
382 if n == 1 {
383 return vec![1];
384 }
385 let floor = weights.iter().cloned().fold(0.0f64, f64::max) / 8_388_608.0;
386 let mut nodes: Vec<(f64, usize)> = weights
387 .iter()
388 .enumerate()
389 .map(|(i, &w)| (w.max(floor).max(f64::MIN_POSITIVE), i))
390 .collect();
391 // Leaves first, then merged nodes, tracked as a forest over `parent`.
392 let mut parent = vec![usize::MAX; n];
393 let mut heap: Vec<(f64, usize)> = nodes.clone();
394 heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap());
395 let mut merged: Vec<(f64, usize)> = Vec::new();
396 let mut next_id = n;
397 while heap.len() + merged.len() > 1 {
398 let mut take = || -> (f64, usize) {
399 let from_heap = heap.last().map(|x| x.0);
400 let from_merged = merged.first().map(|x| x.0);
401 match (from_heap, from_merged) {
402 (Some(a), Some(b)) if a <= b => heap.pop().unwrap(),
403 (Some(_), None) => heap.pop().unwrap(),
404 _ => merged.remove(0),
405 }
406 };
407 let (wa, a) = take();
408 let (wb, b) = take();
409 parent.push(usize::MAX);
410 parent[a] = next_id;
411 parent[b] = next_id;
412 merged.push((wa + wb, next_id));
413 next_id += 1;
414 }
415 nodes.clear();
416
417 let mut lengths = vec![0u8; n];
418 for (i, length) in lengths.iter_mut().enumerate() {
419 let mut node = i;
420 let mut depth = 0u32;
421 while parent[node] != usize::MAX {
422 node = parent[node];
423 depth += 1;
424 }
425 *length = depth.clamp(1, 24) as u8;
426 }
427 // Clamping can leave the tree over-full; rebalance by lengthening the
428 // shallowest entries until Kraft's sum is back at one.
429 balance(&mut lengths);
430 lengths
431}
432
433/// Push a length vector to exactly Kraft-complete, so the decoder's canonical
434/// rebuild has no ambiguity and no hole.
435fn balance(lengths: &mut [u8]) {
436 let kraft = |lengths: &[u8]| -> f64 {
437 lengths
438 .iter()
439 .map(|&l| 2f64.powi(-i32::from(l)))
440 .sum::<f64>()
441 };
442 // Over-full: lengthen the shortest codes.
443 while kraft(lengths) > 1.0 + 1e-12 {
444 let (index, _) = lengths
445 .iter()
446 .enumerate()
447 .min_by_key(|(_, l)| **l)
448 .expect("non-empty");
449 lengths[index] += 1;
450 }
451 // Under-full: shorten the longest, which only ever helps the rare symbols.
452 loop {
453 let sum = kraft(lengths);
454 let (index, &longest) = lengths
455 .iter()
456 .enumerate()
457 .max_by_key(|(_, l)| **l)
458 .expect("non-empty");
459 if longest <= 1 || sum + 2f64.powi(-i32::from(longest)) > 1.0 + 1e-12 {
460 break;
461 }
462 lengths[index] -= 1;
463 }
464}
465
466#[cfg(test)]
467mod tests {
468 use super::*;
469 use crate::bits::BitsOut;
470
471 #[test]
472 fn lookup1_values_matches_the_definition() {
473 assert_eq!(lookup1_values(1, 1), 1);
474 assert_eq!(lookup1_values(64, 2), 8);
475 assert_eq!(lookup1_values(63, 2), 7);
476 assert_eq!(lookup1_values(1000, 3), 10);
477 }
478
479 #[test]
480 fn a_designed_book_decodes_back_through_the_parsed_tree() {
481 // Skewed weights so the lengths differ, which is what exercises the
482 // canonical assignment on both sides.
483 let weights: Vec<f64> = (0..17).map(|i| 1.0 / (1.0 + f64::from(i))).collect();
484 let spec = CodebookSpec::huffman(&weights, Vec::new());
485 assert_eq!(spec.entries(), 17);
486 let kraft: f64 = spec.lengths.iter().map(|&l| 2f64.powi(-i32::from(l))).sum();
487 assert!((kraft - 1.0).abs() < 1e-9, "kraft sum {kraft}");
488
489 let mut out = BitsOut::new();
490 for entry in 0..spec.entries() {
491 spec.write(&mut out, entry);
492 }
493 let bytes = out.finish();
494
495 let (tree, _) = assign_codes(&spec.lengths).expect("tree");
496 let book = Codebook {
497 dimensions: 1,
498 tree,
499 values: Vec::new(),
500 };
501 let mut bits = Bits::new(&bytes);
502 for entry in 0..spec.entries() {
503 assert_eq!(book.decode_scalar(&mut bits), Some(entry as u32));
504 }
505 }
506}