Vorbis I decoder and encoder
Browse files at this commitc0023ffd3f0482a1041216ef30ff2792fcac156eParent: 7cdaf34- feat
- Vorbis I decoder and encoder
10 changed files +3379 -0
- crates/ec-vorbis/Cargo.toml +14 -0
- crates/ec-vorbis/src/bits.rs +150 -0
- crates/ec-vorbis/src/codebook.rs +506 -0
- crates/ec-vorbis/src/decode.rs +464 -0
- crates/ec-vorbis/src/encode.rs +1026 -0
- crates/ec-vorbis/src/floor.rs +334 -0
- crates/ec-vorbis/src/lib.rs +45 -0
- crates/ec-vorbis/src/residue.rs +142 -0
- crates/ec-vorbis/src/setup.rs +595 -0
- crates/ec-vorbis/src/window.rs +103 -0
crates/ec-vorbis/Cargo.tomladded+14 -0
| @@ -0,0 +1,14 @@ | |||
| 1 | +[package] | ||
| 2 | +name = "ec-vorbis" | ||
| 3 | +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." | ||
| 4 | +version.workspace = true | ||
| 5 | +edition.workspace = true | ||
| 6 | +license.workspace = true | ||
| 7 | +authors.workspace = true | ||
| 8 | + | ||
| 9 | +[dependencies] | ||
| 10 | +ec-core.workspace = true | ||
| 11 | +ec-dsp.workspace = true | ||
| 12 | + | ||
| 13 | +[dev-dependencies] | ||
| 14 | +ec-ogg = { path = "../ec-ogg", version = "0.1.0" } | ||
crates/ec-vorbis/src/bits.rsadded+150 -0
| @@ -0,0 +1,150 @@ | |||
| 1 | +//! Packet-local bit access with the Vorbis end-of-packet convention. | ||
| 2 | +//! | ||
| 3 | +//! Reading past the end of a Vorbis packet is not an error. The spec's decode | ||
| 4 | +//! loops read until the packet runs out and take zeroes after that, which is | ||
| 5 | +//! how a truncated final packet still decodes to the audio it does hold. So | ||
| 6 | +//! this reader answers zero past the end and raises a sticky flag; the callers | ||
| 7 | +//! that must not act on a zero — Huffman decode, header parse — ask [`Bits::eop`]. | ||
| 8 | + | ||
| 9 | +use ec_core::{BitReaderLsb, BitWriterLsb}; | ||
| 10 | + | ||
| 11 | +/// LSB-first reader over one packet. | ||
| 12 | +pub struct Bits<'a> { | ||
| 13 | + reader: BitReaderLsb<'a>, | ||
| 14 | + eop: bool, | ||
| 15 | +} | ||
| 16 | + | ||
| 17 | +impl<'a> Bits<'a> { | ||
| 18 | + /// A reader positioned at the first bit of `data`. | ||
| 19 | + pub fn new(data: &'a [u8]) -> Bits<'a> { | ||
| 20 | + Bits { | ||
| 21 | + reader: BitReaderLsb::new(data), | ||
| 22 | + eop: false, | ||
| 23 | + } | ||
| 24 | + } | ||
| 25 | + | ||
| 26 | + /// `n` bits (`n <= 32`), zero once the packet is exhausted. | ||
| 27 | + pub fn read(&mut self, n: u32) -> u32 { | ||
| 28 | + match self.reader.read_bits(n) { | ||
| 29 | + Ok(v) => v, | ||
| 30 | + Err(_) => { | ||
| 31 | + self.eop = true; | ||
| 32 | + 0 | ||
| 33 | + } | ||
| 34 | + } | ||
| 35 | + } | ||
| 36 | + | ||
| 37 | + /// One bit, false once the packet is exhausted. | ||
| 38 | + pub fn bit(&mut self) -> bool { | ||
| 39 | + self.read(1) != 0 | ||
| 40 | + } | ||
| 41 | + | ||
| 42 | + /// True once a read has run past the end of the packet. | ||
| 43 | + pub fn eop(&self) -> bool { | ||
| 44 | + self.eop | ||
| 45 | + } | ||
| 46 | + | ||
| 47 | + /// Bits left before the end of the packet. | ||
| 48 | + pub fn remaining(&self) -> u64 { | ||
| 49 | + self.reader.bits_remaining() | ||
| 50 | + } | ||
| 51 | + | ||
| 52 | + /// The 32-bit float of Vorbis I §9.2.2 — a 21-bit mantissa, a sign and a | ||
| 53 | + /// biased exponent, and *not* IEEE 754: it is decoded with integer | ||
| 54 | + /// arithmetic so every decoder agrees on the last bit. | ||
| 55 | + pub fn float32(&mut self) -> f32 { | ||
| 56 | + let x = self.read(32); | ||
| 57 | + float32_unpack(x) | ||
| 58 | + } | ||
| 59 | +} | ||
| 60 | + | ||
| 61 | +/// Vorbis I §9.2.2 float unpack, split out because the encoder packs the | ||
| 62 | +/// inverse of it. | ||
| 63 | +pub fn float32_unpack(x: u32) -> f32 { | ||
| 64 | + let mantissa = i64::from(x & 0x001f_ffff); | ||
| 65 | + let sign = x & 0x8000_0000 != 0; | ||
| 66 | + let exponent = ((x & 0x7fe0_0000) >> 21) as i32; | ||
| 67 | + let mantissa = if sign { -mantissa } else { mantissa }; | ||
| 68 | + // `exp2` rather than `powi`: the exponent field spans 2^-788..2^235, which | ||
| 69 | + // only stays exact as a power of two. | ||
| 70 | + (mantissa as f64 * f64::from(exponent - 788).exp2()) as f32 | ||
| 71 | +} | ||
| 72 | + | ||
| 73 | +/// The inverse of [`float32_unpack`] for a value an encoder wants to state | ||
| 74 | +/// exactly: mantissa in `[-2^21, 2^21)` scaled by a power of two. | ||
| 75 | +pub fn float32_pack(value: f32) -> u32 { | ||
| 76 | + if value == 0.0 || !value.is_finite() { | ||
| 77 | + return 0; | ||
| 78 | + } | ||
| 79 | + let sign = value < 0.0; | ||
| 80 | + let mut mantissa = f64::from(value.abs()); | ||
| 81 | + let mut exponent = 0i32; | ||
| 82 | + // Normalise into [2^20, 2^21) so the 21-bit mantissa field is fully used. | ||
| 83 | + while mantissa >= 2_097_152.0 { | ||
| 84 | + mantissa /= 2.0; | ||
| 85 | + exponent += 1; | ||
| 86 | + } | ||
| 87 | + while mantissa < 1_048_576.0 { | ||
| 88 | + mantissa *= 2.0; | ||
| 89 | + exponent -= 1; | ||
| 90 | + } | ||
| 91 | + let mantissa = mantissa.round() as u32 & 0x001f_ffff; | ||
| 92 | + let exponent = (exponent + 788).clamp(0, 0x3ff) as u32; | ||
| 93 | + (u32::from(sign) << 31) | (exponent << 21) | mantissa | ||
| 94 | +} | ||
| 95 | + | ||
| 96 | +/// LSB-first writer over one packet, the mirror of [`Bits`]. | ||
| 97 | +#[derive(Default)] | ||
| 98 | +pub struct BitsOut { | ||
| 99 | + writer: BitWriterLsb, | ||
| 100 | +} | ||
| 101 | + | ||
| 102 | +impl BitsOut { | ||
| 103 | + /// An empty packet. | ||
| 104 | + pub fn new() -> BitsOut { | ||
| 105 | + BitsOut::default() | ||
| 106 | + } | ||
| 107 | + | ||
| 108 | + /// Write the low `n` bits of `value`. | ||
| 109 | + pub fn write(&mut self, value: u32, n: u32) { | ||
| 110 | + self.writer.write_bits(value, n); | ||
| 111 | + } | ||
| 112 | + | ||
| 113 | + /// Write one bit. | ||
| 114 | + pub fn bit(&mut self, bit: bool) { | ||
| 115 | + self.writer.write_bit(bit); | ||
| 116 | + } | ||
| 117 | + | ||
| 118 | + /// Bits written so far. | ||
| 119 | + pub fn len(&self) -> u64 { | ||
| 120 | + self.writer.bit_len() | ||
| 121 | + } | ||
| 122 | + | ||
| 123 | + /// The packet, zero-padded to a byte. | ||
| 124 | + pub fn finish(self) -> Vec<u8> { | ||
| 125 | + self.writer.into_bytes() | ||
| 126 | + } | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +#[cfg(test)] | ||
| 130 | +mod tests { | ||
| 131 | + use super::*; | ||
| 132 | + | ||
| 133 | + #[test] | ||
| 134 | + fn float32_round_trips_through_the_spec_format() { | ||
| 135 | + for value in [1.0f32, 0.5, -2.25, 1e-6, 1024.0, -0.0009765625] { | ||
| 136 | + let packed = float32_pack(value); | ||
| 137 | + let back = float32_unpack(packed); | ||
| 138 | + assert!( | ||
| 139 | + (back - value).abs() <= value.abs() * 1e-6, | ||
| 140 | + "{value} -> {packed:#x} -> {back}" | ||
| 141 | + ); | ||
| 142 | + } | ||
| 143 | + assert_eq!(float32_unpack(0), 0.0); | ||
| 144 | + // A read past the end is zero with the flag raised, not an error. | ||
| 145 | + let mut bits = Bits::new(&[0xff]); | ||
| 146 | + assert_eq!(bits.read(8), 0xff); | ||
| 147 | + assert_eq!(bits.read(1), 0); | ||
| 148 | + assert!(bits.eop()); | ||
| 149 | + } | ||
| 150 | +} | ||
crates/ec-vorbis/src/codebook.rsadded+506 -0
| @@ -0,0 +1,506 @@ | |||
| 1 | +//! Codebooks: Huffman lengths in, entry numbers and VQ vectors out. | ||
| 2 | +//! | ||
| 3 | +//! Three things make a Vorbis codebook more than a Huffman table. The lengths | ||
| 4 | +//! themselves come in three encodings (flat, sparse, ordered-by-length). The | ||
| 5 | +//! codeword assignment is canonical but stated as "the next free codeword of | ||
| 6 | +//! this length", which is the same thing read from the other end. And a book | ||
| 7 | +//! may carry a *lookup*: entry numbers index a vector of quantised values, | ||
| 8 | +//! either by taking `dimensions` digits of the entry number in base | ||
| 9 | +//! `lookup_values` (type 1, the packing that makes a 2^24-vector book fit in a | ||
| 10 | +//! few hundred bytes) or by indexing the list directly (type 2). Both are | ||
| 11 | +//! expanded once at parse time, so decode is a tree walk and a slice. | ||
| 12 | + | ||
| 13 | +use ec_core::{Error, Result}; | ||
| 14 | + | ||
| 15 | +use crate::bits::{Bits, BitsOut}; | ||
| 16 | + | ||
| 17 | +/// One parsed codebook. | ||
| 18 | +#[derive(Debug, Clone)] | ||
| 19 | +pub struct Codebook { | ||
| 20 | + /// Values per entry: 1 for a scalar book, more for a VQ book. | ||
| 21 | + pub dimensions: usize, | ||
| 22 | + /// Codeword tree, walked one bit at a time. | ||
| 23 | + tree: Vec<Node>, | ||
| 24 | + /// `entries * dimensions` values, empty when `lookup_type` is 0. | ||
| 25 | + values: Vec<f32>, | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +impl Codebook { | ||
| 29 | + /// Parse one codebook from a setup header (§3.2.1). | ||
| 30 | + pub fn parse(bits: &mut Bits) -> Result<Codebook> { | ||
| 31 | + if bits.read(24) != 0x0056_4342 { | ||
| 32 | + return Err(Error::corrupt("codebook sync pattern")); | ||
| 33 | + } | ||
| 34 | + let dimensions = bits.read(16) as usize; | ||
| 35 | + let entries = bits.read(24) as usize; | ||
| 36 | + if bits.eop() { | ||
| 37 | + return Err(Error::corrupt("codebook header truncated")); | ||
| 38 | + } | ||
| 39 | + if dimensions == 0 || entries == 0 { | ||
| 40 | + return Err(Error::corrupt("empty codebook")); | ||
| 41 | + } | ||
| 42 | + // A book cannot be larger than the packet that describes it: every | ||
| 43 | + // length costs at least one bit, so this is the OOM guard on a header | ||
| 44 | + // that claims 2^24 entries in twenty bytes. | ||
| 45 | + if entries as u64 > bits.remaining() + 64 { | ||
| 46 | + return Err(Error::corrupt("codebook claims more entries than bits")); | ||
| 47 | + } | ||
| 48 | + | ||
| 49 | + let mut lengths = vec![0u8; entries]; | ||
| 50 | + if bits.bit() { | ||
| 51 | + // Ordered: lengths are non-decreasing, stated as run lengths. | ||
| 52 | + let mut entry = 0usize; | ||
| 53 | + let mut length = bits.read(5) + 1; | ||
| 54 | + while entry < entries { | ||
| 55 | + if length > 32 { | ||
| 56 | + return Err(Error::corrupt("ordered codebook overran 32 bits")); | ||
| 57 | + } | ||
| 58 | + let bits_needed = ilog((entries - entry) as u32); | ||
| 59 | + let run = bits.read(bits_needed) as usize; | ||
| 60 | + if entry + run > entries { | ||
| 61 | + return Err(Error::corrupt("ordered codebook run past the end")); | ||
| 62 | + } | ||
| 63 | + lengths[entry..entry + run].fill(length as u8); | ||
| 64 | + entry += run; | ||
| 65 | + length += 1; | ||
| 66 | + if bits.eop() { | ||
| 67 | + return Err(Error::corrupt("ordered codebook truncated")); | ||
| 68 | + } | ||
| 69 | + } | ||
| 70 | + } else { | ||
| 71 | + let sparse = bits.bit(); | ||
| 72 | + for length in lengths.iter_mut() { | ||
| 73 | + if sparse && !bits.bit() { | ||
| 74 | + continue; | ||
| 75 | + } | ||
| 76 | + *length = (bits.read(5) + 1) as u8; | ||
| 77 | + } | ||
| 78 | + if bits.eop() { | ||
| 79 | + return Err(Error::corrupt("codebook lengths truncated")); | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + | ||
| 83 | + let (tree, _) = assign_codes(&lengths)?; | ||
| 84 | + | ||
| 85 | + let lookup_type = bits.read(4); | ||
| 86 | + let values = match lookup_type { | ||
| 87 | + 0 => Vec::new(), | ||
| 88 | + 1 | 2 => { | ||
| 89 | + let minimum = bits.float32(); | ||
| 90 | + let delta = bits.float32(); | ||
| 91 | + let value_bits = bits.read(4) + 1; | ||
| 92 | + let sequence_p = bits.bit(); | ||
| 93 | + let lookup_values = match lookup_type { | ||
| 94 | + 1 => lookup1_values(entries, dimensions), | ||
| 95 | + _ => entries * dimensions, | ||
| 96 | + }; | ||
| 97 | + if bits.eop() || lookup_values as u64 > bits.remaining() + 64 { | ||
| 98 | + return Err(Error::corrupt("codebook lookup truncated")); | ||
| 99 | + } | ||
| 100 | + let multiplicands: Vec<f32> = (0..lookup_values) | ||
| 101 | + .map(|_| bits.read(value_bits) as f32) | ||
| 102 | + .collect(); | ||
| 103 | + expand_lookup( | ||
| 104 | + lookup_type, | ||
| 105 | + entries, | ||
| 106 | + dimensions, | ||
| 107 | + minimum, | ||
| 108 | + delta, | ||
| 109 | + sequence_p, | ||
| 110 | + &multiplicands, | ||
| 111 | + )? | ||
| 112 | + } | ||
| 113 | + other => { | ||
| 114 | + return Err(Error::unsupported( | ||
| 115 | + format!("codebook lookup type {other}"), | ||
| 116 | + "Vorbis I defines 0, 1 and 2", | ||
| 117 | + )); | ||
| 118 | + } | ||
| 119 | + }; | ||
| 120 | + if bits.eop() { | ||
| 121 | + return Err(Error::corrupt("codebook truncated")); | ||
| 122 | + } | ||
| 123 | + | ||
| 124 | + Ok(Codebook { | ||
| 125 | + dimensions, | ||
| 126 | + tree, | ||
| 127 | + values, | ||
| 128 | + }) | ||
| 129 | + } | ||
| 130 | + | ||
| 131 | + /// True when entries carry VQ values, i.e. the book can fill a residue or | ||
| 132 | + /// floor-0 vector rather than only naming a number. | ||
| 133 | + pub fn has_values(&self) -> bool { | ||
| 134 | + !self.values.is_empty() | ||
| 135 | + } | ||
| 136 | + | ||
| 137 | + /// Read one codeword; [`None`] at end of packet or on an undefined path. | ||
| 138 | + pub fn decode_scalar(&self, bits: &mut Bits) -> Option<u32> { | ||
| 139 | + let mut node = 0usize; | ||
| 140 | + loop { | ||
| 141 | + let child = self.tree[node].child[usize::from(bits.bit())]; | ||
| 142 | + if bits.eop() { | ||
| 143 | + return None; | ||
| 144 | + } | ||
| 145 | + match child { | ||
| 146 | + 0 => return None, | ||
| 147 | + c if c < 0 => return Some((-c - 1) as u32), | ||
| 148 | + c => node = c as usize, | ||
| 149 | + } | ||
| 150 | + } | ||
| 151 | + } | ||
| 152 | + | ||
| 153 | + /// Read one codeword and answer its value vector; [`None`] as above. | ||
| 154 | + pub fn decode_vector(&self, bits: &mut Bits) -> Option<&[f32]> { | ||
| 155 | + let entry = self.decode_scalar(bits)? as usize; | ||
| 156 | + self.vector(entry) | ||
| 157 | + } | ||
| 158 | + | ||
| 159 | + /// The value vector of `entry`, when this book has values. | ||
| 160 | + pub fn vector(&self, entry: usize) -> Option<&[f32]> { | ||
| 161 | + let start = entry.checked_mul(self.dimensions)?; | ||
| 162 | + self.values.get(start..start + self.dimensions) | ||
| 163 | + } | ||
| 164 | +} | ||
| 165 | + | ||
| 166 | +/// Greatest `m` with `m^dimensions <= entries` (§9.2.3), computed without | ||
| 167 | +/// `powf` so the boundary case never lands on the wrong side. | ||
| 168 | +pub fn lookup1_values(entries: usize, dimensions: usize) -> usize { | ||
| 169 | + let mut value = 1usize; | ||
| 170 | + loop { | ||
| 171 | + let mut product = 1usize; | ||
| 172 | + let mut overflow = false; | ||
| 173 | + for _ in 0..dimensions { | ||
| 174 | + match product.checked_mul(value + 1) { | ||
| 175 | + Some(p) if p <= entries => product = p, | ||
| 176 | + _ => { | ||
| 177 | + overflow = true; | ||
| 178 | + break; | ||
| 179 | + } | ||
| 180 | + } | ||
| 181 | + } | ||
| 182 | + if overflow { | ||
| 183 | + return value; | ||
| 184 | + } | ||
| 185 | + value += 1; | ||
| 186 | + } | ||
| 187 | +} | ||
| 188 | + | ||
| 189 | +/// Turn multiplicands into one value vector per entry (§3.2.1 "VQ lookup"). | ||
| 190 | +fn expand_lookup( | ||
| 191 | + lookup_type: u32, | ||
| 192 | + entries: usize, | ||
| 193 | + dimensions: usize, | ||
| 194 | + minimum: f32, | ||
| 195 | + delta: f32, | ||
| 196 | + sequence_p: bool, | ||
| 197 | + multiplicands: &[f32], | ||
| 198 | +) -> Result<Vec<f32>> { | ||
| 199 | + let total = entries | ||
| 200 | + .checked_mul(dimensions) | ||
| 201 | + .filter(|n| *n <= 1 << 24) | ||
| 202 | + .ok_or_else(|| Error::corrupt("codebook value table too large"))?; | ||
| 203 | + let mut values = vec![0.0f32; total]; | ||
| 204 | + let lookup_values = multiplicands.len(); | ||
| 205 | + for entry in 0..entries { | ||
| 206 | + let mut last = 0.0f32; | ||
| 207 | + let mut divisor = 1usize; | ||
| 208 | + for i in 0..dimensions { | ||
| 209 | + let offset = match lookup_type { | ||
| 210 | + 1 => (entry / divisor) % lookup_values.max(1), | ||
| 211 | + _ => entry * dimensions + i, | ||
| 212 | + }; | ||
| 213 | + let value = multiplicands.get(offset).copied().unwrap_or(0.0) * delta + minimum + last; | ||
| 214 | + values[entry * dimensions + i] = value; | ||
| 215 | + if sequence_p { | ||
| 216 | + last = value; | ||
| 217 | + } | ||
| 218 | + divisor = divisor.saturating_mul(lookup_values.max(1)); | ||
| 219 | + } | ||
| 220 | + } | ||
| 221 | + Ok(values) | ||
| 222 | +} | ||
| 223 | + | ||
| 224 | +/// `ilog` of §9.2.1: the position of the highest set bit, zero for zero. | ||
| 225 | +pub fn ilog(mut value: u32) -> u32 { | ||
| 226 | + let mut bits = 0; | ||
| 227 | + while value > 0 { | ||
| 228 | + bits += 1; | ||
| 229 | + value >>= 1; | ||
| 230 | + } | ||
| 231 | + bits | ||
| 232 | +} | ||
| 233 | + | ||
| 234 | +/// Codeword assignment (§3.2.1) as a walkable tree, plus the codeword each | ||
| 235 | +/// entry got. | ||
| 236 | +/// | ||
| 237 | +/// The rule is *not* the classic sorted-canonical one: entries are walked in | ||
| 238 | +/// their own order and each takes the first codeword of its length that is | ||
| 239 | +/// still free — so a book whose lengths are not already non-decreasing gets a | ||
| 240 | +/// different assignment than sorting by length would give. (A Laplacian residue | ||
| 241 | +/// book, short codes in the middle and long ones at both ends, is exactly that | ||
| 242 | +/// case; getting it wrong desynchronises every packet while still consuming a | ||
| 243 | +/// plausible number of bits.) | ||
| 244 | +/// | ||
| 245 | +/// An under-populated tree is accepted rather than refused: single-entry books | ||
| 246 | +/// are legal, and streams in the wild (the Xiph `one-entry-codebook` vector | ||
| 247 | +/// among them) lean on the same leniency. What is refused is an *over*-full | ||
| 248 | +/// tree, where an entry has no codeword left to take. | ||
| 249 | +fn assign_codes(lengths: &[u8]) -> Result<(Vec<Node>, Vec<u32>)> { | ||
| 250 | + let mut nodes = vec![Node::default()]; | ||
| 251 | + let mut codes = vec![0u32; lengths.len()]; | ||
| 252 | + for (entry, &length) in lengths.iter().enumerate() { | ||
| 253 | + if length == 0 { | ||
| 254 | + continue; | ||
| 255 | + } | ||
| 256 | + if length > 32 { | ||
| 257 | + return Err(Error::corrupt("codebook codeword longer than 32 bits")); | ||
| 258 | + } | ||
| 259 | + let mut node = 0usize; | ||
| 260 | + let mut code = 0u32; | ||
| 261 | + let mut path: Vec<usize> = Vec::with_capacity(usize::from(length)); | ||
| 262 | + for step in 0..length { | ||
| 263 | + // Depth still to go *below* the branch about to be taken. | ||
| 264 | + let below = length - step - 1; | ||
| 265 | + let branch = (0..2) | ||
| 266 | + .find(|&bit| free_depth(nodes[node].child[bit], &nodes) <= below) | ||
| 267 | + .ok_or_else(|| Error::corrupt("codebook is over-full"))?; | ||
| 268 | + code = (code << 1) | branch as u32; | ||
| 269 | + path.push(node); | ||
| 270 | + match below { | ||
| 271 | + 0 => nodes[node].child[branch] = -((entry as i32) + 1), | ||
| 272 | + _ => { | ||
| 273 | + if nodes[node].child[branch] == 0 { | ||
| 274 | + nodes.push(Node::default()); | ||
| 275 | + nodes[node].child[branch] = (nodes.len() - 1) as i32; | ||
| 276 | + } | ||
| 277 | + node = nodes[node].child[branch] as usize; | ||
| 278 | + } | ||
| 279 | + } | ||
| 280 | + } | ||
| 281 | + // Free depths shrink from the leaf back up to the root. | ||
| 282 | + for &node in path.iter().rev() { | ||
| 283 | + let left = free_depth(nodes[node].child[0], &nodes); | ||
| 284 | + let right = free_depth(nodes[node].child[1], &nodes); | ||
| 285 | + nodes[node].free = left.min(right).saturating_add(1); | ||
| 286 | + } | ||
| 287 | + codes[entry] = code; | ||
| 288 | + } | ||
| 289 | + Ok((nodes, codes)) | ||
| 290 | +} | ||
| 291 | + | ||
| 292 | +/// One node of the codeword tree. | ||
| 293 | +#[derive(Debug, Clone, Copy)] | ||
| 294 | +pub struct Node { | ||
| 295 | + /// Per branch: 0 free, positive a child index, negative the leaf | ||
| 296 | + /// `-(entry + 1)`. | ||
| 297 | + child: [i32; 2], | ||
| 298 | + /// Shallowest free slot in this subtree, 255 when there is none. | ||
| 299 | + free: u8, | ||
| 300 | +} | ||
| 301 | + | ||
| 302 | +impl Default for Node { | ||
| 303 | + fn default() -> Node { | ||
| 304 | + // A fresh node has two free branches, so a codeword can end one step | ||
| 305 | + // below it. | ||
| 306 | + Node { | ||
| 307 | + child: [0, 0], | ||
| 308 | + free: 1, | ||
| 309 | + } | ||
| 310 | + } | ||
| 311 | +} | ||
| 312 | + | ||
| 313 | +/// How far below `slot` the shallowest free slot sits; 255 when full. | ||
| 314 | +fn free_depth(slot: i32, nodes: &[Node]) -> u8 { | ||
| 315 | + match slot { | ||
| 316 | + 0 => 0, | ||
| 317 | + s if s < 0 => 255, | ||
| 318 | + s => nodes[s as usize].free, | ||
| 319 | + } | ||
| 320 | +} | ||
| 321 | + | ||
| 322 | +/// A codebook the encoder designed, kept in the shape the setup-header writer | ||
| 323 | +/// and the packet writer both need: lengths to state, codewords to emit. | ||
| 324 | +#[derive(Debug, Clone)] | ||
| 325 | +pub struct CodebookSpec { | ||
| 326 | + /// Values per entry; 1 for every book this encoder writes. | ||
| 327 | + pub dimensions: usize, | ||
| 328 | + /// Codeword length per entry, all non-zero (no sparse books written). | ||
| 329 | + pub lengths: Vec<u8>, | ||
| 330 | + /// Codeword per entry, MSB-first in `lengths[i]` bits. | ||
| 331 | + pub codes: Vec<u32>, | ||
| 332 | + /// Quantised value per entry when the book carries a lookup, empty for a | ||
| 333 | + /// pure symbol book. | ||
| 334 | + pub values: Vec<f32>, | ||
| 335 | +} | ||
| 336 | + | ||
| 337 | +impl CodebookSpec { | ||
| 338 | + /// Build a book over `weights` (one per entry, a relative frequency). | ||
| 339 | + /// | ||
| 340 | + /// Huffman over the weights, then the canonical assignment the decoder | ||
| 341 | + /// rebuilds from lengths alone. Every entry gets a codeword — a zero weight | ||
| 342 | + /// becomes a long one rather than an absent one, because the encoder must | ||
| 343 | + /// always have *something* to emit for a symbol it can produce. | ||
| 344 | + pub fn huffman(weights: &[f64], values: Vec<f32>) -> CodebookSpec { | ||
| 345 | + let lengths = huffman_lengths(weights); | ||
| 346 | + // The decoder's own rule, run forwards: same order, same choices. | ||
| 347 | + let (_, codes) = assign_codes(&lengths).expect("a Kraft-complete book always assigns"); | ||
| 348 | + CodebookSpec { | ||
| 349 | + dimensions: 1, | ||
| 350 | + lengths, | ||
| 351 | + codes, | ||
| 352 | + values, | ||
| 353 | + } | ||
| 354 | + } | ||
| 355 | + | ||
| 356 | + /// Number of entries. | ||
| 357 | + pub fn entries(&self) -> usize { | ||
| 358 | + self.lengths.len() | ||
| 359 | + } | ||
| 360 | + | ||
| 361 | + /// Emit the codeword for `entry`. | ||
| 362 | + pub fn write(&self, out: &mut BitsOut, entry: usize) { | ||
| 363 | + let length = u32::from(self.lengths[entry]); | ||
| 364 | + let code = self.codes[entry]; | ||
| 365 | + // The stream is LSB-first but a codeword reads MSB-first, so the bits | ||
| 366 | + // go out one at a time from the top. | ||
| 367 | + for depth in (0..length).rev() { | ||
| 368 | + out.bit((code >> depth) & 1 != 0); | ||
| 369 | + } | ||
| 370 | + } | ||
| 371 | +} | ||
| 372 | + | ||
| 373 | +/// Huffman code lengths for `weights`, capped at 24 bits. | ||
| 374 | +/// | ||
| 375 | +/// The cap is enforced by flattening: a weight small enough to earn a 25-bit | ||
| 376 | +/// codeword is raised until it does not. With at most a few hundred entries and | ||
| 377 | +/// weights within a few decades of each other the cap never binds, and when it | ||
| 378 | +/// does the cost is a fraction of a bit on the rarest symbol. | ||
| 379 | +fn huffman_lengths(weights: &[f64]) -> Vec<u8> { | ||
| 380 | + let n = weights.len(); | ||
| 381 | + assert!(n > 0, "a codebook needs at least one entry"); | ||
| 382 | + if n == 1 { | ||
| 383 | + return vec![1]; | ||
| 384 | + } | ||
| 385 | + let floor = weights.iter().cloned().fold(0.0f64, f64::max) / 8_388_608.0; | ||
| 386 | + let mut nodes: Vec<(f64, usize)> = weights | ||
| 387 | + .iter() | ||
| 388 | + .enumerate() | ||
| 389 | + .map(|(i, &w)| (w.max(floor).max(f64::MIN_POSITIVE), i)) | ||
| 390 | + .collect(); | ||
| 391 | + // Leaves first, then merged nodes, tracked as a forest over `parent`. | ||
| 392 | + let mut parent = vec![usize::MAX; n]; | ||
| 393 | + let mut heap: Vec<(f64, usize)> = nodes.clone(); | ||
| 394 | + heap.sort_by(|a, b| b.0.partial_cmp(&a.0).unwrap()); | ||
| 395 | + let mut merged: Vec<(f64, usize)> = Vec::new(); | ||
| 396 | + let mut next_id = n; | ||
| 397 | + while heap.len() + merged.len() > 1 { | ||
| 398 | + let mut take = || -> (f64, usize) { | ||
| 399 | + let from_heap = heap.last().map(|x| x.0); | ||
| 400 | + let from_merged = merged.first().map(|x| x.0); | ||
| 401 | + match (from_heap, from_merged) { | ||
| 402 | + (Some(a), Some(b)) if a <= b => heap.pop().unwrap(), | ||
| 403 | + (Some(_), None) => heap.pop().unwrap(), | ||
| 404 | + _ => merged.remove(0), | ||
| 405 | + } | ||
| 406 | + }; | ||
| 407 | + let (wa, a) = take(); | ||
| 408 | + let (wb, b) = take(); | ||
| 409 | + parent.push(usize::MAX); | ||
| 410 | + parent[a] = next_id; | ||
| 411 | + parent[b] = next_id; | ||
| 412 | + merged.push((wa + wb, next_id)); | ||
| 413 | + next_id += 1; | ||
| 414 | + } | ||
| 415 | + nodes.clear(); | ||
| 416 | + | ||
| 417 | + let mut lengths = vec![0u8; n]; | ||
| 418 | + for (i, length) in lengths.iter_mut().enumerate() { | ||
| 419 | + let mut node = i; | ||
| 420 | + let mut depth = 0u32; | ||
| 421 | + while parent[node] != usize::MAX { | ||
| 422 | + node = parent[node]; | ||
| 423 | + depth += 1; | ||
| 424 | + } | ||
| 425 | + *length = depth.clamp(1, 24) as u8; | ||
| 426 | + } | ||
| 427 | + // Clamping can leave the tree over-full; rebalance by lengthening the | ||
| 428 | + // shallowest entries until Kraft's sum is back at one. | ||
| 429 | + balance(&mut lengths); | ||
| 430 | + lengths | ||
| 431 | +} | ||
| 432 | + | ||
| 433 | +/// Push a length vector to exactly Kraft-complete, so the decoder's canonical | ||
| 434 | +/// rebuild has no ambiguity and no hole. | ||
| 435 | +fn balance(lengths: &mut [u8]) { | ||
| 436 | + let kraft = |lengths: &[u8]| -> f64 { | ||
| 437 | + lengths | ||
| 438 | + .iter() | ||
| 439 | + .map(|&l| 2f64.powi(-i32::from(l))) | ||
| 440 | + .sum::<f64>() | ||
| 441 | + }; | ||
| 442 | + // Over-full: lengthen the shortest codes. | ||
| 443 | + while kraft(lengths) > 1.0 + 1e-12 { | ||
| 444 | + let (index, _) = lengths | ||
| 445 | + .iter() | ||
| 446 | + .enumerate() | ||
| 447 | + .min_by_key(|(_, l)| **l) | ||
| 448 | + .expect("non-empty"); | ||
| 449 | + lengths[index] += 1; | ||
| 450 | + } | ||
| 451 | + // Under-full: shorten the longest, which only ever helps the rare symbols. | ||
| 452 | + loop { | ||
| 453 | + let sum = kraft(lengths); | ||
| 454 | + let (index, &longest) = lengths | ||
| 455 | + .iter() | ||
| 456 | + .enumerate() | ||
| 457 | + .max_by_key(|(_, l)| **l) | ||
| 458 | + .expect("non-empty"); | ||
| 459 | + if longest <= 1 || sum + 2f64.powi(-i32::from(longest)) > 1.0 + 1e-12 { | ||
| 460 | + break; | ||
| 461 | + } | ||
| 462 | + lengths[index] -= 1; | ||
| 463 | + } | ||
| 464 | +} | ||
| 465 | + | ||
| 466 | +#[cfg(test)] | ||
| 467 | +mod tests { | ||
| 468 | + use super::*; | ||
| 469 | + use crate::bits::BitsOut; | ||
| 470 | + | ||
| 471 | + #[test] | ||
| 472 | + fn lookup1_values_matches_the_definition() { | ||
| 473 | + assert_eq!(lookup1_values(1, 1), 1); | ||
| 474 | + assert_eq!(lookup1_values(64, 2), 8); | ||
| 475 | + assert_eq!(lookup1_values(63, 2), 7); | ||
| 476 | + assert_eq!(lookup1_values(1000, 3), 10); | ||
| 477 | + } | ||
| 478 | + | ||
| 479 | + #[test] | ||
| 480 | + fn a_designed_book_decodes_back_through_the_parsed_tree() { | ||
| 481 | + // Skewed weights so the lengths differ, which is what exercises the | ||
| 482 | + // canonical assignment on both sides. | ||
| 483 | + let weights: Vec<f64> = (0..17).map(|i| 1.0 / (1.0 + f64::from(i))).collect(); | ||
| 484 | + let spec = CodebookSpec::huffman(&weights, Vec::new()); | ||
| 485 | + assert_eq!(spec.entries(), 17); | ||
| 486 | + let kraft: f64 = spec.lengths.iter().map(|&l| 2f64.powi(-i32::from(l))).sum(); | ||
| 487 | + assert!((kraft - 1.0).abs() < 1e-9, "kraft sum {kraft}"); | ||
| 488 | + | ||
| 489 | + let mut out = BitsOut::new(); | ||
| 490 | + for entry in 0..spec.entries() { | ||
| 491 | + spec.write(&mut out, entry); | ||
| 492 | + } | ||
| 493 | + let bytes = out.finish(); | ||
| 494 | + | ||
| 495 | + let (tree, _) = assign_codes(&spec.lengths).expect("tree"); | ||
| 496 | + let book = Codebook { | ||
| 497 | + dimensions: 1, | ||
| 498 | + tree, | ||
| 499 | + values: Vec::new(), | ||
| 500 | + }; | ||
| 501 | + let mut bits = Bits::new(&bytes); | ||
| 502 | + for entry in 0..spec.entries() { | ||
| 503 | + assert_eq!(book.decode_scalar(&mut bits), Some(entry as u32)); | ||
| 504 | + } | ||
| 505 | + } | ||
| 506 | +} | ||
crates/ec-vorbis/src/decode.rsadded+464 -0
| @@ -0,0 +1,464 @@ | |||
| 1 | +//! The decoder: header packets in, audio packets in, planar float out. | ||
| 2 | + | ||
| 3 | +use std::collections::VecDeque; | ||
| 4 | + | ||
| 5 | +use ec_core::frame::ChannelPosition::{self, *}; | ||
| 6 | +use ec_core::{ | ||
| 7 | + AudioFrame, AudioParameters, Buf, ChannelLayout, CodecId, CodecParameters, Decoder, Error, | ||
| 8 | + Frame, MediaParameters, Packet, Result, SampleFormat, TimeBase, Timestamp, | ||
| 9 | +}; | ||
| 10 | +use ec_dsp::Mdct; | ||
| 11 | + | ||
| 12 | +use crate::bits::Bits; | ||
| 13 | +use crate::codebook::ilog; | ||
| 14 | +use crate::floor::{self, FloorState}; | ||
| 15 | +use crate::residue; | ||
| 16 | +use crate::setup::{Comments, FloorConfig, Identification, Setup}; | ||
| 17 | +use crate::window::Windows; | ||
| 18 | + | ||
| 19 | +/// Vorbis I decoder. | ||
| 20 | +/// | ||
| 21 | +/// Feed it the three header packets, then audio packets; every audio packet | ||
| 22 | +/// answers the samples that became final when its window closed, which is why | ||
| 23 | +/// the *first* audio packet of a stream answers none — its block only reaches | ||
| 24 | +/// halfway into the first sample the stream states. | ||
| 25 | +pub struct VorbisDecoder { | ||
| 26 | + ident: Identification, | ||
| 27 | + comments: Comments, | ||
| 28 | + setup: Setup, | ||
| 29 | + params: CodecParameters, | ||
| 30 | + layout: ChannelLayout, | ||
| 31 | + /// `to_ec[vorbis channel] = ec-core channel`. | ||
| 32 | + to_ec: Vec<usize>, | ||
| 33 | + windows: Windows, | ||
| 34 | + mdct_short: Mdct<f32>, | ||
| 35 | + mdct_long: Mdct<f32>, | ||
| 36 | + /// Per channel, the overlap-add accumulator, in Vorbis channel order. | ||
| 37 | + lap: Vec<Vec<f32>>, | ||
| 38 | + /// Absolute sample position of `lap[..][0]`. | ||
| 39 | + lap_start: i64, | ||
| 40 | + /// Centre of the block decoded last, absolute; `None` before the first. | ||
| 41 | + centre: Option<i64>, | ||
| 42 | + /// Blocksize of the block decoded last. | ||
| 43 | + previous_n: usize, | ||
| 44 | + /// Samples handed out so far, for the frames' timestamps. | ||
| 45 | + position: i64, | ||
| 46 | + /// Timestamp the next frame carries, when the container stated one. | ||
| 47 | + next_pts: Option<i64>, | ||
| 48 | + frames: VecDeque<Frame>, | ||
| 49 | + drained: bool, | ||
| 50 | +} | ||
| 51 | + | ||
| 52 | +impl VorbisDecoder { | ||
| 53 | + /// Build a decoder from the three header packets, in order. | ||
| 54 | + pub fn new(headers: &[&[u8]]) -> Result<VorbisDecoder> { | ||
| 55 | + let [ident, comment, setup] = headers else { | ||
| 56 | + return Err(Error::corrupt(format!( | ||
| 57 | + "Vorbis needs 3 header packets, got {}", | ||
| 58 | + headers.len() | ||
| 59 | + ))); | ||
| 60 | + }; | ||
| 61 | + let ident = Identification::parse(ident)?; | ||
| 62 | + let comments = Comments::parse(comment)?; | ||
| 63 | + let setup = Setup::parse(setup, &ident)?; | ||
| 64 | + let channels = usize::from(ident.channels); | ||
| 65 | + let (layout, to_ec) = channel_map(channels); | ||
| 66 | + let params = CodecParameters { | ||
| 67 | + codec: CodecId::Vorbis, | ||
| 68 | + media: MediaParameters::Audio(AudioParameters { | ||
| 69 | + sample_rate: ident.rate, | ||
| 70 | + layout: layout.clone(), | ||
| 71 | + format: Some(SampleFormat::F32), | ||
| 72 | + bits_per_sample: None, | ||
| 73 | + }), | ||
| 74 | + extradata: None, | ||
| 75 | + }; | ||
| 76 | + Ok(VorbisDecoder { | ||
| 77 | + windows: Windows::new(ident.blocksize_0, ident.blocksize_1), | ||
| 78 | + mdct_short: Mdct::new(ident.blocksize_0), | ||
| 79 | + mdct_long: Mdct::new(ident.blocksize_1), | ||
| 80 | + lap: vec![Vec::new(); channels], | ||
| 81 | + lap_start: 0, | ||
| 82 | + centre: None, | ||
| 83 | + previous_n: ident.blocksize_1, | ||
| 84 | + position: 0, | ||
| 85 | + next_pts: None, | ||
| 86 | + frames: VecDeque::new(), | ||
| 87 | + drained: false, | ||
| 88 | + ident, | ||
| 89 | + comments, | ||
| 90 | + setup, | ||
| 91 | + params, | ||
| 92 | + layout, | ||
| 93 | + to_ec, | ||
| 94 | + }) | ||
| 95 | + } | ||
| 96 | + | ||
| 97 | + /// Build a decoder from Xiph-laced `extradata`, the form containers carry | ||
| 98 | + /// the three headers in. | ||
| 99 | + pub fn from_extradata(extradata: &[u8]) -> Result<VorbisDecoder> { | ||
| 100 | + let packets = unlace(extradata)?; | ||
| 101 | + let borrowed: Vec<&[u8]> = packets.iter().map(|p| &p[..]).collect(); | ||
| 102 | + VorbisDecoder::new(&borrowed) | ||
| 103 | + } | ||
| 104 | + | ||
| 105 | + /// The identification header's contents. | ||
| 106 | + pub fn identification(&self) -> &Identification { | ||
| 107 | + &self.ident | ||
| 108 | + } | ||
| 109 | + | ||
| 110 | + /// The comment header's contents. | ||
| 111 | + pub fn comments(&self) -> &Comments { | ||
| 112 | + &self.comments | ||
| 113 | + } | ||
| 114 | + | ||
| 115 | + /// Channel layout of the decoded frames. | ||
| 116 | + pub fn layout(&self) -> &ChannelLayout { | ||
| 117 | + &self.layout | ||
| 118 | + } | ||
| 119 | + | ||
| 120 | + /// Decode one audio packet into per-channel samples in ec-core channel | ||
| 121 | + /// order. The first packet of a stream answers empty vectors. | ||
| 122 | + pub fn decode_audio(&mut self, data: &[u8]) -> Result<Vec<Vec<f32>>> { | ||
| 123 | + let channels = usize::from(self.ident.channels); | ||
| 124 | + let mut bits = Bits::new(data); | ||
| 125 | + if bits.bit() { | ||
| 126 | + return Err(Error::corrupt("audio packet flagged as a header")); | ||
| 127 | + } | ||
| 128 | + let mode_bits = ilog(self.setup.modes.len() as u32 - 1); | ||
| 129 | + let mode_index = bits.read(mode_bits) as usize; | ||
| 130 | + let Some(&mode) = self.setup.modes.get(mode_index) else { | ||
| 131 | + return Err(Error::corrupt( | ||
| 132 | + "audio packet names a mode that is not there", | ||
| 133 | + )); | ||
| 134 | + }; | ||
| 135 | + let n = match mode.block_flag { | ||
| 136 | + true => self.ident.blocksize_1, | ||
| 137 | + false => self.ident.blocksize_0, | ||
| 138 | + }; | ||
| 139 | + let half = n / 2; | ||
| 140 | + let (previous_long, next_long) = match mode.block_flag { | ||
| 141 | + true => (bits.bit(), bits.bit()), | ||
| 142 | + false => (true, true), | ||
| 143 | + }; | ||
| 144 | + if bits.eop() { | ||
| 145 | + return Err(Error::corrupt("audio packet header truncated")); | ||
| 146 | + } | ||
| 147 | + | ||
| 148 | + let mapping = &self.setup.mappings[mode.mapping]; | ||
| 149 | + let mut floors = Vec::with_capacity(channels); | ||
| 150 | + let mut no_residue = Vec::with_capacity(channels); | ||
| 151 | + for &submap in mapping.mux.iter().take(channels) { | ||
| 152 | + let state = match &self.setup.floors[mapping.submaps[submap].0] { | ||
| 153 | + FloorConfig::Zero(config) => { | ||
| 154 | + floor::decode_floor0(config, &self.setup.codebooks, &mut bits) | ||
| 155 | + } | ||
| 156 | + FloorConfig::One(config) => { | ||
| 157 | + floor::decode_floor1(config, &self.setup.codebooks, &mut bits) | ||
| 158 | + } | ||
| 159 | + }; | ||
| 160 | + no_residue.push(state.is_unused()); | ||
| 161 | + floors.push(state); | ||
| 162 | + } | ||
| 163 | + // A coupled pair shares its residue, so one live channel keeps both. | ||
| 164 | + for &(magnitude, angle) in &mapping.coupling { | ||
| 165 | + if !no_residue[magnitude] || !no_residue[angle] { | ||
| 166 | + no_residue[magnitude] = false; | ||
| 167 | + no_residue[angle] = false; | ||
| 168 | + } | ||
| 169 | + } | ||
| 170 | + | ||
| 171 | + let mut spectra: Vec<Vec<f32>> = vec![vec![0.0; half]; channels]; | ||
| 172 | + for (index, &(_, residue_index)) in mapping.submaps.iter().enumerate() { | ||
| 173 | + let members: Vec<usize> = (0..channels).filter(|&c| mapping.mux[c] == index).collect(); | ||
| 174 | + if members.is_empty() { | ||
| 175 | + continue; | ||
| 176 | + } | ||
| 177 | + let config = &self.setup.residues[residue_index]; | ||
| 178 | + let skip: Vec<bool> = members.iter().map(|&c| no_residue[c]).collect(); | ||
| 179 | + let mut decoded: Vec<Vec<f32>> = vec![vec![0.0; half]; members.len()]; | ||
| 180 | + if config.kind == 2 { | ||
| 181 | + // Type 2 codes the whole submap as one interleaved vector, so | ||
| 182 | + // it is decoded whole and split afterwards. | ||
| 183 | + let mut interleaved = vec![vec![0.0f32; half * members.len()]]; | ||
| 184 | + let all_skipped = [skip.iter().all(|&s| s)]; | ||
| 185 | + residue::decode( | ||
| 186 | + config, | ||
| 187 | + &self.setup.codebooks, | ||
| 188 | + &mut bits, | ||
| 189 | + &mut interleaved, | ||
| 190 | + &all_skipped, | ||
| 191 | + ); | ||
| 192 | + residue::deinterleave(&interleaved[0], members.len(), &mut decoded); | ||
| 193 | + } else { | ||
| 194 | + residue::decode( | ||
| 195 | + config, | ||
| 196 | + &self.setup.codebooks, | ||
| 197 | + &mut bits, | ||
| 198 | + &mut decoded, | ||
| 199 | + &skip, | ||
| 200 | + ); | ||
| 201 | + } | ||
| 202 | + for (slot, &channel) in members.iter().enumerate() { | ||
| 203 | + spectra[channel] = std::mem::take(&mut decoded[slot]); | ||
| 204 | + } | ||
| 205 | + } | ||
| 206 | + | ||
| 207 | + // §9.4.2 inverse coupling, newest step first. | ||
| 208 | + for &(magnitude, angle) in mapping.coupling.iter().rev() { | ||
| 209 | + // Taken out and put back so the two vectors can be walked in step; | ||
| 210 | + // a coupling step never names one channel twice. | ||
| 211 | + let mut mags = std::mem::take(&mut spectra[magnitude]); | ||
| 212 | + let mut angles = std::mem::take(&mut spectra[angle]); | ||
| 213 | + for (m, a) in mags.iter_mut().zip(angles.iter_mut()) { | ||
| 214 | + let (new_m, new_a) = match (*m > 0.0, *a > 0.0) { | ||
| 215 | + (true, true) => (*m, *m - *a), | ||
| 216 | + (true, false) => (*m + *a, *m), | ||
| 217 | + (false, true) => (*m, *m + *a), | ||
| 218 | + (false, false) => (*m - *a, *m), | ||
| 219 | + }; | ||
| 220 | + *m = new_m; | ||
| 221 | + *a = new_a; | ||
| 222 | + } | ||
| 223 | + spectra[magnitude] = mags; | ||
| 224 | + spectra[angle] = angles; | ||
| 225 | + } | ||
| 226 | + | ||
| 227 | + // Floor times residue, then out of the frequency domain. | ||
| 228 | + let window = self.windows.get(mode.block_flag, previous_long, next_long); | ||
| 229 | + let mdct = match mode.block_flag { | ||
| 230 | + true => &mut self.mdct_long, | ||
| 231 | + false => &mut self.mdct_short, | ||
| 232 | + }; | ||
| 233 | + let mut curve = vec![0.0f32; half]; | ||
| 234 | + let mut block = vec![0.0f32; n]; | ||
| 235 | + let centre = match self.centre { | ||
| 236 | + Some(previous) => previous + (self.previous_n + n) as i64 / 4, | ||
| 237 | + None => { | ||
| 238 | + self.lap_start = 0; | ||
| 239 | + self.lap = vec![vec![0.0; n]; channels]; | ||
| 240 | + n as i64 / 2 | ||
| 241 | + } | ||
| 242 | + }; | ||
| 243 | + let start = centre - n as i64 / 2; | ||
| 244 | + | ||
| 245 | + for channel in 0..channels { | ||
| 246 | + match &floors[channel] { | ||
| 247 | + FloorState::Unused => spectra[channel].fill(0.0), | ||
| 248 | + FloorState::One { y, step2 } => { | ||
| 249 | + let submap = mapping.mux[channel]; | ||
| 250 | + let FloorConfig::One(config) = &self.setup.floors[mapping.submaps[submap].0] | ||
| 251 | + else { | ||
| 252 | + return Err(Error::corrupt("floor type changed between packets")); | ||
| 253 | + }; | ||
| 254 | + floor::render_floor1(config, y, step2, &mut curve); | ||
| 255 | + for (value, &gain) in spectra[channel].iter_mut().zip(curve.iter()) { | ||
| 256 | + *value *= gain; | ||
| 257 | + } | ||
| 258 | + } | ||
| 259 | + FloorState::Zero { | ||
| 260 | + amplitude, | ||
| 261 | + coefficients, | ||
| 262 | + } => { | ||
| 263 | + let submap = mapping.mux[channel]; | ||
| 264 | + let FloorConfig::Zero(config) = &self.setup.floors[mapping.submaps[submap].0] | ||
| 265 | + else { | ||
| 266 | + return Err(Error::corrupt("floor type changed between packets")); | ||
| 267 | + }; | ||
| 268 | + floor::render_floor0(config, *amplitude, coefficients, &mut curve); | ||
| 269 | + for (value, &gain) in spectra[channel].iter_mut().zip(curve.iter()) { | ||
| 270 | + *value *= gain; | ||
| 271 | + } | ||
| 272 | + } | ||
| 273 | + } | ||
| 274 | + // Undo the codec-side normalisation ec-dsp's inverse applies: a | ||
| 275 | + // Vorbis coefficient is already `2/N` of the raw transform, so the | ||
| 276 | + // synthesis here is the plain sum. | ||
| 277 | + for value in spectra[channel].iter_mut() { | ||
| 278 | + *value *= (half / 2) as f32; | ||
| 279 | + } | ||
| 280 | + mdct.inverse_windowed(&spectra[channel], window, &mut block); | ||
| 281 | + let lap = &mut self.lap[channel]; | ||
| 282 | + let offset = (start - self.lap_start).max(0) as usize; | ||
| 283 | + if lap.len() < offset + n { | ||
| 284 | + lap.resize(offset + n, 0.0); | ||
| 285 | + } | ||
| 286 | + // A block starting before what has already been handed out only | ||
| 287 | + // ever reaches back into its own zero run (§4.3.1 puts the slope | ||
| 288 | + // inside the block when the neighbour is shorter), so the skipped | ||
| 289 | + // samples are zeroes by construction. | ||
| 290 | + let skipped = (self.lap_start - start).max(0) as usize; | ||
| 291 | + for i in skipped..n { | ||
| 292 | + lap[offset + i - skipped] += block[i]; | ||
| 293 | + } | ||
| 294 | + } | ||
| 295 | + | ||
| 296 | + let emit = (centre - self.lap_start).max(0) as usize; | ||
| 297 | + let first = self.centre.is_none(); | ||
| 298 | + let mut out = vec![Vec::new(); channels]; | ||
| 299 | + for (channel, lap) in self.lap.iter_mut().enumerate() { | ||
| 300 | + let take = emit.min(lap.len()); | ||
| 301 | + let head: Vec<f32> = lap.drain(..take).collect(); | ||
| 302 | + if !first { | ||
| 303 | + out[self.to_ec[channel]] = head; | ||
| 304 | + } | ||
| 305 | + } | ||
| 306 | + self.lap_start = centre; | ||
| 307 | + self.centre = Some(centre); | ||
| 308 | + self.previous_n = n; | ||
| 309 | + Ok(out) | ||
| 310 | + } | ||
| 311 | + | ||
| 312 | + /// Drop the lapping state after a seek; the next packet starts a new run. | ||
| 313 | + pub fn reset_state(&mut self) { | ||
| 314 | + self.centre = None; | ||
| 315 | + self.lap_start = 0; | ||
| 316 | + self.position = 0; | ||
| 317 | + for lap in &mut self.lap { | ||
| 318 | + lap.clear(); | ||
| 319 | + } | ||
| 320 | + self.frames.clear(); | ||
| 321 | + self.drained = false; | ||
| 322 | + } | ||
| 323 | +} | ||
| 324 | + | ||
| 325 | +/// Vorbis channel order (§4.3.9) mapped onto [`ChannelLayout`]'s order. | ||
| 326 | +/// | ||
| 327 | +/// Vorbis orders a 5.1 stream FL, FC, FR, BL, BR, LFE and a 7.1 stream FL, FC, | ||
| 328 | +/// FR, SL, SR, BL, BR, LFE; this family orders both FL, FR, FC, LFE, ... So the | ||
| 329 | +/// two named surround layouts are permuted on the way out and everything else | ||
| 330 | +/// passes through in the order the stream states, carrying the positions Vorbis | ||
| 331 | +/// names for it. | ||
| 332 | +pub fn channel_map(channels: usize) -> (ChannelLayout, Vec<usize>) { | ||
| 333 | + let positions: &[ChannelPosition] = match channels { | ||
| 334 | + 1 => &[FrontCenter], | ||
| 335 | + 2 => &[FrontLeft, FrontRight], | ||
| 336 | + 3 => &[FrontLeft, FrontCenter, FrontRight], | ||
| 337 | + 4 => &[FrontLeft, FrontRight, BackLeft, BackRight], | ||
| 338 | + 5 => &[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight], | ||
| 339 | + 6 => &[FrontLeft, FrontCenter, FrontRight, BackLeft, BackRight, Lfe], | ||
| 340 | + 7 => &[ | ||
| 341 | + FrontLeft, | ||
| 342 | + FrontCenter, | ||
| 343 | + FrontRight, | ||
| 344 | + SideLeft, | ||
| 345 | + SideRight, | ||
| 346 | + BackCenter, | ||
| 347 | + Lfe, | ||
| 348 | + ], | ||
| 349 | + 8 => &[ | ||
| 350 | + FrontLeft, | ||
| 351 | + FrontCenter, | ||
| 352 | + FrontRight, | ||
| 353 | + SideLeft, | ||
| 354 | + SideRight, | ||
| 355 | + BackLeft, | ||
| 356 | + BackRight, | ||
| 357 | + Lfe, | ||
| 358 | + ], | ||
| 359 | + _ => &[], | ||
| 360 | + }; | ||
| 361 | + match channels { | ||
| 362 | + 1 => (ChannelLayout::Mono, vec![0]), | ||
| 363 | + 2 => (ChannelLayout::Stereo, vec![0, 1]), | ||
| 364 | + 6 => (ChannelLayout::Surround5_1, vec![0, 2, 1, 4, 5, 3]), | ||
| 365 | + 8 => (ChannelLayout::Surround7_1, vec![0, 2, 1, 6, 7, 4, 5, 3]), | ||
| 366 | + n if n <= 8 => (ChannelLayout::Custom(positions.to_vec()), (0..n).collect()), | ||
| 367 | + n => (ChannelLayout::from_count(n), (0..n).collect()), | ||
| 368 | + } | ||
| 369 | +} | ||
| 370 | + | ||
| 371 | +/// The Xiph lacing containers wrap the three headers in. | ||
| 372 | +fn unlace(data: &[u8]) -> Result<Vec<Vec<u8>>> { | ||
| 373 | + let count = *data | ||
| 374 | + .first() | ||
| 375 | + .ok_or_else(|| Error::corrupt("empty Vorbis extradata"))? as usize; | ||
| 376 | + if count != 2 { | ||
| 377 | + return Err(Error::corrupt("Vorbis extradata does not hold 3 packets")); | ||
| 378 | + } | ||
| 379 | + let mut lengths = Vec::with_capacity(2); | ||
| 380 | + let mut pos = 1usize; | ||
| 381 | + for _ in 0..count { | ||
| 382 | + let mut length = 0usize; | ||
| 383 | + loop { | ||
| 384 | + let byte = *data | ||
| 385 | + .get(pos) | ||
| 386 | + .ok_or_else(|| Error::corrupt("Vorbis extradata lacing"))?; | ||
| 387 | + pos += 1; | ||
| 388 | + length += usize::from(byte); | ||
| 389 | + if byte != 255 { | ||
| 390 | + break; | ||
| 391 | + } | ||
| 392 | + } | ||
| 393 | + lengths.push(length); | ||
| 394 | + } | ||
| 395 | + let mut packets = Vec::with_capacity(3); | ||
| 396 | + for length in lengths { | ||
| 397 | + let end = pos | ||
| 398 | + .checked_add(length) | ||
| 399 | + .filter(|end| *end <= data.len()) | ||
| 400 | + .ok_or_else(|| Error::corrupt("Vorbis extradata is shorter than it states"))?; | ||
| 401 | + packets.push(data[pos..end].to_vec()); | ||
| 402 | + pos = end; | ||
| 403 | + } | ||
| 404 | + packets.push(data[pos..].to_vec()); | ||
| 405 | + Ok(packets) | ||
| 406 | +} | ||
| 407 | + | ||
| 408 | +impl Decoder for VorbisDecoder { | ||
| 409 | + fn codec_parameters(&self) -> &CodecParameters { | ||
| 410 | + &self.params | ||
| 411 | + } | ||
| 412 | + | ||
| 413 | + fn send_packet(&mut self, packet: &Packet) -> Result<()> { | ||
| 414 | + let samples = self.decode_audio(&packet.data)?; | ||
| 415 | + if samples.iter().all(Vec::is_empty) { | ||
| 416 | + // The first packet of a run: its block only reaches the first | ||
| 417 | + // sample the stream states, so there is nothing final yet. | ||
| 418 | + self.next_pts = packet.pts; | ||
| 419 | + return Ok(()); | ||
| 420 | + } | ||
| 421 | + let count = samples[0].len(); | ||
| 422 | + let data: Vec<Buf> = samples | ||
| 423 | + .into_iter() | ||
| 424 | + .map(|channel| { | ||
| 425 | + let mut bytes = Vec::with_capacity(channel.len() * 4); | ||
| 426 | + for value in channel { | ||
| 427 | + bytes.extend_from_slice(&value.to_le_bytes()); | ||
| 428 | + } | ||
| 429 | + Buf::from_vec(bytes) | ||
| 430 | + }) | ||
| 431 | + .collect(); | ||
| 432 | + let mut frame = AudioFrame::try_new( | ||
| 433 | + SampleFormat::F32, | ||
| 434 | + true, | ||
| 435 | + self.layout.clone(), | ||
| 436 | + self.ident.rate, | ||
| 437 | + count, | ||
| 438 | + data, | ||
| 439 | + )?; | ||
| 440 | + let base = TimeBase::new(1, i64::from(self.ident.rate)); | ||
| 441 | + frame.pts = Some(Timestamp::new(self.next_pts.unwrap_or(self.position), base)); | ||
| 442 | + self.next_pts = None; | ||
| 443 | + self.position += count as i64; | ||
| 444 | + self.frames.push_back(Frame::Audio(frame)); | ||
| 445 | + Ok(()) | ||
| 446 | + } | ||
| 447 | + | ||
| 448 | + fn receive_frame(&mut self) -> Result<Frame> { | ||
| 449 | + match self.frames.pop_front() { | ||
| 450 | + Some(frame) => Ok(frame), | ||
| 451 | + None if self.drained => Err(Error::Eof), | ||
| 452 | + None => Err(Error::NeedMore), | ||
| 453 | + } | ||
| 454 | + } | ||
| 455 | + | ||
| 456 | + fn flush(&mut self) -> Result<()> { | ||
| 457 | + self.drained = true; | ||
| 458 | + Ok(()) | ||
| 459 | + } | ||
| 460 | + | ||
| 461 | + fn reset(&mut self) { | ||
| 462 | + self.reset_state(); | ||
| 463 | + } | ||
| 464 | +} | ||
crates/ec-vorbis/src/encode.rsadded+1026 -0
| @@ -0,0 +1,1026 @@ | |||
| 1 | +//! The encoder: PCM in, Vorbis packets out, with a setup header written for the | ||
| 2 | +//! stream's own channel layout. | ||
| 3 | +//! | ||
| 4 | +//! ## What the analysis actually is | ||
| 5 | +//! | ||
| 6 | +//! Per block, per channel: an MDCT, a peak magnitude per floor point, a | ||
| 7 | +//! spreading function over those points (a one-pole decay up and down the | ||
| 8 | +//! spectrum, which is the cheap stand-in for a masking curve), an absolute | ||
| 9 | +//! threshold of hearing under it, and a headroom the rate loop moves. The floor | ||
| 10 | +//! that comes out is the quantiser step: the residue is the spectrum divided by | ||
| 11 | +//! the floor and rounded, so headroom in dB *is* precision in bits. That is | ||
| 12 | +//! psychoacoustics-lite and it is stated as such — there is no tonality | ||
| 13 | +//! estimate, no temporal pre-echo control and no per-band bit allocation beyond | ||
| 14 | +//! what the floor implies. | ||
| 15 | +//! | ||
| 16 | +//! ## Codebooks | ||
| 17 | +//! | ||
| 18 | +//! Designed here rather than inherited: a floor book over the folded amplitude | ||
| 19 | +//! range, a class book over partition-class pairs, and four residue books whose | ||
| 20 | +//! ranges (+-1, +-4, +-16, +-127) the partition classifier picks between. All of | ||
| 21 | +//! them are Huffman codes over stated distributions, built at construction and | ||
| 22 | +//! written into every stream's own setup header — which is why this encoder | ||
| 23 | +//! needs no embedded profile and has no channel count it cannot serve. | ||
| 24 | + | ||
| 25 | +use std::collections::VecDeque; | ||
| 26 | + | ||
| 27 | +use ec_core::{ | ||
| 28 | + AudioParameters, Buf, CodecId, CodecParameters, Encoder, Error, Frame, MediaParameters, Packet, | ||
| 29 | + Result, SampleFormat, TimeBase, | ||
| 30 | +}; | ||
| 31 | +use ec_dsp::Mdct; | ||
| 32 | + | ||
| 33 | +use crate::bits::{BitsOut, float32_pack}; | ||
| 34 | +use crate::codebook::{CodebookSpec, ilog}; | ||
| 35 | +use crate::decode::channel_map; | ||
| 36 | +use crate::floor::render_floor1; | ||
| 37 | +use crate::setup::Floor1; | ||
| 38 | +use crate::window; | ||
| 39 | + | ||
| 40 | +/// Long block size; this encoder codes long blocks only. | ||
| 41 | +const BLOCK: usize = 2048; | ||
| 42 | +/// Samples between block centres. | ||
| 43 | +const HOP: usize = BLOCK / 2; | ||
| 44 | +/// Coefficients per block. | ||
| 45 | +const HALF: usize = BLOCK / 2; | ||
| 46 | +/// Coefficients per residue partition. | ||
| 47 | +const PARTITION: usize = 32; | ||
| 48 | +/// Floor X points besides the two endpoints. | ||
| 49 | +const FLOOR_POINTS: usize = 20; | ||
| 50 | +/// Floor values per class. | ||
| 51 | +const FLOOR_CLASS_DIM: usize = 4; | ||
| 52 | +/// Residue classes; class 0 codes nothing at all. | ||
| 53 | +const CLASSES: usize = 5; | ||
| 54 | +/// Vorbis states spectral coefficients on the scale where a full-scale tone is | ||
| 55 | +/// a coefficient of about one, which is what lets the floor table (whose top is | ||
| 56 | +/// exactly 1.0) carry them. That is `2/N` times the unnormalised transform | ||
| 57 | +/// ec-dsp computes, `N` being the coefficient count. | ||
| 58 | +const VORBIS_MDCT_SCALE: f32 = 2.0 / HALF as f32; | ||
| 59 | +/// Largest quantised residue each class's book can state. | ||
| 60 | +const CLASS_RANGE: [i32; CLASSES] = [0, 1, 4, 16, 127]; | ||
| 61 | + | ||
| 62 | +/// How the encoder is set up. | ||
| 63 | +#[derive(Debug, Clone, Copy, PartialEq)] | ||
| 64 | +pub struct EncoderConfig { | ||
| 65 | + /// Sample rate in Hz. | ||
| 66 | + pub sample_rate: u32, | ||
| 67 | + /// Channel count, in [`ec_core::ChannelLayout`] order. | ||
| 68 | + pub channels: u16, | ||
| 69 | + /// Target bitrate. Zero or less runs in pure quality mode. | ||
| 70 | + pub bitrate_bps: i32, | ||
| 71 | + /// Quality on `[0, 1]`: where the rate loop starts, and the fixed setting | ||
| 72 | + /// when `bitrate_bps` is not positive. | ||
| 73 | + pub quality: f32, | ||
| 74 | +} | ||
| 75 | + | ||
| 76 | +impl Default for EncoderConfig { | ||
| 77 | + fn default() -> EncoderConfig { | ||
| 78 | + EncoderConfig { | ||
| 79 | + sample_rate: 48_000, | ||
| 80 | + channels: 2, | ||
| 81 | + bitrate_bps: 128_000, | ||
| 82 | + quality: 0.5, | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | +} | ||
| 86 | + | ||
| 87 | +/// One encoded packet and where it ends. | ||
| 88 | +#[derive(Debug, Clone, PartialEq, Eq)] | ||
| 89 | +pub struct EncodedPacket { | ||
| 90 | + /// Packet payload. | ||
| 91 | + pub data: Vec<u8>, | ||
| 92 | + /// Sample position this packet ends at — the Ogg granule. | ||
| 93 | + pub granule: i64, | ||
| 94 | + /// Samples this packet finalises. | ||
| 95 | + pub samples: i64, | ||
| 96 | +} | ||
| 97 | + | ||
| 98 | +/// Vorbis I encoder. | ||
| 99 | +pub struct VorbisEncoder { | ||
| 100 | + config: EncoderConfig, | ||
| 101 | + params: CodecParameters, | ||
| 102 | + /// `to_vorbis[ec channel] = vorbis channel`. | ||
| 103 | + to_vorbis: Vec<usize>, | ||
| 104 | + headers: Vec<Vec<u8>>, | ||
| 105 | + floor: Floor1, | ||
| 106 | + floor_book: CodebookSpec, | ||
| 107 | + class_book: CodebookSpec, | ||
| 108 | + residue_books: Vec<CodebookSpec>, | ||
| 109 | + /// Absolute threshold of hearing per floor point, in dBFS. | ||
| 110 | + ath: Vec<f64>, | ||
| 111 | + /// Channel pairs coupled by the mapping; empty unless stereo. | ||
| 112 | + coupling: Vec<(usize, usize)>, | ||
| 113 | + mdct: Mdct<f32>, | ||
| 114 | + window: Vec<f32>, | ||
| 115 | + /// Per Vorbis channel, input samples with the first block's left half of | ||
| 116 | + /// zeroes already in front. | ||
| 117 | + buffer: Vec<Vec<f32>>, | ||
| 118 | + /// Input samples taken from the caller. | ||
| 119 | + fed: i64, | ||
| 120 | + /// Blocks already emitted. | ||
| 121 | + blocks: i64, | ||
| 122 | + /// Granule of the packet emitted last. | ||
| 123 | + granule: i64, | ||
| 124 | + /// Headroom under the masking curve, in dB — the rate loop's variable. | ||
| 125 | + headroom: f64, | ||
| 126 | + finished: bool, | ||
| 127 | + packets: VecDeque<EncodedPacket>, | ||
| 128 | +} | ||
| 129 | + | ||
| 130 | +impl VorbisEncoder { | ||
| 131 | + /// Build an encoder and write its three header packets. | ||
| 132 | + pub fn new(config: EncoderConfig) -> Result<VorbisEncoder> { | ||
| 133 | + let channels = usize::from(config.channels); | ||
| 134 | + if channels == 0 || channels > 255 { | ||
| 135 | + return Err(Error::unsupported( | ||
| 136 | + format!("{channels} channels"), | ||
| 137 | + "Vorbis states a channel count in one byte", | ||
| 138 | + )); | ||
| 139 | + } | ||
| 140 | + if config.sample_rate == 0 { | ||
| 141 | + return Err(Error::corrupt("encoder sample rate of zero")); | ||
| 142 | + } | ||
| 143 | + let (layout, to_ec) = channel_map(channels); | ||
| 144 | + let mut to_vorbis = vec![0usize; channels]; | ||
| 145 | + for (vorbis, &ec) in to_ec.iter().enumerate() { | ||
| 146 | + to_vorbis[ec] = vorbis; | ||
| 147 | + } | ||
| 148 | + // Coupling pays for a stereo pair and nothing else here: the surround | ||
| 149 | + // layouts have no two channels that carry the same programme. | ||
| 150 | + let coupling = match channels { | ||
| 151 | + 2 => vec![(0usize, 1usize)], | ||
| 152 | + _ => Vec::new(), | ||
| 153 | + }; | ||
| 154 | + | ||
| 155 | + let floor = build_floor(); | ||
| 156 | + let floor_book = design_floor_book(); | ||
| 157 | + let class_book = design_class_book(); | ||
| 158 | + let residue_books = design_residue_books(); | ||
| 159 | + let ath = floor | ||
| 160 | + .x_list | ||
| 161 | + .iter() | ||
| 162 | + .map(|&x| { | ||
| 163 | + let hz = f64::from(config.sample_rate) * 0.5 * f64::from(x) / HALF as f64; | ||
| 164 | + absolute_threshold(hz) | ||
| 165 | + }) | ||
| 166 | + .collect(); | ||
| 167 | + | ||
| 168 | + let headers = write_headers( | ||
| 169 | + &config, | ||
| 170 | + channels, | ||
| 171 | + &floor, | ||
| 172 | + &floor_book, | ||
| 173 | + &class_book, | ||
| 174 | + &residue_books, | ||
| 175 | + &coupling, | ||
| 176 | + ); | ||
| 177 | + let params = CodecParameters { | ||
| 178 | + codec: CodecId::Vorbis, | ||
| 179 | + media: MediaParameters::Audio(AudioParameters { | ||
| 180 | + sample_rate: config.sample_rate, | ||
| 181 | + layout, | ||
| 182 | + format: Some(SampleFormat::F32), | ||
| 183 | + bits_per_sample: None, | ||
| 184 | + }), | ||
| 185 | + extradata: Some(Buf::from_vec(lace(&headers))), | ||
| 186 | + }; | ||
| 187 | + | ||
| 188 | + let quality = f64::from(config.quality.clamp(0.0, 1.0)); | ||
| 189 | + Ok(VorbisEncoder { | ||
| 190 | + mdct: Mdct::new(BLOCK), | ||
| 191 | + window: window::build(BLOCK, BLOCK, true, true), | ||
| 192 | + // The first block is centred on input sample 0, so its left half is | ||
| 193 | + // the only pre-roll there is and the caller never sees it. | ||
| 194 | + buffer: vec![vec![0.0; HOP]; channels], | ||
| 195 | + fed: 0, | ||
| 196 | + blocks: 0, | ||
| 197 | + granule: 0, | ||
| 198 | + headroom: 4.0 + 26.0 * quality, | ||
| 199 | + finished: false, | ||
| 200 | + packets: VecDeque::new(), | ||
| 201 | + config, | ||
| 202 | + params, | ||
| 203 | + to_vorbis, | ||
| 204 | + headers, | ||
| 205 | + floor, | ||
| 206 | + floor_book, | ||
| 207 | + class_book, | ||
| 208 | + residue_books, | ||
| 209 | + ath, | ||
| 210 | + coupling, | ||
| 211 | + }) | ||
| 212 | + } | ||
| 213 | + | ||
| 214 | + /// The three header packets, in order. | ||
| 215 | + pub fn headers(&self) -> Vec<&[u8]> { | ||
| 216 | + self.headers.iter().map(|h| &h[..]).collect() | ||
| 217 | + } | ||
| 218 | + | ||
| 219 | + /// The three header packets Xiph-laced, the form containers carry. | ||
| 220 | + pub fn extradata(&self) -> Vec<u8> { | ||
| 221 | + lace(&self.headers) | ||
| 222 | + } | ||
| 223 | + | ||
| 224 | + /// Parameters describing the stream, `extradata` included. | ||
| 225 | + pub fn parameters(&self) -> &CodecParameters { | ||
| 226 | + &self.params | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + /// Push planar samples, one slice per channel in [`ec_core::ChannelLayout`] order. | ||
| 230 | + pub fn push_planar(&mut self, channels: &[&[f32]]) -> Result<()> { | ||
| 231 | + if channels.len() != usize::from(self.config.channels) { | ||
| 232 | + return Err(Error::corrupt(format!( | ||
| 233 | + "{} channels pushed into a {}-channel encoder", | ||
| 234 | + channels.len(), | ||
| 235 | + self.config.channels | ||
| 236 | + ))); | ||
| 237 | + } | ||
| 238 | + if self.finished { | ||
| 239 | + return Err(Error::corrupt("samples pushed after finish")); | ||
| 240 | + } | ||
| 241 | + let samples = channels.first().map_or(0, |c| c.len()); | ||
| 242 | + for (ec, data) in channels.iter().enumerate() { | ||
| 243 | + if data.len() != samples { | ||
| 244 | + return Err(Error::corrupt("channels of different lengths")); | ||
| 245 | + } | ||
| 246 | + self.buffer[self.to_vorbis[ec]].extend_from_slice(data); | ||
| 247 | + } | ||
| 248 | + self.fed += samples as i64; | ||
| 249 | + self.encode_ready(); | ||
| 250 | + Ok(()) | ||
| 251 | + } | ||
| 252 | + | ||
| 253 | + /// Push interleaved samples in [`ec_core::ChannelLayout`] order. | ||
| 254 | + pub fn push_interleaved(&mut self, samples: &[f32]) -> Result<()> { | ||
| 255 | + let channels = usize::from(self.config.channels); | ||
| 256 | + if !samples.len().is_multiple_of(channels) { | ||
| 257 | + return Err(Error::corrupt("interleaved push is not a whole frame")); | ||
| 258 | + } | ||
| 259 | + if self.finished { | ||
| 260 | + return Err(Error::corrupt("samples pushed after finish")); | ||
| 261 | + } | ||
| 262 | + for (i, &value) in samples.iter().enumerate() { | ||
| 263 | + self.buffer[self.to_vorbis[i % channels]].push(value); | ||
| 264 | + } | ||
| 265 | + self.fed += (samples.len() / channels) as i64; | ||
| 266 | + self.encode_ready(); | ||
| 267 | + Ok(()) | ||
| 268 | + } | ||
| 269 | + | ||
| 270 | + /// No more input; pad the grid out and encode the tail. | ||
| 271 | + pub fn finish(&mut self) { | ||
| 272 | + if self.finished { | ||
| 273 | + return; | ||
| 274 | + } | ||
| 275 | + self.finished = true; | ||
| 276 | + // Enough blocks for every input sample to sit left of a block centre, | ||
| 277 | + // and enough padding for that last block to be whole. | ||
| 278 | + let last = ((self.fed + HOP as i64 - 1) / HOP as i64).max(1) as usize; | ||
| 279 | + let needed = last * HOP + BLOCK; | ||
| 280 | + for channel in &mut self.buffer { | ||
| 281 | + if channel.len() < needed { | ||
| 282 | + channel.resize(needed, 0.0); | ||
| 283 | + } | ||
| 284 | + } | ||
| 285 | + self.encode_ready(); | ||
| 286 | + } | ||
| 287 | + | ||
| 288 | + /// Take the next packet, or [`Error::Eof`] once the encoder is drained. | ||
| 289 | + pub fn next_packet(&mut self) -> Result<EncodedPacket> { | ||
| 290 | + match self.packets.pop_front() { | ||
| 291 | + Some(packet) => Ok(packet), | ||
| 292 | + None if self.finished => Err(Error::Eof), | ||
| 293 | + None => Err(Error::NeedMore), | ||
| 294 | + } | ||
| 295 | + } | ||
| 296 | + | ||
| 297 | + /// Encode every block the buffer now holds whole. | ||
| 298 | + /// | ||
| 299 | + /// Block `k` is centred on input sample `k * HOP`, and that centre is the | ||
| 300 | + /// granule: the decoder's output reaches exactly there when the block's | ||
| 301 | + /// window closes. The last block's granule is the input's own sample count | ||
| 302 | + /// instead, which is what trims the grid's overshoot off the file. | ||
| 303 | + fn encode_ready(&mut self) { | ||
| 304 | + let channels = usize::from(self.config.channels); | ||
| 305 | + loop { | ||
| 306 | + if self.finished && self.blocks > 0 && self.granule >= self.fed { | ||
| 307 | + break; | ||
| 308 | + } | ||
| 309 | + let start = self.blocks as usize * HOP; | ||
| 310 | + if self.buffer[0].len() < start + BLOCK { | ||
| 311 | + break; | ||
| 312 | + } | ||
| 313 | + let centre = self.blocks * HOP as i64; | ||
| 314 | + let granule = match self.finished { | ||
| 315 | + true => centre.min(self.fed), | ||
| 316 | + false => centre, | ||
| 317 | + }; | ||
| 318 | + let data = self.encode_block(start, channels); | ||
| 319 | + self.packets.push_back(EncodedPacket { | ||
| 320 | + data, | ||
| 321 | + granule, | ||
| 322 | + samples: (granule - self.granule).max(0), | ||
| 323 | + }); | ||
| 324 | + self.granule = granule; | ||
| 325 | + self.blocks += 1; | ||
| 326 | + } | ||
| 327 | + } | ||
| 328 | + | ||
| 329 | + /// One block: analyse, quantise, write. | ||
| 330 | + fn encode_block(&mut self, start: usize, channels: usize) -> Vec<u8> { | ||
| 331 | + let mut spectra: Vec<Vec<f32>> = Vec::with_capacity(channels); | ||
| 332 | + let mut block = vec![0.0f32; BLOCK]; | ||
| 333 | + for channel in 0..channels { | ||
| 334 | + block.copy_from_slice(&self.buffer[channel][start..start + BLOCK]); | ||
| 335 | + let mut coefficients = vec![0.0f32; HALF]; | ||
| 336 | + self.mdct | ||
| 337 | + .forward_windowed(&block, &self.window, &mut coefficients); | ||
| 338 | + for value in coefficients.iter_mut() { | ||
| 339 | + *value *= VORBIS_MDCT_SCALE; | ||
| 340 | + } | ||
| 341 | + spectra.push(coefficients); | ||
| 342 | + } | ||
| 343 | + | ||
| 344 | + // Floor per channel — one shared floor per coupled pair, so the two | ||
| 345 | + // normalised spectra are on the same scale and the angle channel is | ||
| 346 | + // small where the pair agrees. | ||
| 347 | + let mut curves: Vec<Vec<f32>> = vec![Vec::new(); channels]; | ||
| 348 | + let mut floor_values: Vec<Vec<i32>> = vec![Vec::new(); channels]; | ||
| 349 | + let mut coded = vec![false; channels]; | ||
| 350 | + for &(magnitude, angle) in &self.coupling { | ||
| 351 | + let peaks = self.peaks_of(&[&spectra[magnitude], &spectra[angle]]); | ||
| 352 | + let (y, step2) = self.fit_floor(&peaks); | ||
| 353 | + let mut curve = vec![0.0f32; HALF]; | ||
| 354 | + render_floor1(&self.floor, &y, &step2, &mut curve); | ||
| 355 | + curves[magnitude] = curve.clone(); | ||
| 356 | + curves[angle] = curve; | ||
| 357 | + floor_values[magnitude] = y.clone(); | ||
| 358 | + floor_values[angle] = y; | ||
| 359 | + coded[magnitude] = true; | ||
| 360 | + coded[angle] = true; | ||
| 361 | + } | ||
| 362 | + for channel in 0..channels { | ||
| 363 | + if coded[channel] { | ||
| 364 | + continue; | ||
| 365 | + } | ||
| 366 | + let peaks = self.peaks_of(&[&spectra[channel]]); | ||
| 367 | + let (y, step2) = self.fit_floor(&peaks); | ||
| 368 | + let mut curve = vec![0.0f32; HALF]; | ||
| 369 | + render_floor1(&self.floor, &y, &step2, &mut curve); | ||
| 370 | + curves[channel] = curve; | ||
| 371 | + floor_values[channel] = y; | ||
| 372 | + } | ||
| 373 | + | ||
| 374 | + // Normalise, couple, quantise. | ||
| 375 | + let mut quantised: Vec<Vec<i32>> = (0..channels) | ||
| 376 | + .map(|channel| { | ||
| 377 | + spectra[channel] | ||
| 378 | + .iter() | ||
| 379 | + .zip(curves[channel].iter()) | ||
| 380 | + .map(|(&value, &floor)| match floor > 0.0 { | ||
| 381 | + true => value / floor, | ||
| 382 | + false => 0.0, | ||
| 383 | + }) | ||
| 384 | + .map(|normalised| normalised.round() as i32) | ||
| 385 | + .collect::<Vec<i32>>() | ||
| 386 | + }) | ||
| 387 | + .collect(); | ||
| 388 | + for &(magnitude, angle) in &self.coupling { | ||
| 389 | + // Taken out and put back so the pair can be walked in step; a | ||
| 390 | + // coupling step never names one channel twice. | ||
| 391 | + let mut left = std::mem::take(&mut quantised[magnitude]); | ||
| 392 | + let mut right = std::mem::take(&mut quantised[angle]); | ||
| 393 | + for (l, r) in left.iter_mut().zip(right.iter_mut()) { | ||
| 394 | + let (m, a) = couple(*l, *r); | ||
| 395 | + *l = m; | ||
| 396 | + *r = a; | ||
| 397 | + } | ||
| 398 | + quantised[magnitude] = left; | ||
| 399 | + quantised[angle] = right; | ||
| 400 | + } | ||
| 401 | + let limit = CLASS_RANGE[CLASSES - 1]; | ||
| 402 | + for channel in quantised.iter_mut() { | ||
| 403 | + for value in channel.iter_mut() { | ||
| 404 | + *value = (*value).clamp(-limit, limit); | ||
| 405 | + } | ||
| 406 | + } | ||
| 407 | + | ||
| 408 | + let mut out = BitsOut::new(); | ||
| 409 | + out.write(0, 1); | ||
| 410 | + // One mode means `ilog(modes - 1)` is zero bits: there is nothing to | ||
| 411 | + // state. The two window flags follow because the mode is a long block. | ||
| 412 | + out.bit(true); | ||
| 413 | + out.bit(true); | ||
| 414 | + for values in floor_values.iter().take(channels) { | ||
| 415 | + self.write_floor(&mut out, values); | ||
| 416 | + } | ||
| 417 | + self.write_residue(&mut out, &quantised); | ||
| 418 | + let bits = out.len(); | ||
| 419 | + self.update_rate(bits, channels); | ||
| 420 | + out.finish() | ||
| 421 | + } | ||
| 422 | + | ||
| 423 | + /// Peak magnitude around each floor X point, over every channel given. | ||
| 424 | + /// | ||
| 425 | + /// Each point owns the coefficients halfway to its neighbours either side, | ||
| 426 | + /// so the whole spectrum is covered exactly once and a peak between two | ||
| 427 | + /// points still raises the floor that has to carry it. | ||
| 428 | + fn peaks_of(&self, spectra: &[&Vec<f32>]) -> Vec<f64> { | ||
| 429 | + let x = &self.floor.x_list; | ||
| 430 | + x.iter() | ||
| 431 | + .map(|¢re| { | ||
| 432 | + let below = x.iter().filter(|&&o| o < centre).max().copied(); | ||
| 433 | + let above = x.iter().filter(|&&o| o > centre).min().copied(); | ||
| 434 | + let lo = below.map_or(0, |b| ((b + centre) / 2) as usize); | ||
| 435 | + let hi = above.map_or(HALF, |a| ((a + centre) / 2) as usize + 1); | ||
| 436 | + let lo = lo.min(HALF - 1); | ||
| 437 | + let hi = hi.clamp(lo + 1, HALF); | ||
| 438 | + let mut peak = 0.0f64; | ||
| 439 | + for spectrum in spectra { | ||
| 440 | + for &value in &spectrum[lo..hi] { | ||
| 441 | + peak = peak.max(f64::from(value.abs())); | ||
| 442 | + } | ||
| 443 | + } | ||
| 444 | + peak | ||
| 445 | + }) | ||
| 446 | + .collect() | ||
| 447 | + } | ||
| 448 | + | ||
| 449 | + /// Turn peak magnitudes into coded floor amplitudes. | ||
| 450 | + /// | ||
| 451 | + /// Spread first (a masker covers its neighbours), then subtract the rate | ||
| 452 | + /// loop's headroom, then hold the absolute threshold of hearing as a lower | ||
| 453 | + /// bound: below it the residue quantises to zero and costs a class-0 | ||
| 454 | + /// partition. | ||
| 455 | + fn fit_floor(&self, peaks: &[f64]) -> (Vec<i32>, Vec<bool>) { | ||
| 456 | + let mut db: Vec<f64> = peaks | ||
| 457 | + .iter() | ||
| 458 | + .map(|&peak| 20.0 * (peak.max(1e-9)).log10()) | ||
| 459 | + .collect(); | ||
| 460 | + // Frequency order, not coding order: spreading is a fact about the ear. | ||
| 461 | + let order = &self.floor.sorted; | ||
| 462 | + for window in order.windows(2) { | ||
| 463 | + let (previous, current) = (window[0], window[1]); | ||
| 464 | + db[current] = db[current].max(db[previous] - 12.0); | ||
| 465 | + } | ||
| 466 | + for window in order.windows(2).rev() { | ||
| 467 | + let (current, next) = (window[0], window[1]); | ||
| 468 | + db[current] = db[current].max(db[next] - 24.0); | ||
| 469 | + } | ||
| 470 | + let target: Vec<f64> = db | ||
| 471 | + .iter() | ||
| 472 | + .zip(self.ath.iter()) | ||
| 473 | + .map(|(&level, &threshold)| (level - self.headroom).max(threshold)) | ||
| 474 | + .collect(); | ||
| 475 | + let y: Vec<i32> = target | ||
| 476 | + .iter() | ||
| 477 | + .map(|&level| ((level / (140.0 / 256.0)).round() as i32 + 255).clamp(0, 255)) | ||
| 478 | + .collect(); | ||
| 479 | + self.fold_floor(&y) | ||
| 480 | + } | ||
| 481 | + | ||
| 482 | + /// Run the decoder's own amplitude synthesis forwards, so the curve the | ||
| 483 | + /// encoder normalises against is the curve the decoder will draw. | ||
| 484 | + fn fold_floor(&self, wanted: &[i32]) -> (Vec<i32>, Vec<bool>) { | ||
| 485 | + let values = wanted.len(); | ||
| 486 | + let range = 256i32; | ||
| 487 | + let mut final_y = vec![0i32; values]; | ||
| 488 | + let mut step2 = vec![false; values]; | ||
| 489 | + final_y[0] = wanted[0]; | ||
| 490 | + final_y[1] = wanted[1]; | ||
| 491 | + step2[0] = true; | ||
| 492 | + step2[1] = true; | ||
| 493 | + for i in 2..values { | ||
| 494 | + let (low, high) = self.floor.neighbours[i]; | ||
| 495 | + let predicted = predict( | ||
| 496 | + self.floor.x_list[low], | ||
| 497 | + final_y[low], | ||
| 498 | + self.floor.x_list[high], | ||
| 499 | + final_y[high], | ||
| 500 | + self.floor.x_list[i], | ||
| 501 | + ); | ||
| 502 | + let value = fold(predicted, wanted[i], range); | ||
| 503 | + if value != 0 { | ||
| 504 | + step2[low] = true; | ||
| 505 | + step2[high] = true; | ||
| 506 | + step2[i] = true; | ||
| 507 | + } | ||
| 508 | + final_y[i] = wanted[i]; | ||
| 509 | + } | ||
| 510 | + (final_y, step2) | ||
| 511 | + } | ||
| 512 | + | ||
| 513 | + /// Write one channel's floor: the two endpoints raw, the rest folded | ||
| 514 | + /// against their neighbours and Huffman coded. | ||
| 515 | + fn write_floor(&self, out: &mut BitsOut, y: &[i32]) { | ||
| 516 | + out.bit(true); | ||
| 517 | + out.write(y[0] as u32, 8); | ||
| 518 | + out.write(y[1] as u32, 8); | ||
| 519 | + for i in 2..y.len() { | ||
| 520 | + let (low, high) = self.floor.neighbours[i]; | ||
| 521 | + let predicted = predict( | ||
| 522 | + self.floor.x_list[low], | ||
| 523 | + y[low], | ||
| 524 | + self.floor.x_list[high], | ||
| 525 | + y[high], | ||
| 526 | + self.floor.x_list[i], | ||
| 527 | + ); | ||
| 528 | + let value = fold(predicted, y[i], 256); | ||
| 529 | + self.floor_book.write(out, value as usize); | ||
| 530 | + } | ||
| 531 | + } | ||
| 532 | + | ||
| 533 | + /// Write the residue: one type-2 interleaved vector over every channel, | ||
| 534 | + /// classified per partition and coded in one pass. | ||
| 535 | + fn write_residue(&self, out: &mut BitsOut, quantised: &[Vec<i32>]) { | ||
| 536 | + let channels = quantised.len(); | ||
| 537 | + let total = HALF * channels; | ||
| 538 | + let mut interleaved = vec![0i32; total]; | ||
| 539 | + for (i, slot) in interleaved.iter_mut().enumerate() { | ||
| 540 | + *slot = quantised[i % channels][i / channels]; | ||
| 541 | + } | ||
| 542 | + let partitions = total / PARTITION; | ||
| 543 | + let classes: Vec<usize> = (0..partitions) | ||
| 544 | + .map(|partition| { | ||
| 545 | + let slice = &interleaved[partition * PARTITION..(partition + 1) * PARTITION]; | ||
| 546 | + let peak = slice.iter().map(|v| v.abs()).max().unwrap_or(0); | ||
| 547 | + CLASS_RANGE | ||
| 548 | + .iter() | ||
| 549 | + .position(|&range| peak <= range) | ||
| 550 | + .unwrap_or(CLASSES - 1) | ||
| 551 | + }) | ||
| 552 | + .collect(); | ||
| 553 | + let per_word = self.class_book.dimensions; | ||
| 554 | + let mut partition = 0usize; | ||
| 555 | + while partition < partitions { | ||
| 556 | + let mut word = 0usize; | ||
| 557 | + for i in 0..per_word { | ||
| 558 | + word = word * CLASSES + classes.get(partition + i).copied().unwrap_or(0); | ||
| 559 | + } | ||
| 560 | + self.class_book.write(out, word); | ||
| 561 | + for _ in 0..per_word { | ||
| 562 | + if partition >= partitions { | ||
| 563 | + break; | ||
| 564 | + } | ||
| 565 | + let class = classes[partition]; | ||
| 566 | + if class > 0 { | ||
| 567 | + let book = &self.residue_books[class - 1]; | ||
| 568 | + let range = CLASS_RANGE[class]; | ||
| 569 | + for &value in &interleaved[partition * PARTITION..(partition + 1) * PARTITION] { | ||
| 570 | + book.write(out, (value.clamp(-range, range) + range) as usize); | ||
| 571 | + } | ||
| 572 | + } | ||
| 573 | + partition += 1; | ||
| 574 | + } | ||
| 575 | + } | ||
| 576 | + } | ||
| 577 | + | ||
| 578 | + /// Move the headroom so the running bitrate meets the target. | ||
| 579 | + /// | ||
| 580 | + /// One dB of headroom is about one sixth of a bit per coefficient, so the | ||
| 581 | + /// step is the bit error divided by that — a proportional loop that settles | ||
| 582 | + /// within a few blocks and is clamped either side so a transient cannot | ||
| 583 | + /// swing the whole file. | ||
| 584 | + fn update_rate(&mut self, bits: u64, channels: usize) { | ||
| 585 | + if self.config.bitrate_bps <= 0 { | ||
| 586 | + return; | ||
| 587 | + } | ||
| 588 | + let target = | ||
| 589 | + f64::from(self.config.bitrate_bps) * HOP as f64 / f64::from(self.config.sample_rate); | ||
| 590 | + let coefficients = (HALF * channels) as f64; | ||
| 591 | + let step = ((target - bits as f64) / (coefficients / 6.0)).clamp(-2.0, 2.0); | ||
| 592 | + // Negative headroom is not a mistake: it puts the floor *above* the | ||
| 593 | + // signal, which quantises the coefficients under it to zero and lets a | ||
| 594 | + // whole partition become class 0 for two bits. Without that a low target | ||
| 595 | + // cannot be reached at all — coding every coefficient with the shortest | ||
| 596 | + // codeword there is already costs about a bit each. | ||
| 597 | + self.headroom = (self.headroom + step).clamp(-24.0, 36.0); | ||
| 598 | + } | ||
| 599 | +} | ||
| 600 | + | ||
| 601 | +/// Forward square-polar coupling (§9.4.2 run backwards). | ||
| 602 | +fn couple(left: i32, right: i32) -> (i32, i32) { | ||
| 603 | + match left > 0 { | ||
| 604 | + true => match left > right { | ||
| 605 | + true => (left, left - right), | ||
| 606 | + false => (right, left - right), | ||
| 607 | + }, | ||
| 608 | + false => match right > left { | ||
| 609 | + true => (left, right - left), | ||
| 610 | + false => (right, right - left), | ||
| 611 | + }, | ||
| 612 | + } | ||
| 613 | +} | ||
| 614 | + | ||
| 615 | +/// §7.2.2 `render_point`, which both sides of the floor coding need. | ||
| 616 | +fn predict(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 { | ||
| 617 | + let dy = y1 - y0; | ||
| 618 | + let adx = (x1 - x0) as i32; | ||
| 619 | + let ady = dy.abs(); | ||
| 620 | + let off = (ady * (x - x0) as i32) / adx; | ||
| 621 | + match dy < 0 { | ||
| 622 | + true => y0 - off, | ||
| 623 | + false => y0 + off, | ||
| 624 | + } | ||
| 625 | +} | ||
| 626 | + | ||
| 627 | +/// The exact inverse of §7.2.3's amplitude synthesis: the value to code so the | ||
| 628 | +/// decoder lands on `wanted`. | ||
| 629 | +fn fold(predicted: i32, wanted: i32, range: i32) -> i32 { | ||
| 630 | + let high_room = range - predicted; | ||
| 631 | + let low_room = predicted; | ||
| 632 | + let room = high_room.min(low_room) * 2; | ||
| 633 | + let delta = wanted - predicted; | ||
| 634 | + if delta == 0 { | ||
| 635 | + return 0; | ||
| 636 | + } | ||
| 637 | + if delta > 0 && 2 * delta < room { | ||
| 638 | + return 2 * delta; | ||
| 639 | + } | ||
| 640 | + if delta < 0 && -2 * delta - 1 < room { | ||
| 641 | + return -2 * delta - 1; | ||
| 642 | + } | ||
| 643 | + match high_room > low_room { | ||
| 644 | + true => wanted - predicted + low_room, | ||
| 645 | + false => predicted - wanted + high_room - 1, | ||
| 646 | + } | ||
| 647 | +} | ||
| 648 | + | ||
| 649 | +/// The floor-1 configuration this encoder writes and renders against. | ||
| 650 | +fn build_floor() -> Floor1 { | ||
| 651 | + let mut sorted_x: Vec<u32> = Vec::with_capacity(FLOOR_POINTS); | ||
| 652 | + let mut last = 0u32; | ||
| 653 | + for i in 0..FLOOR_POINTS { | ||
| 654 | + let t = i as f64 / (FLOOR_POINTS - 1) as f64; | ||
| 655 | + // Log spacing over the band, nudged to stay strictly increasing at the | ||
| 656 | + // bottom where the grid is finer than one coefficient. | ||
| 657 | + let value = (1023f64).powf(t).round() as u32; | ||
| 658 | + last = value.max(last + 1); | ||
| 659 | + sorted_x.push(last); | ||
| 660 | + } | ||
| 661 | + // Coding order: endpoints first, then repeated bisection, so every value is | ||
| 662 | + // predicted from the two coded values that bracket it most closely. | ||
| 663 | + let mut x_list = vec![0u32, HALF as u32]; | ||
| 664 | + let mut ranges = vec![(0usize, sorted_x.len())]; | ||
| 665 | + while let Some((lo, hi)) = ranges.pop() { | ||
| 666 | + if lo >= hi { | ||
| 667 | + continue; | ||
| 668 | + } | ||
| 669 | + let mid = (lo + hi) / 2; | ||
| 670 | + x_list.push(sorted_x[mid]); | ||
| 671 | + ranges.insert(0, (lo, mid)); | ||
| 672 | + ranges.insert(0, (mid + 1, hi)); | ||
| 673 | + } | ||
| 674 | + let values = x_list.len(); | ||
| 675 | + let mut sorted: Vec<usize> = (0..values).collect(); | ||
| 676 | + sorted.sort_by_key(|&i| x_list[i]); | ||
| 677 | + let neighbours = (0..values) | ||
| 678 | + .map(|i| { | ||
| 679 | + let mut low = 0usize; | ||
| 680 | + let mut high = 0usize; | ||
| 681 | + let mut low_x = None; | ||
| 682 | + let mut high_x = None; | ||
| 683 | + for j in 0..i { | ||
| 684 | + if x_list[j] < x_list[i] && low_x.is_none_or(|b| x_list[j] > b) { | ||
| 685 | + low = j; | ||
| 686 | + low_x = Some(x_list[j]); | ||
| 687 | + } | ||
| 688 | + if x_list[j] > x_list[i] && high_x.is_none_or(|b| x_list[j] < b) { | ||
| 689 | + high = j; | ||
| 690 | + high_x = Some(x_list[j]); | ||
| 691 | + } | ||
| 692 | + } | ||
| 693 | + (low, high) | ||
| 694 | + }) | ||
| 695 | + .collect(); | ||
| 696 | + let partitions = (values - 2) / FLOOR_CLASS_DIM; | ||
| 697 | + Floor1 { | ||
| 698 | + partition_classes: vec![0; partitions], | ||
| 699 | + class_dimensions: vec![FLOOR_CLASS_DIM], | ||
| 700 | + class_subclasses: vec![0], | ||
| 701 | + class_masterbooks: vec![0], | ||
| 702 | + subclass_books: vec![vec![0]], | ||
| 703 | + multiplier: 1, | ||
| 704 | + x_list, | ||
| 705 | + sorted, | ||
| 706 | + neighbours, | ||
| 707 | + } | ||
| 708 | +} | ||
| 709 | + | ||
| 710 | +/// Folded floor amplitudes: mostly small corrections, occasionally an escape | ||
| 711 | +/// near the top of the range. | ||
| 712 | +fn design_floor_book() -> CodebookSpec { | ||
| 713 | + let weights: Vec<f64> = (0..256) | ||
| 714 | + .map(|v| (-(f64::from(v)) / 7.0).exp() + 0.002) | ||
| 715 | + .collect(); | ||
| 716 | + CodebookSpec::huffman(&weights, Vec::new()) | ||
| 717 | +} | ||
| 718 | + | ||
| 719 | +/// Class pairs, on the assumption that most partitions are silent. | ||
| 720 | +fn design_class_book() -> CodebookSpec { | ||
| 721 | + let per_class = [0.55f64, 0.20, 0.15, 0.08, 0.02]; | ||
| 722 | + let mut weights = Vec::with_capacity(CLASSES * CLASSES); | ||
| 723 | + for first in per_class { | ||
| 724 | + for second in per_class { | ||
| 725 | + weights.push(first * second); | ||
| 726 | + } | ||
| 727 | + } | ||
| 728 | + let mut spec = CodebookSpec::huffman(&weights, Vec::new()); | ||
| 729 | + spec.dimensions = 2; | ||
| 730 | + spec | ||
| 731 | +} | ||
| 732 | + | ||
| 733 | +/// One book per non-silent class, Laplacian over its own range. | ||
| 734 | +fn design_residue_books() -> Vec<CodebookSpec> { | ||
| 735 | + CLASS_RANGE[1..] | ||
| 736 | + .iter() | ||
| 737 | + .map(|&range| { | ||
| 738 | + let sigma = f64::from(range).max(1.0) / 2.5; | ||
| 739 | + let weights: Vec<f64> = (-range..=range) | ||
| 740 | + .map(|v| (-f64::from(v.abs()) / sigma).exp() + 1e-4) | ||
| 741 | + .collect(); | ||
| 742 | + let values: Vec<f32> = (-range..=range).map(|v| v as f32).collect(); | ||
| 743 | + CodebookSpec::huffman(&weights, values) | ||
| 744 | + }) | ||
| 745 | + .collect() | ||
| 746 | +} | ||
| 747 | + | ||
| 748 | +/// Absolute threshold of hearing in dBFS, full scale taken as 96 dB SPL. | ||
| 749 | +fn absolute_threshold(hz: f64) -> f64 { | ||
| 750 | + let khz = (hz / 1000.0).clamp(0.02, 20.0); | ||
| 751 | + let spl = | ||
| 752 | + 3.64 * khz.powf(-0.8) - 6.5 * (-0.6 * (khz - 3.3).powi(2)).exp() + 0.001 * khz.powi(4); | ||
| 753 | + (spl - 96.0).clamp(-120.0, -10.0) | ||
| 754 | +} | ||
| 755 | + | ||
| 756 | +/// The three header packets, in order. | ||
| 757 | +fn write_headers( | ||
| 758 | + config: &EncoderConfig, | ||
| 759 | + channels: usize, | ||
| 760 | + floor: &Floor1, | ||
| 761 | + floor_book: &CodebookSpec, | ||
| 762 | + class_book: &CodebookSpec, | ||
| 763 | + residue_books: &[CodebookSpec], | ||
| 764 | + coupling: &[(usize, usize)], | ||
| 765 | +) -> Vec<Vec<u8>> { | ||
| 766 | + let mut ident = vec![1u8]; | ||
| 767 | + ident.extend_from_slice(b"vorbis"); | ||
| 768 | + ident.extend_from_slice(&0u32.to_le_bytes()); | ||
| 769 | + ident.push(channels as u8); | ||
| 770 | + ident.extend_from_slice(&config.sample_rate.to_le_bytes()); | ||
| 771 | + ident.extend_from_slice(&0i32.to_le_bytes()); | ||
| 772 | + ident.extend_from_slice(&config.bitrate_bps.max(0).to_le_bytes()); | ||
| 773 | + ident.extend_from_slice(&0i32.to_le_bytes()); | ||
| 774 | + let log2 = |n: usize| n.trailing_zeros() as u8; | ||
| 775 | + ident.push(log2(BLOCK) | (log2(BLOCK) << 4)); | ||
| 776 | + ident.push(1); | ||
| 777 | + | ||
| 778 | + let mut comment = vec![3u8]; | ||
| 779 | + comment.extend_from_slice(b"vorbis"); | ||
| 780 | + let vendor = b"ec-vorbis"; | ||
| 781 | + comment.extend_from_slice(&(vendor.len() as u32).to_le_bytes()); | ||
| 782 | + comment.extend_from_slice(vendor); | ||
| 783 | + comment.extend_from_slice(&0u32.to_le_bytes()); | ||
| 784 | + comment.push(1); | ||
| 785 | + | ||
| 786 | + let mut out = BitsOut::new(); | ||
| 787 | + for byte in [5u8].iter().chain(b"vorbis") { | ||
| 788 | + out.write(u32::from(*byte), 8); | ||
| 789 | + } | ||
| 790 | + let books: Vec<&CodebookSpec> = std::iter::once(floor_book) | ||
| 791 | + .chain(std::iter::once(class_book)) | ||
| 792 | + .chain(residue_books.iter()) | ||
| 793 | + .collect(); | ||
| 794 | + out.write(books.len() as u32 - 1, 8); | ||
| 795 | + for book in &books { | ||
| 796 | + write_codebook(&mut out, book); | ||
| 797 | + } | ||
| 798 | + // One time-domain transform, stated as zero. | ||
| 799 | + out.write(0, 6); | ||
| 800 | + out.write(0, 16); | ||
| 801 | + // One floor, type 1. | ||
| 802 | + out.write(0, 6); | ||
| 803 | + out.write(1, 16); | ||
| 804 | + out.write(floor.partition_classes.len() as u32, 5); | ||
| 805 | + for _ in &floor.partition_classes { | ||
| 806 | + out.write(0, 4); | ||
| 807 | + } | ||
| 808 | + out.write(FLOOR_CLASS_DIM as u32 - 1, 3); | ||
| 809 | + out.write(0, 2); | ||
| 810 | + // Book number plus one; zero would mean "this subclass codes nothing". | ||
| 811 | + out.write(1, 8); | ||
| 812 | + out.write(0, 2); | ||
| 813 | + let range_bits = ilog(HALF as u32) - 1; | ||
| 814 | + out.write(range_bits, 4); | ||
| 815 | + for &x in floor.x_list.iter().skip(2) { | ||
| 816 | + out.write(x, range_bits); | ||
| 817 | + } | ||
| 818 | + // One residue, type 2, over every channel of the one submap. | ||
| 819 | + out.write(0, 6); | ||
| 820 | + out.write(2, 16); | ||
| 821 | + out.write(0, 24); | ||
| 822 | + out.write((HALF * channels) as u32, 24); | ||
| 823 | + out.write(PARTITION as u32 - 1, 24); | ||
| 824 | + out.write(CLASSES as u32 - 1, 6); | ||
| 825 | + out.write(1, 8); | ||
| 826 | + for class in 0..CLASSES { | ||
| 827 | + // Class 0 codes nothing at all; the rest have one book in pass 0. | ||
| 828 | + out.write(u32::from(class > 0), 3); | ||
| 829 | + out.write(0, 1); | ||
| 830 | + } | ||
| 831 | + for class in 1..CLASSES { | ||
| 832 | + out.write(class as u32 + 1, 8); | ||
| 833 | + } | ||
| 834 | + // One mapping, type 0. | ||
| 835 | + out.write(0, 6); | ||
| 836 | + out.write(0, 16); | ||
| 837 | + out.write(0, 1); | ||
| 838 | + match coupling.is_empty() { | ||
| 839 | + true => out.write(0, 1), | ||
| 840 | + false => { | ||
| 841 | + out.write(1, 1); | ||
| 842 | + out.write(coupling.len() as u32 - 1, 8); | ||
| 843 | + let field = ilog(channels as u32 - 1); | ||
| 844 | + for &(magnitude, angle) in coupling { | ||
| 845 | + out.write(magnitude as u32, field); | ||
| 846 | + out.write(angle as u32, field); | ||
| 847 | + } | ||
| 848 | + } | ||
| 849 | + } | ||
| 850 | + out.write(0, 2); | ||
| 851 | + out.write(0, 8); | ||
| 852 | + out.write(0, 8); | ||
| 853 | + out.write(0, 8); | ||
| 854 | + // One mode: a long block on mapping 0. | ||
| 855 | + out.write(0, 6); | ||
| 856 | + out.write(1, 1); | ||
| 857 | + out.write(0, 16); | ||
| 858 | + out.write(0, 16); | ||
| 859 | + out.write(0, 8); | ||
| 860 | + out.write(1, 1); | ||
| 861 | + let setup = out.finish(); | ||
| 862 | + | ||
| 863 | + vec![ident, comment, setup] | ||
| 864 | +} | ||
| 865 | + | ||
| 866 | +/// One codebook in setup-header form: flat lengths, and a scalar lookup when | ||
| 867 | +/// the book carries values. | ||
| 868 | +fn write_codebook(out: &mut BitsOut, book: &CodebookSpec) { | ||
| 869 | + out.write(0x0056_4342, 24); | ||
| 870 | + out.write(book.dimensions as u32, 16); | ||
| 871 | + out.write(book.entries() as u32, 24); | ||
| 872 | + out.write(0, 1); | ||
| 873 | + out.write(0, 1); | ||
| 874 | + for &length in &book.lengths { | ||
| 875 | + out.write(u32::from(length) - 1, 5); | ||
| 876 | + } | ||
| 877 | + if book.values.is_empty() { | ||
| 878 | + out.write(0, 4); | ||
| 879 | + return; | ||
| 880 | + } | ||
| 881 | + // Lookup type 1 with one dimension: the entry number *is* the index, so | ||
| 882 | + // `minimum + i * delta` states every value in `ilog(entries)` bits each. | ||
| 883 | + out.write(1, 4); | ||
| 884 | + let minimum = book.values[0]; | ||
| 885 | + out.write(float32_pack(minimum), 32); | ||
| 886 | + out.write(float32_pack(1.0), 32); | ||
| 887 | + let value_bits = ilog(book.entries() as u32 - 1).max(1); | ||
| 888 | + out.write(value_bits - 1, 4); | ||
| 889 | + out.write(0, 1); | ||
| 890 | + for i in 0..book.entries() { | ||
| 891 | + out.write(i as u32, value_bits); | ||
| 892 | + } | ||
| 893 | +} | ||
| 894 | + | ||
| 895 | +/// Xiph lacing of the three headers, the form containers carry them in. | ||
| 896 | +fn lace(headers: &[Vec<u8>]) -> Vec<u8> { | ||
| 897 | + let mut out = vec![2u8]; | ||
| 898 | + for header in headers.iter().take(headers.len() - 1) { | ||
| 899 | + let mut length = header.len(); | ||
| 900 | + while length >= 255 { | ||
| 901 | + out.push(255); | ||
| 902 | + length -= 255; | ||
| 903 | + } | ||
| 904 | + out.push(length as u8); | ||
| 905 | + } | ||
| 906 | + for header in headers { | ||
| 907 | + out.extend_from_slice(header); | ||
| 908 | + } | ||
| 909 | + out | ||
| 910 | +} | ||
| 911 | + | ||
| 912 | +impl Encoder for VorbisEncoder { | ||
| 913 | + fn codec_parameters(&self) -> &CodecParameters { | ||
| 914 | + &self.params | ||
| 915 | + } | ||
| 916 | + | ||
| 917 | + fn send_frame(&mut self, frame: &Frame) -> Result<()> { | ||
| 918 | + let Frame::Audio(audio) = frame else { | ||
| 919 | + return Err(Error::corrupt("video frame pushed into an audio encoder")); | ||
| 920 | + }; | ||
| 921 | + if audio.format != SampleFormat::F32 { | ||
| 922 | + return Err(Error::unsupported( | ||
| 923 | + format!("{:?} input", audio.format), | ||
| 924 | + "this encoder takes 32-bit float samples", | ||
| 925 | + )); | ||
| 926 | + } | ||
| 927 | + let channels = usize::from(self.config.channels); | ||
| 928 | + let mut planes: Vec<Vec<f32>> = vec![Vec::with_capacity(audio.samples); channels]; | ||
| 929 | + match audio.planar { | ||
| 930 | + true => { | ||
| 931 | + for (channel, plane) in audio.data.iter().enumerate().take(channels) { | ||
| 932 | + planes[channel] = floats(plane, audio.samples); | ||
| 933 | + } | ||
| 934 | + } | ||
| 935 | + false => { | ||
| 936 | + let interleaved = floats(&audio.data[0], audio.samples * channels); | ||
| 937 | + for (i, value) in interleaved.into_iter().enumerate() { | ||
| 938 | + planes[i % channels].push(value); | ||
| 939 | + } | ||
| 940 | + } | ||
| 941 | + } | ||
| 942 | + let borrowed: Vec<&[f32]> = planes.iter().map(|p| &p[..]).collect(); | ||
| 943 | + self.push_planar(&borrowed) | ||
| 944 | + } | ||
| 945 | + | ||
| 946 | + fn receive_packet(&mut self) -> Result<Packet> { | ||
| 947 | + let encoded = self.next_packet()?; | ||
| 948 | + let base = TimeBase::new(1, i64::from(self.config.sample_rate)); | ||
| 949 | + let mut packet = Packet::new(0, base, encoded.data); | ||
| 950 | + packet.pts = Some(encoded.granule - encoded.samples); | ||
| 951 | + packet.duration = Some(encoded.samples); | ||
| 952 | + Ok(packet) | ||
| 953 | + } | ||
| 954 | + | ||
| 955 | + fn flush(&mut self) -> Result<()> { | ||
| 956 | + self.finish(); | ||
| 957 | + Ok(()) | ||
| 958 | + } | ||
| 959 | +} | ||
| 960 | + | ||
| 961 | +/// Little-endian floats out of a plane. | ||
| 962 | +fn floats(plane: &Buf, count: usize) -> Vec<f32> { | ||
| 963 | + plane | ||
| 964 | + .chunks_exact(4) | ||
| 965 | + .take(count) | ||
| 966 | + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) | ||
| 967 | + .collect() | ||
| 968 | +} | ||
| 969 | + | ||
| 970 | +#[cfg(test)] | ||
| 971 | +mod tests { | ||
| 972 | + use super::*; | ||
| 973 | + | ||
| 974 | + #[test] | ||
| 975 | + fn folding_is_the_exact_inverse_of_the_decoder() { | ||
| 976 | + // Every predicted/wanted pair in the range must survive the fold, or | ||
| 977 | + // the encoder and the decoder disagree about the floor. | ||
| 978 | + for predicted in [0i32, 1, 40, 128, 200, 255] { | ||
| 979 | + for wanted in 0..256i32 { | ||
| 980 | + let value = fold(predicted, wanted, 256); | ||
| 981 | + assert!((0..256).contains(&value), "{predicted}->{wanted}: {value}"); | ||
| 982 | + assert_eq!( | ||
| 983 | + unfold(predicted, value, 256), | ||
| 984 | + wanted, | ||
| 985 | + "predicted {predicted}, wanted {wanted}, coded {value}" | ||
| 986 | + ); | ||
| 987 | + } | ||
| 988 | + } | ||
| 989 | + } | ||
| 990 | + | ||
| 991 | + /// §7.2.3 as the decoder runs it, for the test above to check against. | ||
| 992 | + fn unfold(predicted: i32, value: i32, range: i32) -> i32 { | ||
| 993 | + let high_room = range - predicted; | ||
| 994 | + let low_room = predicted; | ||
| 995 | + let room = high_room.min(low_room) * 2; | ||
| 996 | + if value == 0 { | ||
| 997 | + return predicted; | ||
| 998 | + } | ||
| 999 | + match value >= room { | ||
| 1000 | + true => match high_room > low_room { | ||
| 1001 | + true => value - low_room + predicted, | ||
| 1002 | + false => predicted - value + high_room - 1, | ||
| 1003 | + }, | ||
| 1004 | + false => match value & 1 == 1 { | ||
| 1005 | + true => predicted - (value + 1) / 2, | ||
| 1006 | + false => predicted + value / 2, | ||
| 1007 | + }, | ||
| 1008 | + } | ||
| 1009 | + } | ||
| 1010 | + | ||
| 1011 | + #[test] | ||
| 1012 | + fn coupling_round_trips_every_sign_case() { | ||
| 1013 | + for left in -8..=8i32 { | ||
| 1014 | + for right in -8..=8i32 { | ||
| 1015 | + let (m, a) = couple(left, right); | ||
| 1016 | + let (back_l, back_r) = match (m > 0, a > 0) { | ||
| 1017 | + (true, true) => (m, m - a), | ||
| 1018 | + (true, false) => (m + a, m), | ||
| 1019 | + (false, true) => (m, m + a), | ||
| 1020 | + (false, false) => (m - a, m), | ||
| 1021 | + }; | ||
| 1022 | + assert_eq!((back_l, back_r), (left, right), "{left},{right}"); | ||
| 1023 | + } | ||
| 1024 | + } | ||
| 1025 | + } | ||
| 1026 | +} | ||
crates/ec-vorbis/src/floor.rsadded+334 -0
| @@ -0,0 +1,334 @@ | |||
| 1 | +//! Floor decode and curve synthesis — the spectral envelope a residue rides on. | ||
| 2 | +//! | ||
| 3 | +//! Two floor types share nothing but their job. Floor 1 (§7.2) is a | ||
| 4 | +//! piecewise-linear curve in a 0.54 dB quantised log domain, drawn with | ||
| 5 | +//! integer Bresenham arithmetic so every decoder draws the same line. Floor 0 | ||
| 6 | +//! (§6.2) is an LSP filter response evaluated on a Bark-spaced map — only old | ||
| 7 | +//! encoders emit it, and the Xiph `lsp-test` vectors are exactly those. | ||
| 8 | + | ||
| 9 | +use std::sync::LazyLock; | ||
| 10 | + | ||
| 11 | +use crate::bits::Bits; | ||
| 12 | +use crate::codebook::{Codebook, ilog}; | ||
| 13 | +use crate::setup::{Floor0, Floor1}; | ||
| 14 | + | ||
| 15 | +/// §7.2.4's amplitude table, 256 entries of `10^((y - 255) * 140/256 / 20)`. | ||
| 16 | +/// | ||
| 17 | +/// The spec prints the values; this states the law behind them, which is the | ||
| 18 | +/// same table to within a float ulp (its first entry, `1.0649863e-07`, is | ||
| 19 | +/// `10^(-255 * 0.02734375)` exactly). Generated rather than pasted so the | ||
| 20 | +/// relationship to the 140 dB the floor spans stays visible. | ||
| 21 | +static INVERSE_DB: LazyLock<[f32; 256]> = LazyLock::new(|| { | ||
| 22 | + let mut table = [0.0f32; 256]; | ||
| 23 | + for (y, slot) in table.iter_mut().enumerate() { | ||
| 24 | + *slot = 10f64.powf((y as f64 - 255.0) * (140.0 / 256.0) / 20.0) as f32; | ||
| 25 | + } | ||
| 26 | + table | ||
| 27 | +}); | ||
| 28 | + | ||
| 29 | +/// What a floor packet said, kept until the residue is in and the curve is | ||
| 30 | +/// multiplied through. | ||
| 31 | +pub enum FloorState { | ||
| 32 | + /// The channel codes no audio in this packet. | ||
| 33 | + Unused, | ||
| 34 | + /// Floor 1 amplitudes, in coding order, with their step-2 flags. | ||
| 35 | + One { | ||
| 36 | + /// Final Y value per coding-order index. | ||
| 37 | + y: Vec<i32>, | ||
| 38 | + /// Whether the value was coded rather than predicted. | ||
| 39 | + step2: Vec<bool>, | ||
| 40 | + }, | ||
| 41 | + /// Floor 0 amplitude and LSP coefficients. | ||
| 42 | + Zero { | ||
| 43 | + /// Coded amplitude. | ||
| 44 | + amplitude: u32, | ||
| 45 | + /// LSP coefficients. | ||
| 46 | + coefficients: Vec<f32>, | ||
| 47 | + }, | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +impl FloorState { | ||
| 51 | + /// True when the channel has no spectrum this packet. | ||
| 52 | + pub fn is_unused(&self) -> bool { | ||
| 53 | + matches!(self, FloorState::Unused) | ||
| 54 | + } | ||
| 55 | +} | ||
| 56 | + | ||
| 57 | +/// Decode a floor-1 packet header (§7.2.2 and §7.2.3), amplitudes only. | ||
| 58 | +pub fn decode_floor1(floor: &Floor1, codebooks: &[Codebook], bits: &mut Bits) -> FloorState { | ||
| 59 | + if !bits.bit() || bits.eop() { | ||
| 60 | + return FloorState::Unused; | ||
| 61 | + } | ||
| 62 | + let range = [256i32, 128, 86, 64][(floor.multiplier - 1) as usize]; | ||
| 63 | + let values = floor.x_list.len(); | ||
| 64 | + let mut y = vec![0i32; values]; | ||
| 65 | + let field = ilog((range - 1) as u32); | ||
| 66 | + y[0] = bits.read(field) as i32; | ||
| 67 | + y[1] = bits.read(field) as i32; | ||
| 68 | + | ||
| 69 | + let mut offset = 2usize; | ||
| 70 | + for &class in &floor.partition_classes { | ||
| 71 | + let dimensions = floor.class_dimensions[class]; | ||
| 72 | + let subclass_bits = floor.class_subclasses[class]; | ||
| 73 | + let mask = (1u32 << subclass_bits) - 1; | ||
| 74 | + let mut class_value = 0u32; | ||
| 75 | + if subclass_bits > 0 { | ||
| 76 | + let book = &codebooks[floor.class_masterbooks[class]]; | ||
| 77 | + match book.decode_scalar(bits) { | ||
| 78 | + Some(value) => class_value = value, | ||
| 79 | + None => return FloorState::Unused, | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + for _ in 0..dimensions { | ||
| 83 | + let book = floor.subclass_books[class][(class_value & mask) as usize]; | ||
| 84 | + class_value >>= subclass_bits; | ||
| 85 | + if offset >= values { | ||
| 86 | + break; | ||
| 87 | + } | ||
| 88 | + y[offset] = match book { | ||
| 89 | + book if book >= 0 => match codebooks[book as usize].decode_scalar(bits) { | ||
| 90 | + Some(value) => value as i32, | ||
| 91 | + None => return FloorState::Unused, | ||
| 92 | + }, | ||
| 93 | + _ => 0, | ||
| 94 | + }; | ||
| 95 | + offset += 1; | ||
| 96 | + } | ||
| 97 | + } | ||
| 98 | + if bits.eop() { | ||
| 99 | + return FloorState::Unused; | ||
| 100 | + } | ||
| 101 | + | ||
| 102 | + // §7.2.3 amplitude synthesis: every value past the first two is a | ||
| 103 | + // correction to the line its two already-coded neighbours predict, folded | ||
| 104 | + // into the room that line leaves above and below. | ||
| 105 | + let mut final_y = y.clone(); | ||
| 106 | + let mut step2 = vec![false; values]; | ||
| 107 | + step2[0] = true; | ||
| 108 | + step2[1] = true; | ||
| 109 | + for i in 2..values { | ||
| 110 | + let (low, high) = floor.neighbours[i]; | ||
| 111 | + let predicted = render_point( | ||
| 112 | + floor.x_list[low], | ||
| 113 | + final_y[low], | ||
| 114 | + floor.x_list[high], | ||
| 115 | + final_y[high], | ||
| 116 | + floor.x_list[i], | ||
| 117 | + ); | ||
| 118 | + let val = y[i]; | ||
| 119 | + let high_room = range - predicted; | ||
| 120 | + let low_room = predicted; | ||
| 121 | + let room = high_room.min(low_room) * 2; | ||
| 122 | + if val != 0 { | ||
| 123 | + step2[low] = true; | ||
| 124 | + step2[high] = true; | ||
| 125 | + step2[i] = true; | ||
| 126 | + final_y[i] = match val >= room { | ||
| 127 | + true => match high_room > low_room { | ||
| 128 | + true => val - low_room + predicted, | ||
| 129 | + false => predicted - val + high_room - 1, | ||
| 130 | + }, | ||
| 131 | + false => match val & 1 == 1 { | ||
| 132 | + true => predicted - (val + 1) / 2, | ||
| 133 | + false => predicted + val / 2, | ||
| 134 | + }, | ||
| 135 | + }; | ||
| 136 | + } else { | ||
| 137 | + step2[i] = false; | ||
| 138 | + final_y[i] = predicted; | ||
| 139 | + } | ||
| 140 | + final_y[i] = final_y[i].clamp(0, range - 1); | ||
| 141 | + } | ||
| 142 | + FloorState::One { y: final_y, step2 } | ||
| 143 | +} | ||
| 144 | + | ||
| 145 | +/// Draw the floor-1 curve into `out` (§7.2.4), one value per coefficient. | ||
| 146 | +pub fn render_floor1(floor: &Floor1, y: &[i32], step2: &[bool], out: &mut [f32]) { | ||
| 147 | + let n = out.len(); | ||
| 148 | + let table = &*INVERSE_DB; | ||
| 149 | + let multiplier = floor.multiplier; | ||
| 150 | + let mut lx = 0usize; | ||
| 151 | + let mut ly = y[0] * multiplier; | ||
| 152 | + let mut hx = 0usize; | ||
| 153 | + let mut hy = ly; | ||
| 154 | + for &i in floor.sorted.iter().skip(1) { | ||
| 155 | + if !step2[i] { | ||
| 156 | + continue; | ||
| 157 | + } | ||
| 158 | + hy = y[i] * multiplier; | ||
| 159 | + hx = floor.x_list[i] as usize; | ||
| 160 | + render_line(lx, ly, hx, hy, out, table); | ||
| 161 | + lx = hx; | ||
| 162 | + ly = hy; | ||
| 163 | + } | ||
| 164 | + if hx < n { | ||
| 165 | + render_line(hx, hy, n, hy, out, table); | ||
| 166 | + } | ||
| 167 | +} | ||
| 168 | + | ||
| 169 | +/// §7.2.2 `render_point`: the height a line between two coded values has at `x`. | ||
| 170 | +fn render_point(x0: u32, y0: i32, x1: u32, y1: i32, x: u32) -> i32 { | ||
| 171 | + let dy = y1 - y0; | ||
| 172 | + let adx = (x1 - x0) as i32; | ||
| 173 | + let ady = dy.abs(); | ||
| 174 | + let off = (ady * (x - x0) as i32) / adx; | ||
| 175 | + match dy < 0 { | ||
| 176 | + true => y0 - off, | ||
| 177 | + false => y0 + off, | ||
| 178 | + } | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +/// §7.2.4 `render_line`: integer Bresenham, so two decoders never disagree by | ||
| 182 | +/// one sample of tilt. | ||
| 183 | +fn render_line(x0: usize, y0: i32, x1: usize, y1: i32, out: &mut [f32], table: &[f32; 256]) { | ||
| 184 | + let n = out.len(); | ||
| 185 | + let dy = y1 - y0; | ||
| 186 | + let adx = (x1 - x0) as i32; | ||
| 187 | + if adx <= 0 { | ||
| 188 | + return; | ||
| 189 | + } | ||
| 190 | + let mut ady = dy.abs(); | ||
| 191 | + let base = dy / adx; | ||
| 192 | + let sy = match dy < 0 { | ||
| 193 | + true => base - 1, | ||
| 194 | + false => base + 1, | ||
| 195 | + }; | ||
| 196 | + ady -= base.abs() * adx; | ||
| 197 | + let mut y = y0; | ||
| 198 | + let mut err = 0i32; | ||
| 199 | + if x0 < n { | ||
| 200 | + out[x0] = table[y.clamp(0, 255) as usize]; | ||
| 201 | + } | ||
| 202 | + let end = x1.min(n); | ||
| 203 | + for slot in out[(x0 + 1).min(end)..end].iter_mut() { | ||
| 204 | + err += ady; | ||
| 205 | + if err >= adx { | ||
| 206 | + err -= adx; | ||
| 207 | + y += sy; | ||
| 208 | + } else { | ||
| 209 | + y += base; | ||
| 210 | + } | ||
| 211 | + *slot = table[y.clamp(0, 255) as usize]; | ||
| 212 | + } | ||
| 213 | +} | ||
| 214 | + | ||
| 215 | +/// Decode a floor-0 packet header (§6.2.2): an amplitude and an LSP vector. | ||
| 216 | +pub fn decode_floor0(floor: &Floor0, codebooks: &[Codebook], bits: &mut Bits) -> FloorState { | ||
| 217 | + let amplitude = bits.read(floor.amplitude_bits); | ||
| 218 | + if bits.eop() { | ||
| 219 | + return FloorState::Unused; | ||
| 220 | + } | ||
| 221 | + if amplitude == 0 { | ||
| 222 | + return FloorState::Unused; | ||
| 223 | + } | ||
| 224 | + // §6.2.2 states the book number in `ilog(number_of_books)` bits — the count | ||
| 225 | + // itself, not the largest index, which is one bit wider than it looks. | ||
| 226 | + let index = bits.read(ilog(floor.books.len() as u32)) as usize; | ||
| 227 | + let Some(&book) = floor.books.get(index) else { | ||
| 228 | + return FloorState::Unused; | ||
| 229 | + }; | ||
| 230 | + let book = &codebooks[book]; | ||
| 231 | + if !book.has_values() { | ||
| 232 | + return FloorState::Unused; | ||
| 233 | + } | ||
| 234 | + let mut coefficients = Vec::with_capacity(floor.order); | ||
| 235 | + let mut last = 0.0f32; | ||
| 236 | + while coefficients.len() < floor.order { | ||
| 237 | + let Some(vector) = book.decode_vector(bits) else { | ||
| 238 | + return FloorState::Unused; | ||
| 239 | + }; | ||
| 240 | + for &value in vector { | ||
| 241 | + coefficients.push(value + last); | ||
| 242 | + } | ||
| 243 | + last = *coefficients.last().unwrap_or(&0.0); | ||
| 244 | + } | ||
| 245 | + coefficients.truncate(floor.order); | ||
| 246 | + FloorState::Zero { | ||
| 247 | + amplitude, | ||
| 248 | + coefficients, | ||
| 249 | + } | ||
| 250 | +} | ||
| 251 | + | ||
| 252 | +/// Draw the floor-0 curve into `out` (§6.2.3): the LSP pair evaluated on a | ||
| 253 | +/// Bark-spaced frequency map, one height per Bark bin. | ||
| 254 | +pub fn render_floor0(floor: &Floor0, amplitude: u32, coefficients: &[f32], out: &mut [f32]) { | ||
| 255 | + let n = out.len(); | ||
| 256 | + if n == 0 || coefficients.is_empty() { | ||
| 257 | + out.fill(0.0); | ||
| 258 | + return; | ||
| 259 | + } | ||
| 260 | + let order = coefficients.len(); | ||
| 261 | + let bark_size = floor.bark_map_size as f64; | ||
| 262 | + let scale = bark_size / bark(0.5 * f64::from(floor.rate)); | ||
| 263 | + let map: Vec<f64> = (0..n) | ||
| 264 | + .map(|i| { | ||
| 265 | + let hz = f64::from(floor.rate) * 0.5 * i as f64 / n as f64; | ||
| 266 | + (bark(hz) * scale).floor().clamp(0.0, bark_size - 1.0) | ||
| 267 | + }) | ||
| 268 | + .collect(); | ||
| 269 | + let amplitude_max = ((1u64 << floor.amplitude_bits) - 1) as f64; | ||
| 270 | + let offset = f64::from(floor.amplitude_offset); | ||
| 271 | + let cos_theta: Vec<f64> = coefficients.iter().map(|&c| f64::from(c).cos()).collect(); | ||
| 272 | + | ||
| 273 | + let mut i = 0usize; | ||
| 274 | + while i < n { | ||
| 275 | + let bin = map[i]; | ||
| 276 | + let omega = std::f64::consts::PI * bin / bark_size; | ||
| 277 | + let cos_omega = omega.cos(); | ||
| 278 | + // P and Q are the two LSP polynomials on the unit circle; their | ||
| 279 | + // prefactors are the (1 +- z^-1) factors the odd and even orders differ | ||
| 280 | + // by, and each root contributes 4(cos(theta) - cos(omega))^2. | ||
| 281 | + let (mut p, mut q) = match order % 2 { | ||
| 282 | + 1 => (1.0 - cos_omega * cos_omega, 0.25), | ||
| 283 | + _ => ((1.0 - cos_omega) * 0.5, (1.0 + cos_omega) * 0.5), | ||
| 284 | + }; | ||
| 285 | + let mut j = 1usize; | ||
| 286 | + while j < order { | ||
| 287 | + let d = cos_theta[j] - cos_omega; | ||
| 288 | + p *= 4.0 * d * d; | ||
| 289 | + j += 2; | ||
| 290 | + } | ||
| 291 | + let mut j = 0usize; | ||
| 292 | + while j < order { | ||
| 293 | + let d = cos_theta[j] - cos_omega; | ||
| 294 | + q *= 4.0 * d * d; | ||
| 295 | + j += 2; | ||
| 296 | + } | ||
| 297 | + let value = (0.11512925 | ||
| 298 | + * (f64::from(amplitude) * offset / (amplitude_max * (p + q).sqrt()) - offset)) | ||
| 299 | + .exp() as f32; | ||
| 300 | + while i < n && map[i] == bin { | ||
| 301 | + out[i] = value; | ||
| 302 | + i += 1; | ||
| 303 | + } | ||
| 304 | + } | ||
| 305 | +} | ||
| 306 | + | ||
| 307 | +/// §6.2.3's Bark scale. | ||
| 308 | +fn bark(x: f64) -> f64 { | ||
| 309 | + 13.1 * (0.00074 * x).atan() + 2.24 * (0.0000000185 * x * x).atan() + 0.0001 * x | ||
| 310 | +} | ||
| 311 | + | ||
| 312 | +#[cfg(test)] | ||
| 313 | +mod tests { | ||
| 314 | + use super::*; | ||
| 315 | + | ||
| 316 | + #[test] | ||
| 317 | + fn inverse_db_table_matches_the_spec_endpoints() { | ||
| 318 | + let table = &*INVERSE_DB; | ||
| 319 | + assert!((table[0] - 1.0649863e-07).abs() < 1e-13, "{}", table[0]); | ||
| 320 | + assert!((table[255] - 1.0).abs() < 1e-6, "{}", table[255]); | ||
| 321 | + // Monotonic, which is what makes a bigger Y a louder floor. | ||
| 322 | + assert!(table.windows(2).all(|w| w[1] > w[0])); | ||
| 323 | + } | ||
| 324 | + | ||
| 325 | + #[test] | ||
| 326 | + fn render_line_draws_the_spec_slope() { | ||
| 327 | + let mut out = vec![0.0f32; 8]; | ||
| 328 | + let table = &*INVERSE_DB; | ||
| 329 | + render_line(0, 0, 8, 16, &mut out, table); | ||
| 330 | + // Sixteen steps over eight samples is two per sample, starting at zero. | ||
| 331 | + let expect: Vec<f32> = (0..8).map(|i| table[i * 2]).collect(); | ||
| 332 | + assert_eq!(out, expect); | ||
| 333 | + } | ||
| 334 | +} | ||
crates/ec-vorbis/src/lib.rsadded+45 -0
| @@ -0,0 +1,45 @@ | |||
| 1 | +//! Vorbis I — decoder and encoder. | ||
| 2 | +//! | ||
| 3 | +//! The decoder is the whole format: both floor types, all three residue types, | ||
| 4 | +//! square-polar channel coupling, every legal blocksize and the four window | ||
| 5 | +//! shapes a long block takes next to a short one. It is written against the | ||
| 6 | +//! Xiph Vorbis I specification and nothing else. | ||
| 7 | +//! | ||
| 8 | +//! The encoder is deliberately narrower and states its own terms: | ||
| 9 | +//! | ||
| 10 | +//! - **Any channel count, natively.** Mono, stereo and surround each get a | ||
| 11 | +//! setup header written for that layout, with coupling where coupling pays | ||
| 12 | +//! (stereo) and none where it does not. There is no stereo-only profile to | ||
| 13 | +//! work around and no dual-mono widening of a mono mix. | ||
| 14 | +//! - **No pre-roll.** The first block is centred on input sample 0, so the | ||
| 15 | +//! decoder's first output sample *is* input sample 0. A caller does not feed | ||
| 16 | +//! silence ahead of the mix and does not subtract a hop from every granule. | ||
| 17 | +//! - **Exact length.** The last packet's granule states the input's own sample | ||
| 18 | +//! count, so a file decodes to exactly as many samples as went in — no block | ||
| 19 | +//! grid overshoot survives to the player. | ||
| 20 | +//! - **ABR.** [`EncoderConfig::bitrate_bps`] is tracked by a feedback loop over | ||
| 21 | +//! the headroom the floor leaves under the masking curve; | ||
| 22 | +//! [`EncoderConfig::quality`] sets where that loop starts, and holds the | ||
| 23 | +//! headroom still when no bitrate is asked for. The loop tracks rather than | ||
| 24 | +//! hits: a signal too simple to spend the budget on comes out under it. | ||
| 25 | +//! | ||
| 26 | +//! Timing contract: an audio packet answers the samples that became final when | ||
| 27 | +//! its window closed, so the *first* packet of a stream answers none. That is | ||
| 28 | +//! Vorbis, not an artefact — a block's left half is only half of the samples it | ||
| 29 | +//! overlaps. | ||
| 30 | + | ||
| 31 | +#![forbid(unsafe_code)] | ||
| 32 | +#![warn(missing_docs)] | ||
| 33 | + | ||
| 34 | +mod bits; | ||
| 35 | +mod codebook; | ||
| 36 | +mod decode; | ||
| 37 | +mod encode; | ||
| 38 | +mod floor; | ||
| 39 | +mod residue; | ||
| 40 | +mod setup; | ||
| 41 | +mod window; | ||
| 42 | + | ||
| 43 | +pub use decode::{VorbisDecoder, channel_map}; | ||
| 44 | +pub use encode::{EncoderConfig, VorbisEncoder}; | ||
| 45 | +pub use setup::{Comments, Identification}; | ||
crates/ec-vorbis/src/residue.rsadded+142 -0
| @@ -0,0 +1,142 @@ | |||
| 1 | +//! Residue decode (§8): the spectrum that rides on the floor. | ||
| 2 | +//! | ||
| 3 | +//! All three residue types share one loop — partitions classified in groups, | ||
| 4 | +//! then up to eight refinement passes over those classes — and differ only in | ||
| 5 | +//! how a partition's values are laid out. Type 2 differs one level up: it codes | ||
| 6 | +//! every channel of a submap as one interleaved vector, which is what makes | ||
| 7 | +//! coupled stereo cheap. | ||
| 8 | + | ||
| 9 | +use crate::bits::Bits; | ||
| 10 | +use crate::codebook::Codebook; | ||
| 11 | +use crate::setup::ResidueConfig; | ||
| 12 | + | ||
| 13 | +/// Decode one residue into `vectors`, which the caller has zeroed. | ||
| 14 | +/// | ||
| 15 | +/// For types 0 and 1 there is one vector per channel of the submap; for type 2 | ||
| 16 | +/// the caller passes a single interleaved vector `channels * n` long. Channels | ||
| 17 | +/// flagged in `skip` are not coded at all (an unused floor, or a coupling | ||
| 18 | +/// partner already covered). | ||
| 19 | +pub fn decode( | ||
| 20 | + config: &ResidueConfig, | ||
| 21 | + codebooks: &[Codebook], | ||
| 22 | + bits: &mut Bits, | ||
| 23 | + vectors: &mut [Vec<f32>], | ||
| 24 | + skip: &[bool], | ||
| 25 | +) { | ||
| 26 | + let Some(size) = vectors.first().map(Vec::len) else { | ||
| 27 | + return; | ||
| 28 | + }; | ||
| 29 | + if skip.iter().all(|&s| s) { | ||
| 30 | + return; | ||
| 31 | + } | ||
| 32 | + let begin = config.begin.min(size); | ||
| 33 | + let end = config.end.min(size); | ||
| 34 | + let to_read = end.saturating_sub(begin); | ||
| 35 | + let partitions = to_read / config.partition_size; | ||
| 36 | + if partitions == 0 { | ||
| 37 | + return; | ||
| 38 | + } | ||
| 39 | + let classbook = &codebooks[config.classbook]; | ||
| 40 | + let per_word = classbook.dimensions.max(1); | ||
| 41 | + let classes = config.classifications as u32; | ||
| 42 | + let mut classification = vec![vec![0u8; partitions + per_word]; vectors.len()]; | ||
| 43 | + | ||
| 44 | + for pass in 0..8usize { | ||
| 45 | + let mut partition = 0usize; | ||
| 46 | + while partition < partitions { | ||
| 47 | + if pass == 0 { | ||
| 48 | + for (channel, row) in classification.iter_mut().enumerate() { | ||
| 49 | + if skip[channel] { | ||
| 50 | + continue; | ||
| 51 | + } | ||
| 52 | + let Some(mut word) = classbook.decode_scalar(bits) else { | ||
| 53 | + return; | ||
| 54 | + }; | ||
| 55 | + // The class word packs `per_word` classes, most recent | ||
| 56 | + // partition in the least significant digit. | ||
| 57 | + for i in (0..per_word).rev() { | ||
| 58 | + row[partition + i] = (word % classes) as u8; | ||
| 59 | + word /= classes; | ||
| 60 | + } | ||
| 61 | + } | ||
| 62 | + } | ||
| 63 | + for _ in 0..per_word { | ||
| 64 | + if partition >= partitions { | ||
| 65 | + break; | ||
| 66 | + } | ||
| 67 | + for (channel, vector) in vectors.iter_mut().enumerate() { | ||
| 68 | + if skip[channel] { | ||
| 69 | + continue; | ||
| 70 | + } | ||
| 71 | + let class = usize::from(classification[channel][partition]); | ||
| 72 | + let book = config.books[class][pass]; | ||
| 73 | + if book < 0 { | ||
| 74 | + continue; | ||
| 75 | + } | ||
| 76 | + let offset = begin + partition * config.partition_size; | ||
| 77 | + let slice = &mut vector[offset..offset + config.partition_size]; | ||
| 78 | + if !decode_partition(config.kind, &codebooks[book as usize], bits, slice) { | ||
| 79 | + return; | ||
| 80 | + } | ||
| 81 | + } | ||
| 82 | + partition += 1; | ||
| 83 | + } | ||
| 84 | + } | ||
| 85 | + } | ||
| 86 | +} | ||
| 87 | + | ||
| 88 | +/// One partition's worth of values, added onto what earlier passes left. | ||
| 89 | +fn decode_partition(kind: u8, book: &Codebook, bits: &mut Bits, out: &mut [f32]) -> bool { | ||
| 90 | + if !book.has_values() { | ||
| 91 | + return false; | ||
| 92 | + } | ||
| 93 | + let dimensions = book.dimensions; | ||
| 94 | + match kind { | ||
| 95 | + // Type 0 lays a codeword's values out strided, so one codeword covers | ||
| 96 | + // the whole partition at `step` spacing. | ||
| 97 | + 0 => { | ||
| 98 | + let step = out.len() / dimensions.max(1); | ||
| 99 | + for i in 0..step { | ||
| 100 | + let Some(values) = book.decode_vector(bits) else { | ||
| 101 | + return false; | ||
| 102 | + }; | ||
| 103 | + for (j, &value) in values.iter().enumerate() { | ||
| 104 | + if let Some(slot) = out.get_mut(i + j * step) { | ||
| 105 | + *slot += value; | ||
| 106 | + } | ||
| 107 | + } | ||
| 108 | + } | ||
| 109 | + } | ||
| 110 | + // Types 1 and 2 lay them out contiguously. | ||
| 111 | + _ => { | ||
| 112 | + let mut i = 0usize; | ||
| 113 | + while i < out.len() { | ||
| 114 | + let Some(values) = book.decode_vector(bits) else { | ||
| 115 | + return false; | ||
| 116 | + }; | ||
| 117 | + for &value in values { | ||
| 118 | + if i >= out.len() { | ||
| 119 | + break; | ||
| 120 | + } | ||
| 121 | + out[i] += value; | ||
| 122 | + i += 1; | ||
| 123 | + } | ||
| 124 | + if dimensions == 0 { | ||
| 125 | + return false; | ||
| 126 | + } | ||
| 127 | + } | ||
| 128 | + } | ||
| 129 | + } | ||
| 130 | + true | ||
| 131 | +} | ||
| 132 | + | ||
| 133 | +/// Spread a type-2 interleaved vector back over its channels. | ||
| 134 | +pub fn deinterleave(interleaved: &[f32], channels: usize, out: &mut [Vec<f32>]) { | ||
| 135 | + for (i, &value) in interleaved.iter().enumerate() { | ||
| 136 | + let channel = i % channels; | ||
| 137 | + let position = i / channels; | ||
| 138 | + if let Some(slot) = out[channel].get_mut(position) { | ||
| 139 | + *slot = value; | ||
| 140 | + } | ||
| 141 | + } | ||
| 142 | +} | ||
crates/ec-vorbis/src/setup.rsadded+595 -0
| @@ -0,0 +1,595 @@ | |||
| 1 | +//! The three header packets: identification, comment, setup. | ||
| 2 | +//! | ||
| 3 | +//! Everything a Vorbis stream needs before its first audio packet lives here — | ||
| 4 | +//! the blocksizes, the codebooks, and the floor/residue/mapping/mode | ||
| 5 | +//! configurations that audio packets index by number. The setup header is | ||
| 6 | +//! parsed once; audio decode after that is pure lookup. | ||
| 7 | + | ||
| 8 | +use ec_core::{Error, Result}; | ||
| 9 | + | ||
| 10 | +use crate::bits::Bits; | ||
| 11 | +use crate::codebook::{Codebook, ilog}; | ||
| 12 | + | ||
| 13 | +/// Identification header (§4.2.2). | ||
| 14 | +#[derive(Debug, Clone, Copy, PartialEq, Eq)] | ||
| 15 | +pub struct Identification { | ||
| 16 | + /// Channel count, in Vorbis channel order. | ||
| 17 | + pub channels: u8, | ||
| 18 | + /// Sample rate in Hz. | ||
| 19 | + pub rate: u32, | ||
| 20 | + /// Nominal bitrate the encoder stated, 0 when it stated none. | ||
| 21 | + pub bitrate_nominal: i32, | ||
| 22 | + /// Short block size in samples. | ||
| 23 | + pub blocksize_0: usize, | ||
| 24 | + /// Long block size in samples. | ||
| 25 | + pub blocksize_1: usize, | ||
| 26 | +} | ||
| 27 | + | ||
| 28 | +impl Identification { | ||
| 29 | + /// Parse the identification packet, header byte included. | ||
| 30 | + pub fn parse(data: &[u8]) -> Result<Identification> { | ||
| 31 | + let mut bits = Bits::new(header_body(data, 1)?); | ||
| 32 | + let version = bits.read(32); | ||
| 33 | + if version != 0 { | ||
| 34 | + return Err(Error::unsupported( | ||
| 35 | + format!("Vorbis bitstream version {version}"), | ||
| 36 | + "only version 0 (Vorbis I) is defined", | ||
| 37 | + )); | ||
| 38 | + } | ||
| 39 | + let channels = bits.read(8) as u8; | ||
| 40 | + let rate = bits.read(32); | ||
| 41 | + let _bitrate_maximum = bits.read(32) as i32; | ||
| 42 | + let bitrate_nominal = bits.read(32) as i32; | ||
| 43 | + let _bitrate_minimum = bits.read(32) as i32; | ||
| 44 | + let blocksize_0 = 1usize << bits.read(4); | ||
| 45 | + let blocksize_1 = 1usize << bits.read(4); | ||
| 46 | + let framing = bits.bit(); | ||
| 47 | + if bits.eop() || !framing { | ||
| 48 | + return Err(Error::corrupt("identification header truncated")); | ||
| 49 | + } | ||
| 50 | + if channels == 0 || rate == 0 { | ||
| 51 | + return Err(Error::corrupt("identification header states no audio")); | ||
| 52 | + } | ||
| 53 | + let legal = |n: usize| n.is_power_of_two() && (64..=8192).contains(&n); | ||
| 54 | + if !legal(blocksize_0) || !legal(blocksize_1) || blocksize_0 > blocksize_1 { | ||
| 55 | + return Err(Error::corrupt(format!( | ||
| 56 | + "blocksizes {blocksize_0}/{blocksize_1}" | ||
| 57 | + ))); | ||
| 58 | + } | ||
| 59 | + Ok(Identification { | ||
| 60 | + channels, | ||
| 61 | + rate, | ||
| 62 | + bitrate_nominal, | ||
| 63 | + blocksize_0, | ||
| 64 | + blocksize_1, | ||
| 65 | + }) | ||
| 66 | + } | ||
| 67 | +} | ||
| 68 | + | ||
| 69 | +/// Comment header (§5): the vendor string and the tag list. | ||
| 70 | +#[derive(Debug, Clone, Default, PartialEq, Eq)] | ||
| 71 | +pub struct Comments { | ||
| 72 | + /// Encoder identification. | ||
| 73 | + pub vendor: String, | ||
| 74 | + /// `NAME=value` tags, in file order, with the name upper-cased. | ||
| 75 | + pub tags: Vec<(String, String)>, | ||
| 76 | +} | ||
| 77 | + | ||
| 78 | +impl Comments { | ||
| 79 | + /// Parse the comment packet, header byte included. | ||
| 80 | + /// | ||
| 81 | + /// A malformed tag is skipped rather than fatal: metadata never stops | ||
| 82 | + /// audio from playing. | ||
| 83 | + pub fn parse(data: &[u8]) -> Result<Comments> { | ||
| 84 | + let body = header_body(data, 3)?; | ||
| 85 | + let mut pos = 0usize; | ||
| 86 | + let take = |pos: &mut usize| -> Option<String> { | ||
| 87 | + let len = u32::from_le_bytes(body.get(*pos..*pos + 4)?.try_into().ok()?) as usize; | ||
| 88 | + *pos += 4; | ||
| 89 | + let text = body.get(*pos..pos.checked_add(len)?)?; | ||
| 90 | + *pos += len; | ||
| 91 | + Some(String::from_utf8_lossy(text).into_owned()) | ||
| 92 | + }; | ||
| 93 | + let vendor = take(&mut pos).ok_or_else(|| Error::corrupt("comment vendor string"))?; | ||
| 94 | + let count = u32::from_le_bytes( | ||
| 95 | + body.get(pos..pos + 4) | ||
| 96 | + .ok_or_else(|| Error::corrupt("comment count"))? | ||
| 97 | + .try_into() | ||
| 98 | + .map_err(|_| Error::corrupt("comment count"))?, | ||
| 99 | + ); | ||
| 100 | + pos += 4; | ||
| 101 | + let mut tags = Vec::new(); | ||
| 102 | + for _ in 0..count { | ||
| 103 | + let Some(entry) = take(&mut pos) else { break }; | ||
| 104 | + if let Some((name, value)) = entry.split_once('=') { | ||
| 105 | + tags.push((name.to_ascii_uppercase(), value.to_string())); | ||
| 106 | + } | ||
| 107 | + } | ||
| 108 | + Ok(Comments { vendor, tags }) | ||
| 109 | + } | ||
| 110 | +} | ||
| 111 | + | ||
| 112 | +/// Floor type 0: an LSP curve (§6.2). | ||
| 113 | +#[derive(Debug, Clone)] | ||
| 114 | +pub struct Floor0 { | ||
| 115 | + /// LSP order. | ||
| 116 | + pub order: usize, | ||
| 117 | + /// Rate the bark map is built against. | ||
| 118 | + pub rate: u32, | ||
| 119 | + /// Bark map resolution. | ||
| 120 | + pub bark_map_size: usize, | ||
| 121 | + /// Bits the amplitude is stated in. | ||
| 122 | + pub amplitude_bits: u32, | ||
| 123 | + /// dB offset applied to the amplitude. | ||
| 124 | + pub amplitude_offset: f32, | ||
| 125 | + /// Books the coefficient vector may be coded with. | ||
| 126 | + pub books: Vec<usize>, | ||
| 127 | +} | ||
| 128 | + | ||
| 129 | +/// Floor type 1: a piecewise-linear curve in dB (§7.2). | ||
| 130 | +#[derive(Debug, Clone)] | ||
| 131 | +pub struct Floor1 { | ||
| 132 | + /// Class of each partition, in order. | ||
| 133 | + pub partition_classes: Vec<usize>, | ||
| 134 | + /// Values per class. | ||
| 135 | + pub class_dimensions: Vec<usize>, | ||
| 136 | + /// Subclass bits per class. | ||
| 137 | + pub class_subclasses: Vec<u32>, | ||
| 138 | + /// Book naming the subclass, per class; unused when `class_subclasses` is 0. | ||
| 139 | + pub class_masterbooks: Vec<usize>, | ||
| 140 | + /// Book per subclass, `-1` for "this subclass codes nothing". | ||
| 141 | + pub subclass_books: Vec<Vec<i32>>, | ||
| 142 | + /// dB step per Y unit. | ||
| 143 | + pub multiplier: i32, | ||
| 144 | + /// X coordinate of every value, in coding order. | ||
| 145 | + pub x_list: Vec<u32>, | ||
| 146 | + /// Indices of `x_list` sorted by X, the order the curve is rendered in. | ||
| 147 | + pub sorted: Vec<usize>, | ||
| 148 | + /// Per value, the coding-order index of the nearest lower/higher X already | ||
| 149 | + /// coded, precomputed because the decode loop needs it per packet. | ||
| 150 | + pub neighbours: Vec<(usize, usize)>, | ||
| 151 | +} | ||
| 152 | + | ||
| 153 | +/// One floor configuration. | ||
| 154 | +#[derive(Debug, Clone)] | ||
| 155 | +pub enum FloorConfig { | ||
| 156 | + /// LSP floor. | ||
| 157 | + Zero(Floor0), | ||
| 158 | + /// Piecewise-linear floor. | ||
| 159 | + One(Floor1), | ||
| 160 | +} | ||
| 161 | + | ||
| 162 | +/// Residue configuration (§8). | ||
| 163 | +#[derive(Debug, Clone)] | ||
| 164 | +pub struct ResidueConfig { | ||
| 165 | + /// 0, 1 or 2 — how a partition's values are laid out. | ||
| 166 | + pub kind: u8, | ||
| 167 | + /// First coefficient coded. | ||
| 168 | + pub begin: usize, | ||
| 169 | + /// One past the last coefficient coded. | ||
| 170 | + pub end: usize, | ||
| 171 | + /// Coefficients per partition. | ||
| 172 | + pub partition_size: usize, | ||
| 173 | + /// Number of classes. | ||
| 174 | + pub classifications: usize, | ||
| 175 | + /// Book the class words are coded with. | ||
| 176 | + pub classbook: usize, | ||
| 177 | + /// Book per (class, pass), `-1` where the pass codes nothing. | ||
| 178 | + pub books: Vec<[i32; 8]>, | ||
| 179 | +} | ||
| 180 | + | ||
| 181 | +/// Mapping configuration (§4.2.4): which floor and residue serve which channel, | ||
| 182 | +/// and which channel pairs are coupled. | ||
| 183 | +#[derive(Debug, Clone)] | ||
| 184 | +pub struct MappingConfig { | ||
| 185 | + /// `(magnitude, angle)` channel per coupling step. | ||
| 186 | + pub coupling: Vec<(usize, usize)>, | ||
| 187 | + /// Submap per channel. | ||
| 188 | + pub mux: Vec<usize>, | ||
| 189 | + /// `(floor, residue)` per submap. | ||
| 190 | + pub submaps: Vec<(usize, usize)>, | ||
| 191 | +} | ||
| 192 | + | ||
| 193 | +/// One mode (§4.2.4): a block size and a mapping. | ||
| 194 | +#[derive(Debug, Clone, Copy)] | ||
| 195 | +pub struct Mode { | ||
| 196 | + /// False for a short block, true for a long one. | ||
| 197 | + pub block_flag: bool, | ||
| 198 | + /// Mapping this mode decodes with. | ||
| 199 | + pub mapping: usize, | ||
| 200 | +} | ||
| 201 | + | ||
| 202 | +/// Everything the setup header configures. | ||
| 203 | +#[derive(Debug, Clone)] | ||
| 204 | +pub struct Setup { | ||
| 205 | + /// Codebooks, indexed by number. | ||
| 206 | + pub codebooks: Vec<Codebook>, | ||
| 207 | + /// Floor configurations. | ||
| 208 | + pub floors: Vec<FloorConfig>, | ||
| 209 | + /// Residue configurations. | ||
| 210 | + pub residues: Vec<ResidueConfig>, | ||
| 211 | + /// Mapping configurations. | ||
| 212 | + pub mappings: Vec<MappingConfig>, | ||
| 213 | + /// Modes; an audio packet's first field is an index into this. | ||
| 214 | + pub modes: Vec<Mode>, | ||
| 215 | +} | ||
| 216 | + | ||
| 217 | +impl Setup { | ||
| 218 | + /// Parse the setup packet, header byte included. | ||
| 219 | + pub fn parse(data: &[u8], ident: &Identification) -> Result<Setup> { | ||
| 220 | + let mut bits = Bits::new(header_body(data, 5)?); | ||
| 221 | + let channels = usize::from(ident.channels); | ||
| 222 | + | ||
| 223 | + let codebook_count = bits.read(8) as usize + 1; | ||
| 224 | + let mut codebooks = Vec::with_capacity(codebook_count); | ||
| 225 | + for _ in 0..codebook_count { | ||
| 226 | + codebooks.push(Codebook::parse(&mut bits)?); | ||
| 227 | + } | ||
| 228 | + | ||
| 229 | + // Time-domain transforms: a placeholder in Vorbis I, but the field is | ||
| 230 | + // there and must read zero. | ||
| 231 | + let time_count = bits.read(6) + 1; | ||
| 232 | + for _ in 0..time_count { | ||
| 233 | + if bits.read(16) != 0 { | ||
| 234 | + return Err(Error::corrupt("time domain transform is not zero")); | ||
| 235 | + } | ||
| 236 | + } | ||
| 237 | + | ||
| 238 | + let floor_count = bits.read(6) as usize + 1; | ||
| 239 | + let mut floors = Vec::with_capacity(floor_count); | ||
| 240 | + for _ in 0..floor_count { | ||
| 241 | + floors.push(parse_floor(&mut bits, &codebooks, ident)?); | ||
| 242 | + } | ||
| 243 | + | ||
| 244 | + let residue_count = bits.read(6) as usize + 1; | ||
| 245 | + let mut residues = Vec::with_capacity(residue_count); | ||
| 246 | + for _ in 0..residue_count { | ||
| 247 | + residues.push(parse_residue(&mut bits, codebooks.len())?); | ||
| 248 | + } | ||
| 249 | + | ||
| 250 | + let mapping_count = bits.read(6) as usize + 1; | ||
| 251 | + let mut mappings = Vec::with_capacity(mapping_count); | ||
| 252 | + for _ in 0..mapping_count { | ||
| 253 | + mappings.push(parse_mapping( | ||
| 254 | + &mut bits, | ||
| 255 | + channels, | ||
| 256 | + floors.len(), | ||
| 257 | + residues.len(), | ||
| 258 | + )?); | ||
| 259 | + } | ||
| 260 | + | ||
| 261 | + let mode_count = bits.read(6) as usize + 1; | ||
| 262 | + let mut modes = Vec::with_capacity(mode_count); | ||
| 263 | + for _ in 0..mode_count { | ||
| 264 | + let block_flag = bits.bit(); | ||
| 265 | + let window_type = bits.read(16); | ||
| 266 | + let transform_type = bits.read(16); | ||
| 267 | + let mapping = bits.read(8) as usize; | ||
| 268 | + if window_type != 0 || transform_type != 0 { | ||
| 269 | + return Err(Error::corrupt("mode states an undefined transform")); | ||
| 270 | + } | ||
| 271 | + if mapping >= mappings.len() { | ||
| 272 | + return Err(Error::corrupt("mode names a mapping that is not there")); | ||
| 273 | + } | ||
| 274 | + modes.push(Mode { | ||
| 275 | + block_flag, | ||
| 276 | + mapping, | ||
| 277 | + }); | ||
| 278 | + } | ||
| 279 | + | ||
| 280 | + if !bits.bit() || bits.eop() { | ||
| 281 | + return Err(Error::corrupt("setup header framing")); | ||
| 282 | + } | ||
| 283 | + | ||
| 284 | + Ok(Setup { | ||
| 285 | + codebooks, | ||
| 286 | + floors, | ||
| 287 | + residues, | ||
| 288 | + mappings, | ||
| 289 | + modes, | ||
| 290 | + }) | ||
| 291 | + } | ||
| 292 | +} | ||
| 293 | + | ||
| 294 | +/// Strip and check the `type, "vorbis"` prefix every header carries. | ||
| 295 | +fn header_body(data: &[u8], kind: u8) -> Result<&[u8]> { | ||
| 296 | + if data.len() < 7 || data[0] != kind || &data[1..7] != b"vorbis" { | ||
| 297 | + return Err(Error::corrupt(format!( | ||
| 298 | + "not a Vorbis header of type {kind}" | ||
| 299 | + ))); | ||
| 300 | + } | ||
| 301 | + Ok(&data[7..]) | ||
| 302 | +} | ||
| 303 | + | ||
| 304 | +fn parse_floor( | ||
| 305 | + bits: &mut Bits, | ||
| 306 | + codebooks: &[Codebook], | ||
| 307 | + ident: &Identification, | ||
| 308 | +) -> Result<FloorConfig> { | ||
| 309 | + match bits.read(16) { | ||
| 310 | + 0 => { | ||
| 311 | + let order = bits.read(8) as usize; | ||
| 312 | + let rate = bits.read(16); | ||
| 313 | + let bark_map_size = bits.read(16) as usize; | ||
| 314 | + let amplitude_bits = bits.read(6); | ||
| 315 | + let amplitude_offset = bits.read(8) as f32; | ||
| 316 | + let book_count = bits.read(4) as usize + 1; | ||
| 317 | + let mut books = Vec::with_capacity(book_count); | ||
| 318 | + for _ in 0..book_count { | ||
| 319 | + let book = bits.read(8) as usize; | ||
| 320 | + if book >= codebooks.len() { | ||
| 321 | + return Err(Error::corrupt("floor 0 names a book that is not there")); | ||
| 322 | + } | ||
| 323 | + books.push(book); | ||
| 324 | + } | ||
| 325 | + if bits.eop() || order == 0 || bark_map_size == 0 || amplitude_bits > 32 { | ||
| 326 | + return Err(Error::corrupt("floor 0 configuration")); | ||
| 327 | + } | ||
| 328 | + Ok(FloorConfig::Zero(Floor0 { | ||
| 329 | + order, | ||
| 330 | + rate, | ||
| 331 | + bark_map_size, | ||
| 332 | + amplitude_bits, | ||
| 333 | + amplitude_offset, | ||
| 334 | + books, | ||
| 335 | + })) | ||
| 336 | + } | ||
| 337 | + 1 => { | ||
| 338 | + let partitions = bits.read(5) as usize; | ||
| 339 | + let mut partition_classes = Vec::with_capacity(partitions); | ||
| 340 | + let mut max_class = 0usize; | ||
| 341 | + for _ in 0..partitions { | ||
| 342 | + let class = bits.read(4) as usize; | ||
| 343 | + max_class = max_class.max(class); | ||
| 344 | + partition_classes.push(class); | ||
| 345 | + } | ||
| 346 | + let class_count = if partitions == 0 { 0 } else { max_class + 1 }; | ||
| 347 | + let mut class_dimensions = Vec::with_capacity(class_count); | ||
| 348 | + let mut class_subclasses = Vec::with_capacity(class_count); | ||
| 349 | + let mut class_masterbooks = Vec::with_capacity(class_count); | ||
| 350 | + let mut subclass_books = Vec::with_capacity(class_count); | ||
| 351 | + for _ in 0..class_count { | ||
| 352 | + let dimensions = bits.read(3) as usize + 1; | ||
| 353 | + let subclasses = bits.read(2); | ||
| 354 | + let masterbook = if subclasses > 0 { | ||
| 355 | + let book = bits.read(8) as usize; | ||
| 356 | + if book >= codebooks.len() { | ||
| 357 | + return Err(Error::corrupt( | ||
| 358 | + "floor 1 names a masterbook that is not there", | ||
| 359 | + )); | ||
| 360 | + } | ||
| 361 | + book | ||
| 362 | + } else { | ||
| 363 | + 0 | ||
| 364 | + }; | ||
| 365 | + let mut books = Vec::with_capacity(1 << subclasses); | ||
| 366 | + for _ in 0..(1u32 << subclasses) { | ||
| 367 | + let book = bits.read(8) as i32 - 1; | ||
| 368 | + if book >= codebooks.len() as i32 { | ||
| 369 | + return Err(Error::corrupt("floor 1 names a book that is not there")); | ||
| 370 | + } | ||
| 371 | + books.push(book); | ||
| 372 | + } | ||
| 373 | + class_dimensions.push(dimensions); | ||
| 374 | + class_subclasses.push(subclasses); | ||
| 375 | + class_masterbooks.push(masterbook); | ||
| 376 | + subclass_books.push(books); | ||
| 377 | + } | ||
| 378 | + let multiplier = bits.read(2) as i32 + 1; | ||
| 379 | + let range_bits = bits.read(4); | ||
| 380 | + let mut x_list = vec![0u32, 1u32 << range_bits]; | ||
| 381 | + for &class in &partition_classes { | ||
| 382 | + for _ in 0..class_dimensions[class] { | ||
| 383 | + x_list.push(bits.read(range_bits)); | ||
| 384 | + } | ||
| 385 | + } | ||
| 386 | + if bits.eop() { | ||
| 387 | + return Err(Error::corrupt("floor 1 configuration truncated")); | ||
| 388 | + } | ||
| 389 | + if x_list.len() > 65 { | ||
| 390 | + return Err(Error::corrupt("floor 1 states more than 65 values")); | ||
| 391 | + } | ||
| 392 | + // The X list must be distinct or the curve has two heights at one | ||
| 393 | + // place; a stream that says so is corrupt, not a rendering choice. | ||
| 394 | + let mut seen = x_list.clone(); | ||
| 395 | + seen.sort_unstable(); | ||
| 396 | + if seen.windows(2).any(|w| w[0] == w[1]) { | ||
| 397 | + return Err(Error::corrupt("floor 1 repeats an X coordinate")); | ||
| 398 | + } | ||
| 399 | + if *seen.last().unwrap_or(&0) as usize > ident.blocksize_1 / 2 { | ||
| 400 | + return Err(Error::corrupt("floor 1 X coordinate past the block")); | ||
| 401 | + } | ||
| 402 | + let mut sorted: Vec<usize> = (0..x_list.len()).collect(); | ||
| 403 | + sorted.sort_by_key(|&i| x_list[i]); | ||
| 404 | + let neighbours = (0..x_list.len()) | ||
| 405 | + .map(|i| (low_neighbour(&x_list, i), high_neighbour(&x_list, i))) | ||
| 406 | + .collect(); | ||
| 407 | + Ok(FloorConfig::One(Floor1 { | ||
| 408 | + partition_classes, | ||
| 409 | + class_dimensions, | ||
| 410 | + class_subclasses, | ||
| 411 | + class_masterbooks, | ||
| 412 | + subclass_books, | ||
| 413 | + multiplier, | ||
| 414 | + x_list, | ||
| 415 | + sorted, | ||
| 416 | + neighbours, | ||
| 417 | + })) | ||
| 418 | + } | ||
| 419 | + other => Err(Error::unsupported( | ||
| 420 | + format!("floor type {other}"), | ||
| 421 | + "Vorbis I defines floor 0 and floor 1", | ||
| 422 | + )), | ||
| 423 | + } | ||
| 424 | +} | ||
| 425 | + | ||
| 426 | +/// Coding-order index of the largest X below `x_list[i]` among values already | ||
| 427 | +/// coded (§7.2.2 `low_neighbor`). | ||
| 428 | +fn low_neighbour(x_list: &[u32], i: usize) -> usize { | ||
| 429 | + let mut best = 0usize; | ||
| 430 | + let mut best_x = None; | ||
| 431 | + for (j, &x) in x_list.iter().enumerate().take(i) { | ||
| 432 | + if x < x_list[i] && best_x.is_none_or(|b| x > b) { | ||
| 433 | + best = j; | ||
| 434 | + best_x = Some(x); | ||
| 435 | + } | ||
| 436 | + } | ||
| 437 | + best | ||
| 438 | +} | ||
| 439 | + | ||
| 440 | +/// The mirror of [`low_neighbour`]. | ||
| 441 | +fn high_neighbour(x_list: &[u32], i: usize) -> usize { | ||
| 442 | + let mut best = 0usize; | ||
| 443 | + let mut best_x = None; | ||
| 444 | + for (j, &x) in x_list.iter().enumerate().take(i) { | ||
| 445 | + if x > x_list[i] && best_x.is_none_or(|b| x < b) { | ||
| 446 | + best = j; | ||
| 447 | + best_x = Some(x); | ||
| 448 | + } | ||
| 449 | + } | ||
| 450 | + best | ||
| 451 | +} | ||
| 452 | + | ||
| 453 | +fn parse_residue(bits: &mut Bits, codebook_count: usize) -> Result<ResidueConfig> { | ||
| 454 | + let kind = bits.read(16); | ||
| 455 | + if kind > 2 { | ||
| 456 | + return Err(Error::unsupported( | ||
| 457 | + format!("residue type {kind}"), | ||
| 458 | + "Vorbis I defines 0, 1 and 2", | ||
| 459 | + )); | ||
| 460 | + } | ||
| 461 | + let begin = bits.read(24) as usize; | ||
| 462 | + let end = bits.read(24) as usize; | ||
| 463 | + let partition_size = bits.read(24) as usize + 1; | ||
| 464 | + let classifications = bits.read(6) as usize + 1; | ||
| 465 | + let classbook = bits.read(8) as usize; | ||
| 466 | + if bits.eop() || classbook >= codebook_count || end < begin { | ||
| 467 | + return Err(Error::corrupt("residue configuration")); | ||
| 468 | + } | ||
| 469 | + let mut cascade = Vec::with_capacity(classifications); | ||
| 470 | + for _ in 0..classifications { | ||
| 471 | + let low = bits.read(3); | ||
| 472 | + let high = if bits.bit() { bits.read(5) } else { 0 }; | ||
| 473 | + cascade.push((high << 3) | low); | ||
| 474 | + } | ||
| 475 | + let mut books = Vec::with_capacity(classifications); | ||
| 476 | + for &cascade in &cascade { | ||
| 477 | + let mut row = [-1i32; 8]; | ||
| 478 | + for (pass, slot) in row.iter_mut().enumerate() { | ||
| 479 | + if cascade & (1 << pass) != 0 { | ||
| 480 | + let book = bits.read(8) as usize; | ||
| 481 | + if book >= codebook_count { | ||
| 482 | + return Err(Error::corrupt("residue names a book that is not there")); | ||
| 483 | + } | ||
| 484 | + *slot = book as i32; | ||
| 485 | + } | ||
| 486 | + } | ||
| 487 | + books.push(row); | ||
| 488 | + } | ||
| 489 | + if bits.eop() { | ||
| 490 | + return Err(Error::corrupt("residue configuration truncated")); | ||
| 491 | + } | ||
| 492 | + Ok(ResidueConfig { | ||
| 493 | + kind: kind as u8, | ||
| 494 | + begin, | ||
| 495 | + end, | ||
| 496 | + partition_size, | ||
| 497 | + classifications, | ||
| 498 | + classbook, | ||
| 499 | + books, | ||
| 500 | + }) | ||
| 501 | +} | ||
| 502 | + | ||
| 503 | +fn parse_mapping( | ||
| 504 | + bits: &mut Bits, | ||
| 505 | + channels: usize, | ||
| 506 | + floor_count: usize, | ||
| 507 | + residue_count: usize, | ||
| 508 | +) -> Result<MappingConfig> { | ||
| 509 | + if bits.read(16) != 0 { | ||
| 510 | + return Err(Error::unsupported( | ||
| 511 | + "mapping type other than 0", | ||
| 512 | + "Vorbis I defines mapping type 0 only", | ||
| 513 | + )); | ||
| 514 | + } | ||
| 515 | + let submap_count = if bits.bit() { | ||
| 516 | + bits.read(4) as usize + 1 | ||
| 517 | + } else { | ||
| 518 | + 1 | ||
| 519 | + }; | ||
| 520 | + let mut coupling = Vec::new(); | ||
| 521 | + if bits.bit() { | ||
| 522 | + let steps = bits.read(8) as usize + 1; | ||
| 523 | + let field = ilog((channels - 1) as u32); | ||
| 524 | + for _ in 0..steps { | ||
| 525 | + let magnitude = bits.read(field) as usize; | ||
| 526 | + let angle = bits.read(field) as usize; | ||
| 527 | + if magnitude == angle || magnitude >= channels || angle >= channels { | ||
| 528 | + return Err(Error::corrupt("coupling step names an impossible pair")); | ||
| 529 | + } | ||
| 530 | + coupling.push((magnitude, angle)); | ||
| 531 | + } | ||
| 532 | + } | ||
| 533 | + if bits.read(2) != 0 { | ||
| 534 | + return Err(Error::corrupt("mapping reserved bits are not zero")); | ||
| 535 | + } | ||
| 536 | + let mux = match submap_count > 1 { | ||
| 537 | + true => (0..channels) | ||
| 538 | + .map(|_| { | ||
| 539 | + let submap = bits.read(4) as usize; | ||
| 540 | + match submap < submap_count { | ||
| 541 | + true => Ok(submap), | ||
| 542 | + false => Err(Error::corrupt("channel names a submap that is not there")), | ||
| 543 | + } | ||
| 544 | + }) | ||
| 545 | + .collect::<Result<Vec<_>>>()?, | ||
| 546 | + false => vec![0; channels], | ||
| 547 | + }; | ||
| 548 | + let mut submaps = Vec::with_capacity(submap_count); | ||
| 549 | + for _ in 0..submap_count { | ||
| 550 | + let _unused = bits.read(8); | ||
| 551 | + let floor = bits.read(8) as usize; | ||
| 552 | + let residue = bits.read(8) as usize; | ||
| 553 | + if floor >= floor_count || residue >= residue_count { | ||
| 554 | + return Err(Error::corrupt( | ||
| 555 | + "submap names a floor or residue that is not there", | ||
| 556 | + )); | ||
| 557 | + } | ||
| 558 | + submaps.push((floor, residue)); | ||
| 559 | + } | ||
| 560 | + if bits.eop() { | ||
| 561 | + return Err(Error::corrupt("mapping truncated")); | ||
| 562 | + } | ||
| 563 | + Ok(MappingConfig { | ||
| 564 | + coupling, | ||
| 565 | + mux, | ||
| 566 | + submaps, | ||
| 567 | + }) | ||
| 568 | +} | ||
| 569 | + | ||
| 570 | +#[cfg(test)] | ||
| 571 | +mod tests { | ||
| 572 | + use super::*; | ||
| 573 | + | ||
| 574 | + #[test] | ||
| 575 | + fn identification_refuses_what_it_cannot_decode() { | ||
| 576 | + assert!(Identification::parse(b"garbage").is_err()); | ||
| 577 | + // Type 1 header, blocksizes 256/2048, 2 channels, 44100 Hz. | ||
| 578 | + let mut header = vec![1u8]; | ||
| 579 | + header.extend_from_slice(b"vorbis"); | ||
| 580 | + header.extend_from_slice(&0u32.to_le_bytes()); | ||
| 581 | + header.push(2); | ||
| 582 | + header.extend_from_slice(&44_100u32.to_le_bytes()); | ||
| 583 | + header.extend_from_slice(&0i32.to_le_bytes()); | ||
| 584 | + header.extend_from_slice(&128_000i32.to_le_bytes()); | ||
| 585 | + header.extend_from_slice(&0i32.to_le_bytes()); | ||
| 586 | + header.push(0xb8); // blocksize_0 = 2^8, blocksize_1 = 2^11 | ||
| 587 | + header.push(0x01); // framing | ||
| 588 | + let ident = Identification::parse(&header).expect("identification"); | ||
| 589 | + assert_eq!(ident.channels, 2); | ||
| 590 | + assert_eq!(ident.rate, 44_100); | ||
| 591 | + assert_eq!(ident.blocksize_0, 256); | ||
| 592 | + assert_eq!(ident.blocksize_1, 2048); | ||
| 593 | + assert_eq!(ident.bitrate_nominal, 128_000); | ||
| 594 | + } | ||
| 595 | +} | ||
crates/ec-vorbis/src/window.rsadded+103 -0
| @@ -0,0 +1,103 @@ | |||
| 1 | +//! Vorbis windows (§4.3.1), including the asymmetric long-block shapes. | ||
| 2 | +//! | ||
| 3 | +//! A long block next to a short one does not use the long slope: it uses the | ||
| 4 | +//! *short* slope, centred where the short block's own slope will be, and is | ||
| 5 | +//! flat or zero either side of it. That is what makes the two windows still add | ||
| 6 | +//! to one across the overlap, and it is the whole reason a Vorbis decoder needs | ||
| 7 | +//! four long-window variants rather than one. | ||
| 8 | + | ||
| 9 | +/// The Vorbis slope of `n` samples: `sin(pi/2 * sin^2((i + 1/2)/n * pi/2))`, | ||
| 10 | +/// rising from 0 to 1. | ||
| 11 | +fn slope(n: usize) -> Vec<f32> { | ||
| 12 | + (0..n) | ||
| 13 | + .map(|i| { | ||
| 14 | + let x = (i as f64 + 0.5) / n as f64 * std::f64::consts::FRAC_PI_2; | ||
| 15 | + let s = x.sin(); | ||
| 16 | + (std::f64::consts::FRAC_PI_2 * s * s).sin() as f32 | ||
| 17 | + }) | ||
| 18 | + .collect() | ||
| 19 | +} | ||
| 20 | + | ||
| 21 | +/// One window of `n` samples for a block whose neighbours are long or short. | ||
| 22 | +/// | ||
| 23 | +/// `short` is the stream's short blocksize; it is what sets the slope width | ||
| 24 | +/// when a neighbour is short. For a short block itself both flags are true by | ||
| 25 | +/// construction (its slopes are already the narrow ones). | ||
| 26 | +pub fn build(n: usize, short: usize, previous_long: bool, next_long: bool) -> Vec<f32> { | ||
| 27 | + let mut window = vec![0.0f32; n]; | ||
| 28 | + let (left_start, left_n) = match previous_long { | ||
| 29 | + true => (0usize, n / 2), | ||
| 30 | + false => (n / 4 - short / 4, short / 2), | ||
| 31 | + }; | ||
| 32 | + let (right_start, right_n) = match next_long { | ||
| 33 | + true => (n / 2, n / 2), | ||
| 34 | + false => (n * 3 / 4 - short / 4, short / 2), | ||
| 35 | + }; | ||
| 36 | + let left = slope(left_n); | ||
| 37 | + let right = slope(right_n); | ||
| 38 | + for (i, value) in left.iter().enumerate() { | ||
| 39 | + window[left_start + i] = *value; | ||
| 40 | + } | ||
| 41 | + window[left_start + left_n..right_start].fill(1.0); | ||
| 42 | + // The right slope is the left one read backwards, which is what makes the | ||
| 43 | + // pair Princen-Bradley. | ||
| 44 | + for i in 0..right_n { | ||
| 45 | + window[right_start + i] = right[right_n - 1 - i]; | ||
| 46 | + } | ||
| 47 | + window | ||
| 48 | +} | ||
| 49 | + | ||
| 50 | +/// The four long-block variants plus the short one, built once per stream. | ||
| 51 | +pub struct Windows { | ||
| 52 | + short: Vec<f32>, | ||
| 53 | + long: [Vec<f32>; 4], | ||
| 54 | +} | ||
| 55 | + | ||
| 56 | +impl Windows { | ||
| 57 | + /// Build every window a stream with these blocksizes can ask for. | ||
| 58 | + pub fn new(blocksize_0: usize, blocksize_1: usize) -> Windows { | ||
| 59 | + Windows { | ||
| 60 | + short: build(blocksize_0, blocksize_0, true, true), | ||
| 61 | + long: [ | ||
| 62 | + build(blocksize_1, blocksize_0, false, false), | ||
| 63 | + build(blocksize_1, blocksize_0, false, true), | ||
| 64 | + build(blocksize_1, blocksize_0, true, false), | ||
| 65 | + build(blocksize_1, blocksize_0, true, true), | ||
| 66 | + ], | ||
| 67 | + } | ||
| 68 | + } | ||
| 69 | + | ||
| 70 | + /// The window for one block. | ||
| 71 | + pub fn get(&self, long: bool, previous_long: bool, next_long: bool) -> &[f32] { | ||
| 72 | + match long { | ||
| 73 | + false => &self.short, | ||
| 74 | + true => &self.long[usize::from(previous_long) * 2 + usize::from(next_long)], | ||
| 75 | + } | ||
| 76 | + } | ||
| 77 | +} | ||
| 78 | + | ||
| 79 | +#[cfg(test)] | ||
| 80 | +mod tests { | ||
| 81 | + use super::*; | ||
| 82 | + | ||
| 83 | + #[test] | ||
| 84 | + fn overlapping_windows_add_to_one() { | ||
| 85 | + // Long block against long block: the two slopes are the classic | ||
| 86 | + // Princen-Bradley pair, so squares sum to one across the overlap. | ||
| 87 | + let long = build(2048, 256, true, true); | ||
| 88 | + for i in 0..1024 { | ||
| 89 | + let sum = long[1024 + i] * long[1024 + i] + long[i] * long[i]; | ||
| 90 | + assert!((sum - 1.0).abs() < 1e-6, "{i}: {sum}"); | ||
| 91 | + } | ||
| 92 | + // Long block against a short neighbour: the long window's right slope | ||
| 93 | + // is the short window's own slope, sitting where the short block will | ||
| 94 | + // put its left one, and is zero past it. | ||
| 95 | + let to_short = build(2048, 256, true, false); | ||
| 96 | + let short = build(256, 256, true, true); | ||
| 97 | + assert!(to_short[2047] == 0.0 && to_short[1600] == 0.0); | ||
| 98 | + for i in 0..128 { | ||
| 99 | + let sum = to_short[1472 + i] * to_short[1472 + i] + short[i] * short[i]; | ||
| 100 | + assert!((sum - 1.0).abs() < 1e-6, "{i}: {sum}"); | ||
| 101 | + } | ||
| 102 | + } | ||
| 103 | +} | ||