Oregami
Repositories/oxedyne/fe2o3

oxedyne/fe2o3/fe2o3_graphics/src/wav.rs

7.8 KiB, 7 runs

created by r352662578:79646, which is this file's identity for as long as the history lasts, whatever it is later renamed to

download · who wrote it · its history

1//! WAV read to and written from planar samples, for a caller that measures or changes the sound.
2//!
3//! Read: integer PCM of 8, 16, 24 or 32 bits and IEEE float of 32 or 64, plain or as WAVE_FORMAT_EXTENSIBLE naming one of
4//! the two, each sample scaled to -1.0..1.0. A `data` length of 0xFFFFFFFF, as a recorder writes while it streams, or one
5//! past the file's end, is the bytes there are. Any other coding (ADPCM, A-law) is refused by its format tag.
6//! Written: 16 or 24-bit integer or 32-bit float PCM, clipped to the range and rounded to the nearest step.
7//! Resampled: to any rate, by a windowed sinc low-passed below the lower rate's half.
8
9use oxedyne_fe2o3_core::prelude::*;
10
11
12const TAPS: i64 = 32; // sinc taps either side of a resampled point, at a cut-off of the full band
13
14
15/// How a WAV's samples are coded.
16#[derive(Clone, Copy, Debug, PartialEq, Eq)]
17pub enum Pcm {
18 Int(u16), // signed integer of the given bits (8-bit WAV is unsigned on disk)
19 Float(u16), // IEEE float of 32 or 64 bits
20}
21
22impl Pcm {
23 /// ffmpeg's name for the coding, as ffprobe gives it.
24 pub fn name(&self) -> &'static str {
25 match self {
26 Self::Int(8) => "pcm_u8",
27 Self::Int(16) => "pcm_s16le",
28 Self::Int(24) => "pcm_s24le",
29 Self::Int(_) => "pcm_s32le",
30 Self::Float(32) => "pcm_f32le",
31 Self::Float(_) => "pcm_f64le",
32 }
33 }
34
35 pub fn bits(&self) -> u16 {
36 match self {
37 Self::Int(b) => *b,
38 Self::Float(b) => *b,
39 }
40 }
41}
42
43/// A sound held as one vector of samples a channel.
44#[derive(Clone, Debug, PartialEq)]
45pub struct Wav {
46 pub rate: u32,
47 pub pcm: Pcm,
48 pub chans: Vec<Vec<f32>>,
49}
50
51impl Wav {
52
53 pub fn frames(&self) -> usize {
54 self.chans.first().map_or(0, Vec::len)
55 }
56
57 pub fn secs(&self) -> f64 {
58 self.frames() as f64 / self.rate.max(1) as f64
59 }
60
61 pub fn read(b: &[u8]) -> Outcome<Self> {
62 if b.len() < 12 || &b[0..4] != b"RIFF" || &b[8..12] != b"WAVE" {
63 return Err(err!("The file is not a WAV: it does not begin RIFF...WAVE."; Invalid, Input, Decode));
64 }
65 let le16 = |i: usize| b.get(i..i + 2).map(|x| u16::from_le_bytes([x[0], x[1]]));
66 let le32 = |i: usize| b.get(i..i + 4).map(|x| u32::from_le_bytes([x[0], x[1], x[2], x[3]]));
67 let (mut i, mut fmt) = (12usize, None);
68 while i + 8 <= b.len() {
69 let n = res!(le32(i + 4).ok_or_else(|| err!("A WAV chunk header is cut short."; Invalid, Input, Decode))) as usize;
70 match &b[i..i + 4] {
71 b"fmt " => {
72 let f = |k: usize| le16(i + 8 + k).ok_or_else(|| err!("The WAV's fmt chunk is cut short."; Invalid, Input, Decode));
73 let (mut tag, chans, bits) = (res!(f(0)), res!(f(2)), res!(f(14)));
74 let rate = res!(le32(i + 12).ok_or_else(|| err!("The WAV's fmt chunk is cut short."; Invalid, Input, Decode)));
75 if tag == 0xFFFE {
76 tag = res!(f(24)); // the sub-format GUID's first two bytes
77 }
78 let pcm = match (tag, bits) {
79 (1, 8 | 16 | 24 | 32) => Pcm::Int(bits),
80 (3, 32 | 64) => Pcm::Float(bits),
81 _ => return Err(err!("The WAV is coded as format {} at {} bits, which is \
82 not PCM or float.", tag, bits; Invalid, Input, Unimplemented)),
83 };
84 if chans == 0 || rate == 0 {
85 return Err(err!("The WAV states {} channels at {} Hz.", chans, rate; Invalid, Input, Decode));
86 }
87 fmt = Some((pcm, chans as usize, rate));
88 },
89 b"data" => {
90 let (pcm, nc, rate) = res!(fmt.ok_or_else(|| err!("The WAV's data comes before its fmt chunk."; Invalid, Input, Decode)));
91 let d = &b[i + 8..(i + 8).saturating_add(n).min(b.len())];
92 let w = pcm.bits() as usize / 8;
93 let frames = d.len() / (w * nc);
94 let mut chans = vec![Vec::with_capacity(frames); nc];
95 for f in 0..frames {
96 for (c, ch) in chans.iter_mut().enumerate() {
97 let s = &d[(f * nc + c) * w..][..w];
98 ch.push(match pcm {
99 Pcm::Int(8) => (s[0] as f32 - 128.0) / 128.0,
100 Pcm::Int(16) => i16::from_le_bytes([s[0], s[1]]) as f32 / 32768.0,
101 Pcm::Int(24) => (i32::from_le_bytes([0, s[0], s[1], s[2]]) >> 8) as f32 / 8_388_608.0,
102 Pcm::Int(_) => i32::from_le_bytes([s[0], s[1], s[2], s[3]]) as f32 / 2_147_483_648.0,
103 Pcm::Float(32) => f32::from_le_bytes([s[0], s[1], s[2], s[3]]),
104 Pcm::Float(_) => f64::from_le_bytes([s[0], s[1], s[2], s[3], s[4], s[5], s[6], s[7]]) as f32,
105 });
106 }
107 }
108 return Ok(Self { rate, pcm, chans });
109 },
110 _ => {},
111 }
112 i += 8 + n + (n & 1);
113 }
114 Err(err!("The WAV has no data chunk."; Invalid, Input, Missing))
115 }
116
117 /// The sound as a WAV file coded `pcm` (16 or 24-bit integer, or 32-bit float).
118 pub fn write(&self, pcm: Pcm) -> Outcome<Vec<u8>> {
119 let w = match pcm {
120 Pcm::Int(16) => 2,
121 Pcm::Int(24) => 3,
122 Pcm::Float(32) => 4,
123 _ => return Err(err!("A WAV is written at 16 or 24-bit integer or 32-bit float, not {:?}.", pcm; Invalid, Input, Unimplemented)),
124 };
125 let (nc, frames) = (self.chans.len(), self.frames());
126 if nc == 0 || nc > u16::MAX as usize || self.chans.iter().any(|c| c.len() != frames) {
127 return Err(err!("A WAV needs one or more channels of equal length; these are {} channels.", nc; Invalid, Input));
128 }
129 let n = frames * nc * w;
130 if n + 36 > u32::MAX as usize {
131 return Err(err!("{} bytes of samples will not fit a WAV's 32-bit length.", n; Invalid, Input, Excessive));
132 }
133 let mut b = Vec::with_capacity(44 + n);
134 b.extend_from_slice(b"RIFF");
135 b.extend_from_slice(&((36 + n) as u32).to_le_bytes());
136 b.extend_from_slice(b"WAVEfmt ");
137 b.extend_from_slice(&16u32.to_le_bytes());
138 b.extend_from_slice(&(if let Pcm::Float(_) = pcm { 3u16 } else { 1u16 }).to_le_bytes());
139 b.extend_from_slice(&(nc as u16).to_le_bytes());
140 b.extend_from_slice(&self.rate.to_le_bytes());
141 b.extend_from_slice(&(self.rate * (nc * w) as u32).to_le_bytes());
142 b.extend_from_slice(&((nc * w) as u16).to_le_bytes());
143 b.extend_from_slice(&pcm.bits().to_le_bytes());
144 b.extend_from_slice(b"data");
145 b.extend_from_slice(&(n as u32).to_le_bytes());
146 for f in 0..frames {
147 for c in &self.chans {
148 let x = c[f].clamp(-1.0, 1.0);
149 match pcm {
150 Pcm::Int(16) => b.extend_from_slice(&((x * 32767.0).round() as i16).to_le_bytes()),
151 Pcm::Int(_) => b.extend_from_slice(&((x * 8_388_607.0).round() as i32).to_le_bytes()[..3]),
152 Pcm::Float(_) => b.extend_from_slice(&c[f].to_le_bytes()),
153 }
154 }
155 }
156 Ok(b)
157 }
158
159 /// The sound at `rate` samples a second, by a Blackman-windowed sinc whose cut-off falls to the lower of the two
160 /// rates' halves, so a rate brought down is not folded back into the audible band.
161 pub fn resample(&self, rate: u32) -> Outcome<Self> {
162 if rate == 0 || self.rate == 0 {
163 return Err(err!("A sound is resampled between two rates above nought, not {} to {} Hz.", self.rate, rate; Invalid, Input));
164 }
165 if rate == self.rate {
166 return Ok(self.clone());
167 }
168 let (from, to) = (self.rate as f64, rate as f64);
169 let step = from / to; // input frames an output frame
170 let fc = (to / from).min(1.0); // cut-off, as a fraction of the input's half rate
171 let half = (TAPS as f64 / fc).ceil() as i64; // taps either side, widened as the cut-off falls
172 let n = self.frames();
173 let m = ((n as f64) / step).round() as usize;
174 let pi = std::f64::consts::PI;
175 let chans = self.chans.iter().map(|c| {
176 (0..m).map(|j| {
177 let t = j as f64 * step;
178 let k0 = t.floor() as i64;
179 let (mut y, mut wsum) = (0f64, 0f64);
180 for k in (k0 - half + 1)..=(k0 + half) {
181 let d = t - k as f64;
182 let x = d * fc;
183 let s = if x == 0.0 { 1.0 } else { (pi * x).sin() / (pi * x) };
184 let a = (d / (half as f64 + 1.0) + 1.0) / 2.0; // window position, 0..1 across the span
185 let win = 0.42 - 0.5 * (2.0 * pi * a).cos() + 0.08 * (4.0 * pi * a).cos();
186 let w = s * win;
187 wsum += w;
188 if (0..n as i64).contains(&k) {
189 y += w * c[k as usize] as f64;
190 }
191 }
192 (if wsum != 0.0 { y / wsum } else { 0.0 }) as f32
193 }).collect()
194 }).collect();
195 Ok(Self { rate, pcm: self.pcm, chans })
196 }
197}