forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

huffman.rs478 lines, 16.0 KiBHistoryRawDownload
1//! Layer III Huffman coding: the table registry, a decode tree built once per
2//! process, and the encoder's cost/write side.
3
4use crate::huffman_tables::*;
5use ec_core::bitio::BitReader;
6use ec_core::error::{Error, Result};
7use std::sync::OnceLock;
8
9/// One code table as the bitstream refers to it.
10#[derive(Clone, Copy, Debug)]
11pub(crate) struct Table {
12 /// `(length, code)` indexed by `x * dim + y`.
13 pub codes: &'static [(u8, u16)],
14 /// Values per axis; `x` and `y` run `0..dim`, the top one being an escape
15 /// when `linbits` is non-zero.
16 pub dim: u16,
17 /// Extra magnitude bits read when a value is `dim - 1`.
18 pub linbits: u8,
19}
20
21/// The 32 big-value table slots. 4 and 14 are not assigned by the standard;
22/// 16..=23 and 24..=31 share one code table each and differ only in `linbits`.
23pub(crate) fn big_table(select: usize) -> Result<Table> {
24 let t = |codes: &'static [(u8, u16)], dim: u16, linbits: u8| Table {
25 codes,
26 dim,
27 linbits,
28 };
29 Ok(match select {
30 0 => t(&[], 0, 0),
31 1 => t(&T1, 2, 0),
32 2 => t(&T2, 3, 0),
33 3 => t(&T3, 3, 0),
34 5 => t(&T5, 4, 0),
35 6 => t(&T6, 4, 0),
36 7 => t(&T7, 6, 0),
37 8 => t(&T8, 6, 0),
38 9 => t(&T9, 6, 0),
39 10 => t(&T10, 8, 0),
40 11 => t(&T11, 8, 0),
41 12 => t(&T12, 8, 0),
42 13 => t(&T13, 16, 0),
43 15 => t(&T15, 16, 0),
44 16..=23 => t(&T16, 16, LINBITS_16[select - 16]),
45 24..=31 => t(&T24, 16, LINBITS_24[select - 24]),
46 _ => {
47 return Err(Error::corrupt(format!(
48 "mp3: Huffman table {select} is not assigned"
49 )));
50 }
51 })
52}
53
54const LINBITS_16: [u8; 8] = [1, 2, 3, 4, 6, 8, 10, 13];
55const LINBITS_24: [u8; 8] = [4, 5, 6, 7, 8, 9, 11, 13];
56
57/// The two count1 (quadruple) tables, selected by `count1table_select`.
58pub(crate) fn count1_table(select: bool) -> &'static [(u8, u16)] {
59 if select { &C1 } else { &C0 }
60}
61
62/// A decode tree: two child slots per node, a negative slot being
63/// `-(value_index + 1)`.
64type Tree = Vec<[i32; 2]>;
65
66fn build_tree(codes: &[(u8, u16)]) -> Tree {
67 let mut tree: Tree = vec![[0, 0]];
68 for (index, &(len, code)) in codes.iter().enumerate() {
69 let mut node = 0usize;
70 let code = u32::from(code);
71 for bit in (0..u32::from(len)).rev() {
72 let branch = ((code >> bit) & 1) as usize;
73 if bit == 0 {
74 tree[node][branch] = -(index as i32 + 1);
75 } else {
76 if tree[node][branch] == 0 {
77 tree.push([0, 0]);
78 tree[node][branch] = (tree.len() - 1) as i32;
79 }
80 node = tree[node][branch] as usize;
81 }
82 }
83 }
84 tree
85}
86
87struct Trees {
88 big: Vec<Option<Tree>>,
89 count1: [Tree; 2],
90}
91
92fn trees() -> &'static Trees {
93 static TREES: OnceLock<Trees> = OnceLock::new();
94 TREES.get_or_init(|| {
95 let mut big = Vec::with_capacity(32);
96 for select in 0..32 {
97 big.push(match big_table(select) {
98 Ok(t) if !t.codes.is_empty() => Some(build_tree(t.codes)),
99 _ => None,
100 });
101 }
102 Trees {
103 big,
104 count1: [build_tree(&C0), build_tree(&C1)],
105 }
106 })
107}
108
109fn walk(tree: &Tree, reader: &mut BitReader<'_>) -> Result<usize> {
110 let mut node = 0usize;
111 loop {
112 let branch = usize::from(reader.read_bit()?);
113 let next = tree[node][branch];
114 if next < 0 {
115 return Ok((-next - 1) as usize);
116 }
117 if next == 0 {
118 return Err(Error::corrupt("mp3: Huffman code not in table"));
119 }
120 node = next as usize;
121 }
122}
123
124/// Decodes one big-value pair into `out`, sign bits and linbits included.
125pub(crate) fn decode_pair(
126 reader: &mut BitReader<'_>,
127 select: usize,
128 table: Table,
129 out: &mut [f32; 2],
130) -> Result<()> {
131 let tree = trees().big[select]
132 .as_ref()
133 .ok_or_else(|| Error::corrupt(format!("mp3: Huffman table {select} is not assigned")))?;
134 let index = walk(tree, reader)?;
135 let values = [
136 (index as u16 / table.dim) as u32,
137 (index as u16 % table.dim) as u32,
138 ];
139 // Order matters and is per value, not per pair: escape bits then sign for
140 // x, then the same for y. Grouping them costs the same number of bits,
141 // which is why only the samples go wrong.
142 for (slot, mut value) in out.iter_mut().zip(values) {
143 if table.linbits > 0 && value == u32::from(table.dim) - 1 {
144 value += reader.read_bits(u32::from(table.linbits))?;
145 }
146 *slot = if value == 0 {
147 0.0
148 } else if reader.read_bit()? {
149 -(value as f32)
150 } else {
151 value as f32
152 };
153 }
154 Ok(())
155}
156
157/// Decodes one count1 quadruple: four values of 0 or +-1.
158pub(crate) fn decode_quad(
159 reader: &mut BitReader<'_>,
160 select: bool,
161 out: &mut [f32; 4],
162) -> Result<()> {
163 let tree = &trees().count1[usize::from(select)];
164 let index = walk(tree, reader)?;
165 for (slot, shift) in out.iter_mut().zip([3, 2, 1, 0]) {
166 let value = (index >> shift) & 1;
167 *slot = if value == 0 {
168 0.0
169 } else if reader.read_bit()? {
170 -1.0
171 } else {
172 1.0
173 };
174 }
175 Ok(())
176}
177
178/// A byte-backed bit accumulator for the granule coder: the same MSB-first
179/// convention as [`ec_core::bitio::BitWriter`], but buffering through a `u64`
180/// accumulator and appending whole bit runs, so a granule's Huffman codes and
181/// its splice into the main-data stream stop costing one call per bit.
182///
183/// The encoder's profile was ~45% inside `BitWriter::write_bit`'s per-bit
184/// branch-store cycle (plus the `Vec<bool>` materialisation every rate-loop
185/// round paid to hand granule bits up to the frame writer); this is the same
186/// bitstream, emitted a word at a time.
187#[derive(Clone, Debug, Default)]
188pub(crate) struct BitBuf {
189 /// Completed bytes.
190 bytes: Vec<u8>,
191 /// Pending bits, top-aligned in the accumulator (`used < 8`).
192 acc: u64,
193 used: u32,
194}
195
196impl BitBuf {
197 /// An empty buffer.
198 pub(crate) fn new() -> BitBuf {
199 BitBuf::default()
200 }
201
202 /// Bits written so far.
203 pub(crate) fn bit_len(&self) -> u32 {
204 (self.bytes.len() as u32) * 8 + self.used
205 }
206
207 /// Appends the low `n` bits of `value` (`n <= 64`), most significant first.
208 ///
209 /// The run is placed after the bits already buffered; when it would spill
210 /// past the accumulator's 64 bits the leading bits complete the buffered
211 /// bytes, those bytes are emitted, and the remainder starts a fresh word.
212 /// Since `used < 8`, the free space is always at least 57 bits, so the
213 /// remainder is under eight bits and the trailing drain below is the same
214 /// one the un-split path runs. A zero-length run is a no-op: the
215 /// scalefactor coder emits one for every band whose `slen` is zero.
216 pub(crate) fn push_bits(&mut self, value: u64, n: u32) {
217 debug_assert!(n <= 64, "push_bits: n = {n} > 64");
218 if n == 0 {
219 return;
220 }
221 let mask = if n >= 64 { u64::MAX } else { (1u64 << n) - 1 };
222 let value = value & mask;
223 let free = 64 - self.used;
224 if n <= free {
225 self.acc |= value << (free - n);
226 self.used += n;
227 } else {
228 // Spill: the run's top `free` bits fill the accumulator exactly,
229 // flush it, then the low `n - free` bits sit at the top of an
230 // empty word.
231 self.acc |= value >> (n - free);
232 self.used = 64;
233 while self.used >= 8 {
234 self.bytes.push((self.acc >> 56) as u8);
235 self.acc <<= 8;
236 self.used -= 8;
237 }
238 let tail = n - free;
239 self.acc |= (value & ((1u64 << tail) - 1)) << (64 - tail);
240 self.used = tail;
241 }
242 while self.used >= 8 {
243 self.bytes.push((self.acc >> 56) as u8);
244 self.acc <<= 8;
245 self.used -= 8;
246 }
247 }
248
249 /// Appends one bit.
250 pub(crate) fn push_bit(&mut self, bit: bool) {
251 if bit {
252 self.acc |= 1u64 << (63 - self.used);
253 }
254 self.used += 1;
255 if self.used == 8 {
256 self.bytes.push((self.acc >> 56) as u8);
257 self.acc = 0;
258 self.used = 0;
259 }
260 }
261
262 /// Appends the first `nbits` of `src`, most significant first — the bulk
263 /// path a granule's bits take into the frame's main-data stream.
264 pub(crate) fn push_bits_from(&mut self, src: &[u8], nbits: u32) {
265 let mut bit = 0;
266 while bit < nbits {
267 let take = (nbits - bit).min(8);
268 let byte = src[(bit / 8) as usize];
269 let off = bit % 8;
270 let value = u64::from(byte >> (8 - off - take)) & ((1u64 << take) - 1);
271 self.push_bits(value, take);
272 bit += take;
273 }
274 }
275
276 /// Appends every bit of `other`.
277 pub(crate) fn append(&mut self, other: &BitBuf) {
278 self.push_bits_from(&other.bytes, (other.bytes.len() as u32) * 8);
279 if other.used > 0 {
280 self.push_bits(other.acc >> (64 - other.used), other.used);
281 }
282 }
283
284 /// Zero-pads to the byte boundary and hands back the bytes, the partial
285 /// byte's unused low bits zero — exactly what `BitWriter` produces.
286 pub(crate) fn into_bytes(mut self) -> Vec<u8> {
287 if self.used > 0 {
288 self.bytes.push((self.acc >> 56) as u8);
289 }
290 self.bytes
291 }
292}
293
294/// Writes one pair; the caller has already checked it fits the table.
295pub(crate) fn write_pair(writer: &mut BitBuf, table: Table, x: i32, y: i32) {
296 let max = u32::from(table.dim) - 1;
297 let escape = table.linbits > 0;
298 let (ax, ay) = (x.unsigned_abs(), y.unsigned_abs());
299 let (ix, iy) = (ax.min(max), ay.min(max));
300 let (len, code) = table.codes[(ix * u32::from(table.dim) + iy) as usize];
301 writer.push_bits(u64::from(code), u32::from(len));
302 for (value, abs) in [(x, ax), (y, ay)] {
303 if abs >= max && escape {
304 writer.push_bits(u64::from(abs - max), u32::from(table.linbits));
305 }
306 if abs != 0 {
307 writer.push_bit(value < 0);
308 }
309 }
310}
311
312/// Bits one count1 quadruple costs.
313pub(crate) fn quad_bits(select: bool, quad: [i32; 4]) -> u32 {
314 let index = quad
315 .iter()
316 .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0));
317 let (len, _) = count1_table(select)[index];
318 u32::from(len) + quad.iter().filter(|v| **v != 0).count() as u32
319}
320
321/// Writes one count1 quadruple.
322pub(crate) fn write_quad(writer: &mut BitBuf, select: bool, quad: [i32; 4]) {
323 let index = quad
324 .iter()
325 .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0));
326 let (len, code) = count1_table(select)[index];
327 writer.push_bits(u64::from(code), u32::from(len));
328 for value in quad {
329 if value != 0 {
330 writer.push_bit(value < 0);
331 }
332 }
333}
334
335#[cfg(test)]
336mod tests {
337 use super::*;
338
339 /// Every table is a complete prefix code over its whole value grid: the
340 /// property the measurement rig checked before these numbers were written,
341 /// re-checked here so a hand edit cannot break it unnoticed.
342 #[test]
343 fn tables_are_complete_prefix_codes() {
344 let mut seen = 0;
345 for select in 0..32 {
346 let Ok(table) = big_table(select) else {
347 continue;
348 };
349 if table.codes.is_empty() {
350 continue;
351 }
352 seen += 1;
353 assert_eq!(
354 table.codes.len(),
355 usize::from(table.dim) * usize::from(table.dim)
356 );
357 let kraft: f64 = table
358 .codes
359 .iter()
360 .map(|(len, _)| 2f64.powi(-i32::from(*len)))
361 .sum();
362 assert!(
363 (kraft - 1.0).abs() < 1e-12,
364 "table {select}: Kraft sum {kraft}"
365 );
366 let tree = build_tree(table.codes);
367 assert_eq!(
368 tree.iter().flatten().filter(|n| **n < 0).count(),
369 table.codes.len()
370 );
371 }
372 assert_eq!(seen, 29, "tables 0..31 minus the four unassigned slots");
373 for select in [false, true] {
374 let codes = count1_table(select);
375 let kraft: f64 = codes
376 .iter()
377 .map(|(len, _)| 2f64.powi(-i32::from(*len)))
378 .sum();
379 assert!((kraft - 1.0).abs() < 1e-12);
380 }
381 }
382
383 #[test]
384 fn pairs_round_trip_through_every_table() {
385 for select in (1..32).filter(|s| big_table(*s).is_ok()) {
386 let table = big_table(select).unwrap();
387 if table.codes.is_empty() {
388 continue;
389 }
390 let max = u32::from(table.dim) - 1;
391 let mut writer = BitBuf::new();
392 let mut wanted = Vec::new();
393 for x in 0..=max {
394 for y in 0..=max {
395 let (sx, sy) = (x as i32, -(y as i32));
396 write_pair(&mut writer, table, sx, sy);
397 wanted.push([sx as f32, sy as f32]);
398 }
399 }
400 let bytes = writer.into_bytes();
401 let mut reader = BitReader::new(&bytes);
402 for want in wanted {
403 let mut got = [0.0f32; 2];
404 decode_pair(&mut reader, select, table, &mut got).unwrap();
405 assert_eq!(got, want, "table {select}");
406 }
407 }
408 }
409
410 /// `push_bits` appends any run up to 64 bits, even one that straddles the
411 /// accumulator's own width, and a zero-length run is a no-op. Byte-for-byte
412 /// against a plain MSB-first reference. The cases that bite: a zero-length
413 /// run at `used == 0` (which the scalefactor path hits whenever `slen` is
414 /// zero) shifted by the full 64, and a run whose leading bits complete the
415 /// buffered bytes plus a remainder.
416 #[test]
417 fn bits_survive_the_accumulator_boundary() {
418 let mut writer = BitBuf::new();
419 let mut bits: Vec<bool> = Vec::new();
420 let push = |writer: &mut BitBuf, bits: &mut Vec<bool>, value: u64, n: u32| {
421 for i in (0..n).rev() {
422 bits.push((value >> i) & 1 == 1);
423 }
424 writer.push_bits(value, n);
425 };
426 for &(value, n) in &[
427 (0u64, 0u32), // zero-length run, empty buffer
428 (0b101, 3), // part-fill
429 (0xABCD_EF01_2345_6789, 64), // a full word, straddling
430 (0b1_0110, 5),
431 (0x00FF_00FF_00FF_00FF, 60), // 5 + 60 > 64: a spill
432 (0, 0), // zero-length mid-stream
433 (0xDEAD_BEEF, 32),
434 (0b111, 3),
435 (0x5555_5555_5555_5555, 57), // another spill
436 ] {
437 push(&mut writer, &mut bits, value, n);
438 }
439 let mut want = Vec::new();
440 let mut byte = 0u8;
441 for (i, bit) in bits.iter().enumerate() {
442 byte = (byte << 1) | u8::from(*bit);
443 if i % 8 == 7 {
444 want.push(byte);
445 byte = 0;
446 }
447 }
448 if !bits.len().is_multiple_of(8) {
449 want.push(byte << (8 - bits.len() % 8));
450 }
451 assert_eq!(writer.into_bytes(), want);
452 }
453
454 #[test]
455 fn quads_round_trip() {
456 for select in [false, true] {
457 let mut writer = BitBuf::new();
458 let mut wanted = Vec::new();
459 for index in 0..16 {
460 let quad = [
461 (index >> 3) & 1,
462 -((index >> 2) & 1),
463 (index >> 1) & 1,
464 -(index & 1),
465 ];
466 write_quad(&mut writer, select, quad);
467 wanted.push(quad.map(|v| v as f32));
468 }
469 let bytes = writer.into_bytes();
470 let mut reader = BitReader::new(&bytes);
471 for want in wanted {
472 let mut got = [0.0f32; 4];
473 decode_quad(&mut reader, select, &mut got).unwrap();
474 assert_eq!(got, want);
475 }
476 }
477 }
478}