#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum PcmSampleFormat {
F32,
S24,
S16,
}
impl PcmSampleFormat {
#[must_use]
pub const fn bytes(self) -> usize {
match self {
Self::F32 => 4,
Self::S24 => 3,
Self::S16 => 2,
}
}
#[must_use]
pub const fn bits(self) -> u16 {
match self {
Self::F32 => 32,
Self::S24 => 24,
Self::S16 => 16,
}
}
pub fn interleave(
self,
planes: &[&[f32]],
plane_order: &[usize],
frames: usize,
out: &mut Vec<u8>,
) {
out.reserve(frames * plane_order.len() * self.bytes());
for frame in 0..frames {
for plane in plane_order.iter().map(|plane| planes[*plane]) {
let sample = plane[frame];
match self {
Self::F32 => out.extend_from_slice(&sample.to_le_bytes()),
Self::S24 => out.extend_from_slice(&pcm_integer(sample, 24).to_le_bytes()[..3]),
Self::S16 => out.extend_from_slice(&pcm_integer(sample, 16).to_le_bytes()[..2]),
}
}
}
}
}
#[must_use]
pub fn pcm_integer(sample: f32, bits: u32) -> i32 {
assert!((2..=32).contains(&bits), "{bits}-bit PCM is not an i32");
let full_scale = f64::from(1_u32 << (bits - 1));
let rounded = (f64::from(sample) * full_scale).round_ties_even();
#[expect(
clippy::cast_possible_truncation,
reason = "clamped to the range, and a NaN casts to zero"
)]
let integer = rounded.clamp(-full_scale, full_scale - 1.0) as i32;
integer
}
#[cfg(test)]
#[path = "pcm_tests.rs"]
mod tests;