forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

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