diff --git a/crates/ec-vorbis/Cargo.toml b/crates/ec-vorbis/Cargo.toml new file mode 100644 index 00000000..54b1771d --- /dev/null +++ b/crates/ec-vorbis/Cargo.toml @@ -0,0 +1,14 @@ +[package] +name = "ec-vorbis" +description = "Vorbis I decoder and encoder: full codebook/floor/residue decode, MDCT via ec-dsp, and an encoder with native mono/stereo/surround setup headers." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core.workspace = true +ec-dsp.workspace = true + +[dev-dependencies] +ec-ogg = { path = "../ec-ogg", version = "0.1.0" } diff --git a/crates/ec-vorbis/src/bits.rs b/crates/ec-vorbis/src/bits.rs new file mode 100644 index 00000000..e3c3db0e --- /dev/null +++ b/crates/ec-vorbis/src/bits.rs @@ -0,0 +1,150 @@ +//! Packet-local bit access with the Vorbis end-of-packet convention. +//! +//! Reading past the end of a Vorbis packet is not an error. The spec's decode +//! loops read until the packet runs out and take zeroes after that, which is +//! how a truncated final packet still decodes to the audio it does hold. So +//! this reader answers zero past the end and raises a sticky flag; the callers +//! that must not act on a zero — Huffman decode, header parse — ask [`Bits::eop`]. + +use ec_core::{BitReaderLsb, BitWriterLsb}; + +/// LSB-first reader over one packet. +pub struct Bits<'a> { + reader: BitReaderLsb<'a>, + eop: bool, +} + +impl<'a> Bits<'a> { + /// A reader positioned at the first bit of `data`. + pub fn new(data: &'a [u8]) -> Bits<'a> { + Bits { + reader: BitReaderLsb::new(data), + eop: false, + } + } + + /// `n` bits (`n <= 32`), zero once the packet is exhausted. + pub fn read(&mut self, n: u32) -> u32 { + match self.reader.read_bits(n) { + Ok(v) => v, + Err(_) => { + self.eop = true; + 0 + } + } + } + + /// One bit, false once the packet is exhausted. + pub fn bit(&mut self) -> bool { + self.read(1) != 0 + } + + /// True once a read has run past the end of the packet. + pub fn eop(&self) -> bool { + self.eop + } + + /// Bits left before the end of the packet. + pub fn remaining(&self) -> u64 { + self.reader.bits_remaining() + } + + /// The 32-bit float of Vorbis I §9.2.2 — a 21-bit mantissa, a sign and a + /// biased exponent, and *not* IEEE 754: it is decoded with integer + /// arithmetic so every decoder agrees on the last bit. + pub fn float32(&mut self) -> f32 { + let x = self.read(32); + float32_unpack(x) + } +} + +/// Vorbis I §9.2.2 float unpack, split out because the encoder packs the +/// inverse of it. +pub fn float32_unpack(x: u32) -> f32 { + let mantissa = i64::from(x & 0x001f_ffff); + let sign = x & 0x8000_0000 != 0; + let exponent = ((x & 0x7fe0_0000) >> 21) as i32; + let mantissa = if sign { -mantissa } else { mantissa }; + // `exp2` rather than `powi`: the exponent field spans 2^-788..2^235, which + // only stays exact as a power of two. + (mantissa as f64 * f64::from(exponent - 788).exp2()) as f32 +} + +/// The inverse of [`float32_unpack`] for a value an encoder wants to state +/// exactly: mantissa in `[-2^21, 2^21)` scaled by a power of two. +pub fn float32_pack(value: f32) -> u32 { + if value == 0.0 || !value.is_finite() { + return 0; + } + let sign = value < 0.0; + let mut mantissa = f64::from(value.abs()); + let mut exponent = 0i32; + // Normalise into [2^20, 2^21) so the 21-bit mantissa field is fully used. + while mantissa >= 2_097_152.0 { + mantissa /= 2.0; + exponent += 1; + } + while mantissa < 1_048_576.0 { + mantissa *= 2.0; + exponent -= 1; + } + let mantissa = mantissa.round() as u32 & 0x001f_ffff; + let exponent = (exponent + 788).clamp(0, 0x3ff) as u32; + (u32::from(sign) << 31) | (exponent << 21) | mantissa +} + +/// LSB-first writer over one packet, the mirror of [`Bits`]. +#[derive(Default)] +pub struct BitsOut { + writer: BitWriterLsb, +} + +impl BitsOut { + /// An empty packet. + pub fn new() -> BitsOut { + BitsOut::default() + } + + /// Write the low `n` bits of `value`. + pub fn write(&mut self, value: u32, n: u32) { + self.writer.write_bits(value, n); + } + + /// Write one bit. + pub fn bit(&mut self, bit: bool) { + self.writer.write_bit(bit); + } + + /// Bits written so far. + pub fn len(&self) -> u64 { + self.writer.bit_len() + } + + /// The packet, zero-padded to a byte. + pub fn finish(self) -> Vec { + self.writer.into_bytes() + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn float32_round_trips_through_the_spec_format() { + for value in [1.0f32, 0.5, -2.25, 1e-6, 1024.0, -0.0009765625] { + let packed = float32_pack(value); + let back = float32_unpack(packed); + assert!( + (back - value).abs() <= value.abs() * 1e-6, + "{value} -> {packed:#x} -> {back}" + ); + } + assert_eq!(float32_unpack(0), 0.0); + // A read past the end is zero with the flag raised, not an error. + let mut bits = Bits::new(&[0xff]); + assert_eq!(bits.read(8), 0xff); + assert_eq!(bits.read(1), 0); + assert!(bits.eop()); + } +} diff --git a/crates/ec-vorbis/src/codebook.rs b/crates/ec-vorbis/src/codebook.rs new file mode 100644 index 00000000..576786f7 --- /dev/null +++ b/crates/ec-vorbis/src/codebook.rs @@ -0,0 +1,506 @@ +//! Codebooks: Huffman lengths in, entry numbers and VQ vectors out. +//! +//! Three things make a Vorbis codebook more than a Huffman table. The lengths +//! themselves come in three encodings (flat, sparse, ordered-by-length). The +//! codeword assignment is canonical but stated as "the next free codeword of +//! this length", which is the same thing read from the other end. And a book +//! may carry a *lookup*: entry numbers index a vector of quantised values, +//! either by taking `dimensions` digits of the entry number in base +//! `lookup_values` (type 1, the packing that makes a 2^24-vector book fit in a +//! few hundred bytes) or by indexing the list directly (type 2). Both are +//! expanded once at parse time, so decode is a tree walk and a slice. + +use ec_core::{Error, Result}; + +use crate::bits::{Bits, BitsOut}; + +/// One parsed codebook. +#[derive(Debug, Clone)] +pub struct Codebook { + /// Values per entry: 1 for a scalar book, more for a VQ book. + pub dimensions: usize, + /// Codeword tree, walked one bit at a time. + tree: Vec, + /// `entries * dimensions` values, empty when `lookup_type` is 0. + values: Vec, +} + +impl Codebook { + /// Parse one codebook from a setup header (§3.2.1). + pub fn parse(bits: &mut Bits) -> Result { + if bits.read(24) != 0x0056_4342 { + return Err(Error::corrupt("codebook sync pattern")); + } + let dimensions = bits.read(16) as usize; + let entries = bits.read(24) as usize; + if bits.eop() { + return Err(Error::corrupt("codebook header truncated")); + } + if dimensions == 0 || entries == 0 { + return Err(Error::corrupt("empty codebook")); + } + // A book cannot be larger than the packet that describes it: every + // length costs at least one bit, so this is the OOM guard on a header + // that claims 2^24 entries in twenty bytes. + if entries as u64 > bits.remaining() + 64 { + return Err(Error::corrupt("codebook claims more entries than bits")); + } + + let mut lengths = vec![0u8; entries]; + if bits.bit() { + // Ordered: lengths are non-decreasing, stated as run lengths. + let mut entry = 0usize; + let mut length = bits.read(5) + 1; + while entry < entries { + if length > 32 { + return Err(Error::corrupt("ordered codebook overran 32 bits")); + } + let bits_needed = ilog((entries - entry) as u32); + let run = bits.read(bits_needed) as usize; + if entry + run > entries { + return Err(Error::corrupt("ordered codebook run past the end")); + } + lengths[entry..entry + run].fill(length as u8); + entry += run; + length += 1; + if bits.eop() { + return Err(Error::corrupt("ordered codebook truncated")); + } + } + } else { + let sparse = bits.bit(); + for length in lengths.iter_mut() { + if sparse && !bits.bit() { + continue; + } + *length = (bits.read(5) + 1) as u8; + } + if bits.eop() { + return Err(Error::corrupt("codebook lengths truncated")); + } + } + + let (tree, _) = assign_codes(&lengths)?; + + let lookup_type = bits.read(4); + let values = match lookup_type { + 0 => Vec::new(), + 1 | 2 => { + let minimum = bits.float32(); + let delta = bits.float32(); + let value_bits = bits.read(4) + 1; + let sequence_p = bits.bit(); + let lookup_values = match lookup_type { + 1 => lookup1_values(entries, dimensions), + _ => entries * dimensions, + }; + if bits.eop() || lookup_values as u64 > bits.remaining() + 64 { + return Err(Error::corrupt("codebook lookup truncated")); + } + let multiplicands: Vec = (0..lookup_values) + .map(|_| bits.read(value_bits) as f32) + .collect(); + expand_lookup( + lookup_type, + entries, + dimensions, + minimum, + delta, + sequence_p, + &multiplicands, + )? + } + other => { + return Err(Error::unsupported( + format!("codebook lookup type {other}"), + "Vorbis I defines 0, 1 and 2", + )); + } + }; + if bits.eop() { + return Err(Error::corrupt("codebook truncated")); + } + + Ok(Codebook { + dimensions, + tree, + values, + }) + } + + /// True when entries carry VQ values, i.e. the book can fill a residue or + /// floor-0 vector rather than only naming a number. + pub fn has_values(&self) -> bool { + !self.values.is_empty() + } + + /// Read one codeword; [`None`] at end of packet or on an undefined path. + pub fn decode_scalar(&self, bits: &mut Bits) -> Option { + let mut node = 0usize; + loop { + let child = self.tree[node].child[usize::from(bits.bit())]; + if bits.eop() { + return None; + } + match child { + 0 => return None, + c if c < 0 => return Some((-c - 1) as u32), + c => node = c as usize, + } + } + } + + /// Read one codeword and answer its value vector; [`None`] as above. + pub fn decode_vector(&self, bits: &mut Bits) -> Option<&[f32]> { + let entry = self.decode_scalar(bits)? as usize; + self.vector(entry) + } + + /// The value vector of `entry`, when this book has values. + pub fn vector(&self, entry: usize) -> Option<&[f32]> { + let start = entry.checked_mul(self.dimensions)?; + self.values.get(start..start + self.dimensions) + } +} + +/// Greatest `m` with `m^dimensions <= entries` (§9.2.3), computed without +/// `powf` so the boundary case never lands on the wrong side. +pub fn lookup1_values(entries: usize, dimensions: usize) -> usize { + let mut value = 1usize; + loop { + let mut product = 1usize; + let mut overflow = false; + for _ in 0..dimensions { + match product.checked_mul(value + 1) { + Some(p) if p <= entries => product = p, + _ => { + overflow = true; + break; + } + } + } + if overflow { + return value; + } + value += 1; + } +} + +/// Turn multiplicands into one value vector per entry (§3.2.1 "VQ lookup"). +fn expand_lookup( + lookup_type: u32, + entries: usize, + dimensions: usize, + minimum: f32, + delta: f32, + sequence_p: bool, + multiplicands: &[f32], +) -> Result> { + let total = entries + .checked_mul(dimensions) + .filter(|n| *n <= 1 << 24) + .ok_or_else(|| Error::corrupt("codebook value table too large"))?; + let mut values = vec![0.0f32; total]; + let lookup_values = multiplicands.len(); + for entry in 0..entries { + let mut last = 0.0f32; + let mut divisor = 1usize; + for i in 0..dimensions { + let offset = match lookup_type { + 1 => (entry / divisor) % lookup_values.max(1), + _ => entry * dimensions + i, + }; + let value = multiplicands.get(offset).copied().unwrap_or(0.0) * delta + minimum + last; + values[entry * dimensions + i] = value; + if sequence_p { + last = value; + } + divisor = divisor.saturating_mul(lookup_values.max(1)); + } + } + Ok(values) +} + +/// `ilog` of §9.2.1: the position of the highest set bit, zero for zero. +pub fn ilog(mut value: u32) -> u32 { + let mut bits = 0; + while value > 0 { + bits += 1; + value >>= 1; + } + bits +} + +/// Codeword assignment (§3.2.1) as a walkable tree, plus the codeword each +/// entry got. +/// +/// The rule is *not* the classic sorted-canonical one: entries are walked in +/// their own order and each takes the first codeword of its length that is +/// still free — so a book whose lengths are not already non-decreasing gets a +/// different assignment than sorting by length would give. (A Laplacian residue +/// book, short codes in the middle and long ones at both ends, is exactly that +/// case; getting it wrong desynchronises every packet while still consuming a +/// plausible number of bits.) +/// +/// An under-populated tree is accepted rather than refused: single-entry books +/// are legal, and streams in the wild (the Xiph `one-entry-codebook` vector +/// among them) lean on the same leniency. What is refused is an *over*-full +/// tree, where an entry has no codeword left to take. +fn assign_codes(lengths: &[u8]) -> Result<(Vec, Vec)> { + let mut nodes = vec![Node::default()]; + let mut codes = vec![0u32; lengths.len()]; + for (entry, &length) in lengths.iter().enumerate() { + if length == 0 { + continue; + } + if length > 32 { + return Err(Error::corrupt("codebook codeword longer than 32 bits")); + } + let mut node = 0usize; + let mut code = 0u32; + let mut path: Vec = Vec::with_capacity(usize::from(length)); + for step in 0..length { + // Depth still to go *below* the branch about to be taken. + let below = length - step - 1; + let branch = (0..2) + .find(|&bit| free_depth(nodes[node].child[bit], &nodes) <= below) + .ok_or_else(|| Error::corrupt("codebook is over-full"))?; + code = (code << 1) | branch as u32; + path.push(node); + match below { + 0 => nodes[node].child[branch] = -((entry as i32) + 1), + _ => { + if nodes[node].child[branch] == 0 { + nodes.push(Node::default()); + nodes[node].child[branch] = (nodes.len() - 1) as i32; + } + node = nodes[node].child[branch] as usize; + } + } + } + // Free depths shrink from the leaf back up to the root. + for &node in path.iter().rev() { + let left = free_depth(nodes[node].child[0], &nodes); + let right = free_depth(nodes[node].child[1], &nodes); + nodes[node].free = left.min(right).saturating_add(1); + } + codes[entry] = code; + } + Ok((nodes, codes)) +} + +/// One node of the codeword tree. +#[derive(Debug, Clone, Copy)] +pub struct Node { + /// Per branch: 0 free, positive a child index, negative the leaf + /// `-(entry + 1)`. + child: [i32; 2], + /// Shallowest free slot in this subtree, 255 when there is none. + free: u8, +} + +impl Default for Node { + fn default() -> Node { + // A fresh node has two free branches, so a codeword can end one step + // below it. + Node { + child: [0, 0], + free: 1, + } + } +} + +/// How far below `slot` the shallowest free slot sits; 255 when full. +fn free_depth(slot: i32, nodes: &[Node]) -> u8 { + match slot { + 0 => 0, + s if s < 0 => 255, + s => nodes[s as usize].free, + } +} + +/// A codebook the encoder designed, kept in the shape the setup-header writer +/// and the packet writer both need: lengths to state, codewords to emit. +#[derive(Debug, Clone)] +pub struct CodebookSpec { + /// Values per entry; 1 for every book this encoder writes. + pub dimensions: usize, + /// Codeword length per entry, all non-zero (no sparse books written). + pub lengths: Vec, + /// Codeword per entry, MSB-first in `lengths[i]` bits. + pub codes: Vec, + /// Quantised value per entry when the book carries a lookup, empty for a + /// pure symbol book. + pub values: Vec, +} + +impl CodebookSpec { + /// Build a book over `weights` (one per entry, a relative frequency). + /// + /// Huffman over the weights, then the canonical assignment the decoder + /// rebuilds from lengths alone. Every entry gets a codeword — a zero weight + /// becomes a long one rather than an absent one, because the encoder must + /// always have *something* to emit for a symbol it can produce. + pub fn huffman(weights: &[f64], values: Vec) -> CodebookSpec { + let lengths = huffman_lengths(weights); + // The decoder's own rule, run forwards: same order, same choices. + let (_, codes) = assign_codes(&lengths).expect("a Kraft-complete book always assigns"); + CodebookSpec { + dimensions: 1, + lengths, + codes, + values, + } + } + + /// Number of entries. + pub fn entries(&self) -> usize { + self.lengths.len() + } + + /// Emit the codeword for `entry`. + pub fn write(&self, out: &mut BitsOut, entry: usize) { + let length = u32::from(self.lengths[entry]); + let code = self.codes[entry]; + // The stream is LSB-first but a codeword reads MSB-first, so the bits + // go out one at a time from the top. + for depth in (0..length).rev() { + out.bit((code >> depth) & 1 != 0); + } + } +} + +/// Huffman code lengths for `weights`, capped at 24 bits. +/// +/// The cap is enforced by flattening: a weight small enough to earn a 25-bit +/// codeword is raised until it does not. With at most a few hundred entries and +/// weights within a few decades of each other the cap never binds, and when it +/// does the cost is a fraction of a bit on the rarest symbol. +fn huffman_lengths(weights: &[f64]) -> Vec { + let n = weights.len(); + assert!(n > 0, "a codebook needs at least one entry"); + if n == 1 { + return vec![1]; + } + let floor = weights.iter().cloned().fold(0.0f64, f64::max) / 8_388_608.0; + let mut nodes: Vec<(f64, usize)> = weights + .iter() + .enumerate() + .map(|(i, &w)| (w.max(floor).max(f64::MIN_POSITIVE), i)) + .collect(); + // Leaves first, then merged nodes, tracked as a forest over `parent`. + let mut parent = vec![usize::MAX; n]; + let mut heap: Vec<(f64, usize)> = nodes.clone(); + heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap()); + let mut merged: Vec<(f64, usize)> = Vec::new(); + let mut next_id = n; + while heap.len() + merged.len() > 1 { + let mut take = || -> (f64, usize) { + let from_heap = heap.last().map(|x| x.0); + let from_merged = merged.first().map(|x| x.0); + match (from_heap, from_merged) { + (Some(a), Some(b)) if a <= b => heap.pop().unwrap(), + (Some(_), None) => heap.pop().unwrap(), + _ => merged.remove(0), + } + }; + let (wa, a) = take(); + let (wb, b) = take(); + parent.push(usize::MAX); + parent[a] = next_id; + parent[b] = next_id; + merged.push((wa + wb, next_id)); + next_id += 1; + } + nodes.clear(); + + let mut lengths = vec![0u8; n]; + for (i, length) in lengths.iter_mut().enumerate() { + let mut node = i; + let mut depth = 0u32; + while parent[node] != usize::MAX { + node = parent[node]; + depth += 1; + } + *length = depth.clamp(1, 24) as u8; + } + // Clamping can leave the tree over-full; rebalance by lengthening the + // shallowest entries until Kraft's sum is back at one. + balance(&mut lengths); + lengths +} + +/// Push a length vector to exactly Kraft-complete, so the decoder's canonical +/// rebuild has no ambiguity and no hole. +fn balance(lengths: &mut [u8]) { + let kraft = |lengths: &[u8]| -> f64 { + lengths + .iter() + .map(|&l| 2f64.powi(-i32::from(l))) + .sum::() + }; + // Over-full: lengthen the shortest codes. + while kraft(lengths) > 1.0 + 1e-12 { + let (index, _) = lengths + .iter() + .enumerate() + .min_by_key(|(_, l)| **l) + .expect("non-empty"); + lengths[index] += 1; + } + // Under-full: shorten the longest, which only ever helps the rare symbols. + loop { + let sum = kraft(lengths); + let (index, &longest) = lengths + .iter() + .enumerate() + .max_by_key(|(_, l)| **l) + .expect("non-empty"); + if longest <= 1 || sum + 2f64.powi(-i32::from(longest)) > 1.0 + 1e-12 { + break; + } + lengths[index] -= 1; + } +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::bits::BitsOut; + + #[test] + fn lookup1_values_matches_the_definition() { + assert_eq!(lookup1_values(1, 1), 1); + assert_eq!(lookup1_values(64, 2), 8); + assert_eq!(lookup1_values(63, 2), 7); + assert_eq!(lookup1_values(1000, 3), 10); + } + + #[test] + fn a_designed_book_decodes_back_through_the_parsed_tree() { + // Skewed weights so the lengths differ, which is what exercises the + // canonical assignment on both sides. + let weights: Vec = (0..17).map(|i| 1.0 / (1.0 + f64::from(i))).collect(); + let spec = CodebookSpec::huffman(&weights, Vec::new()); + assert_eq!(spec.entries(), 17); + let kraft: f64 = spec.lengths.iter().map(|&l| 2f64.powi(-i32::from(l))).sum(); + assert!((kraft - 1.0).abs() < 1e-9, "kraft sum {kraft}"); + + let mut out = BitsOut::new(); + for entry in 0..spec.entries() { + spec.write(&mut out, entry); + } + let bytes = out.finish(); + + let (tree, _) = assign_codes(&spec.lengths).expect("tree"); + let book = Codebook { + dimensions: 1, + tree, + values: Vec::new(), + }; + let mut bits = Bits::new(&bytes); + for entry in 0..spec.entries() { + assert_eq!(book.decode_scalar(&mut bits), Some(entry as u32)); + } + } +} diff --git a/crates/ec-vorbis/src/decode.rs b/crates/ec-vorbis/src/decode.rs new file mode 100644 index 00000000..2860173c --- /dev/null +++ b/crates/ec-vorbis/src/decode.rs @@ -0,0 +1,464 @@ +//! The decoder: header packets in, audio packets in, planar float out. + +use std::collections::VecDeque; + +use ec_core::frame::ChannelPosition::{self, *}; +use ec_core::{ + AudioFrame, AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, Decoder, Error, + Frame, MediaParameters, Packet, Result, SampleFormat, TimeBase, Timestamp, +}; +use ec_dsp::Mdct; + +use crate::bits::Bits; +use crate::codebook::ilog; +use crate::floor::{self, FloorState}; +use crate::residue; +use crate::setup::{Comments, FloorConfig, Identification, Setup}; +use crate::window::Windows; + +/// Vorbis I decoder. +/// +/// Feed it the three header packets, then audio packets; every audio packet +/// answers the samples that became final when its window closed, which is why +/// the *first* audio packet of a stream answers none — its block only reaches +/// halfway into the first sample the stream states. +pub struct VorbisDecoder { + ident: Identification, + comments: Comments, + setup: Setup, + params: CodecParameters, + layout: ChannelLayout, + /// `to_ec[vorbis channel] = ec-core channel`. + to_ec: Vec, + windows: Windows, + mdct_short: Mdct, + mdct_long: Mdct, + /// Per channel, the overlap-add accumulator, in Vorbis channel order. + lap: Vec>, + /// Absolute sample position of `lap[..][0]`. + lap_start: i64, + /// Centre of the block decoded last, absolute; `None` before the first. + centre: Option, + /// Blocksize of the block decoded last. + previous_n: usize, + /// Samples handed out so far, for the frames' timestamps. + position: i64, + /// Timestamp the next frame carries, when the container stated one. + next_pts: Option, + frames: VecDeque, + drained: bool, +} + +impl VorbisDecoder { + /// Build a decoder from the three header packets, in order. + pub fn new(headers: &[&[u8]]) -> Result { + let [ident, comment, setup] = headers else { + return Err(Error::corrupt(format!( + "Vorbis needs 3 header packets, got {}", + headers.len() + ))); + }; + let ident = Identification::parse(ident)?; + let comments = Comments::parse(comment)?; + let setup = Setup::parse(setup, &ident)?; + let channels = usize::from(ident.channels); + let (layout, to_ec) = channel_map(channels); + let params = CodecParameters { + codec: CodecId::Vorbis, + media: MediaParameters::Audio(AudioParameters { + sample_rate: ident.rate, + layout: layout.clone(), + format: Some(SampleFormat::F32), + bits_per_sample: None, + }), + extradata: None, + }; + Ok(VorbisDecoder { + windows: Windows::new(ident.blocksize_0, ident.blocksize_1), + mdct_short: Mdct::new(ident.blocksize_0), + mdct_long: Mdct::new(ident.blocksize_1), + lap: vec![Vec::new(); channels], + lap_start: 0, + centre: None, + previous_n: ident.blocksize_1, + position: 0, + next_pts: None, + frames: VecDeque::new(), + drained: false, + ident, + comments, + setup, + params, + layout, + to_ec, + }) + } + + /// Build a decoder from Xiph-laced `extradata`, the form containers carry + /// the three headers in. + pub fn from_extradata(extradata: &[u8]) -> Result { + let packets = unlace(extradata)?; + let borrowed: Vec<&[u8]> = packets.iter().map(|p| &p[..]).collect(); + VorbisDecoder::new(&borrowed) + } + + /// The identification header's contents. + pub fn identification(&self) -> &Identification { + &self.ident + } + + /// The comment header's contents. + pub fn comments(&self) -> &Comments { + &self.comments + } + + /// Channel layout of the decoded frames. + pub fn layout(&self) -> &ChannelLayout { + &self.layout + } + + /// Decode one audio packet into per-channel samples in ec-core channel + /// order. The first packet of a stream answers empty vectors. + pub fn decode_audio(&mut self, data: &[u8]) -> Result>> { + let channels = usize::from(self.ident.channels); + let mut bits = Bits::new(data); + if bits.bit() { + return Err(Error::corrupt("audio packet flagged as a header")); + } + let mode_bits = ilog(self.setup.modes.len() as u32 - 1); + let mode_index = bits.read(mode_bits) as usize; + let Some(&mode) = self.setup.modes.get(mode_index) else { + return Err(Error::corrupt( + "audio packet names a mode that is not there", + )); + }; + let n = match mode.block_flag { + true => self.ident.blocksize_1, + false => self.ident.blocksize_0, + }; + let half = n / 2; + let (previous_long, next_long) = match mode.block_flag { + true => (bits.bit(), bits.bit()), + false => (true, true), + }; + if bits.eop() { + return Err(Error::corrupt("audio packet header truncated")); + } + + let mapping = &self.setup.mappings[mode.mapping]; + let mut floors = Vec::with_capacity(channels); + let mut no_residue = Vec::with_capacity(channels); + for &submap in mapping.mux.iter().take(channels) { + let state = match &self.setup.floors[mapping.submaps[submap].0] { + FloorConfig::Zero(config) => { + floor::decode_floor0(config, &self.setup.codebooks, &mut bits) + } + FloorConfig::One(config) => { + floor::decode_floor1(config, &self.setup.codebooks, &mut bits) + } + }; + no_residue.push(state.is_unused()); + floors.push(state); + } + // A coupled pair shares its residue, so one live channel keeps both. + for &(magnitude, angle) in &mapping.coupling { + if !no_residue[magnitude] || !no_residue[angle] { + no_residue[magnitude] = false; + no_residue[angle] = false; + } + } + + let mut spectra: Vec> = vec![vec![0.0; half]; channels]; + for (index, &(_, residue_index)) in mapping.submaps.iter().enumerate() { + let members: Vec = (0..channels).filter(|&c| mapping.mux[c] == index).collect(); + if members.is_empty() { + continue; + } + let config = &self.setup.residues[residue_index]; + let skip: Vec = members.iter().map(|&c| no_residue[c]).collect(); + let mut decoded: Vec> = vec![vec![0.0; half]; members.len()]; + if config.kind == 2 { + // Type 2 codes the whole submap as one interleaved vector, so + // it is decoded whole and split afterwards. + let mut interleaved = vec![vec![0.0f32; half * members.len()]]; + let all_skipped = [skip.iter().all(|&s| s)]; + residue::decode( + config, + &self.setup.codebooks, + &mut bits, + &mut interleaved, + &all_skipped, + ); + residue::deinterleave(&interleaved[0], members.len(), &mut decoded); + } else { + residue::decode( + config, + &self.setup.codebooks, + &mut bits, + &mut decoded, + &skip, + ); + } + for (slot, &channel) in members.iter().enumerate() { + spectra[channel] = std::mem::take(&mut decoded[slot]); + } + } + + // §9.4.2 inverse coupling, newest step first. + for &(magnitude, angle) in mapping.coupling.iter().rev() { + // Taken out and put back so the two vectors can be walked in step; + // a coupling step never names one channel twice. + let mut mags = std::mem::take(&mut spectra[magnitude]); + let mut angles = std::mem::take(&mut spectra[angle]); + for (m, a) in mags.iter_mut().zip(angles.iter_mut()) { + let (new_m, new_a) = match (*m > 0.0, *a > 0.0) { + (true, true) => (*m, *m - *a), + (true, false) => (*m + *a, *m), + (false, true) => (*m, *m + *a), + (false, false) => (*m - *a, *m), + }; + *m = new_m; + *a = new_a; + } + spectra[magnitude] = mags; + spectra[angle] = angles; + } + + // Floor times residue, then out of the frequency domain. + let window = self.windows.get(mode.block_flag, previous_long, next_long); + let mdct = match mode.block_flag { + true => &mut self.mdct_long, + false => &mut self.mdct_short, + }; + let mut curve = vec![0.0f32; half]; + let mut block = vec![0.0f32; n]; + let centre = match self.centre { + Some(previous) => previous + (self.previous_n + n) as i64 / 4, + None => { + self.lap_start = 0; + self.lap = vec![vec![0.0; n]; channels]; + n as i64 / 2 + } + }; + let start = centre - n as i64 / 2; + + for channel in 0..channels { + match &floors[channel] { + FloorState::Unused => spectra[channel].fill(0.0), + FloorState::One { y, step2 } => { + let submap = mapping.mux[channel]; + let FloorConfig::One(config) = &self.setup.floors[mapping.submaps[submap].0] + else { + return Err(Error::corrupt("floor type changed between packets")); + }; + floor::render_floor1(config, y, step2, &mut curve); + for (value, &gain) in spectra[channel].iter_mut().zip(curve.iter()) { + *value *= gain; + } + } + FloorState::Zero { + amplitude, + coefficients, + } => { + let submap = mapping.mux[channel]; + let FloorConfig::Zero(config) = &self.setup.floors[mapping.submaps[submap].0] + else { + return Err(Error::corrupt("floor type changed between packets")); + }; + floor::render_floor0(config, *amplitude, coefficients, &mut curve); + for (value, &gain) in spectra[channel].iter_mut().zip(curve.iter()) { + *value *= gain; + } + } + } + // Undo the codec-side normalisation ec-dsp's inverse applies: a + // Vorbis coefficient is already `2/N` of the raw transform, so the + // synthesis here is the plain sum. + for value in spectra[channel].iter_mut() { + *value *= (half / 2) as f32; + } + mdct.inverse_windowed(&spectra[channel], window, &mut block); + let lap = &mut self.lap[channel]; + let offset = (start - self.lap_start).max(0) as usize; + if lap.len() < offset + n { + lap.resize(offset + n, 0.0); + } + // A block starting before what has already been handed out only + // ever reaches back into its own zero run (§4.3.1 puts the slope + // inside the block when the neighbour is shorter), so the skipped + // samples are zeroes by construction. + let skipped = (self.lap_start - start).max(0) as usize; + for i in skipped..n { + lap[offset + i - skipped] += block[i]; + } + } + + let emit = (centre - self.lap_start).max(0) as usize; + let first = self.centre.is_none(); + let mut out = vec![Vec::new(); channels]; + for (channel, lap) in self.lap.iter_mut().enumerate() { + let take = emit.min(lap.len()); + let head: Vec = lap.drain(..take).collect(); + if !first { + out[self.to_ec[channel]] = head; + } + } + self.lap_start = centre; + self.centre = Some(centre); + self.previous_n = n; + Ok(out) + } + + /// Drop the lapping state after a seek; the next packet starts a new run. + pub fn reset_state(&mut self) { + self.centre = None; + self.lap_start = 0; + self.position = 0; + for lap in &mut self.lap { + lap.clear(); + } + self.frames.clear(); + self.drained = false; + } +} + +/// Vorbis channel order (§4.3.9) mapped onto [`ChannelLayout`]'s order. +/// +/// Vorbis orders a 5.1 stream FL, FC, FR, BL, BR, LFE and a 7.1 stream FL, FC, +/// FR, SL, SR, BL, BR, LFE; this family orders both FL, FR, FC, LFE, ... So the +/// two named surround layouts are permuted on the way out and everything else +/// passes through in the order the stream states, carrying the positions Vorbis +/// names for it. +pub fn channel_map(channels: usize) -> (ChannelLayout, Vec) { + let positions: &[ChannelPosition] = match channels { + 1 => &[FrontCenter], + 2 => &[FrontLeft, FrontRight], + 3 => &[FrontLeft, FrontCenter, FrontRight], + 4 => &[FrontLeft, FrontRight, BackLeft, BackRight], + 5 => &[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight], + 6 => &[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight, Lfe], + 7 => &[ + FrontLeft, + FrontCenter, + FrontRight, + SideLeft, + SideRight, + BackCenter, + Lfe, + ], + 8 => &[ + FrontLeft, + FrontCenter, + FrontRight, + SideLeft, + SideRight, + BackLeft, + BackRight, + Lfe, + ], + _ => &[], + }; + match channels { + 1 => (ChannelLayout::Mono, vec![0]), + 2 => (ChannelLayout::Stereo, vec![0, 1]), + 6 => (ChannelLayout::Surround5_1, vec![0, 2, 1, 4, 5, 3]), + 8 => (ChannelLayout::Surround7_1, vec![0, 2, 1, 6, 7, 4, 5, 3]), + n if n <= 8 => (ChannelLayout::Custom(positions.to_vec()), (0..n).collect()), + n => (ChannelLayout::from_count(n), (0..n).collect()), + } +} + +/// The Xiph lacing containers wrap the three headers in. +fn unlace(data: &[u8]) -> Result>> { + let count = *data + .first() + .ok_or_else(|| Error::corrupt("empty Vorbis extradata"))? as usize; + if count != 2 { + return Err(Error::corrupt("Vorbis extradata does not hold 3 packets")); + } + let mut lengths = Vec::with_capacity(2); + let mut pos = 1usize; + for _ in 0..count { + let mut length = 0usize; + loop { + let byte = *data + .get(pos) + .ok_or_else(|| Error::corrupt("Vorbis extradata lacing"))?; + pos += 1; + length += usize::from(byte); + if byte != 255 { + break; + } + } + lengths.push(length); + } + let mut packets = Vec::with_capacity(3); + for length in lengths { + let end = pos + .checked_add(length) + .filter(|end| *end <= data.len()) + .ok_or_else(|| Error::corrupt("Vorbis extradata is shorter than it states"))?; + packets.push(data[pos..end].to_vec()); + pos = end; + } + packets.push(data[pos..].to_vec()); + Ok(packets) +} + +impl Decoder for VorbisDecoder { + fn codec_parameters(&self) -> &CodecParameters { + &self.params + } + + fn send_packet(&mut self, packet: &Packet) -> Result<()> { + let samples = self.decode_audio(&packet.data)?; + if samples.iter().all(Vec::is_empty) { + // The first packet of a run: its block only reaches the first + // sample the stream states, so there is nothing final yet. + self.next_pts = packet.pts; + return Ok(()); + } + let count = samples[0].len(); + let data: Vec = samples + .into_iter() + .map(|channel| { + let mut bytes = Vec::with_capacity(channel.len() * 4); + for value in channel { + bytes.extend_from_slice(&value.to_le_bytes()); + } + Buf::from_vec(bytes) + }) + .collect(); + let mut frame = AudioFrame::try_new( + SampleFormat::F32, + true, + self.layout.clone(), + self.ident.rate, + count, + data, + )?; + let base = TimeBase::new(1, i64::from(self.ident.rate)); + frame.pts = Some(Timestamp::new(self.next_pts.unwrap_or(self.position), base)); + self.next_pts = None; + self.position += count as i64; + self.frames.push_back(Frame::Audio(frame)); + Ok(()) + } + + fn receive_frame(&mut self) -> Result { + match self.frames.pop_front() { + Some(frame) => Ok(frame), + None if self.drained => Err(Error::Eof), + None => Err(Error::NeedMore), + } + } + + fn flush(&mut self) -> Result<()> { + self.drained = true; + Ok(()) + } + + fn reset(&mut self) { + self.reset_state(); + } +} diff --git a/crates/ec-vorbis/src/encode.rs b/crates/ec-vorbis/src/encode.rs new file mode 100644 index 00000000..8d593417 --- /dev/null +++ b/crates/ec-vorbis/src/encode.rs @@ -0,0 +1,1026 @@ +//! The encoder: PCM in, Vorbis packets out, with a setup header written for the +//! stream's own channel layout. +//! +//! ## What the analysis actually is +//! +//! Per block, per channel: an MDCT, a peak magnitude per floor point, a +//! spreading function over those points (a one-pole decay up and down the +//! spectrum, which is the cheap stand-in for a masking curve), an absolute +//! threshold of hearing under it, and a headroom the rate loop moves. The floor +//! that comes out is the quantiser step: the residue is the spectrum divided by +//! the floor and rounded, so headroom in dB *is* precision in bits. That is +//! psychoacoustics-lite and it is stated as such — there is no tonality +//! estimate, no temporal pre-echo control and no per-band bit allocation beyond +//! what the floor implies. +//! +//! ## Codebooks +//! +//! Designed here rather than inherited: a floor book over the folded amplitude +//! range, a class book over partition-class pairs, and four residue books whose +//! ranges (+-1, +-4, +-16, +-127) the partition classifier picks between. All of +//! them are Huffman codes over stated distributions, built at construction and +//! written into every stream's own setup header — which is why this encoder +//! needs no embedded profile and has no channel count it cannot serve. + +use std::collections::VecDeque; + +use ec_core::{ + AudioParameters, Buf, CodecId, CodecParameters, Encoder, Error, Frame, MediaParameters, Packet, + Result, SampleFormat, TimeBase, +}; +use ec_dsp::Mdct; + +use crate::bits::{BitsOut, float32_pack}; +use crate::codebook::{CodebookSpec, ilog}; +use crate::decode::channel_map; +use crate::floor::render_floor1; +use crate::setup::Floor1; +use crate::window; + +/// Long block size; this encoder codes long blocks only. +const BLOCK: usize = 2048; +/// Samples between block centres. +const HOP: usize = BLOCK / 2; +/// Coefficients per block. +const HALF: usize = BLOCK / 2; +/// Coefficients per residue partition. +const PARTITION: usize = 32; +/// Floor X points besides the two endpoints. +const FLOOR_POINTS: usize = 20; +/// Floor values per class. +const FLOOR_CLASS_DIM: usize = 4; +/// Residue classes; class 0 codes nothing at all. +const CLASSES: usize = 5; +/// Vorbis states spectral coefficients on the scale where a full-scale tone is +/// a coefficient of about one, which is what lets the floor table (whose top is +/// exactly 1.0) carry them. That is `2/N` times the unnormalised transform +/// ec-dsp computes, `N` being the coefficient count. +const VORBIS_MDCT_SCALE: f32 = 2.0 / HALF as f32; +/// Largest quantised residue each class's book can state. +const CLASS_RANGE: [i32; CLASSES] = [0, 1, 4, 16, 127]; + +/// How the encoder is set up. +#[derive(Debug, Clone, Copy, PartialEq)] +pub struct EncoderConfig { + /// Sample rate in Hz. + pub sample_rate: u32, + /// Channel count, in [`ec_core::ChannelLayout`] order. + pub channels: u16, + /// Target bitrate. Zero or less runs in pure quality mode. + pub bitrate_bps: i32, + /// Quality on `[0, 1]`: where the rate loop starts, and the fixed setting + /// when `bitrate_bps` is not positive. + pub quality: f32, +} + +impl Default for EncoderConfig { + fn default() -> EncoderConfig { + EncoderConfig { + sample_rate: 48_000, + channels: 2, + bitrate_bps: 128_000, + quality: 0.5, + } + } +} + +/// One encoded packet and where it ends. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct EncodedPacket { + /// Packet payload. + pub data: Vec, + /// Sample position this packet ends at — the Ogg granule. + pub granule: i64, + /// Samples this packet finalises. + pub samples: i64, +} + +/// Vorbis I encoder. +pub struct VorbisEncoder { + config: EncoderConfig, + params: CodecParameters, + /// `to_vorbis[ec channel] = vorbis channel`. + to_vorbis: Vec, + headers: Vec>, + floor: Floor1, + floor_book: CodebookSpec, + class_book: CodebookSpec, + residue_books: Vec, + /// Absolute threshold of hearing per floor point, in dBFS. + ath: Vec, + /// Channel pairs coupled by the mapping; empty unless stereo. + coupling: Vec<(usize, usize)>, + mdct: Mdct, + window: Vec, + /// Per Vorbis channel, input samples with the first block's left half of + /// zeroes already in front. + buffer: Vec>, + /// Input samples taken from the caller. + fed: i64, + /// Blocks already emitted. + blocks: i64, + /// Granule of the packet emitted last. + granule: i64, + /// Headroom under the masking curve, in dB — the rate loop's variable. + headroom: f64, + finished: bool, + packets: VecDeque, +} + +impl VorbisEncoder { + /// Build an encoder and write its three header packets. + pub fn new(config: EncoderConfig) -> Result { + let channels = usize::from(config.channels); + if channels == 0 || channels > 255 { + return Err(Error::unsupported( + format!("{channels} channels"), + "Vorbis states a channel count in one byte", + )); + } + if config.sample_rate == 0 { + return Err(Error::corrupt("encoder sample rate of zero")); + } + let (layout, to_ec) = channel_map(channels); + let mut to_vorbis = vec![0usize; channels]; + for (vorbis, &ec) in to_ec.iter().enumerate() { + to_vorbis[ec] = vorbis; + } + // Coupling pays for a stereo pair and nothing else here: the surround + // layouts have no two channels that carry the same programme. + let coupling = match channels { + 2 => vec![(0usize, 1usize)], + _ => Vec::new(), + }; + + let floor = build_floor(); + let floor_book = design_floor_book(); + let class_book = design_class_book(); + let residue_books = design_residue_books(); + let ath = floor + .x_list + .iter() + .map(|&x| { + let hz = f64::from(config.sample_rate) * 0.5 * f64::from(x) / HALF as f64; + absolute_threshold(hz) + }) + .collect(); + + let headers = write_headers( + &config, + channels, + &floor, + &floor_book, + &class_book, + &residue_books, + &coupling, + ); + let params = CodecParameters { + codec: CodecId::Vorbis, + media: MediaParameters::Audio(AudioParameters { + sample_rate: config.sample_rate, + layout, + format: Some(SampleFormat::F32), + bits_per_sample: None, + }), + extradata: Some(Buf::from_vec(lace(&headers))), + }; + + let quality = f64::from(config.quality.clamp(0.0, 1.0)); + Ok(VorbisEncoder { + mdct: Mdct::new(BLOCK), + window: window::build(BLOCK, BLOCK, true, true), + // The first block is centred on input sample 0, so its left half is + // the only pre-roll there is and the caller never sees it. + buffer: vec![vec![0.0; HOP]; channels], + fed: 0, + blocks: 0, + granule: 0, + headroom: 4.0 + 26.0 * quality, + finished: false, + packets: VecDeque::new(), + config, + params, + to_vorbis, + headers, + floor, + floor_book, + class_book, + residue_books, + ath, + coupling, + }) + } + + /// The three header packets, in order. + pub fn headers(&self) -> Vec<&[u8]> { + self.headers.iter().map(|h| &h[..]).collect() + } + + /// The three header packets Xiph-laced, the form containers carry. + pub fn extradata(&self) -> Vec { + lace(&self.headers) + } + + /// Parameters describing the stream, `extradata` included. + pub fn parameters(&self) -> &CodecParameters { + &self.params + } + + /// Push planar samples, one slice per channel in [`ec_core::ChannelLayout`] order. + pub fn push_planar(&mut self, channels: &[&[f32]]) -> Result<()> { + if channels.len() != usize::from(self.config.channels) { + return Err(Error::corrupt(format!( + "{} channels pushed into a {}-channel encoder", + channels.len(), + self.config.channels + ))); + } + if self.finished { + return Err(Error::corrupt("samples pushed after finish")); + } + let samples = channels.first().map_or(0, |c| c.len()); + for (ec, data) in channels.iter().enumerate() { + if data.len() != samples { + return Err(Error::corrupt("channels of different lengths")); + } + self.buffer[self.to_vorbis[ec]].extend_from_slice(data); + } + self.fed += samples as i64; + self.encode_ready(); + Ok(()) + } + + /// Push interleaved samples in [`ec_core::ChannelLayout`] order. + pub fn push_interleaved(&mut self, samples: &[f32]) -> Result<()> { + let channels = usize::from(self.config.channels); + if !samples.len().is_multiple_of(channels) { + return Err(Error::corrupt("interleaved push is not a whole frame")); + } + if self.finished { + return Err(Error::corrupt("samples pushed after finish")); + } + for (i, &value) in samples.iter().enumerate() { + self.buffer[self.to_vorbis[i % channels]].push(value); + } + self.fed += (samples.len() / channels) as i64; + self.encode_ready(); + Ok(()) + } + + /// No more input; pad the grid out and encode the tail. + pub fn finish(&mut self) { + if self.finished { + return; + } + self.finished = true; + // Enough blocks for every input sample to sit left of a block centre, + // and enough padding for that last block to be whole. + let last = ((self.fed + HOP as i64 - 1) / HOP as i64).max(1) as usize; + let needed = last * HOP + BLOCK; + for channel in &mut self.buffer { + if channel.len() < needed { + channel.resize(needed, 0.0); + } + } + self.encode_ready(); + } + + /// Take the next packet, or [`Error::Eof`] once the encoder is drained. + pub fn next_packet(&mut self) -> Result { + match self.packets.pop_front() { + Some(packet) => Ok(packet), + None if self.finished => Err(Error::Eof), + None => Err(Error::NeedMore), + } + } + + /// Encode every block the buffer now holds whole. + /// + /// Block `k` is centred on input sample `k * HOP`, and that centre is the + /// granule: the decoder's output reaches exactly there when the block's + /// window closes. The last block's granule is the input's own sample count + /// instead, which is what trims the grid's overshoot off the file. + fn encode_ready(&mut self) { + let channels = usize::from(self.config.channels); + loop { + if self.finished && self.blocks > 0 && self.granule >= self.fed { + break; + } + let start = self.blocks as usize * HOP; + if self.buffer[0].len() < start + BLOCK { + break; + } + let centre = self.blocks * HOP as i64; + let granule = match self.finished { + true => centre.min(self.fed), + false => centre, + }; + let data = self.encode_block(start, channels); + self.packets.push_back(EncodedPacket { + data, + granule, + samples: (granule - self.granule).max(0), + }); + self.granule = granule; + self.blocks += 1; + } + } + + /// One block: analyse, quantise, write. + fn encode_block(&mut self, start: usize, channels: usize) -> Vec { + let mut spectra: Vec> = Vec::with_capacity(channels); + let mut block = vec![0.0f32; BLOCK]; + for channel in 0..channels { + block.copy_from_slice(&self.buffer[channel][start..start + BLOCK]); + let mut coefficients = vec![0.0f32; HALF]; + self.mdct + .forward_windowed(&block, &self.window, &mut coefficients); + for value in coefficients.iter_mut() { + *value *= VORBIS_MDCT_SCALE; + } + spectra.push(coefficients); + } + + // Floor per channel — one shared floor per coupled pair, so the two + // normalised spectra are on the same scale and the angle channel is + // small where the pair agrees. + let mut curves: Vec> = vec![Vec::new(); channels]; + let mut floor_values: Vec> = vec![Vec::new(); channels]; + let mut coded = vec![false; channels]; + for &(magnitude, angle) in &self.coupling { + let peaks = self.peaks_of(&[&spectra[magnitude], &spectra[angle]]); + let (y, step2) = self.fit_floor(&peaks); + let mut curve = vec![0.0f32; HALF]; + render_floor1(&self.floor, &y, &step2, &mut curve); + curves[magnitude] = curve.clone(); + curves[angle] = curve; + floor_values[magnitude] = y.clone(); + floor_values[angle] = y; + coded[magnitude] = true; + coded[angle] = true; + } + for channel in 0..channels { + if coded[channel] { + continue; + } + let peaks = self.peaks_of(&[&spectra[channel]]); + let (y, step2) = self.fit_floor(&peaks); + let mut curve = vec![0.0f32; HALF]; + render_floor1(&self.floor, &y, &step2, &mut curve); + curves[channel] = curve; + floor_values[channel] = y; + } + + // Normalise, couple, quantise. + let mut quantised: Vec> = (0..channels) + .map(|channel| { + spectra[channel] + .iter() + .zip(curves[channel].iter()) + .map(|(&value, &floor)| match floor > 0.0 { + true => value / floor, + false => 0.0, + }) + .map(|normalised| normalised.round() as i32) + .collect::>() + }) + .collect(); + for &(magnitude, angle) in &self.coupling { + // Taken out and put back so the pair can be walked in step; a + // coupling step never names one channel twice. + let mut left = std::mem::take(&mut quantised[magnitude]); + let mut right = std::mem::take(&mut quantised[angle]); + for (l, r) in left.iter_mut().zip(right.iter_mut()) { + let (m, a) = couple(*l, *r); + *l = m; + *r = a; + } + quantised[magnitude] = left; + quantised[angle] = right; + } + let limit = CLASS_RANGE[CLASSES - 1]; + for channel in quantised.iter_mut() { + for value in channel.iter_mut() { + *value = (*value).clamp(-limit, limit); + } + } + + let mut out = BitsOut::new(); + out.write(0, 1); + // One mode means `ilog(modes - 1)` is zero bits: there is nothing to + // state. The two window flags follow because the mode is a long block. + out.bit(true); + out.bit(true); + for values in floor_values.iter().take(channels) { + self.write_floor(&mut out, values); + } + self.write_residue(&mut out, &quantised); + let bits = out.len(); + self.update_rate(bits, channels); + out.finish() + } + + /// Peak magnitude around each floor X point, over every channel given. + /// + /// Each point owns the coefficients halfway to its neighbours either side, + /// so the whole spectrum is covered exactly once and a peak between two + /// points still raises the floor that has to carry it. + fn peaks_of(&self, spectra: &[&Vec]) -> Vec { + let x = &self.floor.x_list; + x.iter() + .map(|¢re| { + let below = x.iter().filter(|&&o| o < centre).max().copied(); + let above = x.iter().filter(|&&o| o > centre).min().copied(); + let lo = below.map_or(0, |b| ((b + centre) / 2) as usize); + let hi = above.map_or(HALF, |a| ((a + centre) / 2) as usize + 1); + let lo = lo.min(HALF - 1); + let hi = hi.clamp(lo + 1, HALF); + let mut peak = 0.0f64; + for spectrum in spectra { + for &value in &spectrum[lo..hi] { + peak = peak.max(f64::from(value.abs())); + } + } + peak + }) + .collect() + } + + /// Turn peak magnitudes into coded floor amplitudes. + /// + /// Spread first (a masker covers its neighbours), then subtract the rate + /// loop's headroom, then hold the absolute threshold of hearing as a lower + /// bound: below it the residue quantises to zero and costs a class-0 + /// partition. + fn fit_floor(&self, peaks: &[f64]) -> (Vec, Vec) { + let mut db: Vec = peaks + .iter() + .map(|&peak| 20.0 * (peak.max(1e-9)).log10()) + .collect(); + // Frequency order, not coding order: spreading is a fact about the ear. + let order = &self.floor.sorted; + for window in order.windows(2) { + let (previous, current) = (window[0], window[1]); + db[current] = db[current].max(db[previous] - 12.0); + } + for window in order.windows(2).rev() { + let (current, next) = (window[0], window[1]); + db[current] = db[current].max(db[next] - 24.0); + } + let target: Vec = db + .iter() + .zip(self.ath.iter()) + .map(|(&level, &threshold)| (level - self.headroom).max(threshold)) + .collect(); + let y: Vec = target + .iter() + .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255)) + .collect(); + self.fold_floor(&y) + } + + /// Run the decoder's own amplitude synthesis forwards, so the curve the + /// encoder normalises against is the curve the decoder will draw. + fn fold_floor(&self, wanted: &[i32]) -> (Vec, Vec) { + let values = wanted.len(); + let range = 256i32; + let mut final_y = vec![0i32; values]; + let mut step2 = vec![false; values]; + final_y[0] = wanted[0]; + final_y[1] = wanted[1]; + step2[0] = true; + step2[1] = true; + for i in 2..values { + let (low, high) = self.floor.neighbours[i]; + let predicted = predict( + self.floor.x_list[low], + final_y[low], + self.floor.x_list[high], + final_y[high], + self.floor.x_list[i], + ); + let value = fold(predicted, wanted[i], range); + if value != 0 { + step2[low] = true; + step2[high] = true; + step2[i] = true; + } + final_y[i] = wanted[i]; + } + (final_y, step2) + } + + /// Write one channel's floor: the two endpoints raw, the rest folded + /// against their neighbours and Huffman coded. + fn write_floor(&self, out: &mut BitsOut, y: &[i32]) { + out.bit(true); + out.write(y[0] as u32, 8); + out.write(y[1] as u32, 8); + for i in 2..y.len() { + let (low, high) = self.floor.neighbours[i]; + let predicted = predict( + self.floor.x_list[low], + y[low], + self.floor.x_list[high], + y[high], + self.floor.x_list[i], + ); + let value = fold(predicted, y[i], 256); + self.floor_book.write(out, value as usize); + } + } + + /// Write the residue: one type-2 interleaved vector over every channel, + /// classified per partition and coded in one pass. + fn write_residue(&self, out: &mut BitsOut, quantised: &[Vec]) { + let channels = quantised.len(); + let total = HALF * channels; + let mut interleaved = vec![0i32; total]; + for (i, slot) in interleaved.iter_mut().enumerate() { + *slot = quantised[i % channels][i / channels]; + } + let partitions = total / PARTITION; + let classes: Vec = (0..partitions) + .map(|partition| { + let slice = &interleaved[partition * PARTITION..(partition + 1) * PARTITION]; + let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0); + CLASS_RANGE + .iter() + .position(|&range| peak <= range) + .unwrap_or(CLASSES - 1) + }) + .collect(); + let per_word = self.class_book.dimensions; + let mut partition = 0usize; + while partition < partitions { + let mut word = 0usize; + for i in 0..per_word { + word = word * CLASSES + classes.get(partition + i).copied().unwrap_or(0); + } + self.class_book.write(out, word); + for _ in 0..per_word { + if partition >= partitions { + break; + } + let class = classes[partition]; + if class > 0 { + let book = &self.residue_books[class - 1]; + let range = CLASS_RANGE[class]; + for &value in &interleaved[partition * PARTITION..(partition + 1) * PARTITION] { + book.write(out, (value.clamp(-range, range) + range) as usize); + } + } + partition += 1; + } + } + } + + /// Move the headroom so the running bitrate meets the target. + /// + /// One dB of headroom is about one sixth of a bit per coefficient, so the + /// step is the bit error divided by that — a proportional loop that settles + /// within a few blocks and is clamped either side so a transient cannot + /// swing the whole file. + fn update_rate(&mut self, bits: u64, channels: usize) { + if self.config.bitrate_bps <= 0 { + return; + } + let target = + f64::from(self.config.bitrate_bps) * HOP as f64 / f64::from(self.config.sample_rate); + let coefficients = (HALF * channels) as f64; + let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0); + // Negative headroom is not a mistake: it puts the floor *above* the + // signal, which quantises the coefficients under it to zero and lets a + // whole partition become class 0 for two bits. Without that a low target + // cannot be reached at all — coding every coefficient with the shortest + // codeword there is already costs about a bit each. + self.headroom = (self.headroom + step).clamp(-24.0, 36.0); + } +} + +/// Forward square-polar coupling (§9.4.2 run backwards). +fn couple(left: i32, right: i32) -> (i32, i32) { + match left > 0 { + true => match left > right { + true => (left, left - right), + false => (right, left - right), + }, + false => match right > left { + true => (left, right - left), + false => (right, right - left), + }, + } +} + +/// §7.2.2 `render_point`, which both sides of the floor coding need. +fn predict(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 { + let dy = y1 - y0; + let adx = (x1 - x0) as i32; + let ady = dy.abs(); + let off = (ady * (x - x0) as i32) / adx; + match dy < 0 { + true => y0 - off, + false => y0 + off, + } +} + +/// The exact inverse of §7.2.3's amplitude synthesis: the value to code so the +/// decoder lands on `wanted`. +fn fold(predicted: i32, wanted: i32, range: i32) -> i32 { + let high_room = range - predicted; + let low_room = predicted; + let room = high_room.min(low_room) * 2; + let delta = wanted - predicted; + if delta == 0 { + return 0; + } + if delta > 0 && 2 * delta < room { + return 2 * delta; + } + if delta < 0 && -2 * delta - 1 < room { + return -2 * delta - 1; + } + match high_room > low_room { + true => wanted - predicted + low_room, + false => predicted - wanted + high_room - 1, + } +} + +/// The floor-1 configuration this encoder writes and renders against. +fn build_floor() -> Floor1 { + let mut sorted_x: Vec = Vec::with_capacity(FLOOR_POINTS); + let mut last = 0u32; + for i in 0..FLOOR_POINTS { + let t = i as f64 / (FLOOR_POINTS - 1) as f64; + // Log spacing over the band, nudged to stay strictly increasing at the + // bottom where the grid is finer than one coefficient. + let value = (1023f64).powf(t).round() as u32; + last = value.max(last + 1); + sorted_x.push(last); + } + // Coding order: endpoints first, then repeated bisection, so every value is + // predicted from the two coded values that bracket it most closely. + let mut x_list = vec![0u32, HALF as u32]; + let mut ranges = vec![(0usize, sorted_x.len())]; + while let Some((lo, hi)) = ranges.pop() { + if lo >= hi { + continue; + } + let mid = (lo + hi) / 2; + x_list.push(sorted_x[mid]); + ranges.insert(0, (lo, mid)); + ranges.insert(0, (mid + 1, hi)); + } + let values = x_list.len(); + let mut sorted: Vec = (0..values).collect(); + sorted.sort_by_key(|&i| x_list[i]); + let neighbours = (0..values) + .map(|i| { + let mut low = 0usize; + let mut high = 0usize; + let mut low_x = None; + let mut high_x = None; + for j in 0..i { + if x_list[j] < x_list[i] && low_x.is_none_or(|b| x_list[j] > b) { + low = j; + low_x = Some(x_list[j]); + } + if x_list[j] > x_list[i] && high_x.is_none_or(|b| x_list[j] < b) { + high = j; + high_x = Some(x_list[j]); + } + } + (low, high) + }) + .collect(); + let partitions = (values - 2) / FLOOR_CLASS_DIM; + Floor1 { + partition_classes: vec![0; partitions], + class_dimensions: vec![FLOOR_CLASS_DIM], + class_subclasses: vec![0], + class_masterbooks: vec![0], + subclass_books: vec![vec![0]], + multiplier: 1, + x_list, + sorted, + neighbours, + } +} + +/// Folded floor amplitudes: mostly small corrections, occasionally an escape +/// near the top of the range. +fn design_floor_book() -> CodebookSpec { + let weights: Vec = (0..256) + .map(|v| (-(f64::from(v)) / 7.0).exp() + 0.002) + .collect(); + CodebookSpec::huffman(&weights, Vec::new()) +} + +/// Class pairs, on the assumption that most partitions are silent. +fn design_class_book() -> CodebookSpec { + let per_class = [0.55f64, 0.20, 0.15, 0.08, 0.02]; + let mut weights = Vec::with_capacity(CLASSES * CLASSES); + for first in per_class { + for second in per_class { + weights.push(first * second); + } + } + let mut spec = CodebookSpec::huffman(&weights, Vec::new()); + spec.dimensions = 2; + spec +} + +/// One book per non-silent class, Laplacian over its own range. +fn design_residue_books() -> Vec { + CLASS_RANGE[1..] + .iter() + .map(|&range| { + let sigma = f64::from(range).max(1.0) / 2.5; + let weights: Vec = (-range..=range) + .map(|v| (-f64::from(v.abs()) / sigma).exp() + 1e-4) + .collect(); + let values: Vec = (-range..=range).map(|v| v as f32).collect(); + CodebookSpec::huffman(&weights, values) + }) + .collect() +} + +/// Absolute threshold of hearing in dBFS, full scale taken as 96 dB SPL. +fn absolute_threshold(hz: f64) -> f64 { + let khz = (hz / 1000.0).clamp(0.02, 20.0); + let spl = + 3.64 * khz.powf(-0.8) - 6.5 * (-0.6 * (khz - 3.3).powi(2)).exp() + 0.001 * khz.powi(4); + (spl - 96.0).clamp(-120.0, -10.0) +} + +/// The three header packets, in order. +fn write_headers( + config: &EncoderConfig, + channels: usize, + floor: &Floor1, + floor_book: &CodebookSpec, + class_book: &CodebookSpec, + residue_books: &[CodebookSpec], + coupling: &[(usize, usize)], +) -> Vec> { + let mut ident = vec![1u8]; + ident.extend_from_slice(b"vorbis"); + ident.extend_from_slice(&0u32.to_le_bytes()); + ident.push(channels as u8); + ident.extend_from_slice(&config.sample_rate.to_le_bytes()); + ident.extend_from_slice(&0i32.to_le_bytes()); + ident.extend_from_slice(&config.bitrate_bps.max(0).to_le_bytes()); + ident.extend_from_slice(&0i32.to_le_bytes()); + let log2 = |n: usize| n.trailing_zeros() as u8; + ident.push(log2(BLOCK) | (log2(BLOCK) << 4)); + ident.push(1); + + let mut comment = vec![3u8]; + comment.extend_from_slice(b"vorbis"); + let vendor = b"ec-vorbis"; + comment.extend_from_slice(&(vendor.len() as u32).to_le_bytes()); + comment.extend_from_slice(vendor); + comment.extend_from_slice(&0u32.to_le_bytes()); + comment.push(1); + + let mut out = BitsOut::new(); + for byte in [5u8].iter().chain(b"vorbis") { + out.write(u32::from(*byte), 8); + } + let books: Vec<&CodebookSpec> = std::iter::once(floor_book) + .chain(std::iter::once(class_book)) + .chain(residue_books.iter()) + .collect(); + out.write(books.len() as u32 - 1, 8); + for book in &books { + write_codebook(&mut out, book); + } + // One time-domain transform, stated as zero. + out.write(0, 6); + out.write(0, 16); + // One floor, type 1. + out.write(0, 6); + out.write(1, 16); + out.write(floor.partition_classes.len() as u32, 5); + for _ in &floor.partition_classes { + out.write(0, 4); + } + out.write(FLOOR_CLASS_DIM as u32 - 1, 3); + out.write(0, 2); + // Book number plus one; zero would mean "this subclass codes nothing". + out.write(1, 8); + out.write(0, 2); + let range_bits = ilog(HALF as u32) - 1; + out.write(range_bits, 4); + for &x in floor.x_list.iter().skip(2) { + out.write(x, range_bits); + } + // One residue, type 2, over every channel of the one submap. + out.write(0, 6); + out.write(2, 16); + out.write(0, 24); + out.write((HALF * channels) as u32, 24); + out.write(PARTITION as u32 - 1, 24); + out.write(CLASSES as u32 - 1, 6); + out.write(1, 8); + for class in 0..CLASSES { + // Class 0 codes nothing at all; the rest have one book in pass 0. + out.write(u32::from(class > 0), 3); + out.write(0, 1); + } + for class in 1..CLASSES { + out.write(class as u32 + 1, 8); + } + // One mapping, type 0. + out.write(0, 6); + out.write(0, 16); + out.write(0, 1); + match coupling.is_empty() { + true => out.write(0, 1), + false => { + out.write(1, 1); + out.write(coupling.len() as u32 - 1, 8); + let field = ilog(channels as u32 - 1); + for &(magnitude, angle) in coupling { + out.write(magnitude as u32, field); + out.write(angle as u32, field); + } + } + } + out.write(0, 2); + out.write(0, 8); + out.write(0, 8); + out.write(0, 8); + // One mode: a long block on mapping 0. + out.write(0, 6); + out.write(1, 1); + out.write(0, 16); + out.write(0, 16); + out.write(0, 8); + out.write(1, 1); + let setup = out.finish(); + + vec![ident, comment, setup] +} + +/// One codebook in setup-header form: flat lengths, and a scalar lookup when +/// the book carries values. +fn write_codebook(out: &mut BitsOut, book: &CodebookSpec) { + out.write(0x0056_4342, 24); + out.write(book.dimensions as u32, 16); + out.write(book.entries() as u32, 24); + out.write(0, 1); + out.write(0, 1); + for &length in &book.lengths { + out.write(u32::from(length) - 1, 5); + } + if book.values.is_empty() { + out.write(0, 4); + return; + } + // Lookup type 1 with one dimension: the entry number *is* the index, so + // `minimum + i * delta` states every value in `ilog(entries)` bits each. + out.write(1, 4); + let minimum = book.values[0]; + out.write(float32_pack(minimum), 32); + out.write(float32_pack(1.0), 32); + let value_bits = ilog(book.entries() as u32 - 1).max(1); + out.write(value_bits - 1, 4); + out.write(0, 1); + for i in 0..book.entries() { + out.write(i as u32, value_bits); + } +} + +/// Xiph lacing of the three headers, the form containers carry them in. +fn lace(headers: &[Vec]) -> Vec { + let mut out = vec![2u8]; + for header in headers.iter().take(headers.len() - 1) { + let mut length = header.len(); + while length >= 255 { + out.push(255); + length -= 255; + } + out.push(length as u8); + } + for header in headers { + out.extend_from_slice(header); + } + out +} + +impl Encoder for VorbisEncoder { + fn codec_parameters(&self) -> &CodecParameters { + &self.params + } + + fn send_frame(&mut self, frame: &Frame) -> Result<()> { + let Frame::Audio(audio) = frame else { + return Err(Error::corrupt("video frame pushed into an audio encoder")); + }; + if audio.format != SampleFormat::F32 { + return Err(Error::unsupported( + format!("{:?} input", audio.format), + "this encoder takes 32-bit float samples", + )); + } + let channels = usize::from(self.config.channels); + let mut planes: Vec> = vec![Vec::with_capacity(audio.samples); channels]; + match audio.planar { + true => { + for (channel, plane) in audio.data.iter().enumerate().take(channels) { + planes[channel] = floats(plane, audio.samples); + } + } + false => { + let interleaved = floats(&audio.data[0], audio.samples * channels); + for (i, value) in interleaved.into_iter().enumerate() { + planes[i % channels].push(value); + } + } + } + let borrowed: Vec<&[f32]> = planes.iter().map(|p| &p[..]).collect(); + self.push_planar(&borrowed) + } + + fn receive_packet(&mut self) -> Result { + let encoded = self.next_packet()?; + let base = TimeBase::new(1, i64::from(self.config.sample_rate)); + let mut packet = Packet::new(0, base, encoded.data); + packet.pts = Some(encoded.granule - encoded.samples); + packet.duration = Some(encoded.samples); + Ok(packet) + } + + fn flush(&mut self) -> Result<()> { + self.finish(); + Ok(()) + } +} + +/// Little-endian floats out of a plane. +fn floats(plane: &Buf, count: usize) -> Vec { + plane + .chunks_exact(4) + .take(count) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn folding_is_the_exact_inverse_of_the_decoder() { + // Every predicted/wanted pair in the range must survive the fold, or + // the encoder and the decoder disagree about the floor. + for predicted in [0i32, 1, 40, 128, 200, 255] { + for wanted in 0..256i32 { + let value = fold(predicted, wanted, 256); + assert!((0..256).contains(&value), "{predicted}->{wanted}: {value}"); + assert_eq!( + unfold(predicted, value, 256), + wanted, + "predicted {predicted}, wanted {wanted}, coded {value}" + ); + } + } + } + + /// §7.2.3 as the decoder runs it, for the test above to check against. + fn unfold(predicted: i32, value: i32, range: i32) -> i32 { + let high_room = range - predicted; + let low_room = predicted; + let room = high_room.min(low_room) * 2; + if value == 0 { + return predicted; + } + match value >= room { + true => match high_room > low_room { + true => value - low_room + predicted, + false => predicted - value + high_room - 1, + }, + false => match value & 1 == 1 { + true => predicted - (value + 1) / 2, + false => predicted + value / 2, + }, + } + } + + #[test] + fn coupling_round_trips_every_sign_case() { + for left in -8..=8i32 { + for right in -8..=8i32 { + let (m, a) = couple(left, right); + let (back_l, back_r) = match (m > 0, a > 0) { + (true, true) => (m, m - a), + (true, false) => (m + a, m), + (false, true) => (m, m + a), + (false, false) => (m - a, m), + }; + assert_eq!((back_l, back_r), (left, right), "{left},{right}"); + } + } + } +} diff --git a/crates/ec-vorbis/src/floor.rs b/crates/ec-vorbis/src/floor.rs new file mode 100644 index 00000000..8388bda0 --- /dev/null +++ b/crates/ec-vorbis/src/floor.rs @@ -0,0 +1,334 @@ +//! Floor decode and curve synthesis — the spectral envelope a residue rides on. +//! +//! Two floor types share nothing but their job. Floor 1 (§7.2) is a +//! piecewise-linear curve in a 0.54 dB quantised log domain, drawn with +//! integer Bresenham arithmetic so every decoder draws the same line. Floor 0 +//! (§6.2) is an LSP filter response evaluated on a Bark-spaced map — only old +//! encoders emit it, and the Xiph `lsp-test` vectors are exactly those. + +use std::sync::LazyLock; + +use crate::bits::Bits; +use crate::codebook::{Codebook, ilog}; +use crate::setup::{Floor0, Floor1}; + +/// §7.2.4's amplitude table, 256 entries of `10^((y - 255) * 140/256 / 20)`. +/// +/// The spec prints the values; this states the law behind them, which is the +/// same table to within a float ulp (its first entry, `1.0649863e-07`, is +/// `10^(-255 * 0.02734375)` exactly). Generated rather than pasted so the +/// relationship to the 140 dB the floor spans stays visible. +static INVERSE_DB: LazyLock<[f32; 256]> = LazyLock::new(|| { + let mut table = [0.0f32; 256]; + for (y, slot) in table.iter_mut().enumerate() { + *slot = 10f64.powf((y as f64 - 255.0) * (140.0 / 256.0) / 20.0) as f32; + } + table +}); + +/// What a floor packet said, kept until the residue is in and the curve is +/// multiplied through. +pub enum FloorState { + /// The channel codes no audio in this packet. + Unused, + /// Floor 1 amplitudes, in coding order, with their step-2 flags. + One { + /// Final Y value per coding-order index. + y: Vec, + /// Whether the value was coded rather than predicted. + step2: Vec, + }, + /// Floor 0 amplitude and LSP coefficients. + Zero { + /// Coded amplitude. + amplitude: u32, + /// LSP coefficients. + coefficients: Vec, + }, +} + +impl FloorState { + /// True when the channel has no spectrum this packet. + pub fn is_unused(&self) -> bool { + matches!(self, FloorState::Unused) + } +} + +/// Decode a floor-1 packet header (§7.2.2 and §7.2.3), amplitudes only. +pub fn decode_floor1(floor: &Floor1, codebooks: &[Codebook], bits: &mut Bits) -> FloorState { + if !bits.bit() || bits.eop() { + return FloorState::Unused; + } + let range = [256i32, 128, 86, 64][(floor.multiplier - 1) as usize]; + let values = floor.x_list.len(); + let mut y = vec![0i32; values]; + let field = ilog((range - 1) as u32); + y[0] = bits.read(field) as i32; + y[1] = bits.read(field) as i32; + + let mut offset = 2usize; + for &class in &floor.partition_classes { + let dimensions = floor.class_dimensions[class]; + let subclass_bits = floor.class_subclasses[class]; + let mask = (1u32 << subclass_bits) - 1; + let mut class_value = 0u32; + if subclass_bits > 0 { + let book = &codebooks[floor.class_masterbooks[class]]; + match book.decode_scalar(bits) { + Some(value) => class_value = value, + None => return FloorState::Unused, + } + } + for _ in 0..dimensions { + let book = floor.subclass_books[class][(class_value & mask) as usize]; + class_value >>= subclass_bits; + if offset >= values { + break; + } + y[offset] = match book { + book if book >= 0 => match codebooks[book as usize].decode_scalar(bits) { + Some(value) => value as i32, + None => return FloorState::Unused, + }, + _ => 0, + }; + offset += 1; + } + } + if bits.eop() { + return FloorState::Unused; + } + + // §7.2.3 amplitude synthesis: every value past the first two is a + // correction to the line its two already-coded neighbours predict, folded + // into the room that line leaves above and below. + let mut final_y = y.clone(); + let mut step2 = vec![false; values]; + step2[0] = true; + step2[1] = true; + for i in 2..values { + let (low, high) = floor.neighbours[i]; + let predicted = render_point( + floor.x_list[low], + final_y[low], + floor.x_list[high], + final_y[high], + floor.x_list[i], + ); + let val = y[i]; + let high_room = range - predicted; + let low_room = predicted; + let room = high_room.min(low_room) * 2; + if val != 0 { + step2[low] = true; + step2[high] = true; + step2[i] = true; + final_y[i] = match val >= room { + true => match high_room > low_room { + true => val - low_room + predicted, + false => predicted - val + high_room - 1, + }, + false => match val & 1 == 1 { + true => predicted - (val + 1) / 2, + false => predicted + val / 2, + }, + }; + } else { + step2[i] = false; + final_y[i] = predicted; + } + final_y[i] = final_y[i].clamp(0, range - 1); + } + FloorState::One { y: final_y, step2 } +} + +/// Draw the floor-1 curve into `out` (§7.2.4), one value per coefficient. +pub fn render_floor1(floor: &Floor1, y: &[i32], step2: &[bool], out: &mut [f32]) { + let n = out.len(); + let table = &*INVERSE_DB; + let multiplier = floor.multiplier; + let mut lx = 0usize; + let mut ly = y[0] * multiplier; + let mut hx = 0usize; + let mut hy = ly; + for &i in floor.sorted.iter().skip(1) { + if !step2[i] { + continue; + } + hy = y[i] * multiplier; + hx = floor.x_list[i] as usize; + render_line(lx, ly, hx, hy, out, table); + lx = hx; + ly = hy; + } + if hx < n { + render_line(hx, hy, n, hy, out, table); + } +} + +/// §7.2.2 `render_point`: the height a line between two coded values has at `x`. +fn render_point(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 { + let dy = y1 - y0; + let adx = (x1 - x0) as i32; + let ady = dy.abs(); + let off = (ady * (x - x0) as i32) / adx; + match dy < 0 { + true => y0 - off, + false => y0 + off, + } +} + +/// §7.2.4 `render_line`: integer Bresenham, so two decoders never disagree by +/// one sample of tilt. +fn render_line(x0: usize, y0: i32, x1: usize, y1: i32, out: &mut [f32], table: &[f32; 256]) { + let n = out.len(); + let dy = y1 - y0; + let adx = (x1 - x0) as i32; + if adx <= 0 { + return; + } + let mut ady = dy.abs(); + let base = dy / adx; + let sy = match dy < 0 { + true => base - 1, + false => base + 1, + }; + ady -= base.abs() * adx; + let mut y = y0; + let mut err = 0i32; + if x0 < n { + out[x0] = table[y.clamp(0, 255) as usize]; + } + let end = x1.min(n); + for slot in out[(x0 + 1).min(end)..end].iter_mut() { + err += ady; + if err >= adx { + err -= adx; + y += sy; + } else { + y += base; + } + *slot = table[y.clamp(0, 255) as usize]; + } +} + +/// Decode a floor-0 packet header (§6.2.2): an amplitude and an LSP vector. +pub fn decode_floor0(floor: &Floor0, codebooks: &[Codebook], bits: &mut Bits) -> FloorState { + let amplitude = bits.read(floor.amplitude_bits); + if bits.eop() { + return FloorState::Unused; + } + if amplitude == 0 { + return FloorState::Unused; + } + // §6.2.2 states the book number in `ilog(number_of_books)` bits — the count + // itself, not the largest index, which is one bit wider than it looks. + let index = bits.read(ilog(floor.books.len() as u32)) as usize; + let Some(&book) = floor.books.get(index) else { + return FloorState::Unused; + }; + let book = &codebooks[book]; + if !book.has_values() { + return FloorState::Unused; + } + let mut coefficients = Vec::with_capacity(floor.order); + let mut last = 0.0f32; + while coefficients.len() < floor.order { + let Some(vector) = book.decode_vector(bits) else { + return FloorState::Unused; + }; + for &value in vector { + coefficients.push(value + last); + } + last = *coefficients.last().unwrap_or(&0.0); + } + coefficients.truncate(floor.order); + FloorState::Zero { + amplitude, + coefficients, + } +} + +/// Draw the floor-0 curve into `out` (§6.2.3): the LSP pair evaluated on a +/// Bark-spaced frequency map, one height per Bark bin. +pub fn render_floor0(floor: &Floor0, amplitude: u32, coefficients: &[f32], out: &mut [f32]) { + let n = out.len(); + if n == 0 || coefficients.is_empty() { + out.fill(0.0); + return; + } + let order = coefficients.len(); + let bark_size = floor.bark_map_size as f64; + let scale = bark_size / bark(0.5 * f64::from(floor.rate)); + let map: Vec = (0..n) + .map(|i| { + let hz = f64::from(floor.rate) * 0.5 * i as f64 / n as f64; + (bark(hz) * scale).floor().clamp(0.0, bark_size - 1.0) + }) + .collect(); + let amplitude_max = ((1u64 << floor.amplitude_bits) - 1) as f64; + let offset = f64::from(floor.amplitude_offset); + let cos_theta: Vec = coefficients.iter().map(|&c| f64::from(c).cos()).collect(); + + let mut i = 0usize; + while i < n { + let bin = map[i]; + let omega = std::f64::consts::PI * bin / bark_size; + let cos_omega = omega.cos(); + // P and Q are the two LSP polynomials on the unit circle; their + // prefactors are the (1 +- z^-1) factors the odd and even orders differ + // by, and each root contributes 4(cos(theta) - cos(omega))^2. + let (mut p, mut q) = match order % 2 { + 1 => (1.0 - cos_omega * cos_omega, 0.25), + _ => ((1.0 - cos_omega) * 0.5, (1.0 + cos_omega) * 0.5), + }; + let mut j = 1usize; + while j < order { + let d = cos_theta[j] - cos_omega; + p *= 4.0 * d * d; + j += 2; + } + let mut j = 0usize; + while j < order { + let d = cos_theta[j] - cos_omega; + q *= 4.0 * d * d; + j += 2; + } + let value = (0.11512925 + * (f64::from(amplitude) * offset / (amplitude_max * (p + q).sqrt()) - offset)) + .exp() as f32; + while i < n && map[i] == bin { + out[i] = value; + i += 1; + } + } +} + +/// §6.2.3's Bark scale. +fn bark(x: f64) -> f64 { + 13.1 * (0.00074 * x).atan() + 2.24 * (0.0000000185 * x * x).atan() + 0.0001 * x +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn inverse_db_table_matches_the_spec_endpoints() { + let table = &*INVERSE_DB; + assert!((table[0] - 1.0649863e-07).abs() < 1e-13, "{}", table[0]); + assert!((table[255] - 1.0).abs() < 1e-6, "{}", table[255]); + // Monotonic, which is what makes a bigger Y a louder floor. + assert!(table.windows(2).all(|w| w[1] > w[0])); + } + + #[test] + fn render_line_draws_the_spec_slope() { + let mut out = vec![0.0f32; 8]; + let table = &*INVERSE_DB; + render_line(0, 0, 8, 16, &mut out, table); + // Sixteen steps over eight samples is two per sample, starting at zero. + let expect: Vec = (0..8).map(|i| table[i * 2]).collect(); + assert_eq!(out, expect); + } +} diff --git a/crates/ec-vorbis/src/lib.rs b/crates/ec-vorbis/src/lib.rs new file mode 100644 index 00000000..cc6b2b7b --- /dev/null +++ b/crates/ec-vorbis/src/lib.rs @@ -0,0 +1,45 @@ +//! Vorbis I — decoder and encoder. +//! +//! The decoder is the whole format: both floor types, all three residue types, +//! square-polar channel coupling, every legal blocksize and the four window +//! shapes a long block takes next to a short one. It is written against the +//! Xiph Vorbis I specification and nothing else. +//! +//! The encoder is deliberately narrower and states its own terms: +//! +//! - **Any channel count, natively.** Mono, stereo and surround each get a +//! setup header written for that layout, with coupling where coupling pays +//! (stereo) and none where it does not. There is no stereo-only profile to +//! work around and no dual-mono widening of a mono mix. +//! - **No pre-roll.** The first block is centred on input sample 0, so the +//! decoder's first output sample *is* input sample 0. A caller does not feed +//! silence ahead of the mix and does not subtract a hop from every granule. +//! - **Exact length.** The last packet's granule states the input's own sample +//! count, so a file decodes to exactly as many samples as went in — no block +//! grid overshoot survives to the player. +//! - **ABR.** [`EncoderConfig::bitrate_bps`] is tracked by a feedback loop over +//! the headroom the floor leaves under the masking curve; +//! [`EncoderConfig::quality`] sets where that loop starts, and holds the +//! headroom still when no bitrate is asked for. The loop tracks rather than +//! hits: a signal too simple to spend the budget on comes out under it. +//! +//! Timing contract: an audio packet answers the samples that became final when +//! its window closed, so the *first* packet of a stream answers none. That is +//! Vorbis, not an artefact — a block's left half is only half of the samples it +//! overlaps. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +mod bits; +mod codebook; +mod decode; +mod encode; +mod floor; +mod residue; +mod setup; +mod window; + +pub use decode::{VorbisDecoder, channel_map}; +pub use encode::{EncoderConfig, VorbisEncoder}; +pub use setup::{Comments, Identification}; diff --git a/crates/ec-vorbis/src/residue.rs b/crates/ec-vorbis/src/residue.rs new file mode 100644 index 00000000..3be99d8e --- /dev/null +++ b/crates/ec-vorbis/src/residue.rs @@ -0,0 +1,142 @@ +//! Residue decode (§8): the spectrum that rides on the floor. +//! +//! All three residue types share one loop — partitions classified in groups, +//! then up to eight refinement passes over those classes — and differ only in +//! how a partition's values are laid out. Type 2 differs one level up: it codes +//! every channel of a submap as one interleaved vector, which is what makes +//! coupled stereo cheap. + +use crate::bits::Bits; +use crate::codebook::Codebook; +use crate::setup::ResidueConfig; + +/// Decode one residue into `vectors`, which the caller has zeroed. +/// +/// For types 0 and 1 there is one vector per channel of the submap; for type 2 +/// the caller passes a single interleaved vector `channels * n` long. Channels +/// flagged in `skip` are not coded at all (an unused floor, or a coupling +/// partner already covered). +pub fn decode( + config: &ResidueConfig, + codebooks: &[Codebook], + bits: &mut Bits, + vectors: &mut [Vec], + skip: &[bool], +) { + let Some(size) = vectors.first().map(Vec::len) else { + return; + }; + if skip.iter().all(|&s| s) { + return; + } + let begin = config.begin.min(size); + let end = config.end.min(size); + let to_read = end.saturating_sub(begin); + let partitions = to_read / config.partition_size; + if partitions == 0 { + return; + } + let classbook = &codebooks[config.classbook]; + let per_word = classbook.dimensions.max(1); + let classes = config.classifications as u32; + let mut classification = vec![vec![0u8; partitions + per_word]; vectors.len()]; + + for pass in 0..8usize { + let mut partition = 0usize; + while partition < partitions { + if pass == 0 { + for (channel, row) in classification.iter_mut().enumerate() { + if skip[channel] { + continue; + } + let Some(mut word) = classbook.decode_scalar(bits) else { + return; + }; + // The class word packs `per_word` classes, most recent + // partition in the least significant digit. + for i in (0..per_word).rev() { + row[partition + i] = (word % classes) as u8; + word /= classes; + } + } + } + for _ in 0..per_word { + if partition >= partitions { + break; + } + for (channel, vector) in vectors.iter_mut().enumerate() { + if skip[channel] { + continue; + } + let class = usize::from(classification[channel][partition]); + let book = config.books[class][pass]; + if book < 0 { + continue; + } + let offset = begin + partition * config.partition_size; + let slice = &mut vector[offset..offset + config.partition_size]; + if !decode_partition(config.kind, &codebooks[book as usize], bits, slice) { + return; + } + } + partition += 1; + } + } + } +} + +/// One partition's worth of values, added onto what earlier passes left. +fn decode_partition(kind: u8, book: &Codebook, bits: &mut Bits, out: &mut [f32]) -> bool { + if !book.has_values() { + return false; + } + let dimensions = book.dimensions; + match kind { + // Type 0 lays a codeword's values out strided, so one codeword covers + // the whole partition at `step` spacing. + 0 => { + let step = out.len() / dimensions.max(1); + for i in 0..step { + let Some(values) = book.decode_vector(bits) else { + return false; + }; + for (j, &value) in values.iter().enumerate() { + if let Some(slot) = out.get_mut(i + j * step) { + *slot += value; + } + } + } + } + // Types 1 and 2 lay them out contiguously. + _ => { + let mut i = 0usize; + while i < out.len() { + let Some(values) = book.decode_vector(bits) else { + return false; + }; + for &value in values { + if i >= out.len() { + break; + } + out[i] += value; + i += 1; + } + if dimensions == 0 { + return false; + } + } + } + } + true +} + +/// Spread a type-2 interleaved vector back over its channels. +pub fn deinterleave(interleaved: &[f32], channels: usize, out: &mut [Vec]) { + for (i, &value) in interleaved.iter().enumerate() { + let channel = i % channels; + let position = i / channels; + if let Some(slot) = out[channel].get_mut(position) { + *slot = value; + } + } +} diff --git a/crates/ec-vorbis/src/setup.rs b/crates/ec-vorbis/src/setup.rs new file mode 100644 index 00000000..2c218287 --- /dev/null +++ b/crates/ec-vorbis/src/setup.rs @@ -0,0 +1,595 @@ +//! The three header packets: identification, comment, setup. +//! +//! Everything a Vorbis stream needs before its first audio packet lives here — +//! the blocksizes, the codebooks, and the floor/residue/mapping/mode +//! configurations that audio packets index by number. The setup header is +//! parsed once; audio decode after that is pure lookup. + +use ec_core::{Error, Result}; + +use crate::bits::Bits; +use crate::codebook::{Codebook, ilog}; + +/// Identification header (§4.2.2). +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct Identification { + /// Channel count, in Vorbis channel order. + pub channels: u8, + /// Sample rate in Hz. + pub rate: u32, + /// Nominal bitrate the encoder stated, 0 when it stated none. + pub bitrate_nominal: i32, + /// Short block size in samples. + pub blocksize_0: usize, + /// Long block size in samples. + pub blocksize_1: usize, +} + +impl Identification { + /// Parse the identification packet, header byte included. + pub fn parse(data: &[u8]) -> Result { + let mut bits = Bits::new(header_body(data, 1)?); + let version = bits.read(32); + if version != 0 { + return Err(Error::unsupported( + format!("Vorbis bitstream version {version}"), + "only version 0 (Vorbis I) is defined", + )); + } + let channels = bits.read(8) as u8; + let rate = bits.read(32); + let _bitrate_maximum = bits.read(32) as i32; + let bitrate_nominal = bits.read(32) as i32; + let _bitrate_minimum = bits.read(32) as i32; + let blocksize_0 = 1usize << bits.read(4); + let blocksize_1 = 1usize << bits.read(4); + let framing = bits.bit(); + if bits.eop() || !framing { + return Err(Error::corrupt("identification header truncated")); + } + if channels == 0 || rate == 0 { + return Err(Error::corrupt("identification header states no audio")); + } + let legal = |n: usize| n.is_power_of_two() && (64..=8192).contains(&n); + if !legal(blocksize_0) || !legal(blocksize_1) || blocksize_0 > blocksize_1 { + return Err(Error::corrupt(format!( + "blocksizes {blocksize_0}/{blocksize_1}" + ))); + } + Ok(Identification { + channels, + rate, + bitrate_nominal, + blocksize_0, + blocksize_1, + }) + } +} + +/// Comment header (§5): the vendor string and the tag list. +#[derive(Debug, Clone, Default, PartialEq, Eq)] +pub struct Comments { + /// Encoder identification. + pub vendor: String, + /// `NAME=value` tags, in file order, with the name upper-cased. + pub tags: Vec<(String, String)>, +} + +impl Comments { + /// Parse the comment packet, header byte included. + /// + /// A malformed tag is skipped rather than fatal: metadata never stops + /// audio from playing. + pub fn parse(data: &[u8]) -> Result { + let body = header_body(data, 3)?; + let mut pos = 0usize; + let take = |pos: &mut usize| -> Option { + let len = u32::from_le_bytes(body.get(*pos..*pos + 4)?.try_into().ok()?) as usize; + *pos += 4; + let text = body.get(*pos..pos.checked_add(len)?)?; + *pos += len; + Some(String::from_utf8_lossy(text).into_owned()) + }; + let vendor = take(&mut pos).ok_or_else(|| Error::corrupt("comment vendor string"))?; + let count = u32::from_le_bytes( + body.get(pos..pos + 4) + .ok_or_else(|| Error::corrupt("comment count"))? + .try_into() + .map_err(|_| Error::corrupt("comment count"))?, + ); + pos += 4; + let mut tags = Vec::new(); + for _ in 0..count { + let Some(entry) = take(&mut pos) else { break }; + if let Some((name, value)) = entry.split_once('=') { + tags.push((name.to_ascii_uppercase(), value.to_string())); + } + } + Ok(Comments { vendor, tags }) + } +} + +/// Floor type 0: an LSP curve (§6.2). +#[derive(Debug, Clone)] +pub struct Floor0 { + /// LSP order. + pub order: usize, + /// Rate the bark map is built against. + pub rate: u32, + /// Bark map resolution. + pub bark_map_size: usize, + /// Bits the amplitude is stated in. + pub amplitude_bits: u32, + /// dB offset applied to the amplitude. + pub amplitude_offset: f32, + /// Books the coefficient vector may be coded with. + pub books: Vec, +} + +/// Floor type 1: a piecewise-linear curve in dB (§7.2). +#[derive(Debug, Clone)] +pub struct Floor1 { + /// Class of each partition, in order. + pub partition_classes: Vec, + /// Values per class. + pub class_dimensions: Vec, + /// Subclass bits per class. + pub class_subclasses: Vec, + /// Book naming the subclass, per class; unused when `class_subclasses` is 0. + pub class_masterbooks: Vec, + /// Book per subclass, `-1` for "this subclass codes nothing". + pub subclass_books: Vec>, + /// dB step per Y unit. + pub multiplier: i32, + /// X coordinate of every value, in coding order. + pub x_list: Vec, + /// Indices of `x_list` sorted by X, the order the curve is rendered in. + pub sorted: Vec, + /// Per value, the coding-order index of the nearest lower/higher X already + /// coded, precomputed because the decode loop needs it per packet. + pub neighbours: Vec<(usize, usize)>, +} + +/// One floor configuration. +#[derive(Debug, Clone)] +pub enum FloorConfig { + /// LSP floor. + Zero(Floor0), + /// Piecewise-linear floor. + One(Floor1), +} + +/// Residue configuration (§8). +#[derive(Debug, Clone)] +pub struct ResidueConfig { + /// 0, 1 or 2 — how a partition's values are laid out. + pub kind: u8, + /// First coefficient coded. + pub begin: usize, + /// One past the last coefficient coded. + pub end: usize, + /// Coefficients per partition. + pub partition_size: usize, + /// Number of classes. + pub classifications: usize, + /// Book the class words are coded with. + pub classbook: usize, + /// Book per (class, pass), `-1` where the pass codes nothing. + pub books: Vec<[i32; 8]>, +} + +/// Mapping configuration (§4.2.4): which floor and residue serve which channel, +/// and which channel pairs are coupled. +#[derive(Debug, Clone)] +pub struct MappingConfig { + /// `(magnitude, angle)` channel per coupling step. + pub coupling: Vec<(usize, usize)>, + /// Submap per channel. + pub mux: Vec, + /// `(floor, residue)` per submap. + pub submaps: Vec<(usize, usize)>, +} + +/// One mode (§4.2.4): a block size and a mapping. +#[derive(Debug, Clone, Copy)] +pub struct Mode { + /// False for a short block, true for a long one. + pub block_flag: bool, + /// Mapping this mode decodes with. + pub mapping: usize, +} + +/// Everything the setup header configures. +#[derive(Debug, Clone)] +pub struct Setup { + /// Codebooks, indexed by number. + pub codebooks: Vec, + /// Floor configurations. + pub floors: Vec, + /// Residue configurations. + pub residues: Vec, + /// Mapping configurations. + pub mappings: Vec, + /// Modes; an audio packet's first field is an index into this. + pub modes: Vec, +} + +impl Setup { + /// Parse the setup packet, header byte included. + pub fn parse(data: &[u8], ident: &Identification) -> Result { + let mut bits = Bits::new(header_body(data, 5)?); + let channels = usize::from(ident.channels); + + let codebook_count = bits.read(8) as usize + 1; + let mut codebooks = Vec::with_capacity(codebook_count); + for _ in 0..codebook_count { + codebooks.push(Codebook::parse(&mut bits)?); + } + + // Time-domain transforms: a placeholder in Vorbis I, but the field is + // there and must read zero. + let time_count = bits.read(6) + 1; + for _ in 0..time_count { + if bits.read(16) != 0 { + return Err(Error::corrupt("time domain transform is not zero")); + } + } + + let floor_count = bits.read(6) as usize + 1; + let mut floors = Vec::with_capacity(floor_count); + for _ in 0..floor_count { + floors.push(parse_floor(&mut bits, &codebooks, ident)?); + } + + let residue_count = bits.read(6) as usize + 1; + let mut residues = Vec::with_capacity(residue_count); + for _ in 0..residue_count { + residues.push(parse_residue(&mut bits, codebooks.len())?); + } + + let mapping_count = bits.read(6) as usize + 1; + let mut mappings = Vec::with_capacity(mapping_count); + for _ in 0..mapping_count { + mappings.push(parse_mapping( + &mut bits, + channels, + floors.len(), + residues.len(), + )?); + } + + let mode_count = bits.read(6) as usize + 1; + let mut modes = Vec::with_capacity(mode_count); + for _ in 0..mode_count { + let block_flag = bits.bit(); + let window_type = bits.read(16); + let transform_type = bits.read(16); + let mapping = bits.read(8) as usize; + if window_type != 0 || transform_type != 0 { + return Err(Error::corrupt("mode states an undefined transform")); + } + if mapping >= mappings.len() { + return Err(Error::corrupt("mode names a mapping that is not there")); + } + modes.push(Mode { + block_flag, + mapping, + }); + } + + if !bits.bit() || bits.eop() { + return Err(Error::corrupt("setup header framing")); + } + + Ok(Setup { + codebooks, + floors, + residues, + mappings, + modes, + }) + } +} + +/// Strip and check the `type, "vorbis"` prefix every header carries. +fn header_body(data: &[u8], kind: u8) -> Result<&[u8]> { + if data.len() < 7 || data[0] != kind || &data[1..7] != b"vorbis" { + return Err(Error::corrupt(format!( + "not a Vorbis header of type {kind}" + ))); + } + Ok(&data[7..]) +} + +fn parse_floor( + bits: &mut Bits, + codebooks: &[Codebook], + ident: &Identification, +) -> Result { + match bits.read(16) { + 0 => { + let order = bits.read(8) as usize; + let rate = bits.read(16); + let bark_map_size = bits.read(16) as usize; + let amplitude_bits = bits.read(6); + let amplitude_offset = bits.read(8) as f32; + let book_count = bits.read(4) as usize + 1; + let mut books = Vec::with_capacity(book_count); + for _ in 0..book_count { + let book = bits.read(8) as usize; + if book >= codebooks.len() { + return Err(Error::corrupt("floor 0 names a book that is not there")); + } + books.push(book); + } + if bits.eop() || order == 0 || bark_map_size == 0 || amplitude_bits > 32 { + return Err(Error::corrupt("floor 0 configuration")); + } + Ok(FloorConfig::Zero(Floor0 { + order, + rate, + bark_map_size, + amplitude_bits, + amplitude_offset, + books, + })) + } + 1 => { + let partitions = bits.read(5) as usize; + let mut partition_classes = Vec::with_capacity(partitions); + let mut max_class = 0usize; + for _ in 0..partitions { + let class = bits.read(4) as usize; + max_class = max_class.max(class); + partition_classes.push(class); + } + let class_count = if partitions == 0 { 0 } else { max_class + 1 }; + let mut class_dimensions = Vec::with_capacity(class_count); + let mut class_subclasses = Vec::with_capacity(class_count); + let mut class_masterbooks = Vec::with_capacity(class_count); + let mut subclass_books = Vec::with_capacity(class_count); + for _ in 0..class_count { + let dimensions = bits.read(3) as usize + 1; + let subclasses = bits.read(2); + let masterbook = if subclasses > 0 { + let book = bits.read(8) as usize; + if book >= codebooks.len() { + return Err(Error::corrupt( + "floor 1 names a masterbook that is not there", + )); + } + book + } else { + 0 + }; + let mut books = Vec::with_capacity(1 << subclasses); + for _ in 0..(1u32 << subclasses) { + let book = bits.read(8) as i32 - 1; + if book >= codebooks.len() as i32 { + return Err(Error::corrupt("floor 1 names a book that is not there")); + } + books.push(book); + } + class_dimensions.push(dimensions); + class_subclasses.push(subclasses); + class_masterbooks.push(masterbook); + subclass_books.push(books); + } + let multiplier = bits.read(2) as i32 + 1; + let range_bits = bits.read(4); + let mut x_list = vec![0u32, 1u32 << range_bits]; + for &class in &partition_classes { + for _ in 0..class_dimensions[class] { + x_list.push(bits.read(range_bits)); + } + } + if bits.eop() { + return Err(Error::corrupt("floor 1 configuration truncated")); + } + if x_list.len() > 65 { + return Err(Error::corrupt("floor 1 states more than 65 values")); + } + // The X list must be distinct or the curve has two heights at one + // place; a stream that says so is corrupt, not a rendering choice. + let mut seen = x_list.clone(); + seen.sort_unstable(); + if seen.windows(2).any(|w| w[0] == w[1]) { + return Err(Error::corrupt("floor 1 repeats an X coordinate")); + } + if *seen.last().unwrap_or(&0) as usize > ident.blocksize_1 / 2 { + return Err(Error::corrupt("floor 1 X coordinate past the block")); + } + let mut sorted: Vec = (0..x_list.len()).collect(); + sorted.sort_by_key(|&i| x_list[i]); + let neighbours = (0..x_list.len()) + .map(|i| (low_neighbour(&x_list, i), high_neighbour(&x_list, i))) + .collect(); + Ok(FloorConfig::One(Floor1 { + partition_classes, + class_dimensions, + class_subclasses, + class_masterbooks, + subclass_books, + multiplier, + x_list, + sorted, + neighbours, + })) + } + other => Err(Error::unsupported( + format!("floor type {other}"), + "Vorbis I defines floor 0 and floor 1", + )), + } +} + +/// Coding-order index of the largest X below `x_list[i]` among values already +/// coded (§7.2.2 `low_neighbor`). +fn low_neighbour(x_list: &[u32], i: usize) -> usize { + let mut best = 0usize; + let mut best_x = None; + for (j, &x) in x_list.iter().enumerate().take(i) { + if x < x_list[i] && best_x.is_none_or(|b| x > b) { + best = j; + best_x = Some(x); + } + } + best +} + +/// The mirror of [`low_neighbour`]. +fn high_neighbour(x_list: &[u32], i: usize) -> usize { + let mut best = 0usize; + let mut best_x = None; + for (j, &x) in x_list.iter().enumerate().take(i) { + if x > x_list[i] && best_x.is_none_or(|b| x < b) { + best = j; + best_x = Some(x); + } + } + best +} + +fn parse_residue(bits: &mut Bits, codebook_count: usize) -> Result { + let kind = bits.read(16); + if kind > 2 { + return Err(Error::unsupported( + format!("residue type {kind}"), + "Vorbis I defines 0, 1 and 2", + )); + } + let begin = bits.read(24) as usize; + let end = bits.read(24) as usize; + let partition_size = bits.read(24) as usize + 1; + let classifications = bits.read(6) as usize + 1; + let classbook = bits.read(8) as usize; + if bits.eop() || classbook >= codebook_count || end < begin { + return Err(Error::corrupt("residue configuration")); + } + let mut cascade = Vec::with_capacity(classifications); + for _ in 0..classifications { + let low = bits.read(3); + let high = if bits.bit() { bits.read(5) } else { 0 }; + cascade.push((high << 3) | low); + } + let mut books = Vec::with_capacity(classifications); + for &cascade in &cascade { + let mut row = [-1i32; 8]; + for (pass, slot) in row.iter_mut().enumerate() { + if cascade & (1 << pass) != 0 { + let book = bits.read(8) as usize; + if book >= codebook_count { + return Err(Error::corrupt("residue names a book that is not there")); + } + *slot = book as i32; + } + } + books.push(row); + } + if bits.eop() { + return Err(Error::corrupt("residue configuration truncated")); + } + Ok(ResidueConfig { + kind: kind as u8, + begin, + end, + partition_size, + classifications, + classbook, + books, + }) +} + +fn parse_mapping( + bits: &mut Bits, + channels: usize, + floor_count: usize, + residue_count: usize, +) -> Result { + if bits.read(16) != 0 { + return Err(Error::unsupported( + "mapping type other than 0", + "Vorbis I defines mapping type 0 only", + )); + } + let submap_count = if bits.bit() { + bits.read(4) as usize + 1 + } else { + 1 + }; + let mut coupling = Vec::new(); + if bits.bit() { + let steps = bits.read(8) as usize + 1; + let field = ilog((channels - 1) as u32); + for _ in 0..steps { + let magnitude = bits.read(field) as usize; + let angle = bits.read(field) as usize; + if magnitude == angle || magnitude >= channels || angle >= channels { + return Err(Error::corrupt("coupling step names an impossible pair")); + } + coupling.push((magnitude, angle)); + } + } + if bits.read(2) != 0 { + return Err(Error::corrupt("mapping reserved bits are not zero")); + } + let mux = match submap_count > 1 { + true => (0..channels) + .map(|_| { + let submap = bits.read(4) as usize; + match submap < submap_count { + true => Ok(submap), + false => Err(Error::corrupt("channel names a submap that is not there")), + } + }) + .collect::>>()?, + false => vec![0; channels], + }; + let mut submaps = Vec::with_capacity(submap_count); + for _ in 0..submap_count { + let _unused = bits.read(8); + let floor = bits.read(8) as usize; + let residue = bits.read(8) as usize; + if floor >= floor_count || residue >= residue_count { + return Err(Error::corrupt( + "submap names a floor or residue that is not there", + )); + } + submaps.push((floor, residue)); + } + if bits.eop() { + return Err(Error::corrupt("mapping truncated")); + } + Ok(MappingConfig { + coupling, + mux, + submaps, + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn identification_refuses_what_it_cannot_decode() { + assert!(Identification::parse(b"garbage").is_err()); + // Type 1 header, blocksizes 256/2048, 2 channels, 44100 Hz. + let mut header = vec![1u8]; + header.extend_from_slice(b"vorbis"); + header.extend_from_slice(&0u32.to_le_bytes()); + header.push(2); + header.extend_from_slice(&44_100u32.to_le_bytes()); + header.extend_from_slice(&0i32.to_le_bytes()); + header.extend_from_slice(&128_000i32.to_le_bytes()); + header.extend_from_slice(&0i32.to_le_bytes()); + header.push(0xb8); // blocksize_0 = 2^8, blocksize_1 = 2^11 + header.push(0x01); // framing + let ident = Identification::parse(&header).expect("identification"); + assert_eq!(ident.channels, 2); + assert_eq!(ident.rate, 44_100); + assert_eq!(ident.blocksize_0, 256); + assert_eq!(ident.blocksize_1, 2048); + assert_eq!(ident.bitrate_nominal, 128_000); + } +} diff --git a/crates/ec-vorbis/src/window.rs b/crates/ec-vorbis/src/window.rs new file mode 100644 index 00000000..51758c57 --- /dev/null +++ b/crates/ec-vorbis/src/window.rs @@ -0,0 +1,103 @@ +//! Vorbis windows (§4.3.1), including the asymmetric long-block shapes. +//! +//! A long block next to a short one does not use the long slope: it uses the +//! *short* slope, centred where the short block's own slope will be, and is +//! flat or zero either side of it. That is what makes the two windows still add +//! to one across the overlap, and it is the whole reason a Vorbis decoder needs +//! four long-window variants rather than one. + +/// The Vorbis slope of `n` samples: `sin(pi/2 * sin^2((i + 1/2)/n * pi/2))`, +/// rising from 0 to 1. +fn slope(n: usize) -> Vec { + (0..n) + .map(|i| { + let x = (i as f64 + 0.5) / n as f64 * std::f64::consts::FRAC_PI_2; + let s = x.sin(); + (std::f64::consts::FRAC_PI_2 * s * s).sin() as f32 + }) + .collect() +} + +/// One window of `n` samples for a block whose neighbours are long or short. +/// +/// `short` is the stream's short blocksize; it is what sets the slope width +/// when a neighbour is short. For a short block itself both flags are true by +/// construction (its slopes are already the narrow ones). +pub fn build(n: usize, short: usize, previous_long: bool, next_long: bool) -> Vec { + let mut window = vec![0.0f32; n]; + let (left_start, left_n) = match previous_long { + true => (0usize, n / 2), + false => (n / 4 - short / 4, short / 2), + }; + let (right_start, right_n) = match next_long { + true => (n / 2, n / 2), + false => (n * 3 / 4 - short / 4, short / 2), + }; + let left = slope(left_n); + let right = slope(right_n); + for (i, value) in left.iter().enumerate() { + window[left_start + i] = *value; + } + window[left_start + left_n..right_start].fill(1.0); + // The right slope is the left one read backwards, which is what makes the + // pair Princen-Bradley. + for i in 0..right_n { + window[right_start + i] = right[right_n - 1 - i]; + } + window +} + +/// The four long-block variants plus the short one, built once per stream. +pub struct Windows { + short: Vec, + long: [Vec; 4], +} + +impl Windows { + /// Build every window a stream with these blocksizes can ask for. + pub fn new(blocksize_0: usize, blocksize_1: usize) -> Windows { + Windows { + short: build(blocksize_0, blocksize_0, true, true), + long: [ + build(blocksize_1, blocksize_0, false, false), + build(blocksize_1, blocksize_0, false, true), + build(blocksize_1, blocksize_0, true, false), + build(blocksize_1, blocksize_0, true, true), + ], + } + } + + /// The window for one block. + pub fn get(&self, long: bool, previous_long: bool, next_long: bool) -> &[f32] { + match long { + false => &self.short, + true => &self.long[usize::from(previous_long) * 2 + usize::from(next_long)], + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn overlapping_windows_add_to_one() { + // Long block against long block: the two slopes are the classic + // Princen-Bradley pair, so squares sum to one across the overlap. + let long = build(2048, 256, true, true); + for i in 0..1024 { + let sum = long[1024 + i] * long[1024 + i] + long[i] * long[i]; + assert!((sum - 1.0).abs() < 1e-6, "{i}: {sum}"); + } + // Long block against a short neighbour: the long window's right slope + // is the short window's own slope, sitting where the short block will + // put its left one, and is zero past it. + let to_short = build(2048, 256, true, false); + let short = build(256, 256, true, true); + assert!(to_short[2047] == 0.0 && to_short[1600] == 0.0); + for i in 0..128 { + let sum = to_short[1472 + i] * to_short[1472 + i] + short[i] * short[i]; + assert!((sum - 1.0).abs() < 1e-6, "{i}: {sum}"); + } + } +}