Merge main into feat/audio-g722

This commit is contained in:
el-j committed 2026-11-17 10:12:12 +01:00
commit 3d06331fc8
763 files changed
+107401 -4220

No files matched your search

+189
View File
@@ -0,0 +1,189 @@
//! Compatibility WAVE and AIFF wrappers for embedded PCM essence in interchange files.
//! PCM inside the model is interleaved little-endian signed integers (8-bit unsigned for WAVE).
pub use crate::{pcm_aiff_header as aiff_header, pcm_wav_file as wav_file, pcm_wav_header as wav_header};
/// PCM, channels, sample rate and bits of a WAVE file (integer PCM only).
pub fn parse_wav(b: &[u8]) -> Option<(Vec<u8>, u16, u32, u16)> {
if b.len() < 12 || &b[..4] != b"RIFF" || &b[8..12] != b"WAVE" {
return None;
}
let mut at = 12;
let mut fmt = None;
while at + 8 <= b.len() {
let id = &b[at..at + 4];
let len = u32::from_le_bytes(b[at + 4..at + 8].try_into().ok()?) as usize;
let body = &b[at + 8..(at + 8).saturating_add(len).min(b.len())];
if id == b"fmt " && body.len() >= 16 {
let tag = u16::from_le_bytes([body[0], body[1]]);
let ch = u16::from_le_bytes([body[2], body[3]]);
let sr = u32::from_le_bytes(body[4..8].try_into().ok()?);
let bits = u16::from_le_bytes([body[14], body[15]]);
if tag != 1 && tag != 0xFFFE {
return None;
}
if tag == 0xFFFE {
// The first two bytes of the sub-format GUID carry the real format code.
let sub = body.get(24..26)?;
if u16::from_le_bytes([sub[0], sub[1]]) != 1 {
return None;
}
}
fmt = Some((ch, sr, bits));
} else if id == b"data" {
let (ch, sr, bits) = fmt?;
return Some((body.to_vec(), ch, sr, bits));
}
at = at.checked_add(8usize.checked_add(len)?.checked_add(len & 1)?)?;
}
None
}
/// A complete AIFF file (big-endian PCM) from little-endian PCM.
pub fn aiff_file(pcm: &[u8], channels: u16, sample_rate: u32, bits: u16) -> Vec<u8> {
let bps = bits.div_ceil(8) as usize;
let frames = pcm.len() / (bps * channels.max(1) as usize).max(1);
let mut v = aiff_header(frames as u32, channels, sample_rate, bits);
for s in pcm.chunks_exact(bps.max(1)) {
if bps == 1 {
v.push(s[0] ^ 0x80); // WAVE 8-bit is unsigned, AIFF signed
} else {
v.extend(s.iter().rev());
}
}
if (v.len() - 8) & 1 == 1 {
v.push(0);
}
v
}
/// PCM (converted to little-endian), channels, sample rate and bits of an AIFF / AIFF-C (`NONE`
/// / `twos` / `sowt`) file.
pub fn parse_aiff(b: &[u8]) -> Option<(Vec<u8>, u16, u32, u16)> {
if b.len() < 12 || &b[..4] != b"FORM" || !(&b[8..12] == b"AIFF" || &b[8..12] == b"AIFC") {
return None;
}
let aifc = &b[8..12] == b"AIFC";
let mut at = 12;
let mut comm = None;
while at + 8 <= b.len() {
let id = &b[at..at + 4];
let len = u32::from_be_bytes(b[at + 4..at + 8].try_into().ok()?) as usize;
let body = &b[at + 8..(at + 8).saturating_add(len).min(b.len())];
if id == b"COMM" && body.len() >= 18 {
let ch = u16::from_be_bytes([body[0], body[1]]);
let bits = u16::from_be_bytes([body[6], body[7]]);
let sr = from_extended(body[8..18].try_into().ok()?).round() as u32;
// AIFF has no compression code (trailing COMM bytes mean nothing); AIFF-C must name one
// of the integer PCM codes, or the samples are not integer PCM at all
let little = if aifc {
match body.get(18..22)? {
b"NONE" | b"twos" => false,
b"sowt" => true,
_ => return None,
}
} else {
false
};
comm = Some((ch, sr, bits, little));
} else if id == b"SSND" && body.len() >= 8 {
let (ch, sr, bits, little) = comm?;
let off = u32::from_be_bytes(body[..4].try_into().ok()?) as usize;
let data = body.get(8usize.checked_add(off)?..)?;
let bps = bits.div_ceil(8) as usize;
let mut pcm = Vec::with_capacity(data.len());
for s in data.chunks_exact(bps.max(1)) {
if bps == 1 {
pcm.push(s[0] ^ 0x80);
} else if little {
pcm.extend_from_slice(s);
} else {
pcm.extend(s.iter().rev());
}
}
return Some((pcm, ch, sr, bits));
}
at = at.checked_add(8usize.checked_add(len)?.checked_add(len & 1)?)?;
}
None
}
fn from_extended(b: [u8; 10]) -> f64 {
let e = (u16::from_be_bytes([b[0], b[1]]) & 0x7FFF) as i32;
let m = u64::from_be_bytes(b[2..10].try_into().unwrap_or([0; 8]));
if e == 0 && m == 0 {
return 0.0;
}
m as f64 / (1u64 << 63) as f64 * 2f64.powi(e - 16383)
}
#[cfg(test)]
mod tests {
/// A mutated EDL whose clip ran for days produced an OMF descriptor for more than 4 GiB of
/// PCM: the RIFF size field overflowed ("attempt to add with overflow").
#[test]
fn huge_wav_header_saturates() {
let h = super::wav_header(u32::MAX, 2, u32::MAX, 24);
assert_eq!(&h[4..8], &u32::MAX.to_le_bytes());
}
use super::*;
#[test]
fn accepts_truncated_essence_summaries() {
let mut wav = wav_file(&[1, 2, 3, 4], 1, 48_000, 16);
wav.truncate(46);
assert_eq!(parse_wav(&wav), Some((vec![1, 2], 1, 48_000, 16)));
let mut aiff = aiff_file(&[1, 2, 3, 4], 1, 48_000, 16);
aiff.truncate(56);
assert_eq!(parse_aiff(&aiff), Some((vec![1, 2], 1, 48_000, 16)));
}
#[test]
fn wav_and_aiff_round_trip() {
let pcm: Vec<u8> = (0..48u8).collect(); // 8 stereo 24-bit frames
let w = wav_file(&pcm, 2, 48_000, 24);
assert_eq!(parse_wav(&w), Some((pcm.clone(), 2, 48_000, 24)));
let a = aiff_file(&pcm, 2, 44_100, 24);
assert_eq!(parse_aiff(&a), Some((pcm.clone(), 2, 44_100, 24)));
let p16: Vec<u8> = (0..32u8).collect();
assert_eq!(parse_aiff(&aiff_file(&p16, 1, 96_000, 16)), Some((p16, 1, 96_000, 16)));
assert!(parse_wav(b"RIFF").is_none());
assert!(parse_aiff(&a[..30]).is_none());
for cut in 0..w.len() {
let _ = parse_wav(&w[..cut]);
let _ = parse_aiff(&a[..cut.min(a.len())]);
}
}
#[test]
fn aifc_needs_an_integer_pcm_compression_code() {
let file = |kind: &[u8; 4], code: &[u8]| {
let mut comm = vec![0, 1, 0, 0, 0, 1, 0, 16];
comm.extend_from_slice(&[0x40, 0x0E, 0xBB, 0x80, 0, 0, 0, 0, 0, 0]);
comm.extend_from_slice(code);
let mut body = kind.to_vec();
body.extend_from_slice(b"COMM");
body.extend_from_slice(&(comm.len() as u32).to_be_bytes());
body.extend_from_slice(&comm);
if comm.len() & 1 == 1 {
body.push(0);
}
body.extend_from_slice(b"SSND");
body.extend_from_slice(&10u32.to_be_bytes());
body.extend_from_slice(&[0; 8]);
body.extend_from_slice(&[0x12, 0x34]);
let mut v = b"FORM".to_vec();
v.extend_from_slice(&(body.len() as u32).to_be_bytes());
v.extend_from_slice(&body);
v
};
assert_eq!(parse_aiff(&file(b"AIFC", b"NONE")).map(|p| p.0), Some(vec![0x34, 0x12]));
assert_eq!(parse_aiff(&file(b"AIFC", b"twos")).map(|p| p.0), Some(vec![0x34, 0x12]));
assert_eq!(parse_aiff(&file(b"AIFC", b"sowt")).map(|p| p.0), Some(vec![0x12, 0x34]));
assert!(parse_aiff(&file(b"AIFC", b"fl32")).is_none(), "float samples are not integer PCM");
assert!(parse_aiff(&file(b"AIFC", b"")).is_none(), "AIFF-C without a compression code");
// plain AIFF ignores trailing COMM bytes
assert_eq!(parse_aiff(&file(b"AIFF", b"sowt")).map(|p| p.0), Some(vec![0x34, 0x12]));
}
}
File diff suppressed because it is too large. Load diff
+18 -1
View File
@@ -30,7 +30,8 @@
//! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`, and
//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`), [`mp3`]
//! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-decode`: the frame and file decoder;
//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files).
//! `flac-encode`: the packet encoder), [`qoa`] (`qoa-decode`, `qoa-encode`: whole QOA files),
//! [`gsm`] (`gsm-decode`, `gsm-encode`: GSM 06.10 full-rate speech).
//!
//! The shared types below build with no features.
@@ -43,6 +44,8 @@ pub mod alac;
mod buffer;
#[cfg(feature = "g722")]
pub mod g722;
#[cfg(any(feature = "gsm-decode", feature = "gsm-encode"))]
pub mod gsm;
mod layout;
#[cfg(any(feature = "mp3-encode", feature = "mp3-decode"))]
pub mod mp3;
@@ -58,6 +61,8 @@ pub mod peaks;
pub mod qoa;
#[cfg(feature = "decode-native")]
mod read;
#[cfg(feature = "sbc")]
pub mod sbc;
#[cfg(any(feature = "aac-decode", feature = "alac-decode", feature = "opus-decode", feature = "ac3-decode", feature = "mpa-decode"))]
mod track;
#[cfg(feature = "vorbis-encode")]
@@ -78,6 +83,11 @@ pub mod wav_markers;
))]
mod write;
/// PCM WAVE and AIFF wrappers for interchange essence.
#[cfg(feature = "pcm-encode")]
pub mod essence_pcm;
/// Streaming WAVE and AIFF headers and sample packing.
pub mod pcm_export;
/// Interleaved PCM packet decoding.
pub mod pcm_interleaved;
/// Range-backed PCM WAVE access and a 16-bit PCM writer.
@@ -769,3 +779,10 @@ mod tests {
assert!(matches!(e, AudioError::Encode(_)), "{e}");
}
}
/// DVD and Blu-ray LPCM packet decoding.
pub mod lpcm;
/// Non-seeking canonical WAV streaming primitives.
#[cfg(feature = "pcm-encode")]
pub mod wav_stream;
+118
View File
@@ -0,0 +1,118 @@
//! DVD-Video and Blu-ray LPCM packet grammar and sample decoding.
/// Blu-ray / AVCHD LPCM packet header (4 bytes before the samples).
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct BlurayLpcm {
/// Sample rate in hertz.
pub sample_rate: u32,
/// Number of decoded channels.
pub channels: usize,
/// Significant bits per sample.
pub bits: u32,
}
/// Channels of each channel_assignment code (mono, stereo, 3/0, 2/1, 3/1, 2/2, 3/2, 3/2+LFE,
/// 3/4, 3/4+LFE).
const BD_LPCM_CHANNELS: [usize; 12] = [0, 1, 0, 2, 3, 3, 4, 4, 5, 6, 7, 8];
/// Parse and validate the four-byte Blu-ray LPCM header.
pub fn bluray_lpcm_header(p: &[u8]) -> Option<BlurayLpcm> {
if p.len() < 4 {
return None;
}
let channels = *BD_LPCM_CHANNELS.get((p[2] >> 4) as usize).filter(|&&c| c > 0)?;
let sample_rate = match p[2] & 15 {
1 => 48_000,
4 => 96_000,
5 => 192_000,
_ => return None,
};
let bits = match p[3] >> 6 {
1 => 16,
2 => 20,
3 => 24,
_ => return None,
};
Some(BlurayLpcm { sample_rate, channels, bits })
}
/// Decode one Blu-ray LPCM packet (big-endian; channels padded to an even count; 20-bit
/// samples are stored in 24 bits).
pub fn decode_bluray_lpcm(p: &[u8]) -> Option<Vec<Vec<f32>>> {
let h = bluray_lpcm_header(p)?;
let coded = (h.channels + 1) & !1;
let bps = if h.bits == 16 { 2 } else { 3 };
let data = &p[4..];
let n = data.len() / (coded * bps);
let mut out = vec![Vec::with_capacity(n); h.channels];
for k in 0..n {
for (c, o) in out.iter_mut().enumerate() {
let at = (k * coded + c) * bps;
let v = if bps == 2 {
i16::from_be_bytes([data[at], data[at + 1]]) as f32 / 32768.0
} else {
(i32::from_be_bytes([data[at], data[at + 1], data[at + 2], 0]) >> 8) as f32 / 8_388_608.0
};
o.push(v);
}
}
Some(out)
}
/// Bytes per two sample frames of DVD LPCM. The caller must bound `channels` to the DVD channel range.
pub fn dvd_lpcm_group_bytes(channels: usize, bits: u32) -> usize {
match bits {
16 => 4 * channels,
20 => 5 * channels,
_ => 6 * channels,
}
}
/// Decode DVD-Video LPCM (big-endian). 16-bit samples are interleaved; 20- and 24-bit samples
/// come in groups of two frames: the upper 16 bits of all the group's samples, then their low
/// 4 / 8 bits. The caller must bound `channels` to the DVD channel range.
pub fn decode_dvd_lpcm(data: &[u8], channels: usize, bits: u32) -> Vec<Vec<f32>> {
let ch = channels.max(1);
let group = dvd_lpcm_group_bytes(ch, bits);
let groups = data.len() / group;
let mut out = vec![Vec::with_capacity(groups * 2); ch];
for g in 0..groups {
let b = &data[g * group..(g + 1) * group];
for f in 0..2 {
for (c, o) in out.iter_mut().enumerate() {
let k = f * ch + c;
let hi = i16::from_be_bytes([b[2 * k], b[2 * k + 1]]) as i32;
let v = match bits {
16 => hi as f32 / 32768.0,
20 => {
let nib = b[4 * ch + k / 2];
let lo = if k.is_multiple_of(2) { nib >> 4 } else { nib & 15 } as i32;
((hi << 4) | lo) as f32 / 524_288.0
}
_ => ((hi << 8) | b[4 * ch + k] as i32) as f32 / 8_388_608.0,
};
o.push(v);
}
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn bluray_header_and_even_channel_padding() {
let packet = [0, 0, 0x31, 0x40, 0x40, 0, 0xc0, 0];
assert_eq!(bluray_lpcm_header(&packet), Some(BlurayLpcm { sample_rate: 48_000, channels: 2, bits: 16 }));
assert_eq!(decode_bluray_lpcm(&packet), Some(vec![vec![0.5], vec![-0.5]]));
assert_eq!(decode_bluray_lpcm(&packet[..3]), None);
}
#[test]
fn dvd_lpcm_16_20_and_24_bit_groups() {
assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0], 1, 16), vec![vec![0.5, -0.5]]);
assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0, 0], 1, 20), vec![vec![0.5, -0.5]]);
assert_eq!(decode_dvd_lpcm(&[0x40, 0, 0xc0, 0, 0, 0], 1, 24), vec![vec![0.5, -0.5]]);
assert_eq!(decode_dvd_lpcm(&[1, 2, 3], 1, 16), vec![Vec::<f32>::new()]);
}
}
+287
View File
@@ -0,0 +1,287 @@
//! Audio-only files: WAV (RIFF, little-endian PCM; RF64 past 4 GiB) and AIFF (big-endian PCM),
//! 16, 24 or 32-bit integer or 32-bit float ([`SampleFormat`]), for streaming export.
//! Float WAV is `WAVE_FORMAT_IEEE_FLOAT` with a `fact` chunk; float AIFF is AIFF-C (`fl32`).
//!
//! The header is written first from the known length (`header`), then the samples in chunks
//! (`encode`) and the pad byte (`pad`), so an export streams to disk instead of building the
//! file in memory.
/// PCM representation in an exported file.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum SampleFormat {
/// 16-bit signed integer.
Int16,
/// 24-bit signed integer.
Int24,
/// 32-bit signed integer.
Int32,
/// 32-bit IEEE float.
Float32,
}
impl SampleFormat {
/// Bits per sample.
pub fn bits(self) -> u16 {
match self {
Self::Int16 => 16,
Self::Int24 => 24,
Self::Int32 | Self::Float32 => 32,
}
}
/// Bytes per sample.
pub fn bytes(self) -> usize {
usize::from(self.bits() / 8)
}
/// Whether this is a floating point format.
pub fn is_float(self) -> bool {
self == Self::Float32
}
/// Clip and quantize one sample with symmetric integer full scale; NaN becomes silence.
pub fn quantise(self, s: f32) -> i32 {
let s = s.clamp(-1.0, 1.0);
match self {
Self::Int16 => (s * 32_767.0).round() as i32,
Self::Int24 => (s * 8_388_607.0).round() as i32,
Self::Int32 => (f64::from(s) * 2_147_483_647.0).round() as i32,
Self::Float32 => 0,
}
}
/// Sanitize a floating sample: NaN becomes silence, infinity becomes the largest finite value.
pub fn float(s: f32) -> f32 {
if s.is_nan() { 0.0 } else { s.clamp(f32::MIN, f32::MAX) }
}
}
/// The container of an audio-only export.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PcmContainer {
/// RIFF/WAVE or RF64.
Wav,
/// AIFF or AIFF-C.
Aiff,
}
/// Bytes of sample data for `frames` frames, or None when that does not fit 64 bits.
fn data_len(frames: u64, channels: u16, format: SampleFormat) -> Option<u64> {
frames.checked_mul(u64::from(channels))?.checked_mul(format.bytes() as u64)
}
/// The pad byte after an odd-sized data chunk (RIFF and AIFF chunks are word-aligned).
pub fn pad(frames: u64, channels: u16, format: SampleFormat) -> &'static [u8] {
if data_len(frames, channels, format).is_some_and(|n| n & 1 == 1) { &[0] } else { &[] }
}
/// `KSDATAFORMAT_SUBTYPE_PCM` / `_IEEE_FLOAT` after their first two bytes (the format tag).
const SUBTYPE_TAIL: [u8; 14] = [0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xAA, 0x00, 0x38, 0x9B, 0x71];
/// AIFF-C format version 1 (`FVER`).
const AIFC_VERSION_1: u32 = 0xA280_5140;
/// The AIFF-C compression name of `fl32`, as a Pascal string of even length.
const FL32_NAME: &[u8] = b"\x1532-bit floating point";
/// Everything before the samples of a file of `frames` frames. A WAV whose RIFF size would not
/// fit 32 bits (4 GiB: 24-bit 5.1 at 96 kHz after about 41 minutes) is written as RF64 (EBU Tech
/// 3306), with the 64-bit sizes in a `ds64` chunk. AIFF has no 64-bit form, so a longer AIFF is
/// an error naming WAV instead.
pub fn header(container: PcmContainer, channels: u16, sample_rate: u32, format: SampleFormat, frames: u64) -> Result<Vec<u8>, String> {
let too_long = || "the audio is too long to write".to_string();
if channels == 0 {
return Err("audio needs at least one channel".into());
}
if sample_rate == 0 {
return Err("audio needs a sample rate".into());
}
let bits = format.bits();
let bps = bits / 8;
let float = format.is_float();
let data = data_len(frames, channels, format).ok_or_else(too_long)?;
let block_align = channels.checked_mul(bps).ok_or("too many audio channels")?;
match container {
PcmContainer::Wav => {
let byte_rate =
u32::try_from(u64::from(sample_rate) * u64::from(block_align)).map_err(|_| "the audio sample rate is too high".to_string())?;
let ext = channels > 2;
// plain PCM has no cbSize; IEEE float has an empty one
let fmt_len: u32 = if ext {
40
} else if float {
18
} else {
16
};
// every format but integer PCM has a `fact` chunk (the frame count; RF64: in `ds64`)
let fact_len: u64 = if float { 12 } else { 0 };
let padded = data.checked_add(data & 1).ok_or_else(too_long)?;
// "WAVE" + fmt chunk + fact chunk + data chunk header + samples
let riff = (4 + 8 + u64::from(fmt_len) + fact_len + 8).checked_add(padded).ok_or_else(too_long)?;
let rf64 = riff > u64::from(u32::MAX);
let mut v = Vec::with_capacity(100);
if rf64 {
const DS64: u64 = 8 + 28;
v.extend_from_slice(b"RF64");
v.extend_from_slice(&u32::MAX.to_le_bytes());
v.extend_from_slice(b"WAVEds64");
v.extend_from_slice(&28u32.to_le_bytes());
v.extend_from_slice(&riff.checked_add(DS64).ok_or_else(too_long)?.to_le_bytes());
v.extend_from_slice(&data.to_le_bytes());
v.extend_from_slice(&frames.to_le_bytes());
v.extend_from_slice(&0u32.to_le_bytes()); // no table entries
} else {
v.extend_from_slice(b"RIFF");
v.extend_from_slice(&(riff as u32).to_le_bytes());
v.extend_from_slice(b"WAVE");
}
let tag: u16 = if float { 3 } else { 1 };
v.extend_from_slice(b"fmt ");
v.extend_from_slice(&fmt_len.to_le_bytes());
v.extend_from_slice(&(if ext { 0xFFFE } else { tag }).to_le_bytes());
v.extend_from_slice(&channels.to_le_bytes());
v.extend_from_slice(&sample_rate.to_le_bytes());
v.extend_from_slice(&byte_rate.to_le_bytes());
v.extend_from_slice(&block_align.to_le_bytes());
v.extend_from_slice(&bits.to_le_bytes());
if ext {
// cbSize, valid bits, channel mask, KSDATAFORMAT_SUBTYPE_PCM / _IEEE_FLOAT
v.extend_from_slice(&22u16.to_le_bytes());
v.extend_from_slice(&bits.to_le_bytes());
let mask: u32 = if channels == 6 { 0x3F } else { 0 };
v.extend_from_slice(&mask.to_le_bytes());
v.extend_from_slice(&tag.to_le_bytes());
v.extend_from_slice(&SUBTYPE_TAIL);
} else if float {
v.extend_from_slice(&0u16.to_le_bytes());
}
if float {
v.extend_from_slice(b"fact");
v.extend_from_slice(&4u32.to_le_bytes());
v.extend_from_slice(&(if rf64 { u32::MAX } else { u32::try_from(frames).unwrap_or(u32::MAX) }).to_le_bytes());
}
v.extend_from_slice(b"data");
v.extend_from_slice(&(if rf64 { u32::MAX } else { data as u32 }).to_le_bytes());
Ok(v)
}
PcmContainer::Aiff => {
let aiff_too_long = || "AIFF holds at most 4 GB of audio: export WAV, which has no such limit".to_string();
let frames32 = u32::try_from(frames).map_err(|_| aiff_too_long())?;
// SSND: offset + block size + samples
let ssnd = u32::try_from(data.checked_add(8).ok_or_else(aiff_too_long)?).map_err(|_| aiff_too_long())?;
// floats need AIFF-C: a version chunk, and the compression type and name in COMM
let comm: u32 = if float { 18 + 4 + FL32_NAME.len() as u32 } else { 18 };
let fver: u32 = if float { 8 + 4 } else { 0 };
let form = (4u32 + fver + (8 + comm))
.checked_add(8)
.and_then(|n| n.checked_add(ssnd))
.and_then(|n| n.checked_add(ssnd & 1))
.ok_or_else(aiff_too_long)?;
let mut v = Vec::with_capacity(90);
v.extend_from_slice(b"FORM");
v.extend_from_slice(&form.to_be_bytes());
if float {
v.extend_from_slice(b"AIFCFVER");
v.extend_from_slice(&4u32.to_be_bytes());
v.extend_from_slice(&AIFC_VERSION_1.to_be_bytes());
} else {
v.extend_from_slice(b"AIFF");
}
v.extend_from_slice(b"COMM");
v.extend_from_slice(&comm.to_be_bytes());
v.extend_from_slice(&channels.to_be_bytes());
v.extend_from_slice(&frames32.to_be_bytes());
v.extend_from_slice(&bits.to_be_bytes());
v.extend_from_slice(&extended(sample_rate));
if float {
v.extend_from_slice(b"fl32");
v.extend_from_slice(FL32_NAME);
}
v.extend_from_slice(b"SSND");
v.extend_from_slice(&ssnd.to_be_bytes());
v.extend_from_slice(&0u32.to_be_bytes()); // offset
v.extend_from_slice(&0u32.to_be_bytes()); // block size
Ok(v)
}
}
}
/// Append interleaved samples in `format` (little-endian for WAV, big-endian for AIFF).
pub fn encode(container: PcmContainer, interleaved: &[f32], format: SampleFormat, out: &mut Vec<u8>) {
let bps = format.bytes();
out.reserve(interleaved.len().saturating_mul(bps));
for &s in interleaved {
let q = if format.is_float() { SampleFormat::float(s).to_bits() as i32 } else { format.quantise(s) };
match container {
PcmContainer::Wav => out.extend_from_slice(q.to_le_bytes().get(..bps).unwrap_or_default()),
PcmContainer::Aiff => out.extend_from_slice(q.to_be_bytes().get(4 - bps..).unwrap_or_default()),
}
}
}
/// A whole file in memory (short audio; exports stream with [`header`] and [`encode`]).
fn write_whole(container: PcmContainer, interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result<Vec<u8>, String> {
let per_frame = usize::from(channels.max(1));
if !interleaved.len().is_multiple_of(per_frame) {
return Err("the samples do not make whole frames".into());
}
let frames = (interleaved.len() / per_frame) as u64;
let mut v = header(container, channels, sample_rate, format, frames)?;
encode(container, interleaved, format, &mut v);
v.extend_from_slice(pad(frames, channels, format));
Ok(v)
}
/// A RIFF/WAVE file of interleaved samples. More than two channels are written as
/// `WAVE_FORMAT_EXTENSIBLE` with the speaker mask of the layout (6 channels: L, R, C, LFE, Ls, Rs
/// = `0x3F`).
pub fn write_wav(interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result<Vec<u8>, String> {
write_whole(PcmContainer::Wav, interleaved, channels, sample_rate, format)
}
/// IEEE 754 80-bit extended encoding of a sample rate (AIFF `COMM`).
pub fn extended(rate: u32) -> [u8; 10] {
let mut out = [0u8; 10];
if rate == 0 {
return out;
}
let shift = rate.leading_zeros();
let mant = (rate as u64) << (32 + shift);
let exp = 16383 + 31 - shift as u16;
out[..2].copy_from_slice(&exp.to_be_bytes());
out[2..].copy_from_slice(&mant.to_be_bytes());
out
}
/// An AIFF file (`FORM`/`AIFF`, `COMM` + `SSND`; AIFF-C for floats) of interleaved samples.
pub fn write_aiff(interleaved: &[f32], channels: u16, sample_rate: u32, format: SampleFormat) -> Result<Vec<u8>, String> {
write_whole(PcmContainer::Aiff, interleaved, channels, sample_rate, format)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn streaming_formats_preserve_samples_and_bounds() {
let samples = [1.0, -1.0, f32::NAN];
let wav = write_wav(&samples, 1, 48_000, SampleFormat::Int24).unwrap();
assert_eq!(&wav[..4], b"RIFF");
assert_eq!(&wav[44..53], &[255, 255, 127, 1, 0, 128, 0, 0, 0]);
let h = header(PcmContainer::Wav, 6, 96_000, SampleFormat::Int24, 96_000 * 3600).unwrap();
assert_eq!(&h[..4], b"RF64");
assert!(header(PcmContainer::Aiff, 2, 48_000, SampleFormat::Int24, u64::MAX).is_err());
let aiff = write_aiff(&[0.25, -3.0], 1, 44_100, SampleFormat::Float32).unwrap();
assert_eq!(&aiff[8..12], b"AIFC");
assert_eq!(&aiff[aiff.len() - 8..], [0.25f32.to_be_bytes(), (-3.0f32).to_be_bytes()].concat());
}
#[test]
fn zero_channels_rates_and_partial_frames_are_refused() {
for container in [PcmContainer::Wav, PcmContainer::Aiff] {
assert!(header(container, 0, 48_000, SampleFormat::Int16, 1).is_err());
assert!(header(container, 1, 0, SampleFormat::Int16, 1).is_err());
assert!(header(container, 2, 48_000, SampleFormat::Int16, 0).is_ok(), "zero frames stay valid");
}
assert!(write_wav(&[0.5], 0, 48_000, SampleFormat::Int16).is_err());
assert!(write_wav(&[0.1, 0.2, 0.3], 2, 48_000, SampleFormat::Int16).is_err());
assert!(write_aiff(&[0.1, 0.2, 0.3], 2, 48_000, SampleFormat::Int16).is_err());
assert!(write_aiff(&[0.1, 0.2], 2, 48_000, SampleFormat::Int16).is_ok());
}
}
File diff suppressed because it is too large. Load diff
+119
View File
@@ -0,0 +1,119 @@
//! Canonical RIFF/WAVE header and interleaved sample blocks for non-seekable sinks.
//!
//! Extracted from AniCraft's WAV writer, preserving its byte-level compatibility.
//! Unlike `FileEncoder`, these primitives do not require `Seek` and leave final lengths,
//! chunk padding and sink error handling to the caller. The caller must supply a complete
//! frame count and append exactly that many frames. For odd-length data, append a pad byte
//! (the header includes that padding in the RIFF size); current AniCraft output is always stereo (even).
//! Non-finite samples become silence, including float output. This deliberately differs
//! from the general encoder's infinity handling. Prefer `FileEncoder` for new seekable sinks.
/// Sample formats written.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum Bits {
/// Signed 16-bit PCM.
Int16,
/// Signed 24-bit PCM.
Int24,
/// IEEE 754 32-bit float.
Float32,
}
impl Bits {
fn bytes(self) -> u16 {
match self {
Bits::Int16 => 2,
Bits::Int24 => 3,
Bits::Float32 => 4,
}
}
}
const PCM: u16 = 1;
const FLOAT: u16 = 3;
/// A WAV header for `frames` frames of `channels` channels.
/// Returns `None` for zero rate/channels or any size/byte-rate field overflow.
pub fn header(rate: u32, channels: u16, bits: Bits, frames: u64) -> Option<Vec<u8>> {
if rate == 0 || channels == 0 {
return None;
}
let b = bits.bytes();
let data = u32::try_from(frames.checked_mul(u64::from(b) * u64::from(channels))?).ok()?;
let riff = data.checked_add(36)?.checked_add(data & 1)?;
let block = channels.checked_mul(b)?;
let byte_rate = rate.checked_mul(u32::from(block))?;
let tag = if bits == Bits::Float32 { FLOAT } else { PCM };
let mut h = Vec::with_capacity(44);
h.extend_from_slice(b"RIFF");
h.extend_from_slice(&riff.to_le_bytes());
h.extend_from_slice(b"WAVEfmt ");
h.extend_from_slice(&16u32.to_le_bytes());
h.extend_from_slice(&tag.to_le_bytes());
h.extend_from_slice(&channels.to_le_bytes());
h.extend_from_slice(&rate.to_le_bytes());
h.extend_from_slice(&byte_rate.to_le_bytes());
h.extend_from_slice(&block.to_le_bytes());
h.extend_from_slice(&(b * 8).to_le_bytes());
h.extend_from_slice(b"data");
h.extend_from_slice(&data.to_le_bytes());
Some(h)
}
/// Appends samples in `bits` format. Integers are rounded and clipped to range; `x · 32768`
/// for 16-bit, so 16-bit sources read by [`crate::decode`] come back bit-identical.
pub fn append(out: &mut Vec<u8>, samples: &[f32], bits: Bits) {
out.reserve(samples.len() * usize::from(bits.bytes()));
for &s in samples {
let s = if s.is_finite() { s } else { 0.0 };
match bits {
Bits::Int16 => out.extend_from_slice(&((s * 32_768.0).round().clamp(-32_768.0, 32_767.0) as i16).to_le_bytes()),
Bits::Int24 => {
let v = (f64::from(s) * 8_388_608.0).round().clamp(-8_388_608.0, 8_388_607.0) as i32;
out.extend_from_slice(v.to_le_bytes().get(..3).unwrap_or(&[0, 0, 0]));
}
Bits::Float32 => out.extend_from_slice(&s.to_le_bytes()),
}
}
}
#[cfg(test)]
#[allow(clippy::unwrap_used, clippy::indexing_slicing)]
mod tests {
use super::*;
#[test]
fn canonical_header_and_odd_padding() {
let h = header(48_000, 2, Bits::Int16, 1).unwrap();
assert_eq!(h.len(), 44);
assert_eq!(&h[..12], b"RIFF\x28\0\0\0WAVE");
assert_eq!(&h[28..36], &[0, 238, 2, 0, 4, 0, 16, 0]);
let h = header(8_000, 1, Bits::Int24, 1).unwrap();
assert_eq!(&h[4..8], &40u32.to_le_bytes());
assert_eq!(&h[40..44], &3u32.to_le_bytes());
assert!(header(0, 2, Bits::Int16, 1).is_none());
assert!(header(48_000, 0, Bits::Int16, 1).is_none());
assert!(header(u32::MAX, 2, Bits::Int16, 1).is_none());
assert!(header(48_000, 2, Bits::Float32, u64::MAX).is_none());
assert!(header(48_000, u16::MAX, Bits::Float32, 0).is_none());
}
#[test]
fn samples_preserve_rounding_clipping_silence_and_chunk_boundaries() {
let samples = [-2.0, -1.0, -0.5, 0.0, 0.5, 1.0, 2.0, f32::NAN, f32::INFINITY, f32::NEG_INFINITY];
let mut pcm = Vec::new();
append(&mut pcm, &samples, Bits::Int16);
let expected = [-32768i16, -32768, -16384, 0, 16384, 32767, 32767, 0, 0, 0];
assert_eq!(pcm, expected.iter().flat_map(|s| s.to_le_bytes()).collect::<Vec<_>>());
for bits in [Bits::Int16, Bits::Int24, Bits::Float32] {
let mut whole = Vec::new();
append(&mut whole, &samples, bits);
let mut blocks = Vec::new();
for block in samples.chunks(3) {
append(&mut blocks, block, bits);
}
assert_eq!(whole, blocks);
assert_eq!(&whole[whole.len() - 3 * usize::from(bits.bytes())..], vec![0; 3 * usize::from(bits.bytes())]);
}
}
}