alpha2-media 0.9.0

Host-independent media vocabulary and I/O contracts for alpha2.
Documentation
//! PCM sample formats an audio file stores the mix in.

/// How one PCM sample is stored, little-endian.
#[derive(Copy, Clone, Debug, Eq, Hash, PartialEq)]
pub enum PcmSampleFormat {
    /// 32-bit IEEE float: the mix's samples as they are.
    F32,
    /// 24-bit signed integer.
    S24,
    /// 16-bit signed integer.
    S16,
}

impl PcmSampleFormat {
    /// Bytes one sample takes.
    #[must_use]
    pub const fn bytes(self) -> usize {
        match self {
            Self::F32 => 4,
            Self::S24 => 3,
            Self::S16 => 2,
        }
    }

    /// Bits one sample takes.
    #[must_use]
    pub const fn bits(self) -> u16 {
        match self {
            Self::F32 => 32,
            Self::S24 => 24,
            Self::S16 => 16,
        }
    }

    /// Appends `frames` frames of `planes`, interleaved in the order of `plane_order`, each sample
    /// in this format. Integer samples are [`pcm_integer`]'s.
    ///
    /// # Panics
    /// When `plane_order` names a plane `planes` lacks, or a named plane is shorter than `frames`.
    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]),
                }
            }
        }
    }
}

/// The signed `bits`-bit integer a float sample is stored as: `sample * 2^(bits - 1)` rounded to
/// the nearest integer, ties to the even one, and clamped to the type's range. No dither. A NaN
/// is zero.
///
/// # Panics
/// When `bits` is not 2 to 32.
#[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;