use crate::audio::{AudioBuffer, AudioSpec};
use crate::codec::{CodecId, FourCc};
use crate::error::DecodeError;
use crate::g711::G711Law;
use crate::payload::Payload;
use crate::riff::{self, ByteOrder, ChunkWalker};
use crate::sample::SampleFormat;
use crate::source::StreamSource;
pub(crate) const FORM: FourCc = FourCc(*b"FORM");
pub(crate) const AIFF: FourCc = FourCc(*b"AIFF");
pub(crate) const AIFC: FourCc = FourCc(*b"AIFC");
const COMM: FourCc = FourCc(*b"COMM");
const SSND: FourCc = FourCc(*b"SSND");
const FVER: FourCc = FourCc(*b"FVER");
const FVER_TIMESTAMP: u32 = 0xA280_5140;
const NONE: FourCc = FourCc(*b"NONE");
const TWOS: FourCc = FourCc(*b"twos");
const SOWT: FourCc = FourCc(*b"sowt");
const RAW: FourCc = FourCc(*b"raw ");
const FL32: [FourCc; 2] = [FourCc(*b"fl32"), FourCc(*b"FL32")];
const FL64: [FourCc; 2] = [FourCc(*b"fl64"), FourCc(*b"FL64")];
const ALAW: [FourCc; 2] = [FourCc(*b"alaw"), FourCc(*b"ALAW")];
const ULAW: [FourCc; 2] = [FourCc(*b"ulaw"), FourCc(*b"ULAW")];
const COMM_BYTES_AIFF: u64 = 18;
const COMM_BYTES_AIFC: u64 = 22;
const MAX_COMM_BYTES: u64 = COMM_BYTES_AIFC + 256;
const SSND_PREFIX_BYTES: u64 = 8;
const READY_LIMIT: usize = 65_536;
fn extended_to_f64(bytes: [u8; 10]) -> f64 {
let negative = bytes[0] & 0x80 != 0;
let exponent = (u16::from(bytes[0] & 0x7F) << 8) | u16::from(bytes[1]);
let significand = u64::from_be_bytes([
bytes[2], bytes[3], bytes[4], bytes[5], bytes[6], bytes[7], bytes[8], bytes[9],
]);
let sign = if negative { -1.0 } else { 1.0 };
if exponent == 0x7FFF {
return if significand << 1 == 0 {
sign * f64::INFINITY
} else {
f64::NAN
};
}
if significand == 0 {
return sign * 0.0;
}
let shift = i32::from(exponent.max(1)) - 16383 - 63;
sign * scale_by_power_of_two(significand as f64, shift)
}
fn scale_by_power_of_two(value: f64, shift: i32) -> f64 {
const STEP: i32 = 1000;
let mut value = value;
let mut shift = shift;
while shift != 0 && value != 0.0 && value.is_finite() {
let step = shift.clamp(-STEP, STEP);
value *= f64::from_bits(((step + 1023) as u64) << 52);
shift -= step;
}
value
}
fn rate_to_spec_rate(rate: f64, offset: u64) -> Result<u32, DecodeError> {
if rate < 1.0 || rate > f64::from(u32::MAX) || rate != rate.trunc() {
return Err(DecodeError::Malformed {
expected: "a positive integral sample rate that fits in 32 bits",
offset,
});
}
Ok(rate as u32)
}
fn rate_to_extended(rate: u32) -> [u8; 10] {
debug_assert_ne!(rate, 0, "a zero rate has no normalised form");
let high_bit = 31 - rate.leading_zeros();
let exponent = 16383 + high_bit as u16;
let significand = u64::from(rate) << (63 - high_bit);
let mut bytes = [0u8; 10];
bytes[0] = (exponent >> 8) as u8;
bytes[1] = exponent as u8;
bytes[2..].copy_from_slice(&significand.to_be_bytes());
bytes
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AiffForm {
Aiff,
Aifc,
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum AiffCodec {
PcmI8,
PcmU8,
PcmI16,
PcmI24,
PcmI32,
PcmI16Sowt,
PcmI24Sowt,
PcmI32Sowt,
Float32,
Float64,
ALaw,
MuLaw,
}
impl AiffCodec {
pub fn resolve(compression: FourCc, bits_per_sample: u16) -> Result<Self, DecodeError> {
if compression == NONE || compression == TWOS || compression == SOWT {
let sowt = compression == SOWT;
return match (bits_per_sample, sowt) {
(8, _) => Ok(Self::PcmI8),
(16, false) => Ok(Self::PcmI16),
(24, false) => Ok(Self::PcmI24),
(32, false) => Ok(Self::PcmI32),
(16, true) => Ok(Self::PcmI16Sowt),
(24, true) => Ok(Self::PcmI24Sowt),
(32, true) => Ok(Self::PcmI32Sowt),
_ => Err(DecodeError::UnsupportedSampleFormat {
format: CodecId::FourCc(compression),
bits_per_sample,
}),
};
}
if compression == RAW {
return if bits_per_sample == 8 {
Ok(Self::PcmU8)
} else {
Err(DecodeError::UnsupportedSampleFormat {
format: CodecId::FourCc(compression),
bits_per_sample,
})
};
}
if FL32.contains(&compression) {
return if bits_per_sample == 32 {
Ok(Self::Float32)
} else {
Err(DecodeError::UnsupportedSampleFormat {
format: CodecId::FourCc(compression),
bits_per_sample,
})
};
}
if FL64.contains(&compression) {
return if bits_per_sample == 64 {
Ok(Self::Float64)
} else {
Err(DecodeError::UnsupportedSampleFormat {
format: CodecId::FourCc(compression),
bits_per_sample,
})
};
}
if ALAW.contains(&compression) {
return Ok(Self::ALaw);
}
if ULAW.contains(&compression) {
return Ok(Self::MuLaw);
}
Err(DecodeError::UnsupportedCodec {
codec: CodecId::FourCc(compression),
})
}
pub const fn bytes_per_sample(self) -> usize {
match self {
Self::PcmI8 | Self::PcmU8 | Self::ALaw | Self::MuLaw => 1,
Self::PcmI16 | Self::PcmI16Sowt => 2,
Self::PcmI24 | Self::PcmI24Sowt => 3,
Self::PcmI32 | Self::PcmI32Sowt | Self::Float32 => 4,
Self::Float64 => 8,
}
}
pub const fn sample_format(self) -> Option<SampleFormat> {
match self {
Self::PcmI8 => Some(SampleFormat::I8),
Self::PcmU8 => Some(SampleFormat::U8),
Self::PcmI16 => Some(SampleFormat::I16Be),
Self::PcmI24 => Some(SampleFormat::I24Be),
Self::PcmI32 => Some(SampleFormat::I32Be),
Self::PcmI16Sowt => Some(SampleFormat::I16Le),
Self::PcmI24Sowt => Some(SampleFormat::I24Le),
Self::PcmI32Sowt => Some(SampleFormat::I32Le),
Self::Float32 => Some(SampleFormat::F32Be),
Self::Float64 => Some(SampleFormat::F64Be),
Self::ALaw | Self::MuLaw => None,
}
}
pub const fn law(self) -> Option<G711Law> {
match self {
Self::ALaw => Some(G711Law::ALaw),
Self::MuLaw => Some(G711Law::MuLaw),
_ => None,
}
}
pub const fn bits_per_sample(self) -> u16 {
match self {
Self::PcmI8 | Self::PcmU8 => 8,
Self::PcmI16 | Self::PcmI16Sowt | Self::ALaw | Self::MuLaw => 16,
Self::PcmI24 | Self::PcmI24Sowt => 24,
Self::PcmI32 | Self::PcmI32Sowt | Self::Float32 => 32,
Self::Float64 => 64,
}
}
pub const fn compression_type(self) -> FourCc {
match self {
Self::PcmI8 | Self::PcmI16 | Self::PcmI24 | Self::PcmI32 => NONE,
Self::PcmU8 => RAW,
Self::PcmI16Sowt | Self::PcmI24Sowt | Self::PcmI32Sowt => SOWT,
Self::Float32 => FL32[0],
Self::Float64 => FL64[0],
Self::ALaw => ALAW[0],
Self::MuLaw => ULAW[0],
}
}
pub const fn form(self) -> AiffForm {
match self {
Self::PcmI8 | Self::PcmI16 | Self::PcmI24 | Self::PcmI32 => AiffForm::Aiff,
Self::PcmU8
| Self::PcmI16Sowt
| Self::PcmI24Sowt
| Self::PcmI32Sowt
| Self::Float32
| Self::Float64
| Self::ALaw
| Self::MuLaw => AiffForm::Aifc,
}
}
pub fn decode(self, bytes: &[u8], output: &mut Vec<f32>) -> usize {
match (self.sample_format(), self.law()) {
(Some(format), _) => format.decode(bytes, output),
(_, Some(law)) => law.decode(bytes, output),
_ => 0,
}
}
pub fn encode(self, samples: &[f32], output: &mut Vec<u8>) -> usize {
match (self.sample_format(), self.law()) {
(Some(format), _) => format.encode(samples, output),
(_, Some(law)) => law.encode(samples, output),
_ => 0,
}
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub struct AiffFormat {
pub spec: AudioSpec,
pub codec: AiffCodec,
pub form: AiffForm,
pub compression: FourCc,
pub bits_per_sample: u16,
pub sample_frames: u32,
}
impl AiffFormat {
pub const fn frame_bytes(&self) -> usize {
self.spec.channels as usize * self.codec.bytes_per_sample()
}
fn data_bytes(&self) -> u64 {
u64::from(self.sample_frames) * self.frame_bytes() as u64
}
}
fn check_comm_size(form: AiffForm, size: u64, offset: u64) -> Result<(), DecodeError> {
let minimum = match form {
AiffForm::Aiff => COMM_BYTES_AIFF,
AiffForm::Aifc => COMM_BYTES_AIFC,
};
if size < minimum {
return Err(DecodeError::Malformed {
expected: "a COMM chunk of at least 18 bytes, 22 in AIFF-C",
offset,
});
}
if size > MAX_COMM_BYTES {
return Err(DecodeError::Malformed {
expected: "a COMM chunk of at most 278 bytes, which is all a compressionName can need",
offset,
});
}
Ok(())
}
fn parse_comm(body: &[u8], offset: u64, form: AiffForm) -> Result<AiffFormat, DecodeError> {
let body_at = offset + riff::CHUNK_HEADER_BYTES;
let (Some(channels), Some(sample_frames), Some(bits_per_sample), Some(rate_field)) = (
riff::u16_be_at(body, 0),
riff::u32_be_at(body, 2),
riff::u16_be_at(body, 6),
body.get(8..18),
) else {
return Err(DecodeError::Malformed {
expected: "a COMM chunk of at least 18 bytes, 22 in AIFF-C",
offset,
});
};
if channels == 0 {
return Err(DecodeError::UnsupportedChannelLayout { channels });
}
let mut rate_bytes = [0u8; 10];
rate_bytes.copy_from_slice(rate_field);
let sample_rate = rate_to_spec_rate(extended_to_f64(rate_bytes), body_at + 8)?;
let compression = match form {
AiffForm::Aiff => NONE,
AiffForm::Aifc => {
let Some(compression) = riff::four_cc_at(body, 18) else {
return Err(DecodeError::Malformed {
expected: "a COMM chunk of at least 18 bytes, 22 in AIFF-C",
offset,
});
};
if let Some(&name_len) = body.get(22) {
if 23 + usize::from(name_len) > body.len() {
return Err(DecodeError::Malformed {
expected: "a compressionName that fits its COMM chunk",
offset: body_at + 22,
});
}
}
compression
}
};
Ok(AiffFormat {
spec: AudioSpec::new(sample_rate, channels),
codec: AiffCodec::resolve(compression, bits_per_sample)?,
form,
compression,
bits_per_sample,
sample_frames,
})
}
fn read_form_header(bytes: &[u8]) -> Result<AiffForm, DecodeError> {
let (Some(magic), Some(form)) = (riff::four_cc_at(bytes, 0), riff::four_cc_at(bytes, 8)) else {
return Err(DecodeError::Truncated {
expected: riff::HEADER_BYTES,
available: bytes.len() as u64,
});
};
if magic != FORM {
return Err(DecodeError::UnsupportedContainer { tag: magic });
}
match form {
_ if form == AIFF => Ok(AiffForm::Aiff),
_ if form == AIFC => Ok(AiffForm::Aifc),
_ => Err(DecodeError::UnsupportedContainer { tag: form }),
}
}
fn check_ssnd(
format: &AiffFormat,
body_len: u64,
data_offset: u32,
chunk_offset: u64,
) -> Result<(), DecodeError> {
if body_len < SSND_PREFIX_BYTES {
return Err(DecodeError::Malformed {
expected: "an SSND chunk of at least 8 bytes",
offset: chunk_offset,
});
}
let data_start = SSND_PREFIX_BYTES + u64::from(data_offset);
if data_start > body_len {
return Err(DecodeError::Malformed {
expected: "an SSND offset that fits inside the SSND chunk",
offset: chunk_offset,
});
}
let available = body_len - data_start;
let needed = format.data_bytes();
if available < needed {
return Err(DecodeError::Truncated {
expected: needed,
available,
});
}
if available > needed {
return Err(DecodeError::Malformed {
expected: "an SSND chunk holding exactly numSampleFrames frames",
offset: chunk_offset,
});
}
Ok(())
}
#[derive(Debug, Clone, Copy, PartialEq)]
pub struct AiffReader<'a> {
format: AiffFormat,
data: &'a [u8],
}
impl<'a> AiffReader<'a> {
pub fn new(bytes: &'a [u8]) -> Result<Self, DecodeError> {
let form = read_form_header(bytes)?;
let mut walker = ChunkWalker::new(bytes, ByteOrder::Big);
let mut comm: Option<(AiffFormat, u64)> = None;
let mut ssnd: Option<(&[u8], u64)> = None;
while comm.is_none() || ssnd.is_none() {
let Some(chunk) = walker.next().transpose()? else {
break;
};
if chunk.id == COMM && comm.is_none() {
check_comm_size(form, chunk.body.len() as u64, chunk.offset)?;
comm = Some((parse_comm(chunk.body, chunk.offset, form)?, chunk.offset));
} else if chunk.id == SSND && ssnd.is_none() {
ssnd = Some((chunk.body, chunk.offset));
}
}
let Some((format, _)) = comm else {
return Err(DecodeError::Malformed {
expected: "a COMM chunk",
offset: riff::HEADER_BYTES,
});
};
let Some((body, chunk_offset)) = ssnd else {
if format.sample_frames == 0 {
return Ok(Self { format, data: &[] });
}
return Err(DecodeError::Malformed {
expected: "an SSND chunk",
offset: riff::HEADER_BYTES,
});
};
let data_offset = riff::u32_be_at(body, 0).unwrap_or(0);
check_ssnd(&format, body.len() as u64, data_offset, chunk_offset)?;
let data_start = SSND_PREFIX_BYTES as usize + data_offset as usize;
Ok(Self {
format,
data: &body[data_start..],
})
}
pub const fn format(&self) -> &AiffFormat {
&self.format
}
pub const fn spec(&self) -> AudioSpec {
self.format.spec
}
pub const fn data(&self) -> &'a [u8] {
self.data
}
pub const fn frames(&self) -> u64 {
self.data.len() as u64 / self.format.frame_bytes() as u64
}
pub fn decode(&self, output: &mut Vec<f32>) -> usize {
self.format.codec.decode(self.data, output)
}
pub fn decode_to_end(&self) -> AudioBuffer {
let mut samples =
Vec::with_capacity(self.data.len() / self.format.codec.bytes_per_sample());
self.decode(&mut samples);
AudioBuffer::from_samples(self.format.spec, samples)
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
enum State {
Form,
ChunkHeader,
CommBody { size: usize, offset: u64 },
SsndPrefix { size: u64, offset: u64 },
SsndGap { size: u64, left: u64 },
Skip { size: u64, left: u64 },
Pad,
Data,
Done,
}
#[derive(Debug)]
pub struct AiffStreamDecoder {
state: State,
pending: Vec<u8>,
offset: u64,
form: Option<AiffForm>,
format: Option<AiffFormat>,
payload: Option<Payload>,
ready: Vec<f32>,
ready_read: usize,
data_size: u64,
data_left: u64,
finished: bool,
}
impl Default for AiffStreamDecoder {
fn default() -> Self {
Self::new()
}
}
impl AiffStreamDecoder {
pub fn new() -> Self {
Self {
state: State::Form,
pending: Vec::new(),
offset: 0,
form: None,
format: None,
payload: None,
ready: Vec::new(),
ready_read: 0,
data_size: 0,
data_left: 0,
finished: false,
}
}
pub const fn format(&self) -> Option<AiffFormat> {
self.format
}
pub fn ready_samples(&self) -> usize {
self.ready.len() - self.ready_read
}
fn accumulate(&mut self, bytes: &[u8], need: usize, taken: &mut usize) -> bool {
let want = need.saturating_sub(self.pending.len()).min(bytes.len());
self.pending.extend_from_slice(&bytes[..want]);
*taken += want;
self.offset += want as u64;
self.pending.len() >= need
}
fn start_file(&mut self) -> Result<(), DecodeError> {
self.form = Some(read_form_header(&self.pending)?);
self.pending.clear();
self.state = State::ChunkHeader;
Ok(())
}
fn start_chunk(&mut self) -> Result<(), DecodeError> {
let offset = self.offset - riff::CHUNK_HEADER_BYTES;
let (Some(id), Some(declared)) = (
riff::four_cc_at(&self.pending, 0),
riff::u32_be_at(&self.pending, 4),
) else {
return Err(DecodeError::Truncated {
expected: riff::CHUNK_HEADER_BYTES,
available: self.pending.len() as u64,
});
};
self.pending.clear();
let size = u64::from(declared);
let form = self.form.unwrap_or(AiffForm::Aiff);
if id == COMM && self.format.is_none() {
check_comm_size(form, size, offset)?;
self.state = State::CommBody {
size: size as usize,
offset,
};
return Ok(());
}
if id == SSND {
if self.format.is_none() {
return Err(DecodeError::Malformed {
expected: "a COMM chunk before the SSND chunk",
offset,
});
}
if size < SSND_PREFIX_BYTES {
return Err(DecodeError::Malformed {
expected: "an SSND chunk of at least 8 bytes",
offset,
});
}
self.state = State::SsndPrefix { size, offset };
return Ok(());
}
self.state = if size == 0 {
State::ChunkHeader
} else {
State::Skip { size, left: size }
};
Ok(())
}
fn finish_comm(&mut self, size: usize, offset: u64) -> Result<(), DecodeError> {
let form = self.form.unwrap_or(AiffForm::Aiff);
self.format = Some(parse_comm(&self.pending, offset, form)?);
self.pending.clear();
self.state = if riff::pad_len(size as u64) == 1 {
State::Pad
} else {
State::ChunkHeader
};
Ok(())
}
fn finish_ssnd_prefix(&mut self, size: u64, offset: u64) -> Result<(), DecodeError> {
let Some(format) = self.format else {
return Err(DecodeError::Malformed {
expected: "a COMM chunk before the SSND chunk",
offset,
});
};
let data_offset = riff::u32_be_at(&self.pending, 0).unwrap_or(0);
self.pending.clear();
check_ssnd(&format, size, data_offset, offset)?;
self.payload = Some(Payload::from_parts(
format.codec.sample_format(),
format.codec.law(),
format.spec,
));
self.data_size = format.data_bytes();
self.data_left = self.data_size;
let gap = u64::from(data_offset);
self.state = if gap > 0 {
State::SsndGap {
size: gap,
left: gap,
}
} else if self.data_size == 0 {
State::Done
} else {
State::Data
};
Ok(())
}
fn drain_payload(&mut self) -> Result<(), DecodeError> {
if let Some(payload) = self.payload.as_mut() {
payload.decode(&mut self.ready)?;
}
Ok(())
}
}
impl StreamSource for AiffStreamDecoder {
fn push(&mut self, bytes: &[u8]) -> Result<usize, DecodeError> {
if self.finished {
return Ok(0);
}
let mut taken = 0;
let result = self.push_inner(bytes, &mut taken);
if result.is_err() {
self.finished = true;
}
result.map(|()| taken)
}
fn pull(&mut self, output: &mut Vec<f32>, max_frames: usize) -> Result<usize, DecodeError> {
let Some(format) = self.format else {
return Ok(0);
};
let channels = usize::from(format.spec.channels);
let available = self.ready.len() - self.ready_read;
let frames = (available / channels).min(max_frames);
let count = frames * channels;
output.extend_from_slice(&self.ready[self.ready_read..self.ready_read + count]);
self.ready_read += count;
if self.ready_read == self.ready.len() {
self.ready.clear();
self.ready_read = 0;
} else if self.ready_read >= self.ready.len() / 2 {
self.ready.drain(..self.ready_read);
self.ready_read = 0;
}
Ok(frames)
}
fn spec(&self) -> Option<AudioSpec> {
self.format.map(|format| format.spec)
}
fn buffered_bytes(&self) -> usize {
self.pending.len()
+ self
.payload
.as_ref()
.map_or(0, |payload| payload.buffered_bytes())
}
fn finish(&mut self, output: &mut Vec<f32>) -> Result<usize, DecodeError> {
if self.finished {
return Ok(0);
}
self.finished = true;
match self.state {
State::Done => {}
State::ChunkHeader
if self.pending.is_empty()
&& self.format.is_some_and(|format| format.sample_frames == 0) => {}
State::Form => {
return Err(DecodeError::Truncated {
expected: riff::HEADER_BYTES,
available: self.pending.len() as u64,
})
}
State::Pad | State::ChunkHeader if self.pending.is_empty() => {
return Err(DecodeError::Malformed {
expected: if self.format.is_some() {
"an SSND chunk"
} else {
"a COMM chunk"
},
offset: self.offset,
})
}
State::ChunkHeader | State::Pad => {
return Err(DecodeError::Truncated {
expected: riff::CHUNK_HEADER_BYTES,
available: self.pending.len() as u64,
})
}
State::CommBody { size, .. } => {
return Err(DecodeError::Truncated {
expected: size as u64,
available: self.pending.len() as u64,
})
}
State::SsndPrefix { .. } => {
return Err(DecodeError::Truncated {
expected: SSND_PREFIX_BYTES,
available: self.pending.len() as u64,
})
}
State::SsndGap { size, left } | State::Skip { size, left } => {
return Err(DecodeError::Truncated {
expected: size,
available: size - left,
})
}
State::Data => {
return Err(DecodeError::Truncated {
expected: self.data_size,
available: self.data_size - self.data_left,
})
}
}
if let Some(payload) = self.payload.as_mut() {
payload.flush(&mut self.ready)?;
}
let Some(format) = self.format else {
return Ok(0);
};
let channels = usize::from(format.spec.channels);
let frames = (self.ready.len() - self.ready_read) / channels;
output.extend_from_slice(&self.ready[self.ready_read..self.ready_read + frames * channels]);
self.ready.clear();
self.ready_read = 0;
Ok(frames)
}
fn reset(&mut self) {
*self = Self::new();
}
}
impl AiffStreamDecoder {
fn push_inner(&mut self, bytes: &[u8], taken: &mut usize) -> Result<(), DecodeError> {
while *taken < bytes.len() {
let rest = &bytes[*taken..];
match self.state {
State::Form => {
if !self.accumulate(rest, riff::HEADER_BYTES as usize, taken) {
break;
}
self.start_file()?;
}
State::ChunkHeader => {
if !self.accumulate(rest, riff::CHUNK_HEADER_BYTES as usize, taken) {
break;
}
self.start_chunk()?;
}
State::CommBody { size, offset } => {
if !self.accumulate(rest, size, taken) {
break;
}
self.finish_comm(size, offset)?;
}
State::SsndPrefix { size, offset } => {
if !self.accumulate(rest, SSND_PREFIX_BYTES as usize, taken) {
break;
}
self.finish_ssnd_prefix(size, offset)?;
}
State::SsndGap { size, left } => {
let step = left.min(rest.len() as u64);
*taken += step as usize;
self.offset += step;
let left = left - step;
self.state = if left == 0 {
if self.data_size == 0 {
State::Done
} else {
State::Data
}
} else {
State::SsndGap { size, left }
};
}
State::Skip { size, left } => {
let step = left.min(rest.len() as u64);
*taken += step as usize;
self.offset += step;
let left = left - step;
self.state = if left == 0 {
if riff::pad_len(size) == 1 {
State::Pad
} else {
State::ChunkHeader
}
} else {
State::Skip { size, left }
};
}
State::Pad => {
*taken += 1;
self.offset += 1;
self.state = State::ChunkHeader;
}
State::Data => {
if self.ready.len() - self.ready_read >= READY_LIMIT {
break;
}
let limit = self.data_left.min(rest.len() as u64) as usize;
let fed = match self.payload.as_mut() {
Some(payload) => payload.feed(&rest[..limit])?,
None => 0,
};
self.drain_payload()?;
*taken += fed;
self.offset += fed as u64;
self.data_left -= fed as u64;
if self.data_left == 0 {
self.state = State::Done;
} else if fed == 0 {
break;
}
}
State::Done => {
self.offset += (bytes.len() - *taken) as u64;
*taken = bytes.len();
}
}
}
Ok(())
}
}
const COMM_WRITE_AIFF: u64 = COMM_BYTES_AIFF;
const COMM_WRITE_AIFC: u64 = COMM_BYTES_AIFC + 2;
const FVER_CHUNK_BYTES: u64 = riff::CHUNK_HEADER_BYTES + 4;
fn aiff_form_size(form: AiffForm, data_bytes: u64) -> Option<u64> {
let mut size: u64 = 4; let comm_bytes = match form {
AiffForm::Aiff => COMM_WRITE_AIFF,
AiffForm::Aifc => {
size = size.checked_add(FVER_CHUNK_BYTES)?;
COMM_WRITE_AIFC
}
};
size = size
.checked_add(riff::CHUNK_HEADER_BYTES)?
.checked_add(comm_bytes)?;
let ssnd_body = SSND_PREFIX_BYTES.checked_add(data_bytes)?;
size = size
.checked_add(riff::CHUNK_HEADER_BYTES)?
.checked_add(ssnd_body)?
.checked_add(riff::pad_len(ssnd_body))?;
Some(size)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
pub struct AiffWriter {
spec: AudioSpec,
codec: AiffCodec,
}
impl AiffWriter {
pub const fn new(spec: AudioSpec, codec: AiffCodec) -> Self {
Self { spec, codec }
}
pub const fn spec(&self) -> AudioSpec {
self.spec
}
pub const fn codec(&self) -> AiffCodec {
self.codec
}
pub const fn form(&self) -> AiffForm {
self.codec.form()
}
pub fn write(&self, samples: &[f32], output: &mut Vec<u8>) -> Result<usize, DecodeError> {
let channels = usize::from(self.spec.channels);
if channels == 0 {
return Err(DecodeError::UnsupportedChannelLayout {
channels: self.spec.channels,
});
}
let form = self.codec.form();
if self.spec.sample_rate == 0 {
let comm_at = riff::HEADER_BYTES
+ match form {
AiffForm::Aiff => 0,
AiffForm::Aifc => FVER_CHUNK_BYTES,
};
return Err(DecodeError::Malformed {
expected: "a non-zero sample rate",
offset: comm_at + riff::CHUNK_HEADER_BYTES + 8,
});
}
let bytes_per_sample = self.codec.bytes_per_sample();
let frame_bytes = channels * bytes_per_sample;
let leftover = samples.len() % channels;
if leftover != 0 {
return Err(DecodeError::Truncated {
expected: frame_bytes as u64,
available: (leftover * bytes_per_sample) as u64,
});
}
let data_bytes = (samples.len() as u64).checked_mul(bytes_per_sample as u64);
let declared_form = data_bytes.and_then(|data| aiff_form_size(form, data));
let (Some(data_bytes), Some(declared_form)) = (data_bytes, declared_form) else {
return Err(size_refusal());
};
if declared_form > u64::from(u32::MAX) {
return Err(size_refusal());
}
let frames = (samples.len() / channels) as u32;
let start = output.len();
output.extend_from_slice(FORM.as_bytes());
output.extend_from_slice(&(declared_form as u32).to_be_bytes());
let comm_bytes = match form {
AiffForm::Aiff => {
output.extend_from_slice(AIFF.as_bytes());
COMM_WRITE_AIFF
}
AiffForm::Aifc => {
output.extend_from_slice(AIFC.as_bytes());
output.extend_from_slice(FVER.as_bytes());
output.extend_from_slice(&4u32.to_be_bytes());
output.extend_from_slice(&FVER_TIMESTAMP.to_be_bytes());
COMM_WRITE_AIFC
}
};
output.extend_from_slice(COMM.as_bytes());
output.extend_from_slice(&(comm_bytes as u32).to_be_bytes());
output.extend_from_slice(&self.spec.channels.to_be_bytes());
output.extend_from_slice(&frames.to_be_bytes());
output.extend_from_slice(&self.codec.bits_per_sample().to_be_bytes());
output.extend_from_slice(&rate_to_extended(self.spec.sample_rate));
if form == AiffForm::Aifc {
output.extend_from_slice(self.codec.compression_type().as_bytes());
output.extend_from_slice(&[0, 0]);
}
output.extend_from_slice(SSND.as_bytes());
output.extend_from_slice(&((SSND_PREFIX_BYTES + data_bytes) as u32).to_be_bytes());
output.extend_from_slice(&0u32.to_be_bytes()); output.extend_from_slice(&0u32.to_be_bytes()); self.codec.encode(samples, output);
if riff::pad_len(SSND_PREFIX_BYTES + data_bytes) == 1 {
output.push(0);
}
Ok(output.len() - start)
}
pub fn to_bytes(&self, samples: &[f32]) -> Result<Vec<u8>, DecodeError> {
let mut output = Vec::new();
self.write(samples, &mut output)?;
Ok(output)
}
}
fn size_refusal() -> DecodeError {
DecodeError::Malformed {
expected: "audio that fits within AIFF's 32-bit size fields",
offset: 4,
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_extended_float_parser_matches_hand_computed_values() {
let cases: [([u8; 10], f64); 7] = [
([0x40, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0], 8_000.0),
([0x40, 0x0C, 0xFA, 0, 0, 0, 0, 0, 0, 0], 16_000.0),
([0x40, 0x0E, 0xAC, 0x44, 0, 0, 0, 0, 0, 0], 44_100.0),
([0x40, 0x0E, 0xBB, 0x80, 0, 0, 0, 0, 0, 0], 48_000.0),
([0x40, 0x0D, 0xAC, 0x44, 0, 0, 0, 0, 0, 0], 22_050.0),
([0x40, 0x0C, 0xAC, 0x46, 0, 0, 0, 0, 0, 0], 11_025.5),
([0x3F, 0xFF, 0x80, 0, 0, 0, 0, 0, 0, 0], 1.0),
];
for (bytes, expected) in cases {
assert_eq!(
extended_to_f64(bytes),
expected,
"{bytes:02X?} did not parse to {expected}"
);
}
}
#[test]
fn the_extended_float_parser_handles_the_edges_deterministically() {
assert_eq!(extended_to_f64([0; 10]), 0.0);
assert_eq!(extended_to_f64([0x80, 0, 0, 0, 0, 0, 0, 0, 0, 0]), 0.0);
assert_eq!(
extended_to_f64([0xC0, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0]),
-8_000.0
);
assert_eq!(
extended_to_f64([0x7F, 0xFF, 0x80, 0, 0, 0, 0, 0, 0, 0]),
f64::INFINITY
);
assert_eq!(
extended_to_f64([0xFF, 0xFF, 0x80, 0, 0, 0, 0, 0, 0, 0]),
f64::NEG_INFINITY
);
assert!(extended_to_f64([0x7F, 0xFF, 0xC0, 0, 0, 0, 0, 0, 0, 1]).is_nan());
assert_eq!(
extended_to_f64([0x7F, 0xFE, 0x80, 0, 0, 0, 0, 0, 0, 0]),
f64::INFINITY
);
assert_eq!(extended_to_f64([0, 0, 0, 0, 0, 0, 0, 0, 0, 1]), 0.0);
}
#[test]
fn a_rate_the_spec_cannot_carry_is_rejected_with_its_offset() {
for wrong in [
0.0,
-8_000.0,
11_025.5,
f64::INFINITY,
f64::NEG_INFINITY,
f64::NAN,
f64::from(u32::MAX) + 1.0,
0.25,
] {
let error = rate_to_spec_rate(wrong, 20).expect_err("must reject");
assert!(
matches!(
error,
DecodeError::Malformed {
expected: "a positive integral sample rate that fits in 32 bits",
offset: 20
}
),
"{wrong}: unexpected error: {error}"
);
}
for right in [1.0, 8_000.0, 44_100.0, 192_000.0, f64::from(u32::MAX)] {
assert_eq!(rate_to_spec_rate(right, 20).expect("accept"), right as u32);
}
}
#[test]
fn dispatch_is_on_the_compression_and_the_width_together() {
use AiffCodec::*;
let accepted: [(&[u8; 4], u16, AiffCodec); 16] = [
(b"NONE", 8, PcmI8),
(b"raw ", 8, PcmU8),
(b"NONE", 16, PcmI16),
(b"NONE", 24, PcmI24),
(b"NONE", 32, PcmI32),
(b"twos", 8, PcmI8),
(b"twos", 16, PcmI16),
(b"sowt", 8, PcmI8),
(b"sowt", 16, PcmI16Sowt),
(b"sowt", 24, PcmI24Sowt),
(b"sowt", 32, PcmI32Sowt),
(b"fl32", 32, Float32),
(b"FL32", 32, Float32),
(b"fl64", 64, Float64),
(b"FL64", 64, Float64),
(b"alaw", 16, ALaw),
];
for (compression, bits, codec) in accepted {
assert_eq!(
AiffCodec::resolve(FourCc(*compression), bits).expect("accepted"),
codec,
"{compression:?} at {bits} bits"
);
}
for law_cc in [b"alaw", b"ALAW"] {
for bits in [8u16, 16] {
assert_eq!(
AiffCodec::resolve(FourCc(*law_cc), bits).expect("alaw"),
ALaw
);
}
}
for law_cc in [b"ulaw", b"ULAW"] {
for bits in [8u16, 16] {
assert_eq!(
AiffCodec::resolve(FourCc(*law_cc), bits).expect("ulaw"),
MuLaw
);
}
}
for (compression, bits) in [
(b"NONE", 12u16),
(b"NONE", 64),
(b"sowt", 20),
(b"fl32", 16),
(b"fl64", 32),
(b"raw ", 1),
(b"raw ", 16),
(b"raw ", 24),
(b"raw ", 32),
] {
let error = AiffCodec::resolve(FourCc(*compression), bits).expect_err("must reject");
assert!(
matches!(
&error,
DecodeError::UnsupportedSampleFormat { format, bits_per_sample }
if *format == CodecId::FourCc(FourCc(*compression))
&& *bits_per_sample == bits
),
"{compression:?} at {bits}: unexpected error: {error}"
);
}
for compression in [b"ima4", b"MAC3", b"MAC6", b"QDMC", b"GSM "] {
let error = AiffCodec::resolve(FourCc(*compression), 16).expect_err("must reject");
assert!(
matches!(&error, DecodeError::UnsupportedCodec { codec }
if *codec == CodecId::FourCc(FourCc(*compression))),
"{compression:?}: unexpected error: {error}"
);
}
}
#[test]
fn every_codec_is_linear_or_companded_and_never_both() {
const ALL: [AiffCodec; 12] = [
AiffCodec::PcmI8,
AiffCodec::PcmU8,
AiffCodec::PcmI16,
AiffCodec::PcmI24,
AiffCodec::PcmI32,
AiffCodec::PcmI16Sowt,
AiffCodec::PcmI24Sowt,
AiffCodec::PcmI32Sowt,
AiffCodec::Float32,
AiffCodec::Float64,
AiffCodec::ALaw,
AiffCodec::MuLaw,
];
for codec in ALL {
match codec {
AiffCodec::PcmI8
| AiffCodec::PcmU8
| AiffCodec::PcmI16
| AiffCodec::PcmI24
| AiffCodec::PcmI32
| AiffCodec::PcmI16Sowt
| AiffCodec::PcmI24Sowt
| AiffCodec::PcmI32Sowt
| AiffCodec::Float32
| AiffCodec::Float64
| AiffCodec::ALaw
| AiffCodec::MuLaw => {}
}
assert_ne!(
codec.sample_format().is_some(),
codec.law().is_some(),
"{codec:?} is on both sides or neither"
);
if let Some(format) = codec.sample_format() {
assert_eq!(format.bytes_per_sample(), codec.bytes_per_sample());
} else {
assert_eq!(codec.bytes_per_sample(), 1);
}
}
}
fn comm_aiff(channels: u16, frames: u32, bits: u16, rate: [u8; 10]) -> Vec<u8> {
let mut body = Vec::new();
body.extend_from_slice(&channels.to_be_bytes());
body.extend_from_slice(&frames.to_be_bytes());
body.extend_from_slice(&bits.to_be_bytes());
body.extend_from_slice(&rate);
body
}
const RATE_8K: [u8; 10] = [0x40, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0];
#[test]
fn a_comm_chunk_parses_to_what_it_declared() {
let body = comm_aiff(2, 100, 16, RATE_8K);
let format = parse_comm(&body, 12, AiffForm::Aiff).expect("parse");
assert_eq!(format.spec, AudioSpec::new(8_000, 2));
assert_eq!(format.codec, AiffCodec::PcmI16);
assert_eq!(format.form, AiffForm::Aiff);
assert_eq!(format.compression, NONE);
assert_eq!(format.bits_per_sample, 16);
assert_eq!(format.sample_frames, 100);
assert_eq!(format.frame_bytes(), 4);
}
#[test]
fn a_compression_name_that_overruns_its_chunk_is_malformed() {
let mut body = comm_aiff(1, 4, 16, RATE_8K);
body.extend_from_slice(b"sowt");
body.push(11);
body.extend_from_slice(b"four");
let error = parse_comm(&body, 12, AiffForm::Aifc).expect_err("must reject");
assert!(
matches!(
error,
DecodeError::Malformed {
expected: "a compressionName that fits its COMM chunk",
..
}
),
"unexpected error: {error}"
);
let mut body = comm_aiff(1, 4, 16, RATE_8K);
body.extend_from_slice(b"sowt");
body.push(4);
body.extend_from_slice(b"four");
body.push(0); let format = parse_comm(&body, 12, AiffForm::Aifc).expect("parse");
assert_eq!(format.codec, AiffCodec::PcmI16Sowt);
}
#[test]
fn zero_channels_and_impossible_rates_are_typed_rejections() {
let body = comm_aiff(0, 4, 16, RATE_8K);
assert!(matches!(
parse_comm(&body, 12, AiffForm::Aiff),
Err(DecodeError::UnsupportedChannelLayout { channels: 0 })
));
for bad_rate in [
[0u8; 10], [0xC0, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0], [0x40, 0x0C, 0xAC, 0x46, 0, 0, 0, 0, 0, 0], [0x7F, 0xFF, 0x80, 0, 0, 0, 0, 0, 0, 0], [0x7F, 0xFF, 0xC0, 0, 0, 0, 0, 0, 0, 1], ] {
let body = comm_aiff(1, 4, 16, bad_rate);
let error = parse_comm(&body, 12, AiffForm::Aiff).expect_err("must reject");
assert!(
matches!(
error,
DecodeError::Malformed {
expected: "a positive integral sample rate that fits in 32 bits",
offset: 28
}
),
"{bad_rate:02X?}: unexpected error: {error}"
);
}
}
#[test]
fn the_ssnd_length_must_equal_what_comm_declared() {
let format = parse_comm(&comm_aiff(2, 10, 16, RATE_8K), 12, AiffForm::Aiff).expect("parse");
assert!(check_ssnd(&format, 48, 0, 30).is_ok());
let error = check_ssnd(&format, 40, 0, 30).expect_err("under");
assert!(
matches!(
error,
DecodeError::Truncated {
expected: 40,
available: 32
}
),
"unexpected error: {error}"
);
let error = check_ssnd(&format, 50, 0, 30).expect_err("over");
assert!(
matches!(
error,
DecodeError::Malformed {
expected: "an SSND chunk holding exactly numSampleFrames frames",
offset: 30
}
),
"unexpected error: {error}"
);
assert!(check_ssnd(&format, 52, 4, 30).is_ok());
let error = check_ssnd(&format, 48, u32::MAX, 30).expect_err("offset");
assert!(
matches!(
error,
DecodeError::Malformed {
expected: "an SSND offset that fits inside the SSND chunk",
..
}
),
"unexpected error: {error}"
);
}
#[test]
fn the_extended_float_encoder_matches_hand_computed_values() {
let cases: [(u32, [u8; 10]); 5] = [
(8_000, [0x40, 0x0B, 0xFA, 0, 0, 0, 0, 0, 0, 0]),
(16_000, [0x40, 0x0C, 0xFA, 0, 0, 0, 0, 0, 0, 0]),
(22_050, [0x40, 0x0D, 0xAC, 0x44, 0, 0, 0, 0, 0, 0]),
(44_100, [0x40, 0x0E, 0xAC, 0x44, 0, 0, 0, 0, 0, 0]),
(48_000, [0x40, 0x0E, 0xBB, 0x80, 0, 0, 0, 0, 0, 0]),
];
for (rate, expected) in cases {
assert_eq!(
rate_to_extended(rate),
expected,
"{rate} did not encode to {expected:02X?}"
);
}
}
#[test]
fn the_extended_float_encoder_round_trips_through_the_parser() {
let common = [
8_000u32, 11_025, 16_000, 22_050, 32_000, 44_100, 48_000, 88_200, 96_000, 176_400,
192_000,
];
let sweep = 1..=1_000;
let powers = (0..32).map(|shift| 1u32 << shift);
let extremes = [3u32, u32::MAX - 1, u32::MAX];
for rate in common
.into_iter()
.chain(sweep)
.chain(powers)
.chain(extremes)
{
let parsed = extended_to_f64(rate_to_extended(rate));
assert_eq!(parsed, f64::from(rate), "{rate} did not round-trip");
assert_eq!(rate_to_spec_rate(parsed, 0).expect("integral"), rate);
}
}
#[test]
fn the_size_refusal_happens_exactly_at_the_32_bit_form_limit() {
let ceiling = u64::from(u32::MAX);
const AIFF_OVERHEAD: u64 = 46;
assert_eq!(aiff_form_size(AiffForm::Aiff, 0), Some(AIFF_OVERHEAD));
let largest = ceiling - AIFF_OVERHEAD - 1;
assert_eq!(largest % 2, 0);
assert_eq!(aiff_form_size(AiffForm::Aiff, largest), Some(ceiling - 1));
assert!(aiff_form_size(AiffForm::Aiff, largest).unwrap() <= ceiling);
assert_eq!(
aiff_form_size(AiffForm::Aiff, largest + 1),
Some(ceiling + 1)
);
assert_eq!(
aiff_form_size(AiffForm::Aiff, largest - 1),
Some(ceiling - 1)
);
const AIFC_OVERHEAD: u64 = 64;
assert_eq!(aiff_form_size(AiffForm::Aifc, 0), Some(AIFC_OVERHEAD));
let largest = ceiling - AIFC_OVERHEAD - 1;
assert_eq!(largest % 2, 0);
assert_eq!(aiff_form_size(AiffForm::Aifc, largest), Some(ceiling - 1));
assert_eq!(
aiff_form_size(AiffForm::Aifc, largest + 1),
Some(ceiling + 1)
);
assert_eq!(aiff_form_size(AiffForm::Aiff, u64::MAX), None);
assert_eq!(aiff_form_size(AiffForm::Aifc, u64::MAX - 20), None);
let error = size_refusal();
assert!(
matches!(
error,
DecodeError::Malformed {
expected: "audio that fits within AIFF's 32-bit size fields",
offset: 4
}
),
"unexpected error: {error}"
);
}
#[test]
fn the_writer_rejects_a_partial_trailing_frame() {
let writer = AiffWriter::new(AudioSpec::new(48_000, 3), AiffCodec::PcmI16);
let error = writer.to_bytes(&[0.0; 7]).expect_err("must reject");
assert!(
matches!(
error,
DecodeError::Truncated {
expected: 6,
available: 2
}
),
"unexpected error: {error}"
);
assert!(writer.to_bytes(&[0.0; 6]).is_ok());
assert!(writer.to_bytes(&[0.0; 9]).is_ok());
}
#[test]
fn the_writer_rejects_what_the_header_cannot_express() {
let no_channels = AiffWriter::new(AudioSpec::new(48_000, 0), AiffCodec::PcmI16);
assert!(matches!(
no_channels.to_bytes(&[]),
Err(DecodeError::UnsupportedChannelLayout { channels: 0 })
));
for (codec, rate_at) in [(AiffCodec::PcmI16, 28), (AiffCodec::Float32, 40)] {
let no_rate = AiffWriter::new(AudioSpec::mono(0), codec);
assert!(matches!(
no_rate.to_bytes(&[]),
Err(DecodeError::Malformed {
expected: "a non-zero sample rate",
offset
}) if offset == rate_at
));
}
}
#[test]
fn the_writer_appends_rather_than_clearing() {
let writer = AiffWriter::new(AudioSpec::mono(8_000), AiffCodec::PcmI8);
let mut output = vec![0xAA];
let written = writer.write(&[0.0, 0.0], &mut output).expect("write");
assert_eq!(output[0], 0xAA);
assert_eq!(output.len(), 1 + written);
assert_eq!(written, 12 + 8 + 18 + 8 + 8 + 2);
}
#[test]
fn each_codec_selects_the_form_the_rule_states() {
let cases: [(AiffCodec, AiffForm); 12] = [
(AiffCodec::PcmI8, AiffForm::Aiff),
(AiffCodec::PcmU8, AiffForm::Aifc),
(AiffCodec::PcmI16, AiffForm::Aiff),
(AiffCodec::PcmI24, AiffForm::Aiff),
(AiffCodec::PcmI32, AiffForm::Aiff),
(AiffCodec::PcmI16Sowt, AiffForm::Aifc),
(AiffCodec::PcmI24Sowt, AiffForm::Aifc),
(AiffCodec::PcmI32Sowt, AiffForm::Aifc),
(AiffCodec::Float32, AiffForm::Aifc),
(AiffCodec::Float64, AiffForm::Aifc),
(AiffCodec::ALaw, AiffForm::Aifc),
(AiffCodec::MuLaw, AiffForm::Aifc),
];
for (codec, expected_form) in cases {
let writer = AiffWriter::new(AudioSpec::new(16_000, 2), codec);
assert_eq!(writer.form(), expected_form, "{codec:?}");
let bytes = writer.to_bytes(&[0.0, 0.0]).expect("write");
let form_type = &bytes[8..12];
let has_fver = bytes.windows(4).any(|window| window == b"FVER");
match expected_form {
AiffForm::Aiff => {
assert_eq!(form_type, b"AIFF", "{codec:?}");
assert!(!has_fver, "{codec:?} wrote FVER into a plain AIFF");
}
AiffForm::Aifc => {
assert_eq!(form_type, b"AIFC", "{codec:?}");
assert!(has_fver, "{codec:?} omitted the FVER chunk");
}
}
let reader = AiffReader::new(&bytes).expect("read back");
assert_eq!(reader.format().codec, codec, "{codec:?}");
assert_eq!(reader.format().form, expected_form, "{codec:?}");
}
}
}