rusty_aac 1.0.0

Pure-Rust AAC decoder (LC, Main, LTP, HE-AAC v1/v2 SBR+PS, ER LD/ELD; sample-exact vs FFmpeg on the ISO conformance suite) and AAC-LC encoder (~5x faster than FFmpeg's native encoder, PEAQ-measured). No C/FFI. ADTS/MP4/LATM-LOAS, 7.1 + PCE layouts.
Documentation
//! Generic canonical-prefix Huffman decoder for the AAC spectral and
//! scalefactor codebooks (ISO 14496-3 §4.A.3).
//!
//! Each codebook is two parallel `'static` arrays — `codes[i]` is the codeword
//! and `lens[i]` its bit length — exactly the form the spec/reference tables
//! ship in. Decoding reads bits MSB-first, accumulating until a `(len, code)`
//! pair matches; the codes are prefix-free, so the first match is the symbol.
//! `decode` returns the array index `i`, which the codebook layer unpacks into
//! spectral coefficients. O(maxlen·count) per codeword — codebooks are small,
//! so it is plenty fast and trivially verifiable.

#![allow(dead_code)]

use crate::{Error, Result};

use crate::bits::BitReader;

/// A Huffman codebook: parallel codeword / bit-length tables.
pub struct HuffBook {
    codes: &'static [u32],
    lens: &'static [u8],
    max_len: u8,
    /// Primary lookup table over the next `LUT_BITS` bits: `sym << 8 | len`, or 0
    /// for "longer code, take the scan". Built on first use.
    lut: std::sync::OnceLock<Vec<u32>>,
}

/// Width of the primary lookup (2^11 entries, 8 KiB per book).
const LUT_BITS: u32 = 11;

impl HuffBook {
    pub const fn new(codes: &'static [u32], lens: &'static [u8]) -> HuffBook {
        let mut max = 0u8;
        let mut i = 0;
        while i < lens.len() {
            if lens[i] > max {
                max = lens[i];
            }
            i += 1;
        }
        HuffBook {
            codes,
            lens,
            max_len: max,
            lut: std::sync::OnceLock::new(),
        }
    }

    pub fn count(&self) -> usize {
        self.codes.len()
    }

    /// The `(codeword, bit-length)` for symbol index `i` — the encoder side.
    pub fn code(&self, i: usize) -> (u32, u8) {
        (self.codes[i], self.lens[i])
    }

    fn build_lut(&self) -> Vec<u32> {
        let bits = LUT_BITS.min(self.max_len as u32);
        let mut lut = vec![0u32; 1 << bits];
        for (i, (&c, &l)) in self.codes.iter().zip(self.lens).enumerate() {
            let l = l as u32;
            if l == 0 || l > bits {
                continue;
            }
            let base = (c << (bits - l)) as usize;
            for e in lut.iter_mut().skip(base).take(1 << (bits - l)) {
                *e = ((i as u32) << 8) | l;
            }
        }
        lut
    }

    /// Decode the next codeword, returning its symbol index. One table lookup
    /// for codes up to `LUT_BITS` long; the scan below (the original decoder,
    /// kept as the oracle) for the rare longer ones.
    #[inline]
    pub fn decode(&self, r: &mut BitReader) -> Result<u16> {
        let lut = self.lut.get_or_init(|| self.build_lut());
        let bits = LUT_BITS.min(self.max_len as u32);
        let e = lut[r.peek_bits(bits) as usize];
        if e != 0 {
            r.skip((e & 0xFF) as usize)?;
            return Ok((e >> 8) as u16);
        }
        self.decode_scan(r)
    }

    /// The bit-serial scan decoder (test oracle and long-code fallback).
    pub fn decode_scan(&self, r: &mut BitReader) -> Result<u16> {
        let mut code = 0u32;
        for len in 1..=self.max_len {
            code = (code << 1) | r.read_bit()?;
            for i in 0..self.codes.len() {
                if self.lens[i] == len && self.codes[i] == code {
                    return Ok(i as u16);
                }
            }
        }
        Err(Error::invalid("aac: invalid Huffman codeword"))
    }

    /// Kraft sum Σ 2^-len — 1.0 for a complete code, slightly less if incomplete.
    #[cfg(test)]
    pub fn kraft_sum(&self) -> f64 {
        self.lens.iter().map(|&l| 2f64.powi(-(l as i32))).sum()
    }

    /// True if no codeword is a prefix of another.
    #[cfg(test)]
    pub fn is_prefix_free(&self) -> bool {
        for a in 0..self.codes.len() {
            for b in (a + 1)..self.codes.len() {
                let (la, ca) = (self.lens[a], self.codes[a]);
                let (lb, cb) = (self.lens[b], self.codes[b]);
                let (short_l, short_c, long_l, long_c) = if la <= lb {
                    (la, ca, lb, cb)
                } else {
                    (lb, cb, la, ca)
                };
                if long_c >> (long_l - short_l) == short_c {
                    return false;
                }
            }
        }
        true
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    // A tiny prefix-free book: index 0→"0", 1→"10", 2→"110", 3→"111".
    static TEST_CODES: &[u32] = &[0b0, 0b10, 0b110, 0b111];
    static TEST_LENS: &[u8] = &[1, 2, 3, 3];

    #[test]
    fn decodes_prefix_free_sequence() {
        let book = HuffBook::new(TEST_CODES, TEST_LENS);
        // Stream 0 10 110 111 0 → indices 0 1 2 3 0
        // bits: 0 10 110 111 0 → 0101 1011 10.. = 0x5B 0x80
        let mut r = BitReader::new(&[0x5B, 0x80]);
        let got: Vec<u16> = (0..5).map(|_| book.decode(&mut r).unwrap()).collect();
        assert_eq!(got, vec![0, 1, 2, 3, 0]);
    }

    /// The table decoder must agree with the scan on every codeword of every
    /// spectral and scalefactor book, followed by arbitrary bits.
    #[test]
    fn lut_matches_scan_on_every_book() {
        let mut books: Vec<&HuffBook> = vec![&crate::tables::SCALEFACTOR_BOOK];
        for cb in 1..=11u8 {
            books.push(crate::tables::spectral_book(cb));
        }
        for book in books {
            for i in 0..book.count() {
                let (code, len) = book.code(i);
                // codeword, then a tail of alternating bits, MSB-first into bytes.
                let mut bitsv: Vec<u8> = (0..len).rev().map(|b| ((code >> b) & 1) as u8).collect();
                bitsv.extend((0..23).map(|k| (k % 3 == 0) as u8));
                let mut bytes = vec![0u8; bitsv.len().div_ceil(8) + 1];
                for (k, &b) in bitsv.iter().enumerate() {
                    bytes[k / 8] |= b << (7 - k % 8);
                }
                let mut a = BitReader::new(&bytes);
                let mut b = BitReader::new(&bytes);
                assert_eq!(book.decode(&mut a).unwrap(), i as u16);
                assert_eq!(book.decode_scan(&mut b).unwrap(), i as u16);
                assert_eq!(a.position(), b.position());
            }
        }
    }

    #[test]
    fn structural_helpers() {
        let book = HuffBook::new(TEST_CODES, TEST_LENS);
        assert!((book.kraft_sum() - 1.0).abs() < 1e-12);
        assert!(book.is_prefix_free());
    }
}