alpha2-container 0.10.0

alpha2's own media container layer: MP4/MOV/M4A, Matroska/WebM and audio-only files, demuxed and muxed in pure Rust with edit lists, priming and deterministic output.
Documentation
//! A RIFF WAVE writer of 16- and 24-bit integer and 32-bit float PCM.

use std::io::{BufWriter, Seek, SeekFrom, Write};

use alpha2_media::{MAX_AUDIO_CHANNELS, SpeakerLayout};

use crate::{AudioCodec, ContainerWriter, MuxError, Packet, PcmFormat, TrackId, TrackInfo};

/// RIFF chunk bytes beyond the `data` samples with a plain `fmt ` chunk.
const PLAIN_OVERHEAD: u32 = 36;
/// The same with a `WAVE_FORMAT_EXTENSIBLE` `fmt ` chunk.
const EXTENSIBLE_OVERHEAD: u32 = 60;
const WAVE_FORMAT_PCM: u16 = 1;
const WAVE_FORMAT_IEEE_FLOAT: u16 = 3;
const WAVE_FORMAT_EXTENSIBLE: u16 = 0xfffe;
/// The last 14 bytes of `KSDATAFORMAT_SUBTYPE_PCM` and `KSDATAFORMAT_SUBTYPE_IEEE_FLOAT`, whose
/// first two hold the format tag.
const KSDATAFORMAT_SUBTYPE_TAIL: [u8; 14] = [
    0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71,
];
/// Speaker positions a `WAVEFORMATEXTENSIBLE` channel mask names.
const MASK_POSITIONS: u32 = 18;
const WRITE_BUFFER_BYTES: usize = 1 << 20;

/// The `WAVE_FORMAT_EXTENSIBLE` channel mask of `speakers`, `None` for the default layout of
/// their count, and the order of the planes in a frame, which a mask fixes to its bit order.
///
/// # Errors
/// [`MuxError::Unsupported`] for speakers a mask cannot name: unnamed, repeated, or past its 18
/// positions.
pub fn wave_channel_layout(
    speakers: &SpeakerLayout,
) -> Result<(Option<u32>, Vec<usize>), MuxError> {
    let identity = (0..speakers.channels()).collect::<Vec<_>>();
    if SpeakerLayout::default_for(speakers.channels()) == Some(*speakers) {
        return Ok((None, identity));
    }
    let mut mask = 0_u32;
    for speaker in speakers.speakers() {
        let bit = speaker.ffmpeg_channel();
        if bit >= MASK_POSITIONS || mask & (1 << bit) != 0 {
            return Err(MuxError::Unsupported(format!(
                "a WAVE channel mask cannot say the speakers {}",
                speakers.describe()
            )));
        }
        mask |= 1 << bit;
    }
    let mut order = identity;
    order.sort_by_key(|plane| speakers.speakers()[*plane].ffmpeg_channel());
    Ok((Some(mask), order))
}

#[derive(Clone, Copy, Debug)]
struct Format {
    sample_rate: u32,
    channels: u16,
    bits: u16,
    float: bool,
    channel_mask: Option<u32>,
}

impl Format {
    fn of(track: &TrackInfo) -> Result<Self, MuxError> {
        let audio = track
            .audio
            .as_ref()
            .ok_or_else(|| MuxError::Unsupported("a WAVE file holds audio only".into()))?;
        let AudioCodec::Pcm(pcm) = audio.codec else {
            return Err(MuxError::Unsupported(format!(
                "a WAVE file holds PCM, not {:?}",
                audio.codec
            )));
        };
        let float = match pcm {
            PcmFormat {
                bits: 16 | 24,
                float: false,
                big_endian: false,
                signed: true,
            } => false,
            PcmFormat {
                bits: 32,
                float: true,
                big_endian: false,
                ..
            } => true,
            other => {
                return Err(MuxError::Unsupported(format!(
                    "this WAVE writer takes 16- and 24-bit integer and 32-bit float little-endian PCM, not {other:?}"
                )));
            }
        };
        let channels = usize::try_from(audio.channels).unwrap_or(usize::MAX);
        let speakers = match audio.speakers {
            Some(speakers) if speakers.channels() == channels => speakers,
            Some(speakers) => {
                return Err(MuxError::Invalid(format!(
                    "{channels} channels with the speakers {}",
                    speakers.describe()
                )));
            }
            None => SpeakerLayout::default_for(channels).ok_or_else(|| {
                MuxError::Unsupported(format!("a WAVE file of {channels} channels"))
            })?,
        };
        if audio.sample_rate == 0 || channels == 0 || channels > MAX_AUDIO_CHANNELS {
            return Err(MuxError::Unsupported(format!(
                "a WAVE file of {channels} channels at {} Hz",
                audio.sample_rate
            )));
        }
        let (channel_mask, _) = wave_channel_layout(&speakers)?;
        Ok(Self {
            sample_rate: audio.sample_rate,
            channels: u16::try_from(channels).unwrap_or(u16::MAX),
            bits: pcm.bits,
            float,
            channel_mask,
        })
    }

    const fn format_tag(&self) -> u16 {
        if self.float {
            WAVE_FORMAT_IEEE_FLOAT
        } else {
            WAVE_FORMAT_PCM
        }
    }

