mirror of
https://github.com/storytold/craft-libs.git
synced 2026-11-17 07:44:40 +00:00
* craft-audio: FilmCraft's FLAC encoder and MP1/MP2 decoder speed-ups FLAC: per-order predictor kernels, merged Rice partition sums, the LPC window kept per block length, and batches consumed by offset (filmcraft 5eaff794, d9dad4a5). The output is unchanged: 64 golden cases hash the same before and after. MP1/MP2: the faster synthesis filterbank (filmcraft 51c755e5), with its bit-exact test. * craft-audio: FilmCraft's AAC and Opus decoder speed-ups and refactors AAC: table-driven Huffman decoding, per-stage FFT twiddles and fused stages, reused per-channel work buffers, and the encoder's memoised per-band work (filmcraft f9627280, d587ceed, 6121635c, dc124ab7, 7a532eca). Opus: radix-2/3/4 FFT kernels in the CELT IMDCT, the PVQ table built once, one de-emphasis loop for both channels, the SILK resampler without per-sample divisions and with eight partial sums, concealment and FEC capped at 120 ms (filmcraft bf7ac420, 12e32026, c4dc64d1, eb352ec8, 87b8e22d, 014b5e56, 78d77b72). The per-frame mid-only flag this crate fixed in the SILK decoder is kept in the refactored decode. * craft-media: Ogg CRC-32 by slice-by-16 FilmCraft's 6763f9bf: sixteen independent lookups per 16 input bytes, so opening a file is several times faster. Checked against a bit-at-a-time reference on every short length and alignment, and across every split. * craft-audio: SoundCraft's CAF cookie-size and FLAC vendor-length checks A CAF magic cookie size above the signed range is refused instead of passed to symphonia (soundcraft 3bd3965), and a Vorbis comment block whose vendor string claims more than the block holds is refused (soundcraft ddfe991). Each with its regression test. * craft-audio: AC-3 reads bits through the shared BitReader FilmCraft's 1c9c2e82: the AC-3 decoder's private bit-at-a-time reader is replaced by craft-media's BitReader, with its two tests: the decoded output of 2,000 synthetic and 12 real syncframes (and their damaged variants) hashes the same as before, and the reader agrees with the old one on random reads, skips and overruns. The three AC-3 features now turn on craft-media's bitstream module. * craft-audio: the quantiser rounds without a libm call SoundCraft's d293336, the audio-io part: round-half-away by integer arithmetic in the bounce's inner loop, with its test against f64::round over the quantiser's range.
168 lines
5.6 KiB
Rust
168 lines
5.6 KiB
Rust
//! PCM helpers shared by the WAV, AIFF and FLAC writers: quantization (with optional TPDF
|
|
//! dither), interleaving and layout checks.
|
|
|
|
use crate::{AudioBuffer, AudioError, Result};
|
|
#[cfg(feature = "pcm-encode")]
|
|
use {crate::BitDepth, std::io::Write};
|
|
|
|
/// Converts `f32` samples to integers of a given bit depth, clamping to [-1, 1] and optionally
|
|
/// adding triangular (TPDF) dither of ±1 LSB.
|
|
pub(crate) struct Quantizer {
|
|
bits: u32,
|
|
dither: bool,
|
|
rng: u64,
|
|
}
|
|
|
|
impl Quantizer {
|
|
/// A quantizer for one channel; each channel gets an independent dither sequence.
|
|
pub(crate) fn new(bits: u32, dither: bool, channel: usize) -> Self {
|
|
let rng = 0x9E37_79B9_7F4A_7C15u64 ^ (channel as u64).wrapping_add(1).wrapping_mul(0xD1B5_4A32_D192_ED03);
|
|
Self { bits: bits.clamp(2, 32), dither, rng: if rng == 0 { 1 } else { rng } }
|
|
}
|
|
|
|
/// One quantizer per channel.
|
|
pub(crate) fn per_channel(bits: u32, dither: bool, channels: usize) -> Vec<Self> {
|
|
(0..channels).map(|c| Self::new(bits, dither, c)).collect()
|
|
}
|
|
|
|
/// Uniform in [0, 1) from a xorshift64* generator (deterministic, no OS entropy needed).
|
|
fn uniform(&mut self) -> f64 {
|
|
let mut x = self.rng;
|
|
x ^= x >> 12;
|
|
x ^= x << 25;
|
|
x ^= x >> 27;
|
|
self.rng = x;
|
|
(x.wrapping_mul(0x2545_F491_4F6C_DD1D) >> 11) as f64 / (1u64 << 53) as f64
|
|
}
|
|
|
|
pub(crate) fn quantize(&mut self, x: f32) -> i32 {
|
|
let x = if x.is_nan() { 0.0 } else { x.clamp(-1.0, 1.0) };
|
|
let scale = (1u64 << (self.bits - 1)) as f64;
|
|
let mut v = f64::from(x) * scale;
|
|
if self.dither {
|
|
v += self.uniform() - self.uniform();
|
|
}
|
|
let max = scale - 1.0;
|
|
round_half_away(v.clamp(-scale, max)) as i32
|
|
}
|
|
}
|
|
|
|
/// `v.round()` for values in the `i32` range, without the libm call: the bounce's inner loop.
|
|
#[inline]
|
|
fn round_half_away(v: f64) -> f64 {
|
|
let t = v as i64;
|
|
let f = v - t as f64;
|
|
(t + i64::from(f >= 0.5) - i64::from(f <= -0.5)) as f64
|
|
}
|
|
|
|
/// Bits per sample at `depth`, and whether they are float.
|
|
#[cfg(feature = "pcm-encode")]
|
|
pub(crate) fn sample_format(depth: BitDepth) -> (u16, bool) {
|
|
match depth {
|
|
BitDepth::Int16 => (16, false),
|
|
BitDepth::Int24 => (24, false),
|
|
BitDepth::Int32 => (32, false),
|
|
BitDepth::Float32 => (32, true),
|
|
}
|
|
}
|
|
|
|
/// Interleaves `frames` frames of planar audio (missing samples are silence) as `bits`-bit
|
|
/// samples and writes them to `out`, a few thousand frames at a time through `scratch`.
|
|
#[cfg(feature = "pcm-encode")]
|
|
pub(crate) fn write_interleaved<C: AsRef<[f32]>>(
|
|
out: &mut impl Write,
|
|
scratch: &mut Vec<u8>,
|
|
block: &[C],
|
|
frames: usize,
|
|
quantizers: &mut [Quantizer],
|
|
(bits, is_float): (u16, bool),
|
|
big_endian: bool,
|
|
) -> std::io::Result<()> {
|
|
let size = usize::from(bits / 8);
|
|
let mut start = 0;
|
|
while start < frames {
|
|
let end = frames.min(start + 4096);
|
|
scratch.clear();
|
|
for f in start..end {
|
|
for (c, q) in quantizers.iter_mut().enumerate() {
|
|
let s = block.get(c).and_then(|ch| ch.as_ref().get(f)).copied().unwrap_or(0.0);
|
|
match (is_float, big_endian) {
|
|
(true, false) => scratch.extend_from_slice(&sanitize_float(s).to_le_bytes()),
|
|
(true, true) => scratch.extend_from_slice(&sanitize_float(s).to_be_bytes()),
|
|
(false, false) => scratch.extend_from_slice(q.quantize(s).to_le_bytes().get(..size).unwrap_or_default()),
|
|
(false, true) => scratch.extend_from_slice(q.quantize(s).to_be_bytes().get(4 - size..).unwrap_or_default()),
|
|
}
|
|
}
|
|
}
|
|
out.write_all(scratch)?;
|
|
start = end;
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
/// Preserve finite float samples, mapping NaN to 0 and infinities to their sign (±1).
|
|
#[cfg(feature = "pcm-encode")]
|
|
fn sanitize_float(x: f32) -> f32 {
|
|
if x.is_finite() {
|
|
x
|
|
} else if x.is_nan() {
|
|
0.0
|
|
} else {
|
|
x.signum()
|
|
}
|
|
}
|
|
|
|
/// Check that a buffer is encodable: at least one channel and a non-zero sample rate.
|
|
pub(crate) fn validate_buffer(buf: &AudioBuffer) -> Result<()> {
|
|
validate_layout(buf.channels.len(), buf.sample_rate)
|
|
}
|
|
|
|
/// Check that a stream is encodable: at least one channel and a non-zero sample rate.
|
|
pub(crate) fn validate_layout(channels: usize, sample_rate: u32) -> Result<()> {
|
|
if channels == 0 {
|
|
return Err(AudioError::Encode("buffer has no channels".into()));
|
|
}
|
|
if channels > usize::from(u16::MAX) {
|
|
return Err(AudioError::Encode("too many channels".into()));
|
|
}
|
|
if sample_rate == 0 {
|
|
return Err(AudioError::Encode("sample rate is 0".into()));
|
|
}
|
|
Ok(())
|
|
}
|
|
|
|
#[cfg(test)]
|
|
mod tests {
|
|
use super::*;
|
|
|
|
#[test]
|
|
fn round_half_away_matches_f64_round_on_the_quantizer_range() {
|
|
let edges = [
|
|
0.0,
|
|
-0.0,
|
|
0.5,
|
|
-0.5,
|
|
1.5,
|
|
-1.5,
|
|
2.5,
|
|
0.499_999_999_999_999_94,
|
|
-0.499_999_999_999_999_94,
|
|
8_388_607.5,
|
|
-8_388_608.0,
|
|
2_147_483_647.0,
|
|
-2_147_483_648.0,
|
|
];
|
|
let mut x = 0x2545_f491_4f6c_dd1du64;
|
|
let spread = (0..10_000).map(|_| {
|
|
x ^= x << 13;
|
|
x ^= x >> 7;
|
|
x ^= x << 17;
|
|
(x >> 11) as f64 / (1u64 << 53) as f64 * 4_294_967_295.0 - 2_147_483_648.0
|
|
});
|
|
for v in edges.into_iter().chain(spread) {
|
|
assert!(round_half_away(v) == v.round(), "{v}");
|
|
assert_eq!(round_half_away(v) as i32, v.round() as i32, "{v}");
|
|
}
|
|
}
|
|
}
|