forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

write.rs359 lines, 13.1 KiBHistoryRawDownload
1//! Streaming WAVE writer.
2
3use std::fs::File;
4use std::io::{BufWriter, Seek, SeekFrom, Write};
5use std::path::Path;
6
7use ec_core::{Error, Result};
8
9use crate::{FORMAT_EXTENSIBLE, SampleType, WavSpec};
10
11/// Data bytes at or above which [`WavWriter`] writes an RF64 header instead of
12/// RIFF: the 32-bit size fields cannot hold them. The margin below `u32::MAX`
13/// is the room the RIFF header and a pad byte take up, so a RIFF file never
14/// reaches the limit it would then overflow.
15pub const RF64_THRESHOLD: u64 = 0xFFFF_F000;
16
17/// What the header needs to know before the first sample is written.
18#[derive(Debug, Clone, Copy, PartialEq, Eq)]
19pub struct WavOptions {
20 /// Frames the caller will write. The header's container is chosen from it,
21 /// since a RIFF header cannot be turned into an RF64 one after the fact.
22 /// `0` means unknown, which keeps RIFF; a file that then grows past the
23 /// 32-bit limit is refused at finalize.
24 pub expected_frames: u64,
25 /// Data bytes at or above which the header is RF64. Defaults to
26 /// [`RF64_THRESHOLD`]; tests lower it to exercise the RF64 path cheaply.
27 pub rf64_threshold: u64,
28}
29
30impl Default for WavOptions {
31 fn default() -> Self {
32 WavOptions {
33 expected_frames: 0,
34 rf64_threshold: RF64_THRESHOLD,
35 }
36 }
37}
38
39/// Size of a `ds64` chunk body with an empty table: riffSize, dataSize,
40/// sampleCount (three u64) and tableLength (u32).
41const DS64_LEN: u32 = 28;
42
43/// A sample a [`WavWriter`] accepts.
44///
45/// Integer types write to integer files and `f32` writes to float files; the
46/// crossing combinations are refused rather than guessed at, because the scale
47/// factor between them is a decision the caller owns.
48pub trait Sample: Copy {
49 /// True for the float carriers.
50 const FLOAT: bool;
51 /// The value as a 32-bit integer, at the file's own depth.
52 fn as_i32(self) -> i32;
53 /// The value as an `f32`.
54 fn as_f32(self) -> f32;
55}
56
57macro_rules! int_sample {
58 ($($t:ty),*) => {$(
59 impl Sample for $t {
60 const FLOAT: bool = false;
61 fn as_i32(self) -> i32 {
62 i32::from(self)
63 }
64 fn as_f32(self) -> f32 {
65 self as f32
66 }
67 }
68 )*};
69}
70int_sample!(i8, i16);
71
72impl Sample for i32 {
73 const FLOAT: bool = false;
74 fn as_i32(self) -> i32 {
75 self
76 }
77 fn as_f32(self) -> f32 {
78 self as f32
79 }
80}
81
82impl Sample for f32 {
83 const FLOAT: bool = true;
84 fn as_i32(self) -> i32 {
85 self as i32
86 }
87 fn as_f32(self) -> f32 {
88 self
89 }
90}
91
92/// Writes a WAVE file sample by sample, patching the sizes in [`Self::finalize`].
93///
94/// Samples are interleaved in channel order: one call per channel per frame.
95pub struct WavWriter<W: Write + Seek> {
96 /// `None` only after [`WavWriter::finalize`] has taken it, which is also
97 /// what tells `Drop` there is nothing left to patch.
98 inner: Option<W>,
99 spec: WavSpec,
100 /// Absolute offset of the `RIFF` size field.
101 riff_size_pos: u64,
102 /// Absolute offset of the `fact` sample-count field, when one was written.
103 fact_pos: Option<u64>,
104 /// Absolute offset of the `data` size field.
105 data_size_pos: u64,
106 /// Absolute offset of the `ds64` body when the header is RF64; the 64-bit
107 /// sizes are patched there, and the 32-bit fields stay at `0xFFFFFFFF`.
108 ds64_pos: Option<u64>,
109 /// Samples (not frames) written so far.
110 samples: u64,
111}
112
113impl WavWriter<BufWriter<File>> {
114 /// Create `path`, truncating it, and write the header for `spec`.
115 pub fn create<P: AsRef<Path>>(path: P, spec: WavSpec) -> Result<Self> {
116 WavWriter::create_with_options(path, spec, WavOptions::default())
117 }
118
119 /// [`WavWriter::create`] with the header choices in `options`.
120 pub fn create_with_options<P: AsRef<Path>>(
121 path: P,
122 spec: WavSpec,
123 options: WavOptions,
124 ) -> Result<Self> {
125 WavWriter::with_options(BufWriter::new(File::create(path)?), spec, options)
126 }
127}
128
129impl<W: Write + Seek> WavWriter<W> {
130 /// Write the header for `spec` at the writer's current position, as RIFF.
131 pub fn new(inner: W, spec: WavSpec) -> Result<Self> {
132 WavWriter::with_options(inner, spec, WavOptions::default())
133 }
134
135 /// Write the header for `spec` at the writer's current position. The
136 /// container (RIFF or RF64) follows `options.expected_frames`.
137 pub fn with_options(mut inner: W, spec: WavSpec, options: WavOptions) -> Result<Self> {
138 spec.validate()?;
139 let start = inner.stream_position()?;
140 let extensible = spec.is_extensible();
141 let fmt_len: u32 = if extensible { 40 } else { 16 };
142 let mut h: Vec<u8> = Vec::with_capacity(100);
143
144 let expected_data = options
145 .expected_frames
146 .saturating_mul(spec.block_align() as u64);
147 let rf64 = expected_data >= options.rf64_threshold;
148 let ds64_pos = if rf64 {
149 h.extend_from_slice(b"RF64");
150 h.extend_from_slice(&u32::MAX.to_le_bytes()); // the size is ds64's
151 h.extend_from_slice(b"WAVE");
152 h.extend_from_slice(b"ds64");
153 h.extend_from_slice(&DS64_LEN.to_le_bytes());
154 let pos = start + h.len() as u64;
155 h.extend_from_slice(&[0u8; DS64_LEN as usize]); // patched by finalize
156 Some(pos)
157 } else {
158 h.extend_from_slice(b"RIFF");
159 h.extend_from_slice(&0u32.to_le_bytes()); // patched by finalize
160 h.extend_from_slice(b"WAVE");
161 None
162 };
163 let riff_size_pos = start + 4;
164
165 h.extend_from_slice(b"fmt ");
166 h.extend_from_slice(&fmt_len.to_le_bytes());
167 let tag = if extensible {
168 FORMAT_EXTENSIBLE
169 } else {
170 spec.format_tag()
171 };
172 let block_align = spec.block_align() as u32;
173 h.extend_from_slice(&tag.to_le_bytes());
174 h.extend_from_slice(&spec.channels.to_le_bytes());
175 h.extend_from_slice(&spec.sample_rate.to_le_bytes());
176 h.extend_from_slice(&(spec.sample_rate * block_align).to_le_bytes());
177 h.extend_from_slice(&(block_align as u16).to_le_bytes());
178 h.extend_from_slice(&spec.bits_per_sample.to_le_bytes());
179 if extensible {
180 h.extend_from_slice(&22u16.to_le_bytes()); // cbSize
181 h.extend_from_slice(&spec.bits_per_sample.to_le_bytes()); // valid bits
182 h.extend_from_slice(&spec.channel_mask().to_le_bytes());
183 // KSDATAFORMAT_SUBTYPE_{PCM,IEEE_FLOAT}: the tag, then the fixed
184 // `0000-0010-8000-00aa00389b71` tail every WAVE sub-format shares.
185 h.extend_from_slice(&spec.format_tag().to_le_bytes());
186 h.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00]);
187 h.extend_from_slice(&[0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]);
188 }
189
190 // A `fact` chunk is required for every non-PCM tag and harmless for the
191 // extensible PCM one; it holds the frame count, which finalize knows.
192 let fact_pos = if extensible || spec.sample_format == SampleType::Float {
193 h.extend_from_slice(b"fact");
194 h.extend_from_slice(&4u32.to_le_bytes());
195 let pos = start + h.len() as u64;
196 h.extend_from_slice(&0u32.to_le_bytes());
197 Some(pos)
198 } else {
199 None
200 };
201
202 h.extend_from_slice(b"data");
203 let data_size_pos = start + h.len() as u64;
204 // RF64 keeps the 32-bit data size at its sentinel; ds64 has the real one.
205 let data_placeholder = if rf64 { u32::MAX } else { 0 };
206 h.extend_from_slice(&data_placeholder.to_le_bytes());
207 inner.write_all(&h)?;
208
209 Ok(WavWriter {
210 inner: Some(inner),
211 spec,
212 riff_size_pos,
213 fact_pos,
214 data_size_pos,
215 ds64_pos,
216 samples: 0,
217 })
218 }
219
220 /// The stream being written; present until `finalize` takes it.
221 fn w(&mut self) -> &mut W {
222 self.inner.as_mut().expect("WavWriter used after finalize")
223 }
224
225 /// The spec the header was written with.
226 pub fn spec(&self) -> WavSpec {
227 self.spec
228 }
229
230 /// Frames (one sample per channel) written so far.
231 pub fn duration(&self) -> u64 {
232 self.samples / u64::from(self.spec.channels)
233 }
234
235 /// Write one sample of one channel.
236 pub fn write_sample<S: Sample>(&mut self, sample: S) -> Result<()> {
237 let bits = self.spec.bits_per_sample;
238 match self.spec.sample_format {
239 SampleType::Float => {
240 if !S::FLOAT {
241 return Err(Error::unsupported(
242 "integer samples into a float WAVE file",
243 "the integer-to-float scale factor is the caller's decision",
244 ));
245 }
246 self.w().write_all(&sample.as_f32().to_le_bytes())?;
247 }
248 SampleType::Int => {
249 if S::FLOAT {
250 return Err(Error::unsupported(
251 "float samples into an integer WAVE file",
252 "the float-to-integer scale factor is the caller's decision",
253 ));
254 }
255 let v = sample.as_i32();
256 let limit = 1i64 << (bits - 1);
257 if i64::from(v) < -limit || i64::from(v) >= limit {
258 return Err(Error::corrupt(format!(
259 "sample {v} does not fit {bits} bits"
260 )));
261 }
262 match bits {
263 // 8-bit WAVE is unsigned, biased by 128.
264 8 => self.w().write_all(&[(v + 128) as u8])?,
265 16 => self.w().write_all(&(v as i16).to_le_bytes())?,
266 24 => self.w().write_all(&v.to_le_bytes()[..3])?,
267 _ => self.w().write_all(&v.to_le_bytes())?,
268 }
269 }
270 }
271 self.samples += 1;
272 Ok(())
273 }
274
275 /// Write a run of interleaved samples.
276 pub fn write_samples<S: Sample>(&mut self, samples: &[S]) -> Result<()> {
277 for &s in samples {
278 self.write_sample(s)?;
279 }
280 Ok(())
281 }
282
283 /// Pad to an even boundary, patch the sizes, flush, and hand the stream back.
284 ///
285 /// Dropping instead patches on a best-effort basis and swallows the error;
286 /// only this reports the difference between a finished file and a truncated
287 /// one, which is why it exists next to `Drop`.
288 pub fn finalize(mut self) -> Result<W> {
289 if !self.samples.is_multiple_of(u64::from(self.spec.channels)) {
290 return Err(Error::corrupt(format!(
291 "{} samples is not a whole number of {}-channel frames",
292 self.samples, self.spec.channels
293 )));
294 }
295 self.patch()?;
296 self.w().flush()?;
297 Ok(self.inner.take().expect("WavWriter finalized twice"))
298 }
299
300 /// The size patching both `finalize` and `Drop` go through.
301 fn patch(&mut self) -> Result<()> {
302 let data_bytes = self.samples * self.spec.bytes_per_sample() as u64;
303 let end = self.data_size_pos + 4 + data_bytes;
304 // RIFF chunks are word-aligned: an odd `data` gets a pad byte that its
305 // own size field does not count.
306 let pad = data_bytes % 2;
307 let riff_size = end + pad - (self.riff_size_pos + 4);
308 let frames = self.samples / u64::from(self.spec.channels);
309 if self.ds64_pos.is_none() && riff_size > u64::from(u32::MAX) {
310 return Err(Error::unsupported(
311 "a RIFF WAVE file larger than 4 GiB",
312 "the writer took no expected length, so it wrote RIFF; \
313 give WavOptions::expected_frames to get RF64",
314 ));
315 }
316 let (riff_pos, data_pos) = (self.riff_size_pos, self.data_size_pos);
317 // The `fact` field is 32 bits in both containers; RF64 keeps the full
318 // count in ds64, so past 2^32 frames this field saturates.
319 let fact = self
320 .fact_pos
321 .map(|pos| (pos, frames.min(u64::from(u32::MAX)) as u32));
322 let ds64 = self.ds64_pos;
323 let w = self.w();
324 if pad == 1 {
325 w.seek(SeekFrom::Start(end))?;
326 w.write_all(&[0])?;
327 }
328 match ds64 {
329 Some(pos) => {
330 w.seek(SeekFrom::Start(pos))?;
331 w.write_all(&riff_size.to_le_bytes())?;
332 w.write_all(&data_bytes.to_le_bytes())?;
333 w.write_all(&frames.to_le_bytes())?;
334 // tableLength stays 0: no extra 64-bit sizes to record.
335 }
336 None => {
337 w.seek(SeekFrom::Start(riff_pos))?;
338 w.write_all(&(riff_size as u32).to_le_bytes())?;
339 w.seek(SeekFrom::Start(data_pos))?;
340 w.write_all(&(data_bytes as u32).to_le_bytes())?;
341 }
342 }
343 if let Some((pos, frames)) = fact {
344 w.seek(SeekFrom::Start(pos))?;
345 w.write_all(&frames.to_le_bytes())?;
346 }
347 w.seek(SeekFrom::Start(end + pad))?;
348 Ok(())
349 }
350}
351
352impl<W: Write + Seek> Drop for WavWriter<W> {
353 fn drop(&mut self) {
354 if self.inner.is_some() {
355 let _ = self.patch();
356 let _ = self.w().flush();
357 }
358 }
359}