edith_codecs
Clone
https://git.tahinli.com/Tahinli/edith_codecs.git
0 watching·0 forks·Rust·370.3 MiB·68cf7a6·Tahinli·2 months ago·2975 commits
| 1 | //! Streaming WAVE writer. |
| 2 | |
| 3 | use std::fs::File; |
| 4 | use std::io::{BufWriter, Seek, SeekFrom, Write}; |
| 5 | use std::path::Path; |
| 6 | |
| 7 | use ec_core::{Error, Result}; |
| 8 | |
| 9 | use crate::{FORMAT_EXTENSIBLE, SampleType, WavSpec}; |
| 10 | |
| 11 | /// A sample a [`WavWriter`] accepts. |
| 12 | /// |
| 13 | /// Integer types write to integer files and `f32` writes to float files; the |
| 14 | /// crossing combinations are refused rather than guessed at, because the scale |
| 15 | /// factor between them is a decision the caller owns. |
| 16 | pub trait Sample: Copy { |
| 17 | /// True for the float carriers. |
| 18 | const FLOAT: bool; |
| 19 | /// The value as a 32-bit integer, at the file's own depth. |
| 20 | fn as_i32(self) -> i32; |
| 21 | /// The value as an `f32`. |
| 22 | fn as_f32(self) -> f32; |
| 23 | } |
| 24 | |
| 25 | macro_rules! int_sample { |
| 26 | ($($t:ty),*) => {$( |
| 27 | impl Sample for $t { |
| 28 | const FLOAT: bool = false; |
| 29 | fn as_i32(self) -> i32 { |
| 30 | i32::from(self) |
| 31 | } |
| 32 | fn as_f32(self) -> f32 { |
| 33 | self as f32 |
| 34 | } |
| 35 | } |
| 36 | )*}; |
| 37 | } |
| 38 | int_sample!(i8, i16); |
| 39 | |
| 40 | impl Sample for i32 { |
| 41 | const FLOAT: bool = false; |
| 42 | fn as_i32(self) -> i32 { |
| 43 | self |
| 44 | } |
| 45 | fn as_f32(self) -> f32 { |
| 46 | self as f32 |
| 47 | } |
| 48 | } |
| 49 | |
| 50 | impl Sample for f32 { |
| 51 | const FLOAT: bool = true; |
| 52 | fn as_i32(self) -> i32 { |
| 53 | self as i32 |
| 54 | } |
| 55 | fn as_f32(self) -> f32 { |
| 56 | self |
| 57 | } |
| 58 | } |
| 59 | |
| 60 | /// Writes a WAVE file sample by sample, patching the sizes in [`Self::finalize`]. |
| 61 | /// |
| 62 | /// Samples are interleaved in channel order: one call per channel per frame. |
| 63 | pub struct WavWriter<W: Write + Seek> { |
| 64 | /// `None` only after [`WavWriter::finalize`] has taken it, which is also |
| 65 | /// what tells `Drop` there is nothing left to patch. |
| 66 | inner: Option<W>, |
| 67 | spec: WavSpec, |
| 68 | /// Absolute offset of the `RIFF` size field. |
| 69 | riff_size_pos: u64, |
| 70 | /// Absolute offset of the `fact` sample-count field, when one was written. |
| 71 | fact_pos: Option<u64>, |
| 72 | /// Absolute offset of the `data` size field. |
| 73 | data_size_pos: u64, |
| 74 | /// Samples (not frames) written so far. |
| 75 | samples: u64, |
| 76 | } |
| 77 | |
| 78 | impl WavWriter<BufWriter<File>> { |
| 79 | /// Create `path`, truncating it, and write the header for `spec`. |
| 80 | pub fn create<P: AsRef<Path>>(path: P, spec: WavSpec) -> Result<Self> { |
| 81 | WavWriter::new(BufWriter::new(File::create(path)?), spec) |
| 82 | } |
| 83 | } |
| 84 | |
| 85 | impl<W: Write + Seek> WavWriter<W> { |
| 86 | /// Write the header for `spec` at the writer's current position. |
| 87 | pub fn new(mut inner: W, spec: WavSpec) -> Result<Self> { |
| 88 | spec.validate()?; |
| 89 | let start = inner.stream_position()?; |
| 90 | let extensible = spec.is_extensible(); |
| 91 | let fmt_len: u32 = if extensible { 40 } else { 16 }; |
| 92 | let mut h: Vec<u8> = Vec::with_capacity(60); |
| 93 | |
| 94 | h.extend_from_slice(b"RIFF"); |
| 95 | let riff_size_pos = start + h.len() as u64; |
| 96 | h.extend_from_slice(&0u32.to_le_bytes()); // patched by finalize |
| 97 | h.extend_from_slice(b"WAVE"); |
| 98 | |
| 99 | h.extend_from_slice(b"fmt "); |
| 100 | h.extend_from_slice(&fmt_len.to_le_bytes()); |
| 101 | let tag = if extensible { |
| 102 | FORMAT_EXTENSIBLE |
| 103 | } else { |
| 104 | spec.format_tag() |
| 105 | }; |
| 106 | let block_align = spec.block_align() as u32; |
| 107 | h.extend_from_slice(&tag.to_le_bytes()); |
| 108 | h.extend_from_slice(&spec.channels.to_le_bytes()); |
| 109 | h.extend_from_slice(&spec.sample_rate.to_le_bytes()); |
| 110 | h.extend_from_slice(&(spec.sample_rate * block_align).to_le_bytes()); |
| 111 | h.extend_from_slice(&(block_align as u16).to_le_bytes()); |
| 112 | h.extend_from_slice(&spec.bits_per_sample.to_le_bytes()); |
| 113 | if extensible { |
| 114 | h.extend_from_slice(&22u16.to_le_bytes()); // cbSize |
| 115 | h.extend_from_slice(&spec.bits_per_sample.to_le_bytes()); // valid bits |
| 116 | h.extend_from_slice(&spec.channel_mask().to_le_bytes()); |
| 117 | // KSDATAFORMAT_SUBTYPE_{PCM,IEEE_FLOAT}: the tag, then the fixed |
| 118 | // `0000-0010-8000-00aa00389b71` tail every WAVE sub-format shares. |
| 119 | h.extend_from_slice(&spec.format_tag().to_le_bytes()); |
| 120 | h.extend_from_slice(&[0x00, 0x00, 0x00, 0x00, 0x10, 0x00, 0x80, 0x00]); |
| 121 | h.extend_from_slice(&[0x00, 0xaa, 0x00, 0x38, 0x9b, 0x71]); |
| 122 | } |
| 123 | |
| 124 | // A `fact` chunk is required for every non-PCM tag and harmless for the |
| 125 | // extensible PCM one; it holds the frame count, which finalize knows. |
| 126 | let fact_pos = if extensible || spec.sample_format == SampleType::Float { |
| 127 | h.extend_from_slice(b"fact"); |
| 128 | h.extend_from_slice(&4u32.to_le_bytes()); |
| 129 | let pos = start + h.len() as u64; |
| 130 | h.extend_from_slice(&0u32.to_le_bytes()); |
| 131 | Some(pos) |
| 132 | } else { |
| 133 | None |
| 134 | }; |
| 135 | |
| 136 | h.extend_from_slice(b"data"); |
| 137 | let data_size_pos = start + h.len() as u64; |
| 138 | h.extend_from_slice(&0u32.to_le_bytes()); |
| 139 | inner.write_all(&h)?; |
| 140 | |
| 141 | Ok(WavWriter { |
| 142 | inner: Some(inner), |
| 143 | spec, |
| 144 | riff_size_pos, |
| 145 | fact_pos, |
| 146 | data_size_pos, |
| 147 | samples: 0, |
| 148 | }) |
| 149 | } |
| 150 | |
| 151 | /// The stream being written; present until `finalize` takes it. |
| 152 | fn w(&mut self) -> &mut W { |
| 153 | self.inner.as_mut().expect("WavWriter used after finalize") |
| 154 | } |
| 155 | |
| 156 | /// The spec the header was written with. |
| 157 | pub fn spec(&self) -> WavSpec { |
| 158 | self.spec |
| 159 | } |
| 160 | |
| 161 | /// Frames (one sample per channel) written so far. |
| 162 | pub fn duration(&self) -> u64 { |
| 163 | self.samples / u64::from(self.spec.channels) |
| 164 | } |
| 165 | |
| 166 | /// Write one sample of one channel. |
| 167 | pub fn write_sample<S: Sample>(&mut self, sample: S) -> Result<()> { |
| 168 | let bits = self.spec.bits_per_sample; |
| 169 | match self.spec.sample_format { |
| 170 | SampleType::Float => { |
| 171 | if !S::FLOAT { |
| 172 | return Err(Error::unsupported( |
| 173 | "integer samples into a float WAVE file", |
| 174 | "the integer-to-float scale factor is the caller's decision", |
| 175 | )); |
| 176 | } |
| 177 | self.w().write_all(&sample.as_f32().to_le_bytes())?; |
| 178 | } |
| 179 | SampleType::Int => { |
| 180 | if S::FLOAT { |
| 181 | return Err(Error::unsupported( |
| 182 | "float samples into an integer WAVE file", |
| 183 | "the float-to-integer scale factor is the caller's decision", |
| 184 | )); |
| 185 | } |
| 186 | let v = sample.as_i32(); |
| 187 | let limit = 1i64 << (bits - 1); |
| 188 | if i64::from(v) < -limit || i64::from(v) >= limit { |
| 189 | return Err(Error::corrupt(format!( |
| 190 | "sample {v} does not fit {bits} bits" |
| 191 | ))); |
| 192 | } |
| 193 | match bits { |
| 194 | // 8-bit WAVE is unsigned, biased by 128. |
| 195 | 8 => self.w().write_all(&[(v + 128) as u8])?, |
| 196 | 16 => self.w().write_all(&(v as i16).to_le_bytes())?, |
| 197 | 24 => self.w().write_all(&v.to_le_bytes()[..3])?, |
| 198 | _ => self.w().write_all(&v.to_le_bytes())?, |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | self.samples += 1; |
| 203 | Ok(()) |
| 204 | } |
| 205 | |
| 206 | /// Write a run of interleaved samples. |
| 207 | pub fn write_samples<S: Sample>(&mut self, samples: &[S]) -> Result<()> { |
| 208 | for &s in samples { |
| 209 | self.write_sample(s)?; |
| 210 | } |
| 211 | Ok(()) |
| 212 | } |
| 213 | |
| 214 | /// Pad to an even boundary, patch the sizes, flush, and hand the stream back. |
| 215 | /// |
| 216 | /// Dropping instead patches on a best-effort basis and swallows the error; |
| 217 | /// only this reports the difference between a finished file and a truncated |
| 218 | /// one, which is why it exists next to `Drop`. |
| 219 | pub fn finalize(mut self) -> Result<W> { |
| 220 | if !self.samples.is_multiple_of(u64::from(self.spec.channels)) { |
| 221 | return Err(Error::corrupt(format!( |
| 222 | "{} samples is not a whole number of {}-channel frames", |
| 223 | self.samples, self.spec.channels |
| 224 | ))); |
| 225 | } |
| 226 | self.patch()?; |
| 227 | self.w().flush()?; |
| 228 | Ok(self.inner.take().expect("WavWriter finalized twice")) |
| 229 | } |
| 230 | |
| 231 | /// The size patching both `finalize` and `Drop` go through. |
| 232 | fn patch(&mut self) -> Result<()> { |
| 233 | let data_bytes = self.samples * self.spec.bytes_per_sample() as u64; |
| 234 | let end = self.data_size_pos + 4 + data_bytes; |
| 235 | // RIFF chunks are word-aligned: an odd `data` gets a pad byte that its |
| 236 | // own size field does not count. |
| 237 | let pad = data_bytes % 2; |
| 238 | let riff_size = end + pad - (self.riff_size_pos + 4); |
| 239 | if riff_size > u64::from(u32::MAX) { |
| 240 | return Err(Error::unsupported( |
| 241 | "a WAVE file larger than 4 GiB", |
| 242 | "the 64-bit RF64/BW64 extension is not implemented", |
| 243 | )); |
| 244 | } |
| 245 | let (riff_pos, data_pos) = (self.riff_size_pos, self.data_size_pos); |
| 246 | let fact = self |
| 247 | .fact_pos |
| 248 | .map(|pos| (pos, (self.samples / u64::from(self.spec.channels)) as u32)); |
| 249 | let w = self.w(); |
| 250 | if pad == 1 { |
| 251 | w.seek(SeekFrom::Start(end))?; |
| 252 | w.write_all(&[0])?; |
| 253 | } |
| 254 | w.seek(SeekFrom::Start(riff_pos))?; |
| 255 | w.write_all(&(riff_size as u32).to_le_bytes())?; |
| 256 | if let Some((pos, frames)) = fact { |
| 257 | w.seek(SeekFrom::Start(pos))?; |
| 258 | w.write_all(&frames.to_le_bytes())?; |
| 259 | } |
| 260 | w.seek(SeekFrom::Start(data_pos))?; |
| 261 | w.write_all(&(data_bytes as u32).to_le_bytes())?; |
| 262 | w.seek(SeekFrom::Start(end + pad))?; |
| 263 | Ok(()) |
| 264 | } |
| 265 | } |
| 266 | |
| 267 | impl<W: Write + Seek> Drop for WavWriter<W> { |
| 268 | fn drop(&mut self) { |
| 269 | if self.inner.is_some() { |
| 270 | let _ = self.patch(); |
| 271 | let _ = self.w().flush(); |
| 272 | } |
| 273 | } |
| 274 | } |