mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-25 16:53:05 +00:00
Merge pull request #1959 from el-j/feat/audio-vorbis-decode
craft-audio: native Vorbis I decoder (#1547)
This commit is contained in:
@@ -36,6 +36,8 @@ flac-encode = ["craft-media/bitstream"]
|
||||
# The pure-Rust Vorbis encoder (`vorbis::encoder`) and Ogg Vorbis files through `encode` and
|
||||
# `encode_ogg_vorbis`.
|
||||
vorbis-encode = ["craft-media/ogg"]
|
||||
# The pure-Rust Vorbis decoder (`vorbis::decoder`), packets and whole Ogg Vorbis files.
|
||||
vorbis-decode = ["craft-media/ogg"]
|
||||
# Codec modules on their own, for packet-level use.
|
||||
aac-decode = ["craft-media/bitstream"]
|
||||
# The AAC encoder (`aac::Encoder`), and AAC in M4A through `encode` and `FileEncoder`.
|
||||
@@ -121,6 +123,18 @@ required-features = ["adpcm"]
|
||||
name = "flac_decode"
|
||||
required-features = ["flac-decode", "flac-encode"]
|
||||
|
||||
[[test]]
|
||||
name = "vorbis_decode_oracle"
|
||||
required-features = ["vorbis-decode", "vorbis-encode", "decode"]
|
||||
|
||||
[[test]]
|
||||
name = "vorbis_decode_hostile"
|
||||
required-features = ["vorbis-decode", "vorbis-encode"]
|
||||
|
||||
[[test]]
|
||||
name = "vorbis_decode_synthetic"
|
||||
required-features = ["vorbis-decode"]
|
||||
|
||||
[[test]]
|
||||
name = "gsm_oracle"
|
||||
required-features = ["gsm"]
|
||||
|
||||
@@ -39,6 +39,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou
|
||||
| `alac-encode` | `alac::Encoder`; `encode`, `FileEncoder` for ALAC in M4A | craft-media `isobmff` |
|
||||
| `opus-decode`, `opus-encode` | `opus::Decoder`/`StreamDecoder`, `opus::Encoder` | none |
|
||||
| `vorbis-encode` | `vorbis::encoder::Encoder` (pure Rust); `encode_ogg_vorbis`, `encode_ogg` and `encode` for Ogg Vorbis files (whole buffer; not `FileEncoder`) | craft-media `ogg` |
|
||||
| `vorbis-decode` | `vorbis::decoder::Decoder` (packets), `vorbis::decoder::decode_ogg` (whole Ogg Vorbis files); native Vorbis I: floors 0 and 1, residues 0 to 2, channel coupling, both block sizes. `decode` still reads Vorbis files through symphonia | craft-media `ogg` |
|
||||
| `ac3-decode` | `ac3::Decoder`, `ac3::ProgrammeDecoder` | craft-media `bitstream` |
|
||||
| `ac3-encode`, `eac3-encode` | `ac3::encoder::Encoder`; `encode`, `FileEncoder` for AC-3 and E-AC-3 streams | craft-media `bitstream` |
|
||||
| `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` |
|
||||
|
||||
@@ -13,6 +13,7 @@
|
||||
//! demuxers and [`TrackDecoder`]; everything else (FLAC, Vorbis, CAF, ADPCM, A-law, µ-law) through
|
||||
//! `symphonia`, which is to be replaced by native decoders. Feature `decode-native` is the
|
||||
//! same without symphonia.
|
||||
//! - [`vorbis::decoder`] (feature `vorbis-decode`): the pure-Rust Vorbis I decoder, packets and Ogg files.
|
||||
//! - [`encode_ogg_vorbis`] and [`vorbis::encoder`] (feature `vorbis-encode`): Ogg Vorbis files
|
||||
//! and Vorbis packets from a pure-Rust encoder, 1 to 8 channels, quality -1 to 10, with tags.
|
||||
//! - [`TrackDecoder`] (any decoder feature): one track's packets from any demuxer to planar
|
||||
@@ -71,7 +72,7 @@ pub mod sbc;
|
||||
mod track;
|
||||
#[cfg(feature = "vmd-decode")]
|
||||
pub mod vmd;
|
||||
#[cfg(feature = "vorbis-encode")]
|
||||
#[cfg(any(feature = "vorbis-decode", feature = "vorbis-encode"))]
|
||||
pub mod vorbis;
|
||||
#[cfg(any(feature = "decode-native", feature = "pcm-encode"))]
|
||||
mod wav;
|
||||
|
||||
@@ -0,0 +1,96 @@
|
||||
//! The Vorbis bit reader (Vorbis I §2): bits are taken least significant first from each byte.
|
||||
|
||||
/// Reading past the end of the packet ("end-of-packet", §2.1.8).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub(super) struct Eop;
|
||||
|
||||
pub(super) struct BitReader<'a> {
|
||||
data: &'a [u8],
|
||||
/// The position of the next bit.
|
||||
pos: usize,
|
||||
}
|
||||
|
||||
impl<'a> BitReader<'a> {
|
||||
pub(super) fn new(data: &'a [u8]) -> Self {
|
||||
Self { data, pos: 0 }
|
||||
}
|
||||
|
||||
/// The bits not yet read.
|
||||
pub(super) fn remaining(&self) -> usize {
|
||||
(self.data.len() * 8).saturating_sub(self.pos)
|
||||
}
|
||||
|
||||
/// Read `n` (at most 32) bits as an unsigned integer. A read that does not fit takes nothing.
|
||||
pub(super) fn read(&mut self, n: u32) -> Result<u32, Eop> {
|
||||
if n == 0 {
|
||||
return Ok(0);
|
||||
}
|
||||
if (n as usize) > self.remaining() {
|
||||
self.pos = self.data.len() * 8;
|
||||
return Err(Eop);
|
||||
}
|
||||
let mut value = 0u64;
|
||||
let mut got = 0u32;
|
||||
while got < n {
|
||||
let byte = u64::from(self.data[self.pos / 8]);
|
||||
let shift = (self.pos % 8) as u32;
|
||||
let take = (8 - shift).min(n - got);
|
||||
value |= ((byte >> shift) & ((1 << take) - 1)) << got;
|
||||
got += take;
|
||||
self.pos += take as usize;
|
||||
}
|
||||
Ok(value as u32)
|
||||
}
|
||||
|
||||
pub(super) fn bit(&mut self) -> Result<bool, Eop> {
|
||||
Ok(self.read(1)? == 1)
|
||||
}
|
||||
}
|
||||
|
||||
/// `ilog(x)` (§9.2.1): the position of the highest set bit, 0 for values below 1.
|
||||
pub(super) fn ilog(x: i64) -> u32 {
|
||||
if x <= 0 { 0 } else { 64 - (x as u64).leading_zeros() }
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn reads_least_significant_bit_first() {
|
||||
// Fields come out of each byte from its least significant bit.
|
||||
let mut r = BitReader::new(&[0xFC, 0x08]);
|
||||
assert_eq!(r.read(4), Ok(0xC));
|
||||
assert_eq!(r.read(4), Ok(0xF));
|
||||
assert_eq!(r.read(1), Ok(0));
|
||||
assert_eq!(r.read(3), Ok(4));
|
||||
assert_eq!(r.read(4), Ok(0));
|
||||
assert_eq!(r.read(1), Err(Eop));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn wide_reads_span_bytes_and_zero_bits_are_free() {
|
||||
let mut r = BitReader::new(&[0x01, 0x02, 0x03, 0x04, 0x05]);
|
||||
assert_eq!(r.read(0), Ok(0));
|
||||
assert_eq!(r.read(32), Ok(0x0403_0201));
|
||||
assert_eq!(r.read(8), Ok(5));
|
||||
assert_eq!(r.read(0), Ok(0));
|
||||
assert_eq!(r.read(1), Err(Eop));
|
||||
assert_eq!(r.remaining(), 0);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_failed_read_consumes_the_rest() {
|
||||
let mut r = BitReader::new(&[0xFF]);
|
||||
assert_eq!(r.read(3), Ok(7));
|
||||
assert_eq!(r.read(6), Err(Eop));
|
||||
assert_eq!(r.read(1), Err(Eop));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ilog_matches_the_specification_examples() {
|
||||
for (x, want) in [(0, 0), (1, 1), (2, 2), (3, 2), (4, 3), (7, 3), (-5, 0), (255, 8), (256, 9)] {
|
||||
assert_eq!(ilog(x), want, "ilog({x})");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,409 @@
|
||||
//! Codebooks (Vorbis I §3): a Huffman code over entry numbers and an optional table of vectors.
|
||||
|
||||
use super::Error;
|
||||
use super::bits::{BitReader, Eop, ilog};
|
||||
|
||||
const NONE: u32 = u32::MAX;
|
||||
const LEAF: u32 = 1 << 31;
|
||||
/// Entries a codebook may declare.
|
||||
const MAX_ENTRIES: u32 = 1 << 20;
|
||||
/// Nodes of one codeword tree.
|
||||
const MAX_NODES: usize = 1 << 22;
|
||||
|
||||
#[derive(Clone, Copy)]
|
||||
struct Node {
|
||||
child: [u32; 2],
|
||||
full: bool,
|
||||
}
|
||||
|
||||
pub(super) struct Codebook {
|
||||
pub(super) dimensions: usize,
|
||||
pub(super) entries: usize,
|
||||
tree: Vec<Node>,
|
||||
/// The only used entry of a single-entry book.
|
||||
single: Option<u32>,
|
||||
/// `entries * dimensions` values when the book has a lookup table.
|
||||
vectors: Vec<f32>,
|
||||
}
|
||||
|
||||
/// `float32_unpack` (§9.2.2).
|
||||
fn float32_unpack(x: u32) -> f64 {
|
||||
let mantissa = f64::from(x & 0x001F_FFFF);
|
||||
let exponent = ((x & 0x7FE0_0000) >> 21) as i32;
|
||||
let m = if x & 0x8000_0000 != 0 { -mantissa } else { mantissa };
|
||||
m * 2f64.powi(exponent - 788)
|
||||
}
|
||||
|
||||
/// `lookup1_values` (§9.2.3): the greatest `v` with `v^dimensions <= entries`.
|
||||
fn lookup1_values(entries: u32, dimensions: u32) -> u32 {
|
||||
let mut v = 1u32;
|
||||
loop {
|
||||
let next = u128::from(v) + 1;
|
||||
let mut p = 1u128;
|
||||
for _ in 0..dimensions {
|
||||
p *= next;
|
||||
if p > u128::from(entries) {
|
||||
return v;
|
||||
}
|
||||
}
|
||||
v += 1;
|
||||
}
|
||||
}
|
||||
|
||||
fn insert(tree: &mut Vec<Node>, at: usize, depth: u32, len: u32, entry: u32) -> bool {
|
||||
for b in 0..2 {
|
||||
let child = tree[at].child[b];
|
||||
if depth + 1 == len {
|
||||
if child == NONE {
|
||||
tree[at].child[b] = LEAF | entry;
|
||||
refresh(tree, at);
|
||||
return true;
|
||||
}
|
||||
continue;
|
||||
}
|
||||
if child == NONE {
|
||||
if tree.len() >= MAX_NODES {
|
||||
return false;
|
||||
}
|
||||
tree.push(Node { child: [NONE; 2], full: false });
|
||||
let new = tree.len() - 1;
|
||||
tree[at].child[b] = new as u32;
|
||||
if insert(tree, new, depth + 1, len, entry) {
|
||||
refresh(tree, at);
|
||||
return true;
|
||||
}
|
||||
return false;
|
||||
}
|
||||
if child & LEAF != 0 || tree[child as usize].full {
|
||||
continue;
|
||||
}
|
||||
if insert(tree, child as usize, depth + 1, len, entry) {
|
||||
refresh(tree, at);
|
||||
return true;
|
||||
}
|
||||
}
|
||||
false
|
||||
}
|
||||
|
||||
fn refresh(tree: &mut [Node], at: usize) {
|
||||
let done = |c: u32, t: &[Node]| c != NONE && (c & LEAF != 0 || t[c as usize].full);
|
||||
let full = done(tree[at].child[0], tree) && done(tree[at].child[1], tree);
|
||||
tree[at].full = full;
|
||||
}
|
||||
|
||||
impl Codebook {
|
||||
/// Read one codebook from a setup header. `budget` is the bytes the setup's codebooks may
|
||||
/// still take in all.
|
||||
pub(super) fn read(r: &mut BitReader<'_>, budget: &mut usize) -> Result<Self, Error> {
|
||||
let bad = |m: &'static str| Error::Setup(m);
|
||||
let eop = |_: Eop| Error::Setup("setup header ends inside a codebook");
|
||||
if r.read(24).map_err(eop)? != 0x0056_4342 {
|
||||
return Err(bad("codebook sync pattern missing"));
|
||||
}
|
||||
let dimensions = r.read(16).map_err(eop)?;
|
||||
let entries = r.read(24).map_err(eop)?;
|
||||
if dimensions == 0 || entries == 0 || entries > MAX_ENTRIES {
|
||||
return Err(bad("codebook with no dimensions, no entries or too many"));
|
||||
}
|
||||
let mut lengths: Vec<u8> = Vec::with_capacity(entries as usize);
|
||||
if r.bit().map_err(eop)? {
|
||||
// Ordered: the number of codewords of each length.
|
||||
let mut current = 0u32;
|
||||
let mut len = r.read(5).map_err(eop)? + 1;
|
||||
while current < entries {
|
||||
let number = r.read(ilog(i64::from(entries - current))).map_err(eop)?;
|
||||
if number > entries - current || len > 32 {
|
||||
return Err(bad("ordered codebook lengths overrun the entries"));
|
||||
}
|
||||
lengths.extend(std::iter::repeat_n(len as u8, number as usize));
|
||||
current += number;
|
||||
len += 1;
|
||||
}
|
||||
} else {
|
||||
let sparse = r.bit().map_err(eop)?;
|
||||
for _ in 0..entries {
|
||||
if sparse && !r.bit().map_err(eop)? {
|
||||
lengths.push(0);
|
||||
} else {
|
||||
lengths.push((r.read(5).map_err(eop)? + 1) as u8);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// The codeword tree.
|
||||
let used = lengths.iter().filter(|&&l| l != 0).count();
|
||||
let mut tree = vec![Node { child: [NONE; 2], full: false }];
|
||||
let mut single = None;
|
||||
if used == 1 {
|
||||
let entry = lengths.iter().position(|&l| l != 0).unwrap_or(0);
|
||||
if lengths[entry] != 1 {
|
||||
return Err(bad("a codebook with one used entry must give it length 1"));
|
||||
}
|
||||
single = Some(entry as u32);
|
||||
} else if used > 1 {
|
||||
for (entry, &len) in lengths.iter().enumerate() {
|
||||
if len != 0 && !insert(&mut tree, 0, 0, u32::from(len), entry as u32) {
|
||||
return Err(bad("overspecified codebook"));
|
||||
}
|
||||
}
|
||||
if !tree[0].full {
|
||||
return Err(bad("underspecified codebook"));
|
||||
}
|
||||
}
|
||||
let tree_bytes = tree.len() * std::mem::size_of::<Node>();
|
||||
if tree_bytes > *budget {
|
||||
return Err(Error::Limit("the codebooks are too large"));
|
||||
}
|
||||
*budget -= tree_bytes;
|
||||
|
||||
// The lookup table.
|
||||
let lookup_type = r.read(4).map_err(eop)?;
|
||||
let mut vectors = Vec::new();
|
||||
if lookup_type > 2 {
|
||||
return Err(bad("reserved codebook lookup type"));
|
||||
}
|
||||
if lookup_type != 0 {
|
||||
let minimum = float32_unpack(r.read(32).map_err(eop)?);
|
||||
let delta = float32_unpack(r.read(32).map_err(eop)?);
|
||||
let value_bits = r.read(4).map_err(eop)? + 1;
|
||||
let sequence = r.bit().map_err(eop)?;
|
||||
// Check before multiplying or reading multiplicands: the product can overflow
|
||||
// usize on 32-bit targets, and a type-2 table otherwise allocates before admission.
|
||||
let total = (entries as usize)
|
||||
.checked_mul(dimensions as usize)
|
||||
.filter(|&n| n <= *budget / std::mem::size_of::<f32>())
|
||||
.ok_or(Error::Limit("the codebooks' vector tables are too large"))?;
|
||||
let values = if lookup_type == 1 { lookup1_values(entries, dimensions) as usize } else { total };
|
||||
if !minimum.is_finite() || !delta.is_finite() || values > r.remaining() / value_bits as usize {
|
||||
return Err(bad("codebook lookup table is damaged or truncated"));
|
||||
}
|
||||
let multiplicands: Vec<u32> = (0..values).map(|_| r.read(value_bits).unwrap_or(0)).collect();
|
||||
*budget -= total * std::mem::size_of::<f32>();
|
||||
vectors = vec![0f32; total];
|
||||
for e in 0..entries as usize {
|
||||
let out = &mut vectors[e * dimensions as usize..(e + 1) * dimensions as usize];
|
||||
let mut last = 0f64;
|
||||
let mut divisor = 1usize;
|
||||
for (i, slot) in out.iter_mut().enumerate() {
|
||||
let m = if lookup_type == 1 {
|
||||
let at = (e / divisor) % values;
|
||||
divisor = divisor.saturating_mul(values);
|
||||
multiplicands[at]
|
||||
} else {
|
||||
multiplicands[e * dimensions as usize + i]
|
||||
};
|
||||
let v = f64::from(m) * delta + minimum + last;
|
||||
if sequence {
|
||||
last = v;
|
||||
}
|
||||
*slot = v as f32;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(Self { dimensions: dimensions as usize, entries: entries as usize, tree, single, vectors })
|
||||
}
|
||||
|
||||
/// Whether the book has a lookup table.
|
||||
pub(super) fn has_vectors(&self) -> bool {
|
||||
!self.vectors.is_empty()
|
||||
}
|
||||
|
||||
/// Read a codeword; the entry number (scalar context).
|
||||
pub(super) fn scalar(&self, r: &mut BitReader<'_>) -> Result<u32, Eop> {
|
||||
if let Some(e) = self.single {
|
||||
r.read(1)?;
|
||||
return Ok(e);
|
||||
}
|
||||
let mut at = 0usize;
|
||||
loop {
|
||||
let c = self.tree[at].child[usize::from(r.bit()?)];
|
||||
if c == NONE {
|
||||
return Err(Eop);
|
||||
}
|
||||
if c & LEAF != 0 {
|
||||
return Ok(c & !LEAF);
|
||||
}
|
||||
at = c as usize;
|
||||
}
|
||||
}
|
||||
|
||||
/// Read a codeword and return its vector (VQ context); `None` for a book without a table.
|
||||
pub(super) fn vector(&self, r: &mut BitReader<'_>) -> Result<Option<&[f32]>, Eop> {
|
||||
let e = self.scalar(r)? as usize;
|
||||
Ok(self.vectors.get(e * self.dimensions..(e + 1) * self.dimensions))
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
/// Pack fields least significant bit first.
|
||||
struct W(Vec<u8>, usize);
|
||||
impl W {
|
||||
fn put(&mut self, v: u64, n: u32) {
|
||||
for i in 0..n {
|
||||
if self.1.is_multiple_of(8) {
|
||||
self.0.push(0);
|
||||
}
|
||||
let last = self.0.len() - 1;
|
||||
self.0[last] |= (((v >> i) & 1) as u8) << (self.1 % 8);
|
||||
self.1 += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn book_bytes(lengths: &[u32], lookup: Option<(u32, u32, &[u32])>) -> Vec<u8> {
|
||||
let mut w = W(Vec::new(), 0);
|
||||
w.put(0x56_4342, 24);
|
||||
w.put(1, 16);
|
||||
w.put(lengths.len() as u64, 24);
|
||||
w.put(0, 1); // not ordered
|
||||
w.put(0, 1); // not sparse
|
||||
for &l in lengths {
|
||||
w.put(u64::from(l - 1), 5);
|
||||
}
|
||||
match lookup {
|
||||
None => w.put(0, 4),
|
||||
Some((ty, bits, mult)) => {
|
||||
w.put(u64::from(ty), 4);
|
||||
w.put(0, 32); // minimum: 0.0
|
||||
w.put(0, 32);
|
||||
w.put(u64::from(bits - 1), 4);
|
||||
w.put(0, 1);
|
||||
for &m in mult {
|
||||
w.put(u64::from(m), bits);
|
||||
}
|
||||
}
|
||||
}
|
||||
w.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_specification_example_assigns_its_codewords() {
|
||||
// §3.2.1: lengths 2 4 4 4 4 2 3 3 -> 00, 0100, 0101, 0110, 0111, 10, 110, 111.
|
||||
let bytes = book_bytes(&[2, 4, 4, 4, 4, 2, 3, 3], None);
|
||||
let mut budget = 1 << 26;
|
||||
let book = Codebook::read(&mut BitReader::new(&bytes), &mut budget).expect("book");
|
||||
let code = |bits: &[u8]| {
|
||||
let mut w = W(Vec::new(), 0);
|
||||
for &b in bits {
|
||||
w.put(u64::from(b), 1);
|
||||
}
|
||||
let mut r = BitReader::new(&w.0);
|
||||
book.scalar(&mut r).expect("entry")
|
||||
};
|
||||
assert_eq!(code(&[0, 0]), 0);
|
||||
assert_eq!(code(&[0, 1, 0, 0]), 1);
|
||||
assert_eq!(code(&[0, 1, 1, 1]), 4);
|
||||
assert_eq!(code(&[1, 0]), 5);
|
||||
assert_eq!(code(&[1, 1, 0]), 6);
|
||||
assert_eq!(code(&[1, 1, 1]), 7);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn over_and_underspecified_books_are_errors() {
|
||||
let mut budget = 1 << 26;
|
||||
let over = book_bytes(&[1, 1, 1], None);
|
||||
assert!(Codebook::read(&mut BitReader::new(&over), &mut budget).is_err());
|
||||
let under = book_bytes(&[2, 2, 2], None);
|
||||
assert!(Codebook::read(&mut BitReader::new(&under), &mut budget).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_single_entry_book_sinks_one_bit_of_either_value() {
|
||||
let mut budget = 1 << 26;
|
||||
let bytes = book_bytes(&[1], None);
|
||||
let book = Codebook::read(&mut BitReader::new(&bytes), &mut budget).expect("book");
|
||||
for byte in [0u8, 1] {
|
||||
let data = [byte];
|
||||
let mut r = BitReader::new(&data);
|
||||
assert_eq!(book.scalar(&mut r), Ok(0));
|
||||
assert_eq!(r.remaining(), 7);
|
||||
}
|
||||
let bad = book_bytes(&[2], None);
|
||||
assert!(Codebook::read(&mut BitReader::new(&bad), &mut budget).is_err());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn lookup_type_one_builds_a_lattice() {
|
||||
// 4 entries, 2 dimensions, 2 values per dimension: minimum 0 and delta 1 in the packed
|
||||
// float format are written below by hand (mantissa 1, exponent 788 -> 1.0).
|
||||
let mut w = W(Vec::new(), 0);
|
||||
w.put(0x56_4342, 24);
|
||||
w.put(2, 16);
|
||||
w.put(4, 24);
|
||||
w.put(0, 1);
|
||||
w.put(0, 1);
|
||||
for _ in 0..4 {
|
||||
w.put(1, 5); // length 2 each
|
||||
}
|
||||
w.put(1, 4); // lookup type 1
|
||||
w.put(0, 32); // minimum 0
|
||||
w.put((788u64 << 21) | 1, 32); // delta 1.0
|
||||
w.put(0, 4); // 1 bit per value
|
||||
w.put(0, 1);
|
||||
w.put(0b10, 2); // multiplicands 0, 1
|
||||
let mut budget = 1 << 26;
|
||||
let book = Codebook::read(&mut BitReader::new(&w.0), &mut budget).expect("book");
|
||||
assert_eq!(lookup1_values(4, 2), 2);
|
||||
// Entry e is (m[e % 2], m[(e / 2) % 2]).
|
||||
assert_eq!(book.vectors, vec![0.0, 0.0, 1.0, 0.0, 0.0, 1.0, 1.0, 1.0]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_budget_is_checked_before_reading_lookup_values() {
|
||||
// A valid single-entry tree, but two values exceed the remaining budget.
|
||||
// No multiplicands follow: admission must reject it before reading them.
|
||||
for lookup in [1, 2] {
|
||||
let mut w = W(Vec::new(), 0);
|
||||
w.put(0x56_4342, 24);
|
||||
w.put(2, 16);
|
||||
w.put(1, 24);
|
||||
w.put(0, 1);
|
||||
w.put(0, 1);
|
||||
w.put(0, 5);
|
||||
w.put(lookup, 4);
|
||||
w.put(0, 32);
|
||||
w.put(0, 32);
|
||||
w.put(15, 4);
|
||||
w.put(0, 1);
|
||||
let mut budget = std::mem::size_of::<Node>() + 4;
|
||||
assert!(matches!(Codebook::read(&mut BitReader::new(&w.0), &mut budget), Err(Error::Limit(_))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn vector_size_that_overflows_32_bits_is_refused() {
|
||||
for lookup in [1, 2] {
|
||||
let mut w = W(Vec::new(), 0);
|
||||
w.put(0x56_4342, 24);
|
||||
w.put(65535, 16);
|
||||
w.put(65538, 24); // product is above u32::MAX
|
||||
w.put(0, 1); // unordered
|
||||
w.put(1, 1); // sparse: only one entry is used
|
||||
w.put(1, 1);
|
||||
w.put(0, 5); // length 1
|
||||
for _ in 1..65538 {
|
||||
w.put(0, 1);
|
||||
}
|
||||
w.put(lookup, 4);
|
||||
w.put(0, 32);
|
||||
w.put(0, 32);
|
||||
w.put(0, 4);
|
||||
w.put(0, 1);
|
||||
w.put(0, 1); // lookup type 1's single multiplicand
|
||||
let mut budget = 256 << 20;
|
||||
assert!(matches!(Codebook::read(&mut BitReader::new(&w.0), &mut budget), Err(Error::Limit(_))));
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn helper_functions() {
|
||||
assert_eq!(float32_unpack((788u32 << 21) | 5), 5.0);
|
||||
assert_eq!(float32_unpack(0x8000_0000 | (789u32 << 21) | 3), -6.0);
|
||||
for (entries, dims, want) in [(8, 3, 2), (9, 2, 3), (1, 5, 1), (10, 1, 10), (1000, 3, 10), (4_000_000, 2, 2000)] {
|
||||
assert_eq!(lookup1_values(entries, dims), want, "{entries} entries, {dims} dims");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,385 @@
|
||||
//! Floors (Vorbis I §6 and §7): the spectral envelope each channel's residue is multiplied by.
|
||||
|
||||
use super::Error;
|
||||
use super::bits::{BitReader, Eop, ilog};
|
||||
use super::codebook::Codebook;
|
||||
use super::tables::INVERSE_DB;
|
||||
|
||||
/// Why a floor could not be decoded from a packet.
|
||||
pub(super) enum Fail {
|
||||
/// The packet ended (a nominal event: the channel is silent).
|
||||
Eop,
|
||||
/// The packet names a codebook that does not exist: it cannot be decoded (§6.2.2).
|
||||
Invalid,
|
||||
}
|
||||
|
||||
impl From<Eop> for Fail {
|
||||
fn from(_: Eop) -> Self {
|
||||
Fail::Eop
|
||||
}
|
||||
}
|
||||
|
||||
/// What a decoded floor gives to synthesis.
|
||||
pub(super) enum FloorData {
|
||||
One { y: Vec<i32>, step2: Vec<bool> },
|
||||
Zero { amplitude: u32, coefficients: Vec<f32> },
|
||||
}
|
||||
|
||||
pub(super) struct Floor0 {
|
||||
order: usize,
|
||||
rate: u32,
|
||||
bark_map_size: u32,
|
||||
amplitude_bits: u32,
|
||||
amplitude_offset: u32,
|
||||
books: Vec<usize>,
|
||||
}
|
||||
|
||||
pub(super) struct Floor1 {
|
||||
partition_class: Vec<usize>,
|
||||
class_dimensions: Vec<usize>,
|
||||
class_subclasses: Vec<u32>,
|
||||
class_masterbook: Vec<usize>,
|
||||
subclass_books: Vec<Vec<i32>>,
|
||||
multiplier: i32,
|
||||
range: i32,
|
||||
xlist: Vec<i32>,
|
||||
/// `(low, high)` neighbour positions of each X from index 2 on.
|
||||
neighbours: Vec<(usize, usize)>,
|
||||
/// Indices of `xlist` in ascending X order.
|
||||
sorted: Vec<usize>,
|
||||
}
|
||||
|
||||
pub(super) enum Floor {
|
||||
Zero(Floor0),
|
||||
One(Floor1),
|
||||
}
|
||||
|
||||
fn eop(_: Eop) -> Error {
|
||||
Error::Setup("setup header ends inside a floor")
|
||||
}
|
||||
|
||||
impl Floor {
|
||||
pub(super) fn read(floor_type: u32, r: &mut BitReader<'_>, books: &[Codebook]) -> Result<Self, Error> {
|
||||
match floor_type {
|
||||
0 => {
|
||||
let order = r.read(8).map_err(eop)? as usize;
|
||||
let rate = r.read(16).map_err(eop)?;
|
||||
let bark_map_size = r.read(16).map_err(eop)?;
|
||||
let amplitude_bits = r.read(6).map_err(eop)?;
|
||||
let amplitude_offset = r.read(8).map_err(eop)?;
|
||||
let count = r.read(4).map_err(eop)? as usize + 1;
|
||||
let mut list = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let b = r.read(8).map_err(eop)? as usize;
|
||||
match books.get(b) {
|
||||
Some(book) if book.has_vectors() => list.push(b),
|
||||
_ => return Err(Error::Setup("floor 0 names a missing codebook or one without vectors")),
|
||||
}
|
||||
}
|
||||
if order == 0 || rate == 0 || bark_map_size == 0 || amplitude_bits > 32 {
|
||||
return Err(Error::Setup("floor 0 with a zero order, rate or map size, or more than 32 amplitude bits"));
|
||||
}
|
||||
Ok(Self::Zero(Floor0 { order, rate, bark_map_size, amplitude_bits, amplitude_offset, books: list }))
|
||||
}
|
||||
1 => {
|
||||
let partitions = r.read(5).map_err(eop)? as usize;
|
||||
let mut partition_class = Vec::with_capacity(partitions);
|
||||
for _ in 0..partitions {
|
||||
partition_class.push(r.read(4).map_err(eop)? as usize);
|
||||
}
|
||||
let classes = partition_class.iter().max().map_or(0, |m| m + 1);
|
||||
let (mut class_dimensions, mut class_subclasses, mut class_masterbook, mut subclass_books) = (vec![], vec![], vec![], vec![]);
|
||||
for _ in 0..classes {
|
||||
class_dimensions.push(r.read(3).map_err(eop)? as usize + 1);
|
||||
let subs = r.read(2).map_err(eop)?;
|
||||
class_subclasses.push(subs);
|
||||
let master = if subs != 0 { r.read(8).map_err(eop)? as usize } else { 0 };
|
||||
if subs != 0 && master >= books.len() {
|
||||
return Err(Error::Setup("floor 1 master book out of range"));
|
||||
}
|
||||
class_masterbook.push(master);
|
||||
let mut list = Vec::new();
|
||||
for _ in 0..(1u32 << subs) {
|
||||
let b = r.read(8).map_err(eop)? as i32 - 1;
|
||||
if b >= books.len() as i32 {
|
||||
return Err(Error::Setup("floor 1 subclass book out of range"));
|
||||
}
|
||||
list.push(b);
|
||||
}
|
||||
subclass_books.push(list);
|
||||
}
|
||||
let multiplier = r.read(2).map_err(eop)? as i32 + 1;
|
||||
let rangebits = r.read(4).map_err(eop)?;
|
||||
let mut xlist = vec![0, 1i32 << rangebits];
|
||||
for &c in &partition_class {
|
||||
for _ in 0..class_dimensions[c] {
|
||||
xlist.push(r.read(rangebits).map_err(eop)? as i32);
|
||||
}
|
||||
}
|
||||
if xlist.len() > 65 {
|
||||
return Err(Error::Setup("floor 1 has more than 65 points"));
|
||||
}
|
||||
let mut seen = xlist.clone();
|
||||
seen.sort_unstable();
|
||||
if seen.windows(2).any(|w| w[0] == w[1]) {
|
||||
return Err(Error::Setup("floor 1 repeats an X position"));
|
||||
}
|
||||
// Low and high neighbours (§9.2.4, §9.2.5) of each point, among those before it.
|
||||
let mut neighbours = Vec::new();
|
||||
for i in 2..xlist.len() {
|
||||
let (mut lo, mut hi) = (0usize, 1usize);
|
||||
for j in 0..i {
|
||||
if xlist[j] < xlist[i] && xlist[j] > xlist[lo] {
|
||||
lo = j;
|
||||
}
|
||||
if xlist[j] > xlist[i] && xlist[j] < xlist[hi] {
|
||||
hi = j;
|
||||
}
|
||||
}
|
||||
neighbours.push((lo, hi));
|
||||
}
|
||||
let mut sorted: Vec<usize> = (0..xlist.len()).collect();
|
||||
sorted.sort_by_key(|&i| xlist[i]);
|
||||
let range = [256, 128, 86, 64][multiplier as usize - 1];
|
||||
Ok(Self::One(Floor1 {
|
||||
partition_class,
|
||||
class_dimensions,
|
||||
class_subclasses,
|
||||
class_masterbook,
|
||||
subclass_books,
|
||||
multiplier,
|
||||
range,
|
||||
xlist,
|
||||
neighbours,
|
||||
sorted,
|
||||
}))
|
||||
}
|
||||
_ => Err(Error::Setup("unknown floor type")),
|
||||
}
|
||||
}
|
||||
|
||||
/// Decode one channel's floor from a packet: `None` when the channel is unused this block.
|
||||
pub(super) fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook]) -> Result<Option<FloorData>, Fail> {
|
||||
match self {
|
||||
Self::One(f) => Ok(f.decode(r, books)?),
|
||||
Self::Zero(f) => f.decode(r, books),
|
||||
}
|
||||
}
|
||||
|
||||
/// The floor curve over `n` bins (`n` is half the block size).
|
||||
pub(super) fn curve(&self, data: &FloorData, n: usize) -> Vec<f32> {
|
||||
match (self, data) {
|
||||
(Self::One(f), FloorData::One { y, step2 }) => f.curve(y, step2, n),
|
||||
(Self::Zero(f), FloorData::Zero { amplitude, coefficients }) => f.curve(*amplitude, coefficients, n),
|
||||
_ => vec![0.0; n],
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// `render_point` (§9.2.6).
|
||||
fn render_point(x0: i32, y0: i32, x1: i32, y1: i32, x: i32) -> i32 {
|
||||
let dy = i64::from(y1 - y0);
|
||||
let adx = i64::from(x1 - x0);
|
||||
let err = dy.abs() * i64::from(x - x0);
|
||||
let off = (err / adx) as i32;
|
||||
if dy < 0 { y0 - off } else { y0 + off }
|
||||
}
|
||||
|
||||
/// `render_line` (§9.2.7), writing the bins that fall inside `v`.
|
||||
fn render_line(x0: i32, y0: i32, x1: i32, y1: i32, v: &mut [i32]) {
|
||||
let dy = y1 - y0;
|
||||
let adx = x1 - x0;
|
||||
let base = dy / adx;
|
||||
let ady = dy.abs() - base.abs() * adx;
|
||||
let sy = if dy < 0 { base - 1 } else { base + 1 };
|
||||
let (mut y, mut err) = (y0, 0);
|
||||
if let Some(slot) = usize::try_from(x0).ok().and_then(|x| v.get_mut(x)) {
|
||||
*slot = y;
|
||||
}
|
||||
for x in x0 + 1..x1 {
|
||||
err += ady;
|
||||
if err >= adx {
|
||||
err -= adx;
|
||||
y += sy;
|
||||
} else {
|
||||
y += base;
|
||||
}
|
||||
match usize::try_from(x).ok().and_then(|x| v.get_mut(x)) {
|
||||
Some(slot) => *slot = y,
|
||||
None => break,
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
impl Floor1 {
|
||||
fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook]) -> Result<Option<FloorData>, Eop> {
|
||||
if !r.bit()? {
|
||||
return Ok(None);
|
||||
}
|
||||
let bits = ilog(i64::from(self.range) - 1);
|
||||
let mut y = vec![0i32; self.xlist.len()];
|
||||
y[0] = r.read(bits)? as i32;
|
||||
y[1] = r.read(bits)? as i32;
|
||||
let mut offset = 2usize;
|
||||
for &class in &self.partition_class {
|
||||
let cdim = self.class_dimensions[class];
|
||||
let cbits = self.class_subclasses[class];
|
||||
let csub = (1u32 << cbits) - 1;
|
||||
let mut cval = 0u32;
|
||||
if cbits > 0 {
|
||||
cval = books[self.class_masterbook[class]].scalar(r)?;
|
||||
}
|
||||
for j in 0..cdim {
|
||||
let book = self.subclass_books[class][(cval & csub) as usize];
|
||||
cval >>= cbits;
|
||||
y[offset + j] = if book >= 0 { books[book as usize].scalar(r)? as i32 } else { 0 };
|
||||
}
|
||||
offset += cdim;
|
||||
}
|
||||
|
||||
// Step 1: amplitude synthesis (§7.2.4).
|
||||
let mut step2 = vec![false; self.xlist.len()];
|
||||
step2[0] = true;
|
||||
step2[1] = true;
|
||||
let mut fin = y.clone();
|
||||
for i in 2..self.xlist.len() {
|
||||
let (lo, hi) = self.neighbours[i - 2];
|
||||
let predicted = render_point(self.xlist[lo], fin[lo], self.xlist[hi], fin[hi], self.xlist[i]);
|
||||
let val = y[i];
|
||||
let highroom = self.range - predicted;
|
||||
let lowroom = predicted;
|
||||
let room = if highroom < lowroom { highroom * 2 } else { lowroom * 2 };
|
||||
if val != 0 {
|
||||
step2[lo] = true;
|
||||
step2[hi] = true;
|
||||
step2[i] = true;
|
||||
fin[i] = if val >= room {
|
||||
if highroom > lowroom { val - lowroom + predicted } else { predicted - val + highroom - 1 }
|
||||
} else if val % 2 == 1 {
|
||||
predicted - (val + 1) / 2
|
||||
} else {
|
||||
predicted + val / 2
|
||||
};
|
||||
} else {
|
||||
fin[i] = predicted;
|
||||
}
|
||||
// Valid setups never leave the range; a damaged one must not carry out-of-range values on.
|
||||
fin[i] = fin[i].clamp(0, self.range - 1);
|
||||
}
|
||||
Ok(Some(FloorData::One { y: fin, step2 }))
|
||||
}
|
||||
|
||||
fn curve(&self, fin: &[i32], step2: &[bool], n: usize) -> Vec<f32> {
|
||||
let mut floor = vec![0i32; n];
|
||||
let (mut hx, mut hy) = (0i32, 0i32);
|
||||
let (mut lx, mut ly) = (0i32, fin[self.sorted[0]] * self.multiplier);
|
||||
for &i in &self.sorted[1..] {
|
||||
if step2[i] {
|
||||
hy = fin[i] * self.multiplier;
|
||||
hx = self.xlist[i];
|
||||
render_line(lx, ly, hx, hy, &mut floor);
|
||||
lx = hx;
|
||||
ly = hy;
|
||||
}
|
||||
}
|
||||
if (hx as usize) < n {
|
||||
render_line(hx, hy, n as i32, hy, &mut floor);
|
||||
}
|
||||
floor.iter().map(|&v| INVERSE_DB[v.clamp(0, 255) as usize]).collect()
|
||||
}
|
||||
}
|
||||
|
||||
impl Floor0 {
|
||||
fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook]) -> Result<Option<FloorData>, Fail> {
|
||||
let amplitude = r.read(self.amplitude_bits)?;
|
||||
if amplitude == 0 {
|
||||
return Ok(None);
|
||||
}
|
||||
let book = r.read(ilog(self.books.len() as i64))? as usize;
|
||||
let Some(&book) = self.books.get(book) else { return Err(Fail::Invalid) };
|
||||
let book = &books[book];
|
||||
let mut coefficients: Vec<f32> = Vec::with_capacity(self.order + book.dimensions);
|
||||
let mut last = 0f32;
|
||||
while coefficients.len() < self.order {
|
||||
let Some(v) = book.vector(r)? else { return Err(Fail::Invalid) };
|
||||
coefficients.extend(v.iter().map(|&x| x + last));
|
||||
last = coefficients[coefficients.len() - 1];
|
||||
}
|
||||
Ok(Some(FloorData::Zero { amplitude, coefficients }))
|
||||
}
|
||||
|
||||
fn curve(&self, amplitude: u32, coefficients: &[f32], n: usize) -> Vec<f32> {
|
||||
let bark = |x: f64| 13.1 * (0.00074 * x).atan() + 2.24 * (0.000_000_018_5 * x * x).atan() + 0.0001 * x;
|
||||
let scale = f64::from(self.bark_map_size) / bark(0.5 * f64::from(self.rate));
|
||||
let map: Vec<i64> = (0..n)
|
||||
.map(|i| {
|
||||
let foobar = (bark(f64::from(self.rate) * i as f64 / (2.0 * n as f64)) * scale).floor() as i64;
|
||||
foobar.min(i64::from(self.bark_map_size) - 1)
|
||||
})
|
||||
.collect();
|
||||
let cos_c: Vec<f64> = coefficients.iter().take(self.order).map(|&c| f64::from(c).cos()).collect();
|
||||
let amp = f64::from(amplitude);
|
||||
let offset = f64::from(self.amplitude_offset);
|
||||
let top = (2f64).powi(self.amplitude_bits as i32) - 1.0;
|
||||
let mut out = vec![0f32; n];
|
||||
let mut i = 0usize;
|
||||
while i < n {
|
||||
let omega = std::f64::consts::PI * map[i] as f64 / f64::from(self.bark_map_size);
|
||||
let cw = omega.cos();
|
||||
let (p, q);
|
||||
if self.order % 2 == 1 {
|
||||
let mut pp = 1.0 - cw * cw;
|
||||
for j in 0..(self.order - 1) / 2 {
|
||||
let d = cos_c[2 * j + 1] - cw;
|
||||
pp *= 4.0 * d * d;
|
||||
}
|
||||
let mut qq = 0.25;
|
||||
for j in 0..=(self.order - 1) / 2 {
|
||||
let d = cos_c[2 * j] - cw;
|
||||
qq *= 4.0 * d * d;
|
||||
}
|
||||
p = pp;
|
||||
q = qq;
|
||||
} else {
|
||||
let mut pp = (1.0 - cw) / 2.0;
|
||||
let mut qq = (1.0 + cw) / 2.0;
|
||||
for j in 0..self.order / 2 {
|
||||
let d1 = cos_c[2 * j + 1] - cw;
|
||||
pp *= 4.0 * d1 * d1;
|
||||
let d0 = cos_c[2 * j] - cw;
|
||||
qq *= 4.0 * d0 * d0;
|
||||
}
|
||||
p = pp;
|
||||
q = qq;
|
||||
}
|
||||
let linear = (0.115_129_25 * (amp * offset / (top * (p + q).sqrt()) - offset)).exp() as f32;
|
||||
let key = map[i];
|
||||
while i < n && map[i] == key {
|
||||
out[i] = linear;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
out
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn render_line_matches_a_bresenham_walk() {
|
||||
let mut v = vec![0i32; 16];
|
||||
render_line(0, 0, 8, 4, &mut v);
|
||||
assert_eq!(&v[..8], &[0, 0, 1, 1, 2, 2, 3, 3]);
|
||||
let mut v = vec![0i32; 16];
|
||||
render_line(2, 10, 6, 2, &mut v);
|
||||
assert_eq!(&v[2..6], &[10, 8, 6, 4]);
|
||||
// Lines running past the vector stop at its end.
|
||||
let mut v = vec![0i32; 4];
|
||||
render_line(0, 0, 100, 100, &mut v);
|
||||
assert_eq!(v, vec![0, 1, 2, 3]);
|
||||
assert_eq!(render_point(0, 0, 10, 10, 5), 5);
|
||||
assert_eq!(render_point(0, 10, 10, 0, 5), 5);
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,164 @@
|
||||
//! The inverse MDCT of a block (Vorbis I §4.3.7) and the window slopes.
|
||||
//!
|
||||
//! `y[j] = sum_k X[k] cos(2*pi/n * (j + 1/2 + n/4) * (k + 1/2))` for `n/2` coefficients and `n`
|
||||
//! samples, computed as a DCT-IV of the coefficients through an `n/8`-point complex FFT, then
|
||||
//! unfolded.
|
||||
|
||||
use std::f64::consts::PI;
|
||||
|
||||
#[derive(Clone, Copy, Default)]
|
||||
struct Cpx {
|
||||
re: f64,
|
||||
im: f64,
|
||||
}
|
||||
|
||||
impl Cpx {
|
||||
fn mul(self, o: Cpx) -> Cpx {
|
||||
Cpx { re: self.re * o.re - self.im * o.im, im: self.re * o.im + self.im * o.re }
|
||||
}
|
||||
}
|
||||
|
||||
fn cis(t: f64) -> Cpx {
|
||||
Cpx { re: t.cos(), im: t.sin() }
|
||||
}
|
||||
|
||||
pub(super) struct Imdct {
|
||||
n: usize,
|
||||
twiddle: Vec<Cpx>,
|
||||
post: Vec<Cpx>,
|
||||
fft_tw: Vec<Cpx>,
|
||||
rev: Vec<usize>,
|
||||
}
|
||||
|
||||
impl Imdct {
|
||||
/// For blocks of `n` samples, a power of two of at least 16.
|
||||
pub(super) fn new(n: usize) -> Self {
|
||||
let m = n / 2;
|
||||
let h = m / 2;
|
||||
let twiddle = (0..h).map(|j| cis(-PI * (4.0 * j as f64 + 1.0) / (4.0 * m as f64))).collect();
|
||||
let post = (0..h).map(|k| cis(-PI * k as f64 / m as f64)).collect();
|
||||
let fft_tw = (0..h / 2).map(|j| cis(-2.0 * PI * j as f64 / h as f64)).collect();
|
||||
let bits = h.trailing_zeros();
|
||||
let rev = (0..h).map(|i| if bits == 0 { 0 } else { i.reverse_bits() >> (usize::BITS - bits) }).collect();
|
||||
Self { n, twiddle, post, fft_tw, rev }
|
||||
}
|
||||
|
||||
/// `x`: `n/2` coefficients; `out`: `n` samples.
|
||||
pub(super) fn inverse(&self, x: &[f32], out: &mut [f32]) {
|
||||
let m = self.n / 2;
|
||||
let q = self.n / 4;
|
||||
let h = m / 2;
|
||||
let mut z: Vec<Cpx> = (0..h).map(|j| Cpx { re: f64::from(x[2 * j]), im: f64::from(x[m - 1 - 2 * j]) }.mul(self.twiddle[j])).collect();
|
||||
self.fft(&mut z);
|
||||
let mut v = vec![0f64; m];
|
||||
for (k, c) in z.iter().enumerate() {
|
||||
let d = c.mul(self.post[k]);
|
||||
v[2 * k] = d.re;
|
||||
v[m - 1 - 2 * k] = -d.im;
|
||||
}
|
||||
// Unfold the DCT-IV output to the block.
|
||||
for i in 0..q {
|
||||
out[3 * q - 1 - i] = (-v[i]) as f32;
|
||||
out[3 * q + i] = (-v[i]) as f32;
|
||||
}
|
||||
for i in q..2 * q {
|
||||
out[i - q] = v[i] as f32;
|
||||
out[3 * q - 1 - i] = (-v[i]) as f32;
|
||||
}
|
||||
}
|
||||
|
||||
fn fft(&self, a: &mut [Cpx]) {
|
||||
let h = a.len();
|
||||
for (i, &j) in self.rev.iter().enumerate() {
|
||||
if i < j {
|
||||
a.swap(i, j);
|
||||
}
|
||||
}
|
||||
let mut len = 2;
|
||||
while len <= h {
|
||||
let step = h / len;
|
||||
for start in (0..h).step_by(len) {
|
||||
for k in 0..len / 2 {
|
||||
let w = self.fft_tw[k * step];
|
||||
let u = a[start + k];
|
||||
let t = a[start + k + len / 2].mul(w);
|
||||
a[start + k] = Cpx { re: u.re + t.re, im: u.im + t.im };
|
||||
a[start + k + len / 2] = Cpx { re: u.re - t.re, im: u.im - t.im };
|
||||
}
|
||||
}
|
||||
len *= 2;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/// The rising half of the Vorbis window over `len` samples (§4.3.1):
|
||||
/// `sin(pi/2 * sin^2((i + 0.5) / len * pi/2))`.
|
||||
pub(super) fn slope(len: usize) -> Vec<f32> {
|
||||
(0..len)
|
||||
.map(|i| {
|
||||
let s = (PI / 2.0 * (i as f64 + 0.5) / len as f64).sin();
|
||||
(PI / 2.0 * s * s).sin() as f32
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn matches_the_direct_formula() {
|
||||
for n in [16usize, 64, 256, 2048] {
|
||||
let x: Vec<f32> = (0..n / 2).map(|i| ((i * 7919 % 211) as f32 - 105.0) / 50.0).collect();
|
||||
let mut fast = vec![0f32; n];
|
||||
Imdct::new(n).inverse(&x, &mut fast);
|
||||
for j in [0usize, 1, 2, n / 4, n / 2, n - 1] {
|
||||
let direct: f64 =
|
||||
(0..n / 2).map(|k| f64::from(x[k]) * (2.0 * PI / n as f64 * (j as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos()).sum();
|
||||
assert!((direct - f64::from(fast[j])).abs() < 1e-3 * (1.0 + direct.abs()), "n={n} j={j}: {direct} vs {}", fast[j]);
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn windowed_overlap_add_reconstructs_the_signal() {
|
||||
// Forward MDCT by the definition with the 2/M scale an encoder uses, then this inverse.
|
||||
let n = 64usize;
|
||||
let m = n / 2;
|
||||
let signal: Vec<f64> = (0..n * 6).map(|i| ((i * 37 % 101) as f64 - 50.0) / 50.0).collect();
|
||||
let w: Vec<f32> = slope(m).into_iter().chain(slope(m).into_iter().rev()).collect();
|
||||
let imdct = Imdct::new(n);
|
||||
let mut out = vec![0f64; signal.len()];
|
||||
let mut start = 0;
|
||||
while start + n <= signal.len() {
|
||||
let coeffs: Vec<f32> = (0..m)
|
||||
.map(|k| {
|
||||
let s: f64 = (0..n)
|
||||
.map(|j| {
|
||||
signal[start + j] * f64::from(w[j]) * (2.0 * PI / n as f64 * (j as f64 + 0.5 + n as f64 / 4.0) * (k as f64 + 0.5)).cos()
|
||||
})
|
||||
.sum();
|
||||
(s * 2.0 / m as f64) as f32
|
||||
})
|
||||
.collect();
|
||||
let mut y = vec![0f32; n];
|
||||
imdct.inverse(&coeffs, &mut y);
|
||||
for j in 0..n {
|
||||
out[start + j] += f64::from(y[j]) * f64::from(w[j]);
|
||||
}
|
||||
start += m;
|
||||
}
|
||||
for i in m..signal.len() - m {
|
||||
assert!((out[i] - signal[i]).abs() < 1e-4, "sample {i}: {} vs {}", out[i], signal[i]);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_slope_is_power_complementary() {
|
||||
let s = slope(1024);
|
||||
for i in 0..1024 {
|
||||
let sum = s[i] * s[i] + s[1023 - i] * s[1023 - i];
|
||||
assert!((sum - 1.0).abs() < 1e-5, "{i}: {sum}");
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,552 @@
|
||||
//! A clean-room Vorbis I decoder (feature `vorbis-decode`), written from the Vorbis I
|
||||
//! specification (Xiph.Org, 2020).
|
||||
//!
|
||||
//! [`Decoder`] works on packets: build it from the three header packets (identification, comment
|
||||
//! and setup), then give it audio packets in order. Each call returns the PCM the packet
|
||||
//! completes, planar `f32` in the nominal range -1.0 to 1.0 (not clipped), channels in the order of
|
||||
//! the stream. The first packet only primes the overlap and returns nothing. [`decode_ogg`] reads a
|
||||
//! whole Ogg Vorbis file.
|
||||
//!
|
||||
//! Codebooks, floors 0 and 1, residues 0, 1 and 2, channel coupling and both block sizes with their
|
||||
//! hybrid windows are implemented. Damaged input is an error, never a panic: setup sizes are
|
||||
//! bounded before anything is allocated, and the codeword trees are checked for completeness.
|
||||
|
||||
mod bits;
|
||||
mod codebook;
|
||||
mod floor;
|
||||
mod mdct;
|
||||
mod residue;
|
||||
mod tables;
|
||||
|
||||
use bits::{BitReader, Eop, ilog};
|
||||
use codebook::Codebook;
|
||||
use floor::{Fail, Floor, FloorData};
|
||||
use mdct::{Imdct, slope};
|
||||
use residue::Residue;
|
||||
|
||||
/// Errors of the Vorbis decoder.
|
||||
#[non_exhaustive]
|
||||
#[derive(Debug, Clone, PartialEq, Eq, thiserror::Error)]
|
||||
pub enum Error {
|
||||
/// The identification or comment header is not valid Vorbis.
|
||||
#[error("invalid Vorbis header: {0}")]
|
||||
Header(&'static str),
|
||||
/// The setup header is damaged or uses something Vorbis I does not allow.
|
||||
#[error("invalid Vorbis setup: {0}")]
|
||||
Setup(&'static str),
|
||||
/// The setup or decoded PCM asks for more memory than the decoder allows.
|
||||
#[error("Vorbis decode above the limits: {0}")]
|
||||
Limit(&'static str),
|
||||
/// The packet is not an audio packet (a header, or a packet with its first bit set).
|
||||
#[error("not an audio packet")]
|
||||
NotAudio,
|
||||
/// The packet is damaged: it ends before its mode and window flags are read, or names a mode
|
||||
/// that does not exist.
|
||||
#[error("damaged audio packet: {0}")]
|
||||
Packet(&'static str),
|
||||
/// An Ogg file with no Vorbis stream, or one that cannot be read.
|
||||
#[error("Ogg Vorbis file: {0}")]
|
||||
Ogg(String),
|
||||
}
|
||||
|
||||
/// `Result` of this module.
|
||||
pub type Result<T> = std::result::Result<T, Error>;
|
||||
|
||||
/// The identification header (§4.2.2).
|
||||
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
|
||||
pub struct Identification {
|
||||
/// The channel count, at least 1.
|
||||
pub channels: u8,
|
||||
/// Samples per second per channel.
|
||||
pub sample_rate: u32,
|
||||
/// The maximum bit rate in bits per second, 0 or negative when not set.
|
||||
pub bitrate_maximum: i32,
|
||||
/// The nominal bit rate in bits per second, 0 or negative when not set.
|
||||
pub bitrate_nominal: i32,
|
||||
/// The minimum bit rate in bits per second, 0 or negative when not set.
|
||||
pub bitrate_minimum: i32,
|
||||
/// The short block size in samples.
|
||||
pub blocksize_0: u32,
|
||||
/// The long block size in samples.
|
||||
pub blocksize_1: u32,
|
||||
}
|
||||
|
||||
/// The comment header (§5): a vendor string and `NAME=value` comments.
|
||||
#[derive(Debug, Clone, Default, PartialEq, Eq)]
|
||||
pub struct Comments {
|
||||
/// The vendor string of the encoder.
|
||||
pub vendor: String,
|
||||
/// The user comments, each `NAME=value`.
|
||||
pub comments: Vec<String>,
|
||||
}
|
||||
|
||||
impl Comments {
|
||||
/// The first comment named `name` (case-insensitive), its value.
|
||||
#[must_use]
|
||||
pub fn get(&self, name: &str) -> Option<&str> {
|
||||
self.comments.iter().find_map(|c| {
|
||||
let (k, v) = c.split_once('=')?;
|
||||
k.eq_ignore_ascii_case(name).then_some(v)
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
fn header_start(packet: &[u8], kind: u8) -> Result<BitReader<'_>> {
|
||||
if packet.len() < 7 || packet[0] != kind || &packet[1..7] != b"vorbis" {
|
||||
return Err(Error::Header("wrong packet type or missing \"vorbis\" tag"));
|
||||
}
|
||||
let mut r = BitReader::new(packet);
|
||||
let _ = r.read(8);
|
||||
for _ in 0..6 {
|
||||
let _ = r.read(8);
|
||||
}
|
||||
Ok(r)
|
||||
}
|
||||
|
||||
fn read_identification(packet: &[u8]) -> Result<Identification> {
|
||||
let mut r = header_start(packet, 1)?;
|
||||
let eop = |_: Eop| Error::Header("identification header is truncated");
|
||||
if r.read(32).map_err(eop)? != 0 {
|
||||
return Err(Error::Header("unsupported Vorbis version"));
|
||||
}
|
||||
let channels = r.read(8).map_err(eop)? as u8;
|
||||
let sample_rate = r.read(32).map_err(eop)?;
|
||||
let bitrate_maximum = r.read(32).map_err(eop)? as i32;
|
||||
let bitrate_nominal = r.read(32).map_err(eop)? as i32;
|
||||
let bitrate_minimum = r.read(32).map_err(eop)? as i32;
|
||||
let e0 = r.read(4).map_err(eop)?;
|
||||
let e1 = r.read(4).map_err(eop)?;
|
||||
if !r.bit().map_err(eop)? {
|
||||
return Err(Error::Header("identification header framing bit is not set"));
|
||||
}
|
||||
if channels == 0 || sample_rate == 0 {
|
||||
return Err(Error::Header("no channels or a zero sample rate"));
|
||||
}
|
||||
if !(6..=13).contains(&e0) || !(6..=13).contains(&e1) || e0 > e1 {
|
||||
return Err(Error::Header("block sizes must be powers of two from 64 to 8192, the short one not above the long one"));
|
||||
}
|
||||
Ok(Identification { channels, sample_rate, bitrate_maximum, bitrate_nominal, bitrate_minimum, blocksize_0: 1 << e0, blocksize_1: 1 << e1 })
|
||||
}
|
||||
|
||||
/// Comments are best effort: damage here is not fatal (§4.2.1).
|
||||
fn read_comments(packet: &[u8]) -> Result<Comments> {
|
||||
header_start(packet, 3)?;
|
||||
let mut at = 7usize;
|
||||
let mut take = |n: usize| -> Option<&[u8]> {
|
||||
let s = packet.get(at..at.checked_add(n)?)?;
|
||||
at += n;
|
||||
Some(s)
|
||||
};
|
||||
let word = |b: &[u8]| u32::from_le_bytes([b[0], b[1], b[2], b[3]]) as usize;
|
||||
let mut out = Comments::default();
|
||||
let Some(n) = take(4).map(word) else { return Ok(out) };
|
||||
let Some(vendor) = take(n) else { return Ok(out) };
|
||||
out.vendor = String::from_utf8_lossy(vendor).into_owned();
|
||||
let Some(count) = take(4).map(word) else { return Ok(out) };
|
||||
for _ in 0..count {
|
||||
let Some(n) = take(4).map(word) else { break };
|
||||
let Some(c) = take(n) else { break };
|
||||
out.comments.push(String::from_utf8_lossy(c).into_owned());
|
||||
}
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
struct Mapping {
|
||||
coupling: Vec<(usize, usize)>,
|
||||
mux: Vec<usize>,
|
||||
/// `(floor, residue)` of each submap.
|
||||
submaps: Vec<(usize, usize)>,
|
||||
}
|
||||
|
||||
struct Mode {
|
||||
long: bool,
|
||||
mapping: usize,
|
||||
}
|
||||
|
||||
struct Setup {
|
||||
books: Vec<Codebook>,
|
||||
floors: Vec<Floor>,
|
||||
residues: Vec<Residue>,
|
||||
mappings: Vec<Mapping>,
|
||||
modes: Vec<Mode>,
|
||||
}
|
||||
|
||||
/// Bytes the codebooks of a setup may take in all (codeword trees and vector tables).
|
||||
const CODEBOOK_BUDGET: usize = 256 << 20;
|
||||
|
||||
fn read_setup(packet: &[u8], channels: usize) -> Result<Setup> {
|
||||
let mut r = header_start(packet, 5)?;
|
||||
let eop = |_: Eop| Error::Setup("setup header is truncated");
|
||||
let count = r.read(8).map_err(eop)? as usize + 1;
|
||||
let mut budget = CODEBOOK_BUDGET;
|
||||
let mut books = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
books.push(Codebook::read(&mut r, &mut budget)?);
|
||||
}
|
||||
// Time domain transforms: placeholders.
|
||||
for _ in 0..r.read(6).map_err(eop)? + 1 {
|
||||
if r.read(16).map_err(eop)? != 0 {
|
||||
return Err(Error::Setup("a time domain transform is not zero"));
|
||||
}
|
||||
}
|
||||
let count = r.read(6).map_err(eop)? as usize + 1;
|
||||
let mut floors = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let kind = r.read(16).map_err(eop)?;
|
||||
floors.push(Floor::read(kind, &mut r, &books)?);
|
||||
}
|
||||
let count = r.read(6).map_err(eop)? as usize + 1;
|
||||
let mut residues = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let kind = r.read(16).map_err(eop)?;
|
||||
if kind > 2 {
|
||||
return Err(Error::Setup("unknown residue type"));
|
||||
}
|
||||
residues.push(Residue::read(kind, &mut r, &books)?);
|
||||
}
|
||||
let count = r.read(6).map_err(eop)? as usize + 1;
|
||||
let mut mappings = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
if r.read(16).map_err(eop)? != 0 {
|
||||
return Err(Error::Setup("unknown mapping type"));
|
||||
}
|
||||
let submaps = if r.bit().map_err(eop)? { r.read(4).map_err(eop)? as usize + 1 } else { 1 };
|
||||
let mut coupling = Vec::new();
|
||||
if r.bit().map_err(eop)? {
|
||||
let steps = r.read(8).map_err(eop)? as usize + 1;
|
||||
let bits = ilog(channels as i64 - 1);
|
||||
for _ in 0..steps {
|
||||
let magnitude = r.read(bits).map_err(eop)? as usize;
|
||||
let angle = r.read(bits).map_err(eop)? as usize;
|
||||
if magnitude == angle || magnitude >= channels || angle >= channels {
|
||||
return Err(Error::Setup("channel coupling names an invalid channel pair"));
|
||||
}
|
||||
coupling.push((magnitude, angle));
|
||||
}
|
||||
}
|
||||
if r.read(2).map_err(eop)? != 0 {
|
||||
return Err(Error::Setup("reserved mapping bits are set"));
|
||||
}
|
||||
let mut mux = vec![0usize; channels];
|
||||
if submaps > 1 {
|
||||
for m in &mut mux {
|
||||
*m = r.read(4).map_err(eop)? as usize;
|
||||
if *m >= submaps {
|
||||
return Err(Error::Setup("channel multiplexed to a submap that does not exist"));
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut list = Vec::with_capacity(submaps);
|
||||
for _ in 0..submaps {
|
||||
r.read(8).map_err(eop)?;
|
||||
let floor = r.read(8).map_err(eop)? as usize;
|
||||
let residue = r.read(8).map_err(eop)? as usize;
|
||||
if floor >= floors.len() || residue >= residues.len() {
|
||||
return Err(Error::Setup("submap names a floor or residue that does not exist"));
|
||||
}
|
||||
list.push((floor, residue));
|
||||
}
|
||||
mappings.push(Mapping { coupling, mux, submaps: list });
|
||||
}
|
||||
let count = r.read(6).map_err(eop)? as usize + 1;
|
||||
let mut modes = Vec::with_capacity(count);
|
||||
for _ in 0..count {
|
||||
let long = r.bit().map_err(eop)?;
|
||||
let window = r.read(16).map_err(eop)?;
|
||||
let transform = r.read(16).map_err(eop)?;
|
||||
let mapping = r.read(8).map_err(eop)? as usize;
|
||||
if window != 0 || transform != 0 || mapping >= mappings.len() {
|
||||
return Err(Error::Setup("a mode has a nonzero window or transform type or an unknown mapping"));
|
||||
}
|
||||
modes.push(Mode { long, mapping });
|
||||
}
|
||||
if !r.bit().map_err(eop)? {
|
||||
return Err(Error::Setup("setup header framing bit is not set"));
|
||||
}
|
||||
Ok(Setup { books, floors, residues, mappings, modes })
|
||||
}
|
||||
|
||||
/// The previous block, windowed, kept for overlap-add.
|
||||
struct Previous {
|
||||
n: usize,
|
||||
data: Vec<Vec<f32>>,
|
||||
}
|
||||
|
||||
/// A Vorbis I packet decoder.
|
||||
pub struct Decoder {
|
||||
id: Identification,
|
||||
comments: Comments,
|
||||
setup: Setup,
|
||||
imdct: [Imdct; 2],
|
||||
slopes: [Vec<f32>; 2],
|
||||
previous: Option<Previous>,
|
||||
}
|
||||
|
||||
impl Decoder {
|
||||
/// A decoder from the three header packets, in order. A damaged comment header is tolerated
|
||||
/// (its comments are then empty); the other two must be valid.
|
||||
pub fn new(identification: &[u8], comment: &[u8], setup: &[u8]) -> Result<Self> {
|
||||
let id = read_identification(identification)?;
|
||||
let comments = read_comments(comment)?;
|
||||
let setup = read_setup(setup, usize::from(id.channels))?;
|
||||
let (b0, b1) = (id.blocksize_0 as usize, id.blocksize_1 as usize);
|
||||
Ok(Self { id, comments, setup, imdct: [Imdct::new(b0), Imdct::new(b1)], slopes: [slope(b0 / 2), slope(b1 / 2)], previous: None })
|
||||
}
|
||||
|
||||
/// The identification header.
|
||||
#[must_use]
|
||||
pub fn identification(&self) -> &Identification {
|
||||
&self.id
|
||||
}
|
||||
|
||||
/// The comment header.
|
||||
#[must_use]
|
||||
pub fn comments(&self) -> &Comments {
|
||||
&self.comments
|
||||
}
|
||||
|
||||
/// Forget the previous block, as after a seek: the next packet only primes the overlap again.
|
||||
pub fn reset(&mut self) {
|
||||
self.previous = None;
|
||||
}
|
||||
|
||||
/// The window of a block (§4.3.1).
|
||||
fn window(&self, n: usize, long: bool, prev_long: bool, next_long: bool) -> Vec<f32> {
|
||||
let half = n / 2;
|
||||
let b0 = self.id.blocksize_0 as usize;
|
||||
let mut w = vec![0f32; n];
|
||||
// Left half.
|
||||
if long && !prev_long {
|
||||
let (start, end) = (n / 4 - b0 / 4, n / 4 + b0 / 4);
|
||||
w[start..end].copy_from_slice(&self.slopes[0]);
|
||||
w[end..half].fill(1.0);
|
||||
} else {
|
||||
w[..half].copy_from_slice(&self.slopes[usize::from(long)]);
|
||||
}
|
||||
// Right half.
|
||||
if long && !next_long {
|
||||
let start = 3 * n / 4 - b0 / 4;
|
||||
w[half..start].fill(1.0);
|
||||
for (i, s) in self.slopes[0].iter().rev().enumerate() {
|
||||
w[start + i] = *s;
|
||||
}
|
||||
} else {
|
||||
for (i, s) in self.slopes[usize::from(long)].iter().rev().enumerate() {
|
||||
w[half + i] = *s;
|
||||
}
|
||||
}
|
||||
w
|
||||
}
|
||||
|
||||
/// Decode one audio packet. The result holds one `Vec` per channel, all of the same length:
|
||||
/// the samples this packet completes (none for the first packet after a start or reset).
|
||||
pub fn decode_packet(&mut self, packet: &[u8]) -> Result<Vec<Vec<f32>>> {
|
||||
let channels = usize::from(self.id.channels);
|
||||
let mut r = BitReader::new(packet);
|
||||
match r.bit() {
|
||||
Ok(false) => {}
|
||||
Ok(true) => return Err(Error::NotAudio),
|
||||
Err(_) => return Err(Error::Packet("empty packet")),
|
||||
}
|
||||
let mode_bits = ilog(self.setup.modes.len() as i64 - 1);
|
||||
let mode_number = r.read(mode_bits).map_err(|_| Error::Packet("packet ends inside the mode number"))? as usize;
|
||||
let Some(mode) = self.setup.modes.get(mode_number) else { return Err(Error::Packet("mode number out of range")) };
|
||||
let long = mode.long;
|
||||
let n = if long { self.id.blocksize_1 } else { self.id.blocksize_0 } as usize;
|
||||
let (mut prev_long, mut next_long) = (true, true);
|
||||
if long {
|
||||
prev_long = r.bit().map_err(|_| Error::Packet("packet ends inside the window flags"))?;
|
||||
next_long = r.bit().map_err(|_| Error::Packet("packet ends inside the window flags"))?;
|
||||
}
|
||||
let window = self.window(n, long, prev_long, next_long);
|
||||
let half = n / 2;
|
||||
let mapping = &self.setup.mappings[mode.mapping];
|
||||
|
||||
let spectrum = self.spectrum(&mut r, mapping, half, channels)?;
|
||||
// Inverse transform and window.
|
||||
let which = usize::from(long);
|
||||
let mut blocks: Vec<Vec<f32>> = Vec::with_capacity(channels);
|
||||
for s in &spectrum {
|
||||
let mut y = vec![0f32; n];
|
||||
self.imdct[which].inverse(s, &mut y);
|
||||
for (v, w) in y.iter_mut().zip(&window) {
|
||||
*v *= *w;
|
||||
}
|
||||
blocks.push(y);
|
||||
}
|
||||
|
||||
// Overlap-add with the previous block (§4.3.8).
|
||||
let out = match &self.previous {
|
||||
None => vec![Vec::new(); channels],
|
||||
Some(prev) => {
|
||||
let count = prev.n / 4 + n / 4;
|
||||
blocks
|
||||
.iter()
|
||||
.zip(&prev.data)
|
||||
.map(|(cur, old)| {
|
||||
(0..count)
|
||||
.map(|k| {
|
||||
let a = old.get(prev.n / 2 + k).copied().unwrap_or(0.0);
|
||||
let b = (n / 4 + k).checked_sub(prev.n / 4).and_then(|i| cur.get(i)).copied().unwrap_or(0.0);
|
||||
a + b
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
};
|
||||
self.previous = Some(Previous { n, data: blocks });
|
||||
Ok(out)
|
||||
}
|
||||
|
||||
/// Floors, residues, coupling and the dot product: the spectrum of each channel (§4.3.2 to 4.3.6).
|
||||
fn spectrum(&self, r: &mut BitReader<'_>, mapping: &Mapping, half: usize, channels: usize) -> Result<Vec<Vec<f32>>> {
|
||||
let zero = || vec![vec![0f32; half]; channels];
|
||||
let setup = &self.setup;
|
||||
// Floors, in channel order.
|
||||
let mut floors: Vec<Option<FloorData>> = Vec::with_capacity(channels);
|
||||
for ch in 0..channels {
|
||||
let (floor, _) = mapping.submaps[mapping.mux[ch]];
|
||||
match setup.floors[floor].decode(r, &setup.books) {
|
||||
Ok(f) => floors.push(f),
|
||||
Err(Fail::Eop) => return Ok(zero()),
|
||||
Err(Fail::Invalid) => return Err(Error::Packet("a floor names a codebook that does not exist")),
|
||||
}
|
||||
}
|
||||
let mut no_residue: Vec<bool> = floors.iter().map(Option::is_none).collect();
|
||||
for &(m, a) in &mapping.coupling {
|
||||
if !no_residue[m] || !no_residue[a] {
|
||||
no_residue[m] = false;
|
||||
no_residue[a] = false;
|
||||
}
|
||||
}
|
||||
// Residues, in submap order.
|
||||
let mut residue = zero();
|
||||
for (i, &(_, res)) in mapping.submaps.iter().enumerate() {
|
||||
let members: Vec<usize> = (0..channels).filter(|&c| mapping.mux[c] == i).collect();
|
||||
if members.is_empty() {
|
||||
continue;
|
||||
}
|
||||
let skip: Vec<bool> = members.iter().map(|&c| no_residue[c]).collect();
|
||||
let mut vectors = vec![vec![0f32; half]; members.len()];
|
||||
setup.residues[res].decode(r, &setup.books, half, &skip, &mut vectors);
|
||||
for (v, &c) in vectors.into_iter().zip(&members) {
|
||||
residue[c] = v;
|
||||
}
|
||||
}
|
||||
// Inverse channel coupling (§4.3.5), last step first.
|
||||
for &(m, a) in mapping.coupling.iter().rev() {
|
||||
let mut mag = std::mem::take(&mut residue[m]);
|
||||
let mut ang = std::mem::take(&mut residue[a]);
|
||||
for (mv, av) in mag.iter_mut().zip(ang.iter_mut()) {
|
||||
let (big, small) = (*mv, *av);
|
||||
let (new_m, new_a);
|
||||
if big > 0.0 {
|
||||
if small > 0.0 {
|
||||
new_m = big;
|
||||
new_a = big - small;
|
||||
} else {
|
||||
new_a = big;
|
||||
new_m = big + small;
|
||||
}
|
||||
} else if small > 0.0 {
|
||||
new_m = big;
|
||||
new_a = big + small;
|
||||
} else {
|
||||
new_a = big;
|
||||
new_m = big - small;
|
||||
}
|
||||
*mv = new_m;
|
||||
*av = new_a;
|
||||
}
|
||||
residue[m] = mag;
|
||||
residue[a] = ang;
|
||||
}
|
||||
// The floor times the residue.
|
||||
for ch in 0..channels {
|
||||
match &floors[ch] {
|
||||
Some(data) => {
|
||||
let (floor, _) = mapping.submaps[mapping.mux[ch]];
|
||||
let curve = setup.floors[floor].curve(data, half);
|
||||
for (v, c) in residue[ch].iter_mut().zip(curve) {
|
||||
*v *= c;
|
||||
}
|
||||
}
|
||||
None => residue[ch].fill(0.0),
|
||||
}
|
||||
}
|
||||
Ok(residue)
|
||||
}
|
||||
}
|
||||
|
||||
/// A decoded Ogg Vorbis file.
|
||||
#[derive(Debug, Clone, PartialEq)]
|
||||
pub struct Decoded {
|
||||
/// Samples per second per channel.
|
||||
pub sample_rate: u32,
|
||||
/// One `Vec` of samples per channel.
|
||||
pub channels: Vec<Vec<f32>>,
|
||||
/// The stream's comment header.
|
||||
pub comments: Comments,
|
||||
/// Audio packets that could not be decoded and were skipped.
|
||||
pub damaged_packets: usize,
|
||||
}
|
||||
|
||||
/// Decode the first Vorbis stream of an Ogg file. The result is trimmed to the stream's final
|
||||
/// granule position, so an encoder's padding at the end is dropped. Damaged packets are skipped
|
||||
/// and counted, not fatal. Collected PCM is limited to 256 MiB; use the packet
|
||||
/// decoder for longer streams without retaining the entire output.
|
||||
pub fn decode_ogg(data: &[u8]) -> Result<Decoded> {
|
||||
let ogg = craft_media::ogg::open(data).map_err(|e| Error::Ogg(e.to_string()))?;
|
||||
let index = ogg.stream_of(craft_media::ogg::Codec::Vorbis).ok_or_else(|| Error::Ogg("no Vorbis stream".into()))?;
|
||||
let stream = &ogg.streams[index];
|
||||
let [id, comment, setup, ..] = stream.headers.as_slice() else { return Err(Error::Ogg("the stream has fewer than three header packets".into())) };
|
||||
let mut decoder = Decoder::new(id, comment, setup)?;
|
||||
let channel_count = usize::from(decoder.id.channels);
|
||||
let mut channels = vec![Vec::new(); channel_count];
|
||||
let mut damaged = 0;
|
||||
for i in 0..stream.packets.len() {
|
||||
let packet = ogg.read_packet(data, index, i).map_err(|e| Error::Ogg(e.to_string()))?;
|
||||
match decoder.decode_packet(&packet) {
|
||||
Ok(pcm) => {
|
||||
append_pcm(&mut channels, pcm, 256 << 20)?;
|
||||
}
|
||||
Err(_) => damaged += 1,
|
||||
}
|
||||
}
|
||||
if let Some(total) = stream.last_granule.and_then(|g| usize::try_from(g).ok()) {
|
||||
for c in &mut channels {
|
||||
c.truncate(total);
|
||||
}
|
||||
}
|
||||
Ok(Decoded { sample_rate: decoder.id.sample_rate, channels, comments: decoder.comments.clone(), damaged_packets: damaged })
|
||||
}
|
||||
|
||||
// Admit every channel together before extending any of them. Limit retained PCM,
|
||||
// not the compressed input, setup tables or the decoder's bounded packet scratch.
|
||||
fn append_pcm(channels: &mut [Vec<f32>], pcm: Vec<Vec<f32>>, budget: usize) -> Result<()> {
|
||||
let samples = channels.iter().chain(&pcm).try_fold(0usize, |n, c| n.checked_add(c.len()));
|
||||
if samples.is_none_or(|n| n > budget / std::mem::size_of::<f32>()) {
|
||||
return Err(Error::Limit("decoded PCM exceeds the whole-file budget"));
|
||||
}
|
||||
for (all, new) in channels.iter_mut().zip(pcm) {
|
||||
all.try_reserve_exact(new.len()).map_err(|_| Error::Limit("cannot allocate decoded PCM"))?;
|
||||
all.extend(new);
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod budget_tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn pcm_budget_counts_all_channels_before_extending() {
|
||||
let mut channels = vec![vec![1.0], vec![2.0]];
|
||||
append_pcm(&mut channels, vec![vec![3.0], vec![4.0]], 16).expect("exact budget");
|
||||
let before = channels.clone();
|
||||
assert!(matches!(append_pcm(&mut channels, vec![vec![5.0], vec![6.0]], 23), Err(Error::Limit(_))));
|
||||
assert_eq!(channels, before);
|
||||
append_pcm(&mut channels, vec![Vec::new(), Vec::new()], 16).expect("empty packet");
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,196 @@
|
||||
//! Residues (Vorbis I §8): the fine detail of the spectrum, coded as vectors in passes.
|
||||
|
||||
use super::Error;
|
||||
use super::bits::{BitReader, Eop};
|
||||
use super::codebook::Codebook;
|
||||
|
||||
pub(super) struct Residue {
|
||||
kind: u32,
|
||||
begin: usize,
|
||||
end: usize,
|
||||
partition_size: usize,
|
||||
classifications: usize,
|
||||
classbook: usize,
|
||||
/// `books[class][pass]`.
|
||||
books: Vec<[Option<usize>; 8]>,
|
||||
}
|
||||
|
||||
fn eop(_: Eop) -> Error {
|
||||
Error::Setup("setup header ends inside a residue")
|
||||
}
|
||||
|
||||
impl Residue {
|
||||
pub(super) fn read(kind: u32, r: &mut BitReader<'_>, books: &[Codebook]) -> Result<Self, Error> {
|
||||
let begin = r.read(24).map_err(eop)? as usize;
|
||||
let end = r.read(24).map_err(eop)? as usize;
|
||||
let partition_size = r.read(24).map_err(eop)? as usize + 1;
|
||||
let classifications = r.read(6).map_err(eop)? as usize + 1;
|
||||
let classbook = r.read(8).map_err(eop)? as usize;
|
||||
let Some(cb) = books.get(classbook) else { return Err(Error::Setup("residue class book out of range")) };
|
||||
// classifications ^ dimensions must not exceed the book's entries.
|
||||
let mut reach = 1u128;
|
||||
for _ in 0..cb.dimensions {
|
||||
reach = reach.saturating_mul(classifications as u128);
|
||||
if reach > cb.entries as u128 {
|
||||
return Err(Error::Setup("residue class book has too few entries for its classifications"));
|
||||
}
|
||||
}
|
||||
let mut cascade = Vec::with_capacity(classifications);
|
||||
for _ in 0..classifications {
|
||||
let low = r.read(3).map_err(eop)?;
|
||||
let high = if r.bit().map_err(eop)? { r.read(5).map_err(eop)? } else { 0 };
|
||||
cascade.push(high * 8 + low);
|
||||
}
|
||||
let mut list = Vec::with_capacity(classifications);
|
||||
for &c in &cascade {
|
||||
let mut row = [None; 8];
|
||||
for (j, slot) in row.iter_mut().enumerate() {
|
||||
if c & (1 << j) != 0 {
|
||||
let b = r.read(8).map_err(eop)? as usize;
|
||||
match books.get(b) {
|
||||
Some(book) if book.has_vectors() => *slot = Some(b),
|
||||
_ => return Err(Error::Setup("residue names a missing codebook or one without vectors")),
|
||||
}
|
||||
}
|
||||
}
|
||||
list.push(row);
|
||||
}
|
||||
Ok(Self { kind, begin, end, partition_size, classifications, classbook, books: list })
|
||||
}
|
||||
|
||||
/// Decode a bundle of vectors, each `n` long (half the block size), into `out`; a vector marked
|
||||
/// in `skip` is left zero. End of packet ends decoding where it is (a nominal event).
|
||||
pub(super) fn decode(&self, r: &mut BitReader<'_>, books: &[Codebook], n: usize, skip: &[bool], out: &mut [Vec<f32>]) {
|
||||
let ch = out.len();
|
||||
if skip.iter().all(|&s| s) {
|
||||
return;
|
||||
}
|
||||
if self.kind == 2 {
|
||||
let mut flat = vec![vec![0f32; n * ch]];
|
||||
let _ = self.decode_vectors(r, books, n * ch, &[false], &mut flat);
|
||||
for i in 0..n {
|
||||
for (j, v) in out.iter_mut().enumerate() {
|
||||
v[i] = flat[0][i * ch + j];
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let _ = self.decode_vectors(r, books, n, skip, out);
|
||||
}
|
||||
}
|
||||
|
||||
fn decode_vectors(&self, r: &mut BitReader<'_>, books: &[Codebook], actual: usize, skip: &[bool], out: &mut [Vec<f32>]) -> Result<(), Eop> {
|
||||
let ch = out.len();
|
||||
let begin = self.begin.min(actual);
|
||||
let end = self.end.min(actual);
|
||||
if end <= begin {
|
||||
return Ok(());
|
||||
}
|
||||
let classbook = &books[self.classbook];
|
||||
let cpw = classbook.dimensions;
|
||||
let partitions = (end - begin) / self.partition_size;
|
||||
// Classbook dimensions may greatly exceed the actual partition count.
|
||||
// Retain only digits that this block can use, not padding per channel.
|
||||
let mut classes = vec![vec![0usize; partitions]; ch];
|
||||
for pass in 0..8 {
|
||||
let mut count = 0usize;
|
||||
while count < partitions {
|
||||
if pass == 0 {
|
||||
for j in 0..ch {
|
||||
if skip[j] {
|
||||
continue;
|
||||
}
|
||||
let mut temp = classbook.scalar(r)? as usize;
|
||||
for i in (0..cpw).rev() {
|
||||
if i + count < partitions {
|
||||
classes[j][i + count] = temp % self.classifications;
|
||||
}
|
||||
temp /= self.classifications;
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut i = 0;
|
||||
while i < cpw && count < partitions {
|
||||
for j in 0..ch {
|
||||
if skip[j] {
|
||||
continue;
|
||||
}
|
||||
let Some(book) = self.books[classes[j][count]][pass] else { continue };
|
||||
let book = &books[book];
|
||||
let offset = begin + count * self.partition_size;
|
||||
self.partition(r, book, &mut out[j][offset..offset + self.partition_size])?;
|
||||
}
|
||||
count += 1;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// One partition into `v` (the slice of the vector it covers).
|
||||
fn partition(&self, r: &mut BitReader<'_>, book: &Codebook, v: &mut [f32]) -> Result<(), Eop> {
|
||||
let n = v.len();
|
||||
let dims = book.dimensions;
|
||||
let step = n / dims;
|
||||
if self.kind == 0 {
|
||||
for i in 0..step {
|
||||
let Some(entry) = book.vector(r)? else { return Ok(()) };
|
||||
for (j, &e) in entry.iter().enumerate() {
|
||||
v[i + j * step] += e;
|
||||
}
|
||||
}
|
||||
} else {
|
||||
let mut i = 0;
|
||||
for _ in 0..step {
|
||||
let Some(entry) = book.vector(r)? else { return Ok(()) };
|
||||
for &e in entry {
|
||||
v[i] += e;
|
||||
i += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn huge_class_dimensions_keep_only_actual_partitions() {
|
||||
let mut data = Vec::<u8>::new();
|
||||
let mut bits = 0usize;
|
||||
let mut put = |value: u32, n: usize| {
|
||||
for i in 0..n {
|
||||
if bits.is_multiple_of(8) {
|
||||
data.push(0);
|
||||
}
|
||||
let last = data.len() - 1;
|
||||
data[last] |= (((value >> i) & 1) as u8) << (bits % 8);
|
||||
bits += 1;
|
||||
}
|
||||
};
|
||||
put(0x56_4342, 24);
|
||||
put(65535, 16);
|
||||
put(1, 24);
|
||||
put(0, 1); // unordered, not sparse, one length-1 entry
|
||||
put(0, 1);
|
||||
put(0, 5);
|
||||
put(0, 4); // scalar-only classbook
|
||||
let book = Codebook::read(&mut BitReader::new(&data), &mut (1 << 20)).expect("classbook");
|
||||
let books = [book];
|
||||
for kind in [0, 1] {
|
||||
let residue = Residue { kind, begin: 0, end: 32, partition_size: 1, classifications: 1, classbook: 0, books: vec![[None; 8]] };
|
||||
let mut out = vec![vec![0.0; 32]; 255];
|
||||
let packet = [0u8; 32];
|
||||
let mut r = BitReader::new(&packet);
|
||||
residue.decode(&mut r, &books, 32, &[false; 255], &mut out);
|
||||
assert_eq!(r.remaining(), 1); // one classword per channel, not 32
|
||||
assert!(out.iter().flatten().all(|&x| x == 0.0));
|
||||
let mut r = BitReader::new(&packet);
|
||||
residue.decode(&mut r, &books, 32, &[true; 255], &mut out);
|
||||
assert_eq!(r.remaining(), 256); // skipped channels consume nothing
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,263 @@
|
||||
//! `floor1_inverse_dB_table` (Vorbis I §10.1): the 256 linear amplitudes of the floor 1 integer values.
|
||||
|
||||
// The values are printed to the digits the specification gives them.
|
||||
#![allow(clippy::excessive_precision)]
|
||||
|
||||
pub(super) const INVERSE_DB: [f32; 256] = [
|
||||
1.0649863e-07,
|
||||
1.1341951e-07,
|
||||
1.2079015e-07,
|
||||
1.2863978e-07,
|
||||
1.3699951e-07,
|
||||
1.4590251e-07,
|
||||
1.5538408e-07,
|
||||
1.6548181e-07,
|
||||
1.7623575e-07,
|
||||
1.8768855e-07,
|
||||
1.9988561e-07,
|
||||
2.1287530e-07,
|
||||
2.2670913e-07,
|
||||
2.4144197e-07,
|
||||
2.5713223e-07,
|
||||
2.7384213e-07,
|
||||
2.9163793e-07,
|
||||
3.1059021e-07,
|
||||
3.3077411e-07,
|
||||
3.5226968e-07,
|
||||
3.7516214e-07,
|
||||
3.9954229e-07,
|
||||
4.2550680e-07,
|
||||
4.5315863e-07,
|
||||
4.8260743e-07,
|
||||
5.1396998e-07,
|
||||
5.4737065e-07,
|
||||
5.8294187e-07,
|
||||
6.2082472e-07,
|
||||
6.6116941e-07,
|
||||
7.0413592e-07,
|
||||
7.4989464e-07,
|
||||
7.9862701e-07,
|
||||
8.5052630e-07,
|
||||
9.0579828e-07,
|
||||
9.6466216e-07,
|
||||
1.0273513e-06,
|
||||
1.0941144e-06,
|
||||
1.1652161e-06,
|
||||
1.2409384e-06,
|
||||
1.3215816e-06,
|
||||
1.4074654e-06,
|
||||
1.4989305e-06,
|
||||
1.5963394e-06,
|
||||
1.7000785e-06,
|
||||
1.8105592e-06,
|
||||
1.9282195e-06,
|
||||
2.0535261e-06,
|
||||
2.1869758e-06,
|
||||
2.3290978e-06,
|
||||
2.4804557e-06,
|
||||
2.6416497e-06,
|
||||
2.8133190e-06,
|
||||
2.9961443e-06,
|
||||
3.1908506e-06,
|
||||
3.3982101e-06,
|
||||
3.6190449e-06,
|
||||
3.8542308e-06,
|
||||
4.1047004e-06,
|
||||
4.3714470e-06,
|
||||
4.6555282e-06,
|
||||
4.9580707e-06,
|
||||
5.2802740e-06,
|
||||
5.6234160e-06,
|
||||
5.9888572e-06,
|
||||
6.3780469e-06,
|
||||
6.7925283e-06,
|
||||
7.2339451e-06,
|
||||
7.7040476e-06,
|
||||
8.2047000e-06,
|
||||
8.7378876e-06,
|
||||
9.3057248e-06,
|
||||
9.9104632e-06,
|
||||
1.0554501e-05,
|
||||
1.1240392e-05,
|
||||
1.1970856e-05,
|
||||
1.2748789e-05,
|
||||
1.3577278e-05,
|
||||
1.4459606e-05,
|
||||
1.5399272e-05,
|
||||
1.6400004e-05,
|
||||
1.7465768e-05,
|
||||
1.8600792e-05,
|
||||
1.9809576e-05,
|
||||
2.1096914e-05,
|
||||
2.2467911e-05,
|
||||
2.3928002e-05,
|
||||
2.5482978e-05,
|
||||
2.7139006e-05,
|
||||
2.8902651e-05,
|
||||
3.0780908e-05,
|
||||
3.2781225e-05,
|
||||
3.4911534e-05,
|
||||
3.7180282e-05,
|
||||
3.9596466e-05,
|
||||
4.2169667e-05,
|
||||
4.4910090e-05,
|
||||
4.7828601e-05,
|
||||
5.0936773e-05,
|
||||
5.4246931e-05,
|
||||
5.7772202e-05,
|
||||
6.1526565e-05,
|
||||
6.5524908e-05,
|
||||
6.9783085e-05,
|
||||
7.4317983e-05,
|
||||
7.9147585e-05,
|
||||
8.4291040e-05,
|
||||
8.9768747e-05,
|
||||
9.5602426e-05,
|
||||
0.00010181521,
|
||||
0.00010843174,
|
||||
0.00011547824,
|
||||
0.00012298267,
|
||||
0.00013097477,
|
||||
0.00013948625,
|
||||
0.00014855085,
|
||||
0.00015820453,
|
||||
0.00016848555,
|
||||
0.00017943469,
|
||||
0.00019109536,
|
||||
0.00020351382,
|
||||
0.00021673929,
|
||||
0.00023082423,
|
||||
0.00024582449,
|
||||
0.00026179955,
|
||||
0.00027881276,
|
||||
0.00029693158,
|
||||
0.00031622787,
|
||||
0.00033677814,
|
||||
0.00035866388,
|
||||
0.00038197188,
|
||||
0.00040679456,
|
||||
0.00043323036,
|
||||
0.00046138411,
|
||||
0.00049136745,
|
||||
0.00052329927,
|
||||
0.00055730621,
|
||||
0.00059352311,
|
||||
0.00063209358,
|
||||
0.00067317058,
|
||||
0.00071691700,
|
||||
0.00076350630,
|
||||
0.00081312324,
|
||||
0.00086596457,
|
||||
0.00092223983,
|
||||
0.00098217216,
|
||||
0.0010459992,
|
||||
0.0011139742,
|
||||
0.0011863665,
|
||||
0.0012634633,
|
||||
0.0013455702,
|
||||
0.0014330129,
|
||||
0.0015261382,
|
||||
0.0016253153,
|
||||
0.0017309374,
|
||||
0.0018434235,
|
||||
0.0019632195,
|
||||
0.0020908006,
|
||||
0.0022266726,
|
||||
0.0023713743,
|
||||
0.0025254795,
|
||||
0.0026895994,
|
||||
0.0028643847,
|
||||
0.0030505286,
|
||||
0.0032487691,
|
||||
0.0034598925,
|
||||
0.0036847358,
|
||||
0.0039241906,
|
||||
0.0041792066,
|
||||
0.0044507950,
|
||||
0.0047400328,
|
||||
0.0050480668,
|
||||
0.0053761186,
|
||||
0.0057254891,
|
||||
0.0060975636,
|
||||
0.0064938176,
|
||||
0.0069158225,
|
||||
0.0073652516,
|
||||
0.0078438871,
|
||||
0.0083536271,
|
||||
0.0088964928,
|
||||
0.009474637,
|
||||
0.010090352,
|
||||
0.010746080,
|
||||
0.011444421,
|
||||
0.012188144,
|
||||
0.012980198,
|
||||
0.013823725,
|
||||
0.014722068,
|
||||
0.015678791,
|
||||
0.016697687,
|
||||
0.017782797,
|
||||
0.018938423,
|
||||
0.020169149,
|
||||
0.021479854,
|
||||
0.022875735,
|
||||
0.024362330,
|
||||
0.025945531,
|
||||
0.027631618,
|
||||
0.029427276,
|
||||
0.031339626,
|
||||
0.033376252,
|
||||
0.035545228,
|
||||
0.037855157,
|
||||
0.040315199,
|
||||
0.042935108,
|
||||
0.045725273,
|
||||
0.048696758,
|
||||
0.051861348,
|
||||
0.055231591,
|
||||
0.058820850,
|
||||
0.062643361,
|
||||
0.066714279,
|
||||
0.071049749,
|
||||
0.075666962,
|
||||
0.080584227,
|
||||
0.085821044,
|
||||
0.091398179,
|
||||
0.097337747,
|
||||
0.10366330,
|
||||
0.11039993,
|
||||
0.11757434,
|
||||
0.12521498,
|
||||
0.13335215,
|
||||
0.14201813,
|
||||
0.15124727,
|
||||
0.16107617,
|
||||
0.17154380,
|
||||
0.18269168,
|
||||
0.19456402,
|
||||
0.20720788,
|
||||
0.22067342,
|
||||
0.23501402,
|
||||
0.25028656,
|
||||
0.26655159,
|
||||
0.28387361,
|
||||
0.30232132,
|
||||
0.32196786,
|
||||
0.34289114,
|
||||
0.36517414,
|
||||
0.38890521,
|
||||
0.41417847,
|
||||
0.44109412,
|
||||
0.46975890,
|
||||
0.50028648,
|
||||
0.53279791,
|
||||
0.56742212,
|
||||
0.60429640,
|
||||
0.64356699,
|
||||
0.68538959,
|
||||
0.72993007,
|
||||
0.77736504,
|
||||
0.82788260,
|
||||
0.88168307,
|
||||
0.9389798,
|
||||
1.0,
|
||||
];
|
||||
@@ -1,4 +1,7 @@
|
||||
//! Vorbis I (feature `vorbis-encode`): the pure-Rust [`encoder`]. Decoding Vorbis goes through
|
||||
//! [`crate::decode`].
|
||||
//! Vorbis I: the pure-Rust [`decoder`] (feature `vorbis-decode`) and [`encoder`] (feature
|
||||
//! `vorbis-encode`). `craft_audio::decode` still reads Vorbis files through symphonia.
|
||||
|
||||
#[cfg(feature = "vorbis-decode")]
|
||||
pub mod decoder;
|
||||
#[cfg(feature = "vorbis-encode")]
|
||||
pub mod encoder;
|
||||
|
||||
@@ -0,0 +1,230 @@
|
||||
//! Hostile input to the Vorbis decoder: damaged headers and packets, truncations, and headers that
|
||||
//! ask for absurd sizes. Every case is an error or a result, never a panic or a large allocation.
|
||||
|
||||
use craft_audio::vorbis::decoder::{Decoder, Error, decode_ogg};
|
||||
use craft_audio::{AudioBuffer, OggVorbisOptions, encode_ogg_vorbis};
|
||||
|
||||
fn xorshift(seed: &mut u32) -> u32 {
|
||||
*seed ^= *seed << 13;
|
||||
*seed ^= *seed >> 17;
|
||||
*seed ^= *seed << 5;
|
||||
*seed
|
||||
}
|
||||
|
||||
struct Parts {
|
||||
ogg: Vec<u8>,
|
||||
headers: Vec<Vec<u8>>,
|
||||
packets: Vec<Vec<u8>>,
|
||||
}
|
||||
|
||||
fn parts(channels: usize) -> Parts {
|
||||
let signal: Vec<Vec<f32>> = (0..channels)
|
||||
.map(|c| (0..20_000).map(|i| ((i as f32 * (0.03 + 0.01 * c as f32)).sin() * 0.4) + ((i * 7 % 13) as f32 - 6.0) / 60.0).collect())
|
||||
.collect();
|
||||
let ogg =
|
||||
encode_ogg_vorbis(&AudioBuffer { sample_rate: 44_100, channels: signal }, &OggVorbisOptions::default().with_quality(4.0)).expect("encode");
|
||||
let file = craft_media::ogg::open(ogg.as_slice()).expect("open");
|
||||
let s = &file.streams[0];
|
||||
let packets = (0..s.packets.len()).map(|i| file.read_packet(ogg.as_slice(), 0, i).expect("packet")).collect();
|
||||
Parts { headers: s.headers.clone(), packets, ogg }
|
||||
}
|
||||
|
||||
fn decoder(p: &Parts) -> Decoder {
|
||||
Decoder::new(&p.headers[0], &p.headers[1], &p.headers[2]).expect("valid headers")
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_truncated_header_is_an_error() {
|
||||
let p = parts(2);
|
||||
for which in [0usize, 2] {
|
||||
for n in 0..p.headers[which].len() {
|
||||
let mut h = p.headers.clone();
|
||||
h[which].truncate(n);
|
||||
assert!(Decoder::new(&h[0], &h[1], &h[2]).is_err(), "header {which} cut to {n} bytes");
|
||||
}
|
||||
}
|
||||
// A damaged comment header is not fatal.
|
||||
let mut h = p.headers.clone();
|
||||
h[1].truncate(12);
|
||||
let d = Decoder::new(&h[0], &h[1], &h[2]).expect("comments are best effort");
|
||||
assert!(d.comments().comments.is_empty());
|
||||
assert!(Decoder::new(&p.headers[0], &[], &p.headers[2]).is_err(), "the comment header still needs its tag");
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_headers_never_panic() {
|
||||
let p = parts(2);
|
||||
let mut seed = 99u32;
|
||||
for which in [0usize, 2] {
|
||||
let len = p.headers[which].len();
|
||||
for _ in 0..800 {
|
||||
let mut h = p.headers.clone();
|
||||
for _ in 0..1 + xorshift(&mut seed) % 3 {
|
||||
let at = xorshift(&mut seed) as usize % len;
|
||||
h[which][at] = xorshift(&mut seed) as u8;
|
||||
}
|
||||
if let Ok(mut d) = Decoder::new(&h[0], &h[1], &h[2]) {
|
||||
// A setup that survives must also survive audio packets.
|
||||
for pk in p.packets.iter().take(6) {
|
||||
let _ = d.decode_packet(pk);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_packets_never_panic() {
|
||||
let p = parts(2);
|
||||
let mut seed = 7u32;
|
||||
let mut d = decoder(&p);
|
||||
for pk in &p.packets {
|
||||
for _ in 0..6 {
|
||||
let mut bad = pk.clone();
|
||||
match xorshift(&mut seed) % 3 {
|
||||
0 => bad.truncate(xorshift(&mut seed) as usize % (bad.len() + 1)),
|
||||
1 => {
|
||||
let at = xorshift(&mut seed) as usize % bad.len();
|
||||
bad[at] = xorshift(&mut seed) as u8;
|
||||
}
|
||||
_ => bad = (0..xorshift(&mut seed) % 300).map(|_| xorshift(&mut seed) as u8).collect(),
|
||||
}
|
||||
let _ = d.decode_packet(&bad);
|
||||
}
|
||||
}
|
||||
// The decoder still decodes good packets after all that.
|
||||
d.reset();
|
||||
assert!(d.decode_packet(&p.packets[3]).is_ok());
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn header_packets_and_empty_packets_are_not_audio() {
|
||||
let p = parts(1);
|
||||
let mut d = decoder(&p);
|
||||
assert_eq!(d.decode_packet(&p.headers[0]), Err(Error::NotAudio));
|
||||
assert_eq!(d.decode_packet(&p.headers[2]), Err(Error::NotAudio));
|
||||
assert!(matches!(d.decode_packet(&[]), Err(Error::Packet(_))));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn damaged_files_never_panic() {
|
||||
let p = parts(2);
|
||||
let mut seed = 31u32;
|
||||
for _ in 0..120 {
|
||||
let mut bad = p.ogg.clone();
|
||||
for _ in 0..1 + xorshift(&mut seed) % 4 {
|
||||
let at = xorshift(&mut seed) as usize % bad.len();
|
||||
bad[at] = xorshift(&mut seed) as u8;
|
||||
}
|
||||
let _ = decode_ogg(&bad);
|
||||
bad.truncate(xorshift(&mut seed) as usize % bad.len());
|
||||
let _ = decode_ogg(&bad);
|
||||
}
|
||||
assert!(matches!(decode_ogg(b"not an ogg file"), Err(Error::Ogg(_))));
|
||||
assert!(matches!(decode_ogg(&[]), Err(Error::Ogg(_))));
|
||||
}
|
||||
|
||||
/// A bit writer for hand-built setups.
|
||||
#[derive(Default)]
|
||||
struct W(Vec<u8>, usize);
|
||||
impl W {
|
||||
fn put(&mut self, v: u64, n: u32) {
|
||||
for i in 0..n {
|
||||
if self.1.is_multiple_of(8) {
|
||||
self.0.push(0);
|
||||
}
|
||||
let last = self.0.len() - 1;
|
||||
self.0[last] |= (((v >> i) & 1) as u8) << (self.1 % 8);
|
||||
self.1 += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
fn setup_with_first_book(book: impl FnOnce(&mut W)) -> Vec<u8> {
|
||||
let mut w = W::default();
|
||||
w.put(5, 8);
|
||||
for c in b"vorbis" {
|
||||
w.put(u64::from(*c), 8);
|
||||
}
|
||||
w.put(0, 8); // one book
|
||||
book(&mut w);
|
||||
w.0
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn absurd_codebook_sizes_are_refused_before_allocating() {
|
||||
let p = parts(1);
|
||||
let try_setup = |setup: Vec<u8>| Decoder::new(&p.headers[0], &p.headers[1], &setup);
|
||||
// 2^24 - 1 entries.
|
||||
assert!(
|
||||
try_setup(setup_with_first_book(|w| {
|
||||
w.put(0x56_4342, 24);
|
||||
w.put(1, 16);
|
||||
w.put(0xFF_FFFF, 24);
|
||||
w.put(1, 1); // ordered
|
||||
w.put(0, 5);
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
// An ordered book whose lengths overrun its entries.
|
||||
assert!(
|
||||
try_setup(setup_with_first_book(|w| {
|
||||
w.put(0x56_4342, 24);
|
||||
w.put(1, 16);
|
||||
w.put(8, 24);
|
||||
w.put(1, 1);
|
||||
w.put(0, 5);
|
||||
w.put(0xFF, 4); // asks for more codewords of length 1 than there are entries
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
// A lookup table of 65535 dimensions over a million entries: 69 billion values.
|
||||
assert!(
|
||||
try_setup(setup_with_first_book(|w| {
|
||||
w.put(0x56_4342, 24);
|
||||
w.put(0xFFFF, 16);
|
||||
w.put(1 << 20, 24);
|
||||
w.put(1, 1); // ordered
|
||||
w.put(19, 5); // length 20
|
||||
w.put(1 << 20, 21); // all the entries
|
||||
w.put(2, 4); // lookup type 2
|
||||
w.put(0, 32);
|
||||
w.put(0, 32);
|
||||
w.put(0, 4);
|
||||
w.put(0, 1);
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
// A million-entry book with a legitimate tree but a lookup table that is not in the packet.
|
||||
assert!(
|
||||
try_setup(setup_with_first_book(|w| {
|
||||
w.put(0x56_4342, 24);
|
||||
w.put(4, 16);
|
||||
w.put(1 << 20, 24);
|
||||
w.put(1, 1);
|
||||
w.put(19, 5);
|
||||
w.put(1 << 20, 21);
|
||||
w.put(1, 4); // lookup type 1
|
||||
w.put(0, 32);
|
||||
w.put(0, 32);
|
||||
w.put(15, 4);
|
||||
w.put(0, 1);
|
||||
}))
|
||||
.is_err()
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn identification_header_limits() {
|
||||
let p = parts(1);
|
||||
let mut h = p.headers[0].clone();
|
||||
let setup = &p.headers[2];
|
||||
h[11] = 0; // no channels
|
||||
assert!(matches!(Decoder::new(&h, &p.headers[1], setup), Err(Error::Header(_))));
|
||||
let mut h = p.headers[0].clone();
|
||||
h[28] = 0x95; // a short block size of 2^5 is below the 64 Vorbis allows
|
||||
assert!(matches!(Decoder::new(&h, &p.headers[1], setup), Err(Error::Header(_))));
|
||||
let mut h = p.headers[0].clone();
|
||||
h[7] = 1; // version 1
|
||||
assert!(matches!(Decoder::new(&h, &p.headers[1], setup), Err(Error::Header(_))));
|
||||
}
|
||||
@@ -0,0 +1,216 @@
|
||||
//! The Vorbis decoder against ffmpeg's as the reference (oracle; skipped when ffmpeg is absent, a
|
||||
//! failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`). Streams come from two encoders, this crate's and
|
||||
//! ffmpeg's own, so the setups differ: different floors, residues, block sizes, channel counts and
|
||||
//! coupling. Both decoders must return the same samples.
|
||||
|
||||
use craft_audio::AudioBuffer;
|
||||
use craft_audio::vorbis::decoder::{Decoder, decode_ogg};
|
||||
use craft_audio::{OggVorbisOptions, encode_ogg_vorbis};
|
||||
use std::path::Path;
|
||||
use std::process::Command;
|
||||
|
||||
fn xorshift(seed: &mut u32) -> u32 {
|
||||
*seed ^= *seed << 13;
|
||||
*seed ^= *seed >> 17;
|
||||
*seed ^= *seed << 5;
|
||||
*seed
|
||||
}
|
||||
|
||||
/// A signal with tones, noise bursts, clicks and silence, different in every channel.
|
||||
fn signal(rate: u32, channels: usize, frames: usize) -> Vec<Vec<f32>> {
|
||||
let mut seed = 0x1234_5678u32;
|
||||
(0..channels)
|
||||
.map(|c| {
|
||||
(0..frames)
|
||||
.map(|i| {
|
||||
let t = i as f64 / f64::from(rate);
|
||||
let tone =
|
||||
(t * (220.0 + 110.0 * c as f64) * std::f64::consts::TAU).sin() * 0.3 + (t * 3100.0 * std::f64::consts::TAU).sin() * 0.05;
|
||||
let noise = (f64::from(xorshift(&mut seed) % 2000) - 1000.0) / 6000.0;
|
||||
let s = match (i / (rate as usize / 4)) % 6 {
|
||||
0 | 1 => tone,
|
||||
2 => noise,
|
||||
3 => 0.0,
|
||||
4 => tone + if i % 3000 < 8 { 0.6 } else { 0.0 },
|
||||
_ => tone * (t * 4.0).sin(),
|
||||
};
|
||||
s as f32
|
||||
})
|
||||
.collect()
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
fn ffmpeg_decode(ffmpeg: &Path, ogg: &Path, channels: usize) -> Vec<Vec<f32>> {
|
||||
let out = Command::new(ffmpeg)
|
||||
.args(["-v", "error", "-nostdin", "-i"])
|
||||
.arg(ogg)
|
||||
.args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
|
||||
.output()
|
||||
.expect("run ffmpeg");
|
||||
assert!(out.status.success(), "ffmpeg failed on {}: {}", ogg.display(), String::from_utf8_lossy(&out.stderr));
|
||||
let all: Vec<f32> = out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect();
|
||||
(0..channels).map(|c| all.iter().skip(c).step_by(channels).copied().collect()).collect()
|
||||
}
|
||||
|
||||
/// Each of our channels matches a different one of theirs (ffmpeg reorders the channels of surround
|
||||
/// streams), to within float rounding.
|
||||
fn assert_same(name: &str, ours: &[Vec<f32>], theirs: &[Vec<f32>]) {
|
||||
assert_prefix(name, ours, theirs, true);
|
||||
}
|
||||
|
||||
/// As [`assert_same`], but with `exact` unset ffmpeg may return more samples than we do (it does
|
||||
/// not always trim a stream to its last granule position); the common part must agree.
|
||||
fn assert_prefix(name: &str, ours: &[Vec<f32>], theirs: &[Vec<f32>], exact: bool) {
|
||||
assert_eq!(ours.len(), theirs.len(), "{name}: channel count");
|
||||
assert!(ours.iter().chain(theirs).flatten().all(|v| v.is_finite()), "{name}: non-finite oracle input or output");
|
||||
let mut used = vec![false; theirs.len()];
|
||||
for (c, o) in ours.iter().enumerate() {
|
||||
let mut best: Option<(usize, f32)> = None;
|
||||
for (k, t) in theirs.iter().enumerate() {
|
||||
if used[k] {
|
||||
continue;
|
||||
}
|
||||
if exact {
|
||||
assert_eq!(o.len(), t.len(), "{name}: channel {c} length {} vs ffmpeg {}", o.len(), t.len());
|
||||
} else {
|
||||
assert!(o.len() <= t.len(), "{name}: channel {c} length {} vs ffmpeg {}", o.len(), t.len());
|
||||
}
|
||||
let worst = o.iter().zip(t).map(|(a, b)| (a - b).abs()).fold(0f32, f32::max);
|
||||
if best.is_none_or(|(_, w)| worst < w) {
|
||||
best = Some((k, worst));
|
||||
}
|
||||
}
|
||||
let (k, worst) = best.expect("a free channel");
|
||||
used[k] = true;
|
||||
assert!(worst < 2e-4, "{name}: channel {c} differs from ffmpeg's channel {k} by up to {worst}");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn ffmpeg_decodes_our_encoders_streams_to_the_same_samples() {
|
||||
let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return };
|
||||
let dir = craft_media_testkit::fixture_subdir("vorbis_decode");
|
||||
for (rate, channels, quality) in
|
||||
[(44_100u32, 2usize, 6.0f32), (44_100, 1, 3.0), (48_000, 2, -1.0), (22_050, 1, 10.0), (44_100, 6, 5.0), (32_000, 8, 4.0)]
|
||||
{
|
||||
let buf = AudioBuffer { sample_rate: rate, channels: signal(rate, channels, rate as usize * 2 + 777) };
|
||||
let ogg = encode_ogg_vorbis(&buf, &OggVorbisOptions::default().with_quality(quality)).expect("encode");
|
||||
let file = dir.join(format!("ours_{rate}_{channels}_{quality}.ogg"));
|
||||
std::fs::write(&file, &ogg).expect("write fixture");
|
||||
let decoded = decode_ogg(&ogg).expect("decode");
|
||||
assert_eq!(decoded.damaged_packets, 0);
|
||||
assert_eq!(decoded.sample_rate, rate);
|
||||
assert_same(&format!("our stream {rate} Hz {channels} ch q{quality}"), &decoded.channels, &ffmpeg_decode(&ffmpeg, &file, channels));
|
||||
}
|
||||
}
|
||||
|
||||
/// ffmpeg's own Vorbis encoder (stereo only) writes setups ours does not: coupled channels, residue
|
||||
/// type 2, floor classes with subclasses and master books, two block sizes. The reference is
|
||||
/// Symphonia, an independent decoder. ffmpeg's decoder agrees on the first channel but not on the
|
||||
/// second of these streams, where it differs from both Symphonia and this decoder; the stream does
|
||||
/// not show which reading it means (the channel comes back poorly, about 3 dB SNR, in all three),
|
||||
/// so ffmpeg is compared on the first channel only. The setups ffmpeg's decoder does read the same
|
||||
/// way as we do are covered, on both channels, in `vorbis_decode_synthetic.rs`.
|
||||
#[test]
|
||||
fn we_decode_ffmpegs_encoder_streams_like_symphonia() {
|
||||
let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return };
|
||||
let dir = craft_media_testkit::fixture_subdir("vorbis_decode");
|
||||
for (rate, bitrate) in [(44_100u32, "128k"), (48_000, "96k"), (22_050, "48k"), (32_000, "64k")] {
|
||||
let channels = 2usize;
|
||||
let pcm: Vec<f32> = {
|
||||
let s = signal(rate, channels, rate as usize * 2 + 301);
|
||||
(0..s[0].len()).flat_map(|i| s.iter().map(move |c| c[i])).collect()
|
||||
};
|
||||
let raw = dir.join(format!("src_{rate}_{channels}.f32"));
|
||||
std::fs::write(&raw, pcm.iter().flat_map(|v| v.to_le_bytes()).collect::<Vec<u8>>()).expect("write source");
|
||||
let file = dir.join(format!("ffmpeg_{rate}_{channels}_{bitrate}.ogg"));
|
||||
let out = Command::new(&ffmpeg)
|
||||
.args(["-v", "error", "-nostdin", "-y", "-f", "f32le", "-ar"])
|
||||
.arg(rate.to_string())
|
||||
.arg("-ac")
|
||||
.arg(channels.to_string())
|
||||
.arg("-i")
|
||||
.arg(&raw)
|
||||
.args(["-c:a", "vorbis", "-strict", "-2", "-b:a", bitrate])
|
||||
.arg(&file)
|
||||
.output()
|
||||
.expect("run ffmpeg");
|
||||
assert!(out.status.success(), "ffmpeg could not encode {}: {}", file.display(), String::from_utf8_lossy(&out.stderr));
|
||||
let ogg = std::fs::read(&file).expect("read");
|
||||
let ours = decode_ogg(&ogg).expect("decode");
|
||||
assert_eq!(ours.damaged_packets, 0, "{}", file.display());
|
||||
let (_, symphonia) = craft_audio::decode(&ogg, Some("ogg")).expect("symphonia");
|
||||
let name = format!("ffmpeg-encoded {rate} Hz {bitrate}");
|
||||
assert_prefix(&name, &ours.channels, &symphonia.channels, false);
|
||||
// The first channel also agrees with ffmpeg's decoder.
|
||||
let theirs = ffmpeg_decode(&ffmpeg, &file, channels);
|
||||
assert_prefix(&format!("{name} (channel 0 against ffmpeg)"), &ours.channels[..1], &theirs[..1], true);
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn packets_decode_one_at_a_time_to_the_file_result() {
|
||||
let buf = AudioBuffer { sample_rate: 44_100, channels: signal(44_100, 2, 30_000) };
|
||||
let ogg = encode_ogg_vorbis(&buf, &OggVorbisOptions::default().with_quality(5.0)).expect("encode");
|
||||
let file = craft_media::ogg::open(ogg.as_slice()).expect("open");
|
||||
let s = &file.streams[file.stream_of(craft_media::ogg::Codec::Vorbis).expect("vorbis")];
|
||||
let mut dec = Decoder::new(&s.headers[0], &s.headers[1], &s.headers[2]).expect("decoder");
|
||||
assert_eq!((dec.identification().channels, dec.identification().sample_rate), (2, 44_100));
|
||||
let mut got: Vec<Vec<f32>> = vec![Vec::new(); 2];
|
||||
for i in 0..s.packets.len() {
|
||||
let p = file.read_packet(ogg.as_slice(), 0, i).expect("packet");
|
||||
for (a, b) in got.iter_mut().zip(dec.decode_packet(&p).expect("packet decodes")) {
|
||||
a.extend(b);
|
||||
}
|
||||
}
|
||||
let whole = decode_ogg(&ogg).expect("file");
|
||||
for (a, b) in got.iter().zip(&whole.channels) {
|
||||
assert!(a.len() >= b.len() && a[..b.len()] == b[..]);
|
||||
}
|
||||
// After a reset the next packet only primes the overlap again.
|
||||
dec.reset();
|
||||
let p = file.read_packet(ogg.as_slice(), 0, 5).expect("packet");
|
||||
assert!(dec.decode_packet(&p).expect("decodes").iter().all(Vec::is_empty));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_round_trip_through_our_encoder_is_faithful() {
|
||||
let src = signal(44_100, 2, 44_100);
|
||||
let buf = AudioBuffer { sample_rate: 44_100, channels: src.clone() };
|
||||
let ogg = encode_ogg_vorbis(&buf, &OggVorbisOptions::default().with_quality(8.0)).expect("encode");
|
||||
let out = decode_ogg(&ogg).expect("decode");
|
||||
assert_eq!(out.channels[0].len(), src[0].len());
|
||||
let (mut sig, mut err) = (0f64, 0f64);
|
||||
for (a, b) in src[0].iter().zip(&out.channels[0]) {
|
||||
sig += f64::from(*a) * f64::from(*a);
|
||||
err += f64::from(a - b) * f64::from(a - b);
|
||||
}
|
||||
assert!(10.0 * (sig / err).log10() > 15.0, "SNR {:.1} dB", 10.0 * (sig / err).log10());
|
||||
}
|
||||
|
||||
/// A stream from libvorbis itself (the repository's `tone.ogg` fixture, made with ffmpeg's libvorbis
|
||||
/// wrapper): mono, 8 kHz, the lowest quality.
|
||||
#[test]
|
||||
fn a_libvorbis_stream_decodes_like_ffmpeg() {
|
||||
let path = Path::new(env!("CARGO_MANIFEST_DIR")).join("tests/fixtures/tone.ogg");
|
||||
let ogg = std::fs::read(&path).expect("fixture");
|
||||
let ours = decode_ogg(&ogg).expect("decode");
|
||||
assert_eq!((ours.sample_rate, ours.channels.len(), ours.damaged_packets), (8000, 1, 0));
|
||||
assert!(ours.comments.vendor.contains("Lavf") || ours.comments.vendor.contains("libVorbis"), "vendor {:?}", ours.comments.vendor);
|
||||
assert!(ours.channels[0].iter().any(|s| s.abs() > 0.1), "the fixture is a tone");
|
||||
let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return };
|
||||
assert_prefix("libvorbis tone.ogg", &ours.channels, &ffmpeg_decode(&ffmpeg, &path, 1), false);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "non-finite oracle input or output")]
|
||||
fn oracle_comparison_rejects_nan_output() {
|
||||
assert_same("NaN output", &[vec![f32::NAN]], &[vec![0.0]]);
|
||||
}
|
||||
|
||||
#[test]
|
||||
#[should_panic(expected = "non-finite oracle input or output")]
|
||||
fn oracle_comparison_rejects_nan_reference() {
|
||||
assert_same("NaN reference", &[vec![0.0]], &[vec![f32::NAN]]);
|
||||
}
|
||||
@@ -0,0 +1,384 @@
|
||||
//! Differential tests on streams built by hand: a setup header written here, with floor 0 and
|
||||
//! floor 1 side by side, residues 0, 1 and 2, several submaps and channel coupling, followed by
|
||||
//! random audio packets. Every packet of random bits is decodable, so the two decoders (ours and
|
||||
//! ffmpeg's, the oracle; skipped when ffmpeg is absent, a failure with
|
||||
//! `CRAFT_MEDIA_REQUIRE_ORACLES=1`) must return the same samples, and no encoder's habits narrow
|
||||
//! what is exercised. Floor 0, residue 0 and multi-submap mappings are the parts no encoder here
|
||||
//! writes.
|
||||
|
||||
use craft_audio::vorbis::decoder::{Decoder, decode_ogg};
|
||||
use craft_media::ogg::{PageWriter, vorbis_comment};
|
||||
use std::process::Command;
|
||||
|
||||
fn xorshift(seed: &mut u32) -> u32 {
|
||||
*seed ^= *seed << 13;
|
||||
*seed ^= *seed >> 17;
|
||||
*seed ^= *seed << 5;
|
||||
*seed
|
||||
}
|
||||
|
||||
/// A least-significant-bit-first bit writer.
|
||||
#[derive(Default)]
|
||||
struct W {
|
||||
bytes: Vec<u8>,
|
||||
bits: usize,
|
||||
}
|
||||
|
||||
impl W {
|
||||
fn put(&mut self, v: u64, n: u32) {
|
||||
for i in 0..n {
|
||||
if self.bits.is_multiple_of(8) {
|
||||
self.bytes.push(0);
|
||||
}
|
||||
let last = self.bytes.len() - 1;
|
||||
self.bytes[last] |= (((v >> i) & 1) as u8) << (self.bits % 8);
|
||||
self.bits += 1;
|
||||
}
|
||||
}
|
||||
fn flag(&mut self, b: bool) {
|
||||
self.put(u64::from(b), 1);
|
||||
}
|
||||
}
|
||||
|
||||
fn float_bits(v: f64) -> u64 {
|
||||
// The Vorbis float32 packing: sign, 10-bit exponent biased by 788, 21-bit mantissa.
|
||||
if v == 0.0 {
|
||||
return 0;
|
||||
}
|
||||
let (sign, a) = if v < 0.0 { (1u64 << 31, -v) } else { (0, v) };
|
||||
let mut exp = 0i32;
|
||||
let mut m = a;
|
||||
while m >= (1 << 21) as f64 {
|
||||
m /= 2.0;
|
||||
exp += 1;
|
||||
}
|
||||
while m < (1 << 20) as f64 {
|
||||
m *= 2.0;
|
||||
exp -= 1;
|
||||
}
|
||||
sign | (((exp + 788) as u64) << 21) | (m.round() as u64 & 0x1F_FFFF)
|
||||
}
|
||||
|
||||
/// A complete codebook: `entries` codewords all of length `len` (`entries == 2^len`), optionally
|
||||
/// with a lookup table: `(type, minimum, delta, value_bits, multiplicands)`.
|
||||
fn book(w: &mut W, dims: u32, entries: u32, len: u32, lookup: Option<(u32, f64, f64, u32, Vec<u32>)>) {
|
||||
w.put(0x56_4342, 24);
|
||||
w.put(u64::from(dims), 16);
|
||||
w.put(u64::from(entries), 24);
|
||||
w.flag(false); // not ordered
|
||||
w.flag(false); // not sparse
|
||||
for _ in 0..entries {
|
||||
w.put(u64::from(len - 1), 5);
|
||||
}
|
||||
match lookup {
|
||||
None => w.put(0, 4),
|
||||
Some((ty, min, delta, bits, mult)) => {
|
||||
w.put(u64::from(ty), 4);
|
||||
w.put(float_bits(min), 32);
|
||||
w.put(float_bits(delta), 32);
|
||||
w.put(u64::from(bits - 1), 4);
|
||||
w.flag(ty == 1); // sequence_p: cumulative for the floor 0 book
|
||||
for m in mult {
|
||||
w.put(u64::from(m), bits);
|
||||
}
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
struct Layout {
|
||||
channels: u8,
|
||||
/// The residue type of each of the two residues.
|
||||
residue_types: [u32; 2],
|
||||
/// The submap of each channel (0 or 1): submap 0 uses floor 0 and residue 0, submap 1 uses
|
||||
/// floor 1 and residue 1.
|
||||
mux: Vec<u8>,
|
||||
coupling: Vec<(u8, u8)>,
|
||||
}
|
||||
|
||||
fn identification(channels: u8) -> Vec<u8> {
|
||||
let mut w = W::default();
|
||||
w.put(1, 8);
|
||||
for c in b"vorbis" {
|
||||
w.put(u64::from(*c), 8);
|
||||
}
|
||||
w.put(0, 32);
|
||||
w.put(u64::from(channels), 8);
|
||||
w.put(16_000, 32);
|
||||
w.put(0, 32);
|
||||
w.put(0, 32);
|
||||
w.put(0, 32);
|
||||
w.put(8, 4); // short blocks: 256
|
||||
w.put(10, 4); // long blocks: 1024
|
||||
w.flag(true);
|
||||
w.bytes
|
||||
}
|
||||
|
||||
fn setup(l: &Layout) -> Vec<u8> {
|
||||
let mut w = W::default();
|
||||
w.put(5, 8);
|
||||
for c in b"vorbis" {
|
||||
w.put(u64::from(*c), 8);
|
||||
}
|
||||
// Books: 0 floor 0 vectors, 1 class book, 2 and 3 residue vectors, 4 floor 1 values.
|
||||
w.put(4, 8); // five books
|
||||
book(&mut w, 4, 16, 4, Some((1, 0.7, 0.2, 1, vec![0, 1]))); // lookup1_values(16, 4) = 2
|
||||
book(&mut w, 1, 4, 2, None);
|
||||
book(&mut w, 2, 16, 4, Some((1, -0.4, 0.25, 2, vec![0, 1, 2, 3]))); // lookup1_values(16, 2) = 4
|
||||
book(&mut w, 4, 16, 4, Some((1, -0.3, 0.6, 1, vec![0, 1])));
|
||||
book(&mut w, 1, 128, 7, None);
|
||||
// One time domain placeholder.
|
||||
w.put(0, 6);
|
||||
w.put(0, 16);
|
||||
// Floors: 0 and 1.
|
||||
w.put(1, 6); // two floors
|
||||
w.put(0, 16);
|
||||
w.put(8, 8); // order
|
||||
w.put(16_000, 16); // rate
|
||||
w.put(64, 16); // bark map size
|
||||
w.put(8, 6); // amplitude bits
|
||||
w.put(2, 8); // amplitude offset
|
||||
w.put(0, 4); // one book
|
||||
w.put(0, 8);
|
||||
w.put(1, 16);
|
||||
w.put(1, 5); // one partition
|
||||
w.put(0, 4); // class 0
|
||||
w.put(2, 3); // dimension 3
|
||||
w.put(0, 2); // no subclasses
|
||||
w.put(4 + 1, 8); // subclass book: book 4 (stored plus one)
|
||||
w.put(1, 2); // multiplier 2
|
||||
w.put(8, 4); // rangebits
|
||||
for x in [10, 40, 130] {
|
||||
w.put(x, 8);
|
||||
}
|
||||
// Residues.
|
||||
w.put(1, 6); // two residues
|
||||
for ty in l.residue_types {
|
||||
w.put(u64::from(ty), 16);
|
||||
w.put(0, 24); // begin
|
||||
w.put(if ty == 2 { 96 } else { 48 }, 24); // end
|
||||
w.put(7, 24); // partition size 8
|
||||
w.put(3, 6); // four classifications
|
||||
w.put(1, 8); // class book
|
||||
for _ in 0..4 {
|
||||
w.put(0b011, 3); // passes 0 and 1
|
||||
w.flag(false);
|
||||
}
|
||||
for class in 0..4 {
|
||||
w.put(2 + (class % 2), 8); // pass 0 uses book 2 or 3
|
||||
w.put(3 - (class % 2), 8); // pass 1 uses book 3 or 2
|
||||
}
|
||||
}
|
||||
// One mapping, two submaps.
|
||||
w.put(0, 6);
|
||||
w.put(0, 16);
|
||||
w.flag(true);
|
||||
w.put(1, 4); // two submaps
|
||||
w.flag(!l.coupling.is_empty());
|
||||
if !l.coupling.is_empty() {
|
||||
w.put(l.coupling.len() as u64 - 1, 8);
|
||||
let bits = if l.channels <= 1 { 0 } else { 8 - (l.channels - 1).leading_zeros() };
|
||||
for &(m, a) in &l.coupling {
|
||||
w.put(u64::from(m), bits);
|
||||
w.put(u64::from(a), bits);
|
||||
}
|
||||
}
|
||||
w.put(0, 2);
|
||||
for &m in &l.mux {
|
||||
w.put(u64::from(m), 4);
|
||||
}
|
||||
for sub in 0..2u64 {
|
||||
w.put(0, 8);
|
||||
w.put(sub, 8); // floor
|
||||
w.put(sub, 8); // residue
|
||||
}
|
||||
// Two modes over the one mapping.
|
||||
w.put(1, 6);
|
||||
for long in [false, true] {
|
||||
w.flag(long);
|
||||
w.put(0, 16);
|
||||
w.put(0, 16);
|
||||
w.put(0, 8);
|
||||
}
|
||||
w.flag(true);
|
||||
w.bytes
|
||||
}
|
||||
|
||||
fn stream(l: &Layout, packets: usize, seed: &mut u32) -> Vec<u8> {
|
||||
let mut pages = PageWriter::new(7);
|
||||
let mut out = pages.header(&identification(l.channels));
|
||||
out.extend(pages.header(&vorbis_comment("synthetic", &[("TITLE", "hand built")])));
|
||||
out.extend(pages.header(&setup(l)));
|
||||
// The window flags of a long block say whether its neighbours are long, so choose the block
|
||||
// sizes first.
|
||||
let longs: Vec<bool> = (0..packets).map(|_| !xorshift(seed).is_multiple_of(3)).collect();
|
||||
let mut granule = 0i64;
|
||||
for i in 0..packets {
|
||||
let long = longs[i];
|
||||
// Packet type 0, the mode bit, and for a long block the two neighbour flags.
|
||||
let prev = i == 0 || longs[i - 1];
|
||||
let next = i + 1 >= packets || longs[i + 1];
|
||||
let mut w = W::default();
|
||||
w.flag(false);
|
||||
w.flag(long);
|
||||
if long {
|
||||
w.flag(prev);
|
||||
w.flag(next);
|
||||
}
|
||||
// Floor 0 needs a codebook number that exists, which random bits would not give, so the
|
||||
// channels that use it (the first ones) are written properly: an amplitude, book 0 and two
|
||||
// codewords of its vectors (a full tree of 4-bit codes: the code is the entry number).
|
||||
for _ in 0..l.mux.iter().take_while(|&&m| m == 0).count() {
|
||||
w.put(1 + u64::from(xorshift(seed)) % 24, 8);
|
||||
w.put(0, 1);
|
||||
for _ in 0..2 {
|
||||
let entry = xorshift(seed) % 16;
|
||||
for bit in (0..4).rev() {
|
||||
w.put(u64::from(entry >> bit) & 1, 1);
|
||||
}
|
||||
}
|
||||
}
|
||||
// The rest is random bits, enough that no residue runs out of packet.
|
||||
let mut p = w.bytes;
|
||||
let fixed = p.len();
|
||||
p.extend((0..200 + xorshift(seed) as usize % 200).map(|_| xorshift(seed) as u8));
|
||||
let _ = fixed;
|
||||
// The bits after the fixed fields start mid-byte: the last fixed byte keeps its own bits and
|
||||
// takes random ones above them.
|
||||
let used = w.bits % 8;
|
||||
if used != 0 {
|
||||
let last = fixed - 1;
|
||||
p[last] |= (xorshift(seed) as u8) << used;
|
||||
}
|
||||
if i > 0 {
|
||||
let size = |long: bool| if long { 1024 } else { 256 };
|
||||
granule += (size(longs[i - 1]) / 4 + size(long) / 4) as i64;
|
||||
}
|
||||
out.extend(pages.packet(&p, granule));
|
||||
}
|
||||
out.extend(pages.finish(None));
|
||||
out
|
||||
}
|
||||
|
||||
/// `tolerance`: the largest difference from ffmpeg, as a fraction of the peak output. A floor 0
|
||||
/// curve is an exponential of a quotient that random coefficients can make very large, so where
|
||||
/// two floors meet in one stream (ffmpeg computes in single precision, we in double) the results
|
||||
/// agree only to about a thousandth of the peak.
|
||||
fn run(name: &str, l: &Layout, seed: u32, tolerance: f32) {
|
||||
let mut s = seed;
|
||||
let ogg = stream(l, 40, &mut s);
|
||||
// Packet by packet our decoder must accept every one.
|
||||
let file = craft_media::ogg::open(ogg.as_slice()).expect("open");
|
||||
let st = &file.streams[0];
|
||||
let mut dec = Decoder::new(&st.headers[0], &st.headers[1], &st.headers[2]).expect("setup decodes");
|
||||
let mut total = vec![Vec::new(); usize::from(l.channels)];
|
||||
for i in 0..st.packets.len() {
|
||||
let p = file.read_packet(ogg.as_slice(), 0, i).expect("packet");
|
||||
let pcm = dec.decode_packet(&p).unwrap_or_else(|e| panic!("{name}: packet {i}: {e}"));
|
||||
for (t, c) in total.iter_mut().zip(pcm) {
|
||||
t.extend(c);
|
||||
}
|
||||
}
|
||||
let expected = usize::try_from(st.last_granule.expect("generated final granule")).expect("nonnegative granule");
|
||||
for channel in &total {
|
||||
assert_eq!(channel.len(), expected, "{name}: decoded sample count");
|
||||
assert!(channel.iter().all(|v| v.is_finite()), "{name}: non-finite output");
|
||||
}
|
||||
let whole = decode_ogg(&ogg).expect("whole file");
|
||||
assert_eq!(whole.channels, total, "{name}: packet and file decoding differ");
|
||||
let Some(ffmpeg) = craft_media_testkit::ffmpeg() else { return };
|
||||
let dir = craft_media_testkit::fixture_subdir("vorbis_synthetic");
|
||||
let path = dir.join(format!("{name}.ogg"));
|
||||
std::fs::write(&path, &ogg).expect("write fixture");
|
||||
let out = Command::new(&ffmpeg)
|
||||
.args(["-v", "error", "-nostdin", "-i"])
|
||||
.arg(&path)
|
||||
.args(["-f", "f32le", "-acodec", "pcm_f32le", "-"])
|
||||
.output()
|
||||
.expect("run ffmpeg");
|
||||
assert!(out.status.success(), "{name}: ffmpeg failed: {}", String::from_utf8_lossy(&out.stderr));
|
||||
let all: Vec<f32> = out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect();
|
||||
let ch = usize::from(l.channels);
|
||||
let theirs: Vec<Vec<f32>> = (0..ch).map(|c| all.iter().skip(c).step_by(ch).copied().collect()).collect();
|
||||
assert!(theirs.iter().flatten().all(|v| v.is_finite()), "{name}: non-finite ffmpeg output");
|
||||
for channel in &theirs {
|
||||
assert!(channel.len() >= expected, "{name}: ffmpeg returned fewer than the expected samples");
|
||||
}
|
||||
// ffmpeg puts the channels of surround streams in its own order, so each of ours is matched
|
||||
// with the channel of theirs it agrees with best, and every one of theirs is used once.
|
||||
let mut used = vec![false; ch];
|
||||
#[allow(clippy::needless_range_loop)]
|
||||
for c in 0..ch {
|
||||
let mut best: Option<(usize, f32, f32)> = None;
|
||||
for (k, t) in theirs.iter().enumerate().filter(|(k, _)| !used[*k]) {
|
||||
let n = total[c].len().min(t.len());
|
||||
assert!(n > 1000, "{name}: only {n} samples to compare");
|
||||
let scale = total[c][..n].iter().fold(1e-3f32, |m, v| m.max(v.abs()));
|
||||
let worst = (0..n).map(|i| (total[c][i] - t[i]).abs()).fold(0f32, f32::max);
|
||||
if best.is_none_or(|(_, w, sc)| worst / scale < w / sc) {
|
||||
best = Some((k, worst, scale));
|
||||
}
|
||||
}
|
||||
let (k, worst, scale) = best.expect("a free channel");
|
||||
used[k] = true;
|
||||
assert!(worst <= tolerance * scale + 1e-5, "{name}: channel {c} differs from ffmpeg's channel {k} by {worst} (peak {scale})");
|
||||
}
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_floor_zero_and_residue_zero() {
|
||||
run("mono_f0_r0", &Layout { channels: 1, residue_types: [0, 0], mux: vec![0], coupling: vec![] }, 11, 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_floor_one_and_residue_one() {
|
||||
run("mono_f1_r1", &Layout { channels: 1, residue_types: [1, 1], mux: vec![1], coupling: vec![] }, 12, 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn two_submaps_floor_zero_and_one() {
|
||||
run("stereo_mixed", &Layout { channels: 2, residue_types: [0, 1], mux: vec![0, 1], coupling: vec![] }, 13, 3e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn coupled_stereo_residue_two() {
|
||||
run("stereo_coupled_r2", &Layout { channels: 2, residue_types: [2, 2], mux: vec![1, 1], coupling: vec![(0, 1)] }, 14, 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn six_channels_with_coupling_and_submaps() {
|
||||
let l = Layout { channels: 6, residue_types: [1, 2], mux: vec![0, 0, 0, 1, 1, 1], coupling: vec![(0, 3), (1, 2), (4, 5)] };
|
||||
run("six", &l, 15, 3e-3);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_floor_one_and_residue_zero() {
|
||||
run("mono_f1_r0", &Layout { channels: 1, residue_types: [0, 0], mux: vec![1], coupling: vec![] }, 16, 1e-4);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn mono_floor_zero_and_residue_one() {
|
||||
run("mono_f0_r1", &Layout { channels: 1, residue_types: [1, 1], mux: vec![0], coupling: vec![] }, 17, 1e-4);
|
||||
}
|
||||
|
||||
/// A packet that names a floor 0 codebook that does not exist cannot be decoded (§6.2.2); the
|
||||
/// decoder says so and the stream goes on with the next packet.
|
||||
#[test]
|
||||
fn a_floor_zero_codebook_that_does_not_exist_is_a_packet_error() {
|
||||
let l = Layout { channels: 1, residue_types: [1, 1], mux: vec![0], coupling: vec![] };
|
||||
let mut seed = 5u32;
|
||||
let ogg = stream(&l, 6, &mut seed);
|
||||
let file = craft_media::ogg::open(ogg.as_slice()).expect("open");
|
||||
let st = &file.streams[0];
|
||||
let mut dec = Decoder::new(&st.headers[0], &st.headers[1], &st.headers[2]).expect("decoder");
|
||||
let good = file.read_packet(ogg.as_slice(), 0, 0).expect("packet");
|
||||
assert!(dec.decode_packet(&good).is_ok());
|
||||
// A short block: type 0, mode 0, then the 8 amplitude bits, then book number 1 (only 0 exists).
|
||||
let mut w = W::default();
|
||||
w.flag(false);
|
||||
w.flag(false);
|
||||
w.put(9, 8);
|
||||
w.put(1, 1);
|
||||
w.put(0, 64);
|
||||
assert!(matches!(dec.decode_packet(&w.bytes), Err(craft_audio::vorbis::decoder::Error::Packet(_))));
|
||||
assert!(dec.decode_packet(&good).is_ok(), "the decoder carries on");
|
||||
}
|
||||
Reference in New Issue
Block a user