//! Layer III Huffman coding: the table registry, a decode tree built once per
//! process, and the encoder's cost/write side.
use crate::huffman_tables::*;
use ec_core::bitio::{BitReader, BitWriter};
use ec_core::error::{Error, Result};
use std::sync::OnceLock;
/// One code table as the bitstream refers to it.
#[derive(Clone, Copy, Debug)]
pub(crate) struct Table {
/// `(length, code)` indexed by `x * dim + y`.
pub codes: &'static [(u8, u16)],
/// Values per axis; `x` and `y` run `0..dim`, the top one being an escape
/// when `linbits` is non-zero.
pub dim: u16,
/// Extra magnitude bits read when a value is `dim - 1`.
pub linbits: u8,
}
/// The 32 big-value table slots. 4 and 14 are not assigned by the standard;
/// 16..=23 and 24..=31 share one code table each and differ only in `linbits`.
pub(crate) fn big_table(select: usize) -> Result
{
let t = |codes: &'static [(u8, u16)], dim: u16, linbits: u8| Table {
codes,
dim,
linbits,
};
Ok(match select {
0 => t(&[], 0, 0),
1 => t(&T1, 2, 0),
2 => t(&T2, 3, 0),
3 => t(&T3, 3, 0),
5 => t(&T5, 4, 0),
6 => t(&T6, 4, 0),
7 => t(&T7, 6, 0),
8 => t(&T8, 6, 0),
9 => t(&T9, 6, 0),
10 => t(&T10, 8, 0),
11 => t(&T11, 8, 0),
12 => t(&T12, 8, 0),
13 => t(&T13, 16, 0),
15 => t(&T15, 16, 0),
16..=23 => t(&T16, 16, LINBITS_16[select - 16]),
24..=31 => t(&T24, 16, LINBITS_24[select - 24]),
_ => {
return Err(Error::corrupt(format!(
"mp3: Huffman table {select} is not assigned"
)));
}
})
}
const LINBITS_16: [u8; 8] = [1, 2, 3, 4, 6, 8, 10, 13];
const LINBITS_24: [u8; 8] = [4, 5, 6, 7, 8, 9, 11, 13];
/// The two count1 (quadruple) tables, selected by `count1table_select`.
pub(crate) fn count1_table(select: bool) -> &'static [(u8, u16)] {
if select { &C1 } else { &C0 }
}
/// A decode tree: two child slots per node, a negative slot being
/// `-(value_index + 1)`.
type Tree = Vec<[i32; 2]>;
fn build_tree(codes: &[(u8, u16)]) -> Tree {
let mut tree: Tree = vec![[0, 0]];
for (index, &(len, code)) in codes.iter().enumerate() {
let mut node = 0usize;
let code = u32::from(code);
for bit in (0..u32::from(len)).rev() {
let branch = ((code >> bit) & 1) as usize;
if bit == 0 {
tree[node][branch] = -(index as i32 + 1);
} else {
if tree[node][branch] == 0 {
tree.push([0, 0]);
tree[node][branch] = (tree.len() - 1) as i32;
}
node = tree[node][branch] as usize;
}
}
}
tree
}
struct Trees {
big: Vec