Skip to main content

wavekat_core/
audio.rs

1use std::borrow::Cow;
2
3/// A frame of audio samples with associated sample rate.
4///
5/// `AudioFrame` is the standard audio input type across the WaveKat ecosystem.
6/// It stores samples as f32 normalized to `[-1.0, 1.0]`, regardless of the
7/// original input format.
8///
9/// Construct via [`AudioFrame::new`], which accepts both `&[f32]` (zero-copy)
10/// and `&[i16]` (converts once) through the [`IntoSamples`] trait.
11///
12/// # Examples
13///
14/// ```
15/// use wavekat_core::AudioFrame;
16///
17/// // f32 input — zero-copy via Cow::Borrowed
18/// let samples = [0.1f32, -0.2, 0.3];
19/// let frame = AudioFrame::new(&samples, 16000);
20/// assert_eq!(frame.samples(), &[0.1, -0.2, 0.3]);
21///
22/// // i16 input — normalized to f32 [-1.0, 1.0]
23/// let samples = [i16::MAX, 0, i16::MIN];
24/// let frame = AudioFrame::new(&samples, 16000);
25/// assert!((frame.samples()[0] - 1.0).abs() < 0.001);
26/// ```
27#[derive(Debug, Clone)]
28pub struct AudioFrame<'a> {
29    samples: Cow<'a, [f32]>,
30    sample_rate: u32,
31}
32
33impl<'a> AudioFrame<'a> {
34    /// Create a new audio frame from any supported sample type.
35    ///
36    /// Accepts `&[f32]` (zero-copy) or `&[i16]` (converts to normalized f32).
37    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    /// The audio samples as f32 normalized to `[-1.0, 1.0]`.
45    pub fn samples(&self) -> &[f32] {
46        &self.samples
47    }
48
49    /// Sample rate in Hz (e.g. 16000).
50    pub fn sample_rate(&self) -> u32 {
51        self.sample_rate
52    }
53
54    /// Number of samples in the frame.
55    pub fn len(&self) -> usize {
56        self.samples.len()
57    }
58
59    /// Returns `true` if the frame contains no samples.
60    pub fn is_empty(&self) -> bool {
61        self.samples.is_empty()
62    }
63
64    /// Duration of this frame in seconds.
65    pub fn duration_secs(&self) -> f64 {
66        self.samples.len() as f64 / self.sample_rate as f64
67    }
68
69    /// Consume the frame and return the owned samples.
70    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    /// Construct an owned frame directly from a `Vec<f32>`.
80    ///
81    /// Zero-copy — wraps the vec as `Cow::Owned` without cloning.
82    /// Intended for audio producers (TTS, ASR) that generate owned data.
83    ///
84    /// # Example
85    ///
86    /// ```
87    /// use wavekat_core::AudioFrame;
88    ///
89    /// let samples = vec![0.5f32, -0.5, 0.3];
90    /// let frame = AudioFrame::from_vec(samples, 24000);
91    /// assert_eq!(frame.sample_rate(), 24000);
92    /// assert_eq!(frame.len(), 3);
93    /// ```
94    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    /// Write this frame to a WAV file at `path`.
105    ///
106    /// Always writes mono f32 PCM at the frame's native sample rate.
107    ///
108    /// # Example
109    ///
110    /// ```no_run
111    /// use wavekat_core::AudioFrame;
112    ///
113    /// let frame = AudioFrame::from_vec(vec![0.0f32; 16000], 16000);
114    /// frame.write_wav("output.wav").unwrap();
115    /// ```
116    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    /// Read a mono WAV file and return an owned `AudioFrame`.
134    ///
135    /// Accepts both f32 and i16 WAV files. i16 samples are normalised to
136    /// `[-1.0, 1.0]` (divided by 32768).
137    ///
138    /// # Example
139    ///
140    /// ```no_run
141    /// use wavekat_core::AudioFrame;
142    ///
143    /// let frame = AudioFrame::from_wav("input.wav").unwrap();
144    /// println!("{} Hz, {} samples", frame.sample_rate(), frame.len());
145    /// ```
146    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
161/// Trait for types that can be converted into audio samples.
162///
163/// Implemented for `&[f32]` (zero-copy) and `&[i16]` (normalized conversion).
164pub trait IntoSamples<'a> {
165    /// Convert into f32 samples normalized to `[-1.0, 1.0]`.
166    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        // Cow::Borrowed — the pointer should be the same
220        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        // Write an i16 WAV directly via hound, then read it with from_wav.
269        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}