    const fn overhead(&self) -> u32 {
        if self.channel_mask.is_some() {
            EXTENSIBLE_OVERHEAD
        } else {
            PLAIN_OVERHEAD
        }
    }

    const fn block_align(&self) -> u16 {
        self.channels.saturating_mul(self.bits / 8)
    }

    fn header(&self, data_bytes: u32) -> Vec<u8> {
        let riff_size = data_bytes.saturating_add(self.overhead());
        let block_align = self.block_align();
        let byte_rate = self.sample_rate.saturating_mul(u32::from(block_align));
        let mut header = Vec::with_capacity(68);
        header.extend_from_slice(b"RIFF");
        header.extend_from_slice(&riff_size.to_le_bytes());
        header.extend_from_slice(b"WAVEfmt ");
        let (fmt_size, tag) = match self.channel_mask {
            Some(_) => (40_u32, WAVE_FORMAT_EXTENSIBLE),
            None => (16, self.format_tag()),
        };
        header.extend_from_slice(&fmt_size.to_le_bytes());
        header.extend_from_slice(&tag.to_le_bytes());
        header.extend_from_slice(&self.channels.to_le_bytes());
        header.extend_from_slice(&self.sample_rate.to_le_bytes());
        header.extend_from_slice(&byte_rate.to_le_bytes());
        header.extend_from_slice(&block_align.to_le_bytes());
        header.extend_from_slice(&self.bits.to_le_bytes());
        if let Some(mask) = self.channel_mask {
            header.extend_from_slice(&22_u16.to_le_bytes());
            header.extend_from_slice(&self.bits.to_le_bytes());
            header.extend_from_slice(&mask.to_le_bytes());
            header.extend_from_slice(&self.format_tag().to_le_bytes());
            header.extend_from_slice(&KSDATAFORMAT_SUBTYPE_TAIL);
        }
        header.extend_from_slice(b"data");
        header.extend_from_slice(&data_bytes.to_le_bytes());
        header
    }
}

trait Sink: Write + Seek + Send {}

impl<W: Write + Seek + Send> Sink for W {}

/// A writer of one PCM track into a RIFF WAVE file.
///
/// Packets carry interleaved frames in the order [`wave_channel_layout`] gives, each starting
/// where the last ended.
pub struct WavWriter {
    sink: Box<dyn Sink>,
    format: Option<Format>,
    data_bytes: u32,
    frames: i64,
}

impl WavWriter {
    /// A writer into `file`, open for writing.
    #[must_use]
    pub fn create(file: std::fs::File) -> Self {
        Self::new(BufWriter::with_capacity(WRITE_BUFFER_BYTES, file))
    }

    /// A writer into any writable and seekable `sink`, starting at its offset 0.
    pub fn new<W: Write + Seek + Send + 'static>(sink: W) -> Self {
        Self {
            sink: Box::new(sink),
            format: None,
            data_bytes: 0,
            frames: 0,
        }
    }
}

impl ContainerWriter for WavWriter {
    fn add_track(&mut self, track: &TrackInfo) -> Result<TrackId, MuxError> {
        if self.format.is_some() {
            return Err(MuxError::Invalid("a WAVE file holds one track".into()));
        }
        let format = Format::of(track)?;
        self.sink.seek(SeekFrom::Start(0))?;
        self.sink.write_all(&format.header(0))?;
        self.format = Some(format);
        Ok(TrackId(1))
    }

    fn write(&mut self, packet: Packet) -> Result<(), MuxError> {
        let format = self
            .format
            .ok_or_else(|| MuxError::Invalid("a packet before the track".into()))?;
        if packet.track != TrackId(1) {
            return Err(MuxError::Invalid(format!(
                "a packet of track {} in a WAVE file",
                packet.track.0
            )));
        }
        let align = usize::from(format.block_align());
        if !packet.data.len().is_multiple_of(align) {
            return Err(MuxError::Invalid(format!(
                "{} bytes are not whole frames of {align}",
                packet.data.len()
            )));
        }
        if packet.pts != self.frames {
            return Err(MuxError::Invalid(format!(
                "a packet at sample {} after {} samples",
                packet.pts, self.frames
            )));
        }
        let data_bytes = u32::try_from(packet.data.len())
            .ok()
            .and_then(|bytes| self.data_bytes.checked_add(bytes))
            .filter(|bytes| bytes.checked_add(format.overhead()).is_some())
            .ok_or_else(|| {
                MuxError::Unsupported(format!(
                    "{} frames of {} channels are more than the 4 GiB a WAVE file holds",
                    self.frames + i64::try_from(packet.data.len() / align).unwrap_or(i64::MAX),
                    format.channels
                ))
            })?;
        self.sink.write_all(&packet.data)?;
        self.data_bytes = data_bytes;
        self.frames += i64::try_from(packet.data.len() / align).unwrap_or(i64::MAX);
        Ok(())
    }

    fn finish(mut self: Box<Self>) -> Result<(), MuxError> {
        let format = self
            .format
            .ok_or_else(|| MuxError::Invalid("a WAVE file without its track".into()))?;
        self.sink.seek(SeekFrom::Start(0))?;
        self.sink.write_all(&format.header(self.data_bytes))?;
        self.sink.flush()?;
        Ok(())
    }
}