Skip to main content

alpha2_container/audio/
wav_write.rs

1//! A RIFF WAVE writer of 16- and 24-bit integer and 32-bit float PCM.
2
3use std::io::{BufWriter, Seek, SeekFrom, Write};
4
5use alpha2_media::{MAX_AUDIO_CHANNELS, SpeakerLayout};
6
7use crate::{AudioCodec, ContainerWriter, MuxError, Packet, PcmFormat, TrackId, TrackInfo};
8
9/// RIFF chunk bytes beyond the `data` samples with a plain `fmt ` chunk.
10const PLAIN_OVERHEAD: u32 = 36;
11/// The same with a `WAVE_FORMAT_EXTENSIBLE` `fmt ` chunk.
12const EXTENSIBLE_OVERHEAD: u32 = 60;
13const WAVE_FORMAT_PCM: u16 = 1;
14const WAVE_FORMAT_IEEE_FLOAT: u16 = 3;
15const WAVE_FORMAT_EXTENSIBLE: u16 = 0xfffe;
16/// The last 14 bytes of `KSDATAFORMAT_SUBTYPE_PCM` and `KSDATAFORMAT_SUBTYPE_IEEE_FLOAT`, whose
17/// first two hold the format tag.
18const KSDATAFORMAT_SUBTYPE_TAIL: [u8; 14] = [
19    0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00, 0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71,
20];
21/// Speaker positions a `WAVEFORMATEXTENSIBLE` channel mask names.
22const MASK_POSITIONS: u32 = 18;
23const WRITE_BUFFER_BYTES: usize = 1 << 20;
24
25/// The `WAVE_FORMAT_EXTENSIBLE` channel mask of `speakers`, `None` for the default layout of
26/// their count, and the order of the planes in a frame, which a mask fixes to its bit order.
27///
28/// # Errors
29/// [`MuxError::Unsupported`] for speakers a mask cannot name: unnamed, repeated, or past its 18
30/// positions.
31pub fn wave_channel_layout(
32    speakers: &SpeakerLayout,
33) -> Result<(Option<u32>, Vec<usize>), MuxError> {
34    let identity = (0..speakers.channels()).collect::<Vec<_>>();
35    if SpeakerLayout::default_for(speakers.channels()) == Some(*speakers) {
36        return Ok((None, identity));
37    }
38    let mut mask = 0_u32;
39    for speaker in speakers.speakers() {
40        let bit = speaker.ffmpeg_channel();
41        if bit >= MASK_POSITIONS || mask & (1 << bit) != 0 {
42            return Err(MuxError::Unsupported(format!(
43                "a WAVE channel mask cannot say the speakers {}",
44                speakers.describe()
45            )));
46        }
47        mask |= 1 << bit;
48    }
49    let mut order = identity;
50    order.sort_by_key(|plane| speakers.speakers()[*plane].ffmpeg_channel());
51    Ok((Some(mask), order))
52}
53
54#[derive(Clone, Copy, Debug)]
55struct Format {
56    sample_rate: u32,
57    channels: u16,
58    bits: u16,
59    float: bool,
60    channel_mask: Option<u32>,
61}
62
63impl Format {
64    fn of(track: &TrackInfo) -> Result<Self, MuxError> {
65        let audio = track
66            .audio
67            .as_ref()
68            .ok_or_else(|| MuxError::Unsupported("a WAVE file holds audio only".into()))?;
69        let AudioCodec::Pcm(pcm) = audio.codec else {
70            return Err(MuxError::Unsupported(format!(
71                "a WAVE file holds PCM, not {:?}",
72                audio.codec
73            )));
74        };
75        let float = match pcm {
76            PcmFormat {
77                bits: 16 | 24,
78                float: false,
79                big_endian: false,
80                signed: true,
81            } => false,
82            PcmFormat {
83                bits: 32,
84                float: true,
85                big_endian: false,
86                ..
87            } => true,
88            other => {
89                return Err(MuxError::Unsupported(format!(
90                    "this WAVE writer takes 16- and 24-bit integer and 32-bit float little-endian PCM, not {other:?}"
91                )));
92            }
93        };
94        let channels = usize::try_from(audio.channels).unwrap_or(usize::MAX);
95        let speakers = match audio.speakers {
96            Some(speakers) if speakers.channels() == channels => speakers,
97            Some(speakers) => {
98                return Err(MuxError::Invalid(format!(
99                    "{channels} channels with the speakers {}",
100                    speakers.describe()
101                )));
102            }
103            None => SpeakerLayout::default_for(channels).ok_or_else(|| {
104                MuxError::Unsupported(format!("a WAVE file of {channels} channels"))
105            })?,
106        };
107        if audio.sample_rate == 0 || channels == 0 || channels > MAX_AUDIO_CHANNELS {
108            return Err(MuxError::Unsupported(format!(
109                "a WAVE file of {channels} channels at {} Hz",
110                audio.sample_rate
111            )));
112        }
113        let (channel_mask, _) = wave_channel_layout(&speakers)?;
114        Ok(Self {
115            sample_rate: audio.sample_rate,
116            channels: u16::try_from(channels).unwrap_or(u16::MAX),
117            bits: pcm.bits,
118            float,
119            channel_mask,
120        })
121    }
122
123    const fn format_tag(&self) -> u16 {
124        if self.float {
125            WAVE_FORMAT_IEEE_FLOAT
126        } else {
127            WAVE_FORMAT_PCM
128        }
129    }
130
131    const fn overhead(&self) -> u32 {
132        if self.channel_mask.is_some() {
133            EXTENSIBLE_OVERHEAD
134        } else {
135            PLAIN_OVERHEAD
136        }
137    }
138
139    const fn block_align(&self) -> u16 {
140        self.channels.saturating_mul(self.bits / 8)
141    }
142
143    fn header(&self, data_bytes: u32) -> Vec<u8> {
144        let riff_size = data_bytes.saturating_add(self.overhead());
145        let block_align = self.block_align();
146        let byte_rate = self.sample_rate.saturating_mul(u32::from(block_align));
147        let mut header = Vec::with_capacity(68);
148        header.extend_from_slice(b"RIFF");
149        header.extend_from_slice(&riff_size.to_le_bytes());
150        header.extend_from_slice(b"WAVEfmt ");
151        let (fmt_size, tag) = match self.channel_mask {
152            Some(_) => (40_u32, WAVE_FORMAT_EXTENSIBLE),
153            None => (16, self.format_tag()),
154        };
155        header.extend_from_slice(&fmt_size.to_le_bytes());
156        header.extend_from_slice(&tag.to_le_bytes());
157        header.extend_from_slice(&self.channels.to_le_bytes());
158        header.extend_from_slice(&self.sample_rate.to_le_bytes());
159        header.extend_from_slice(&byte_rate.to_le_bytes());
160        header.extend_from_slice(&block_align.to_le_bytes());
161        header.extend_from_slice(&self.bits.to_le_bytes());
162        if let Some(mask) = self.channel_mask {
163            header.extend_from_slice(&22_u16.to_le_bytes());
164            header.extend_from_slice(&self.bits.to_le_bytes());
165            header.extend_from_slice(&mask.to_le_bytes());
166            header.extend_from_slice(&self.format_tag().to_le_bytes());
167            header.extend_from_slice(&KSDATAFORMAT_SUBTYPE_TAIL);
168        }
169        header.extend_from_slice(b"data");
170        header.extend_from_slice(&data_bytes.to_le_bytes());
171        header
172    }
173}
174
175trait Sink: Write + Seek + Send {}
176
177impl<W: Write + Seek + Send> Sink for W {}
178
179/// A writer of one PCM track into a RIFF WAVE file.
180///
181/// Packets carry interleaved frames in the order [`wave_channel_layout`] gives, each starting
182/// where the last ended.
183pub struct WavWriter {
184    sink: Box<dyn Sink>,
185    format: Option<Format>,
186    data_bytes: u32,
187    frames: i64,
188}
189
190impl WavWriter {
191    /// A writer into `file`, open for writing.
192    #[must_use]
193    pub fn create(file: std::fs::File) -> Self {
194        Self::new(BufWriter::with_capacity(WRITE_BUFFER_BYTES, file))
195    }
196
197    /// A writer into any writable and seekable `sink`, starting at its offset 0.
198    pub fn new<W: Write + Seek + Send + 'static>(sink: W) -> Self {
199        Self {
200            sink: Box::new(sink),
201            format: None,
202            data_bytes: 0,
203            frames: 0,
204        }
205    }
206}
207
208impl ContainerWriter for WavWriter {
209    fn add_track(&mut self, track: &TrackInfo) -> Result<TrackId, MuxError> {
210        if self.format.is_some() {
211            return Err(MuxError::Invalid("a WAVE file holds one track".into()));
212        }
213        let format = Format::of(track)?;
214        self.sink.seek(SeekFrom::Start(0))?;
215        self.sink.write_all(&format.header(0))?;
216        self.format = Some(format);
217        Ok(TrackId(1))
218    }
219
220    fn write(&mut self, packet: Packet) -> Result<(), MuxError> {
221        let format = self
222            .format
223            .ok_or_else(|| MuxError::Invalid("a packet before the track".into()))?;
224        if packet.track != TrackId(1) {
225            return Err(MuxError::Invalid(format!(
226                "a packet of track {} in a WAVE file",
227                packet.track.0
228            )));
229        }
230        let align = usize::from(format.block_align());
231        if !packet.data.len().is_multiple_of(align) {
232            return Err(MuxError::Invalid(format!(
233                "{} bytes are not whole frames of {align}",
234                packet.data.len()
235            )));
236        }
237        if packet.pts != self.frames {
238            return Err(MuxError::Invalid(format!(
239                "a packet at sample {} after {} samples",
240                packet.pts, self.frames
241            )));
242        }
243        let data_bytes = u32::try_from(packet.data.len())
244            .ok()
245            .and_then(|bytes| self.data_bytes.checked_add(bytes))
246            .filter(|bytes| bytes.checked_add(format.overhead()).is_some())
247            .ok_or_else(|| {
248                MuxError::Unsupported(format!(
249                    "{} frames of {} channels are more than the 4 GiB a WAVE file holds",
250                    self.frames + i64::try_from(packet.data.len() / align).unwrap_or(i64::MAX),
251                    format.channels
252                ))
253            })?;
254        self.sink.write_all(&packet.data)?;
255        self.data_bytes = data_bytes;
256        self.frames += i64::try_from(packet.data.len() / align).unwrap_or(i64::MAX);
257        Ok(())
258    }
259
260    fn finish(mut self: Box<Self>) -> Result<(), MuxError> {
261        let format = self
262            .format
263            .ok_or_else(|| MuxError::Invalid("a WAVE file without its track".into()))?;
264        self.sink.seek(SeekFrom::Start(0))?;
265        self.sink.write_all(&format.header(self.data_bytes))?;
266        self.sink.flush()?;
267        Ok(())
268    }
269}