1use std::borrow::Cow;
2
3#[derive(Debug, Clone)]
28pub struct AudioFrame<'a> {
29 samples: Cow<'a, [f32]>,
30 sample_rate: u32,
31}
32
33impl<'a> AudioFrame<'a> {
34 pub fn new(samples: impl IntoSamples<'a>, sample_rate: u32) -> Self {
38 Self {
39 samples: samples.into_samples(),
40 sample_rate,
41 }
42 }
43
44 pub fn samples(&self) -> &[f32] {
46 &self.samples
47 }
48
49 pub fn sample_rate(&self) -> u32 {
51 self.sample_rate
52 }
53
54 pub fn len(&self) -> usize {
56 self.samples.len()
57 }
58
59 pub fn is_empty(&self) -> bool {
61 self.samples.is_empty()
62 }
63
64 pub fn duration_secs(&self) -> f64 {
66 self.samples.len() as f64 / self.sample_rate as f64
67 }
68
69 pub fn into_owned(self) -> AudioFrame<'static> {
71 AudioFrame {
72 samples: Cow::Owned(self.samples.into_owned()),
73 sample_rate: self.sample_rate,
74 }
75 }
76}
77
78impl AudioFrame<'static> {
79 pub fn from_vec(samples: Vec<f32>, sample_rate: u32) -> Self {
95 Self {
96 samples: Cow::Owned(samples),
97 sample_rate,
98 }
99 }
100}
101
102#[cfg(feature = "wav")]
103impl AudioFrame<'_> {
104 pub fn write_wav(&self, path: impl AsRef<std::path::Path>) -> Result<(), hound::Error> {
117 let spec = hound::WavSpec {
118 channels: 1,
119 sample_rate: self.sample_rate,
120 bits_per_sample: 32,
121 sample_format: hound::SampleFormat::Float,
122 };
123 let mut writer = hound::WavWriter::create(path, spec)?;
124 for &sample in self.samples() {
125 writer.write_sample(sample)?;
126 }
127 writer.finalize()
128 }
129}
130
131#[cfg(feature = "wav")]
132impl AudioFrame<'static> {
133 pub fn from_wav(path: impl AsRef<std::path::Path>) -> Result<Self, hound::Error> {
147 let mut reader = hound::WavReader::open(path)?;
148 let spec = reader.spec();
149 let sample_rate = spec.sample_rate;
150 let samples: Vec<f32> = match spec.sample_format {
151 hound::SampleFormat::Float => reader.samples::<f32>().collect::<Result<_, _>>()?,
152 hound::SampleFormat::Int => reader
153 .samples::<i16>()
154 .map(|s| s.map(|v| v as f32 / 32768.0))
155 .collect::<Result<_, _>>()?,
156 };
157 Ok(AudioFrame::from_vec(samples, sample_rate))
158 }
159}
160
161pub trait IntoSamples<'a> {
165 fn into_samples(self) -> Cow<'a, [f32]>;
167}
168
169impl<'a> IntoSamples<'a> for &'a [f32] {
170 #[inline]
171 fn into_samples(self) -> Cow<'a, [f32]> {
172 Cow::Borrowed(self)
173 }
174}
175
176impl<'a> IntoSamples<'a> for &'a Vec<f32> {
177 #[inline]
178 fn into_samples(self) -> Cow<'a, [f32]> {
179 Cow::Borrowed(self.as_slice())
180 }
181}
182
183impl<'a, const N: usize> IntoSamples<'a> for &'a [f32; N] {
184 #[inline]
185 fn into_samples(self) -> Cow<'a, [f32]> {
186 Cow::Borrowed(self.as_slice())
187 }
188}
189
190impl<'a> IntoSamples<'a> for &'a [i16] {
191 #[inline]
192 fn into_samples(self) -> Cow<'a, [f32]> {
193 Cow::Owned(self.iter().map(|&s| s as f32 / 32768.0).collect())
194 }
195}
196
197impl<'a> IntoSamples<'a> for &'a Vec<i16> {
198 #[inline]
199 fn into_samples(self) -> Cow<'a, [f32]> {
200 Cow::Owned(self.iter().map(|&s| s as f32 / 32768.0).collect())
201 }
202}
203
204impl<'a, const N: usize> IntoSamples<'a> for &'a [i16; N] {
205 #[inline]
206 fn into_samples(self) -> Cow<'a, [f32]> {
207 Cow::Owned(self.iter().map(|&s| s as f32 / 32768.0).collect())
208 }
209}
210
211#[cfg(test)]
212mod tests {
213 use super::*;
214
215 #[test]
216 fn f32_is_zero_copy() {
217 let samples = vec![0.1f32, -0.2, 0.3];
218 let frame = AudioFrame::new(samples.as_slice(), 16000);
219 assert!(matches!(frame.samples, Cow::Borrowed(_)));
221 assert_eq!(frame.samples(), &[0.1, -0.2, 0.3]);
222 }
223
224 #[test]
225 fn i16_normalizes_to_f32() {
226 let samples: Vec<i16> = vec![0, 16384, -16384, i16::MAX, i16::MIN];
227 let frame = AudioFrame::new(samples.as_slice(), 16000);
228 assert!(matches!(frame.samples, Cow::Owned(_)));
229
230 let s = frame.samples();
231 assert!((s[0] - 0.0).abs() < f32::EPSILON);
232 assert!((s[1] - 0.5).abs() < 0.001);
233 assert!((s[2] - -0.5).abs() < 0.001);
234 assert!((s[3] - (i16::MAX as f32 / 32768.0)).abs() < f32::EPSILON);
235 assert!((s[4] - -1.0).abs() < f32::EPSILON);
236 }
237
238 #[test]
239 fn metadata() {
240 let samples = vec![0.0f32; 160];
241 let frame = AudioFrame::new(samples.as_slice(), 16000);
242 assert_eq!(frame.sample_rate(), 16000);
243 assert_eq!(frame.len(), 160);
244 assert!(!frame.is_empty());
245 assert!((frame.duration_secs() - 0.01).abs() < 1e-9);
246 }
247
248 #[test]
249 fn empty_frame() {
250 let samples: &[f32] = &[];
251 let frame = AudioFrame::new(samples, 16000);
252 assert!(frame.is_empty());
253 assert_eq!(frame.len(), 0);
254 }
255
256 #[test]
257 fn into_owned() {
258 let samples = vec![0.5f32, -0.5];
259 let frame = AudioFrame::new(samples.as_slice(), 16000);
260 let owned: AudioFrame<'static> = frame.into_owned();
261 assert_eq!(owned.samples(), &[0.5, -0.5]);
262 assert_eq!(owned.sample_rate(), 16000);
263 }
264
265 #[cfg(feature = "wav")]
266 #[test]
267 fn wav_read_i16() {
268 let path = std::env::temp_dir().join("wavekat_test_i16.wav");
270 let spec = hound::WavSpec {
271 channels: 1,
272 sample_rate: 16000,
273 bits_per_sample: 16,
274 sample_format: hound::SampleFormat::Int,
275 };
276 let i16_samples: &[i16] = &[0, i16::MAX, i16::MIN, 16384];
277 let mut writer = hound::WavWriter::create(&path, spec).unwrap();
278 for &s in i16_samples {
279 writer.write_sample(s).unwrap();
280 }
281 writer.finalize().unwrap();
282
283 let frame = AudioFrame::from_wav(&path).unwrap();
284 assert_eq!(frame.sample_rate(), 16000);
285 assert_eq!(frame.len(), 4);
286 let s = frame.samples();
287 assert!((s[0] - 0.0).abs() < 1e-6);
288 assert!((s[1] - (i16::MAX as f32 / 32768.0)).abs() < 1e-6);
289 assert!((s[2] - -1.0).abs() < 1e-6);
290 assert!((s[3] - 0.5).abs() < 1e-4);
291 }
292
293 #[cfg(feature = "wav")]
294 #[test]
295 fn wav_round_trip() {
296 let original = AudioFrame::from_vec(vec![0.5f32, -0.5, 0.0, 1.0], 16000);
297 let path = std::env::temp_dir().join("wavekat_test.wav");
298 original.write_wav(&path).unwrap();
299 let loaded = AudioFrame::from_wav(&path).unwrap();
300 assert_eq!(loaded.sample_rate(), 16000);
301 for (a, b) in original.samples().iter().zip(loaded.samples()) {
302 assert!((a - b).abs() < 1e-6, "sample mismatch: {a} vs {b}");
303 }
304 }
305
306 #[test]
307 fn from_vec_is_zero_copy() {
308 let samples = vec![0.5f32, -0.5];
309 let ptr = samples.as_ptr();
310 let frame = AudioFrame::from_vec(samples, 24000);
311 assert_eq!(frame.samples().as_ptr(), ptr);
312 assert_eq!(frame.sample_rate(), 24000);
313 }
314
315 #[test]
316 fn into_samples_vec_f32() {
317 let samples = vec![0.1f32, -0.2, 0.3];
318 let frame = AudioFrame::new(&samples, 16000);
319 assert!(matches!(frame.samples, Cow::Borrowed(_)));
320 assert_eq!(frame.samples(), &[0.1, -0.2, 0.3]);
321 }
322
323 #[test]
324 fn into_samples_array_f32() {
325 let samples = [0.1f32, -0.2, 0.3];
326 let frame = AudioFrame::new(&samples, 16000);
327 assert!(matches!(frame.samples, Cow::Borrowed(_)));
328 assert_eq!(frame.samples(), &[0.1, -0.2, 0.3]);
329 }
330
331 #[test]
332 fn into_samples_vec_i16() {
333 let samples: Vec<i16> = vec![0, 16384, i16::MIN];
334 let frame = AudioFrame::new(&samples, 16000);
335 assert!(matches!(frame.samples, Cow::Owned(_)));
336 let s = frame.samples();
337 assert!((s[0] - 0.0).abs() < f32::EPSILON);
338 assert!((s[1] - 0.5).abs() < 0.001);
339 assert!((s[2] - -1.0).abs() < f32::EPSILON);
340 }
341
342 #[test]
343 fn into_samples_array_i16() {
344 let samples: [i16; 3] = [0, 16384, i16::MIN];
345 let frame = AudioFrame::new(&samples, 16000);
346 assert!(matches!(frame.samples, Cow::Owned(_)));
347 let s = frame.samples();
348 assert!((s[0] - 0.0).abs() < f32::EPSILON);
349 assert!((s[1] - 0.5).abs() < 0.001);
350 assert!((s[2] - -1.0).abs() < f32::EPSILON);
351 }
352}