logo
  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
// Copyright © 2020-2022 The Fon Contributors.
//
// Licensed under any of:
// - Apache License, Version 2.0 (https://www.apache.org/licenses/LICENSE-2.0)
// - MIT License (https://mit-license.org/)
// - Boost Software License, Version 1.0 (https://www.boost.org/LICENSE_1_0.txt)
// At your choosing (See accompanying files LICENSE_APACHE_2_0.txt,
// LICENSE_MIT.txt and LICENSE_BOOST_1_0.txt).

#[cfg(not(test))]
use crate::math::Libm;

use crate::chan::{Ch16, Ch24, Ch32, Ch64, Channel};
use crate::frame::Frame;
use crate::{Sink, Stream};

use alloc::boxed::Box;
use alloc::slice::{Iter, IterMut};
use alloc::{vec, vec::Vec};

use core::convert::TryInto;
use core::num::NonZeroU32;
use core::{fmt::Debug, mem::size_of, slice::from_raw_parts_mut};

/// Audio buffer (fixed-size array of audio [`Frame`](crate::frame::Frame)s at
/// sample rate specified in hertz).
#[derive(Debug)]
pub struct Audio<Chan: Channel, const CH: usize> {
    // Sample rate of the audio in hertz.
    sample_rate: NonZeroU32,
    // Audio frames.
    frames: Box<[Frame<Chan, CH>]>,
}

impl<Chan: Channel, const CH: usize> Audio<Chan, CH> {
    /// Construct an `Audio` buffer with all all samples set to zero.
    #[inline(always)]
    pub fn with_silence(hz: u32, len: usize) -> Self {
        Self::with_frames(hz, vec![Frame::<Chan, CH>::default(); len])
    }

    /// Construct an `Audio` buffer with owned sample data.   You can get
    /// ownership of the sample data back from the `Audio` buffer as either a
    /// `Vec<S>` or a `Box<[S]>` by calling into().
    #[inline(always)]
    pub fn with_frames<B>(hz: u32, frames: B) -> Self
    where
        B: Into<Box<[Frame<Chan, CH>]>>,
    {
        Audio {
            sample_rate: hz.try_into().unwrap(),
            frames: frames.into(),
        }
    }

    /// Construct an `Audio` buffer from another `Audio` buffer of a different
    /// format.
    #[inline(always)]
    pub fn with_audio<Ch, const N: usize>(hz: u32, audio: &Audio<Ch, N>) -> Self
    where
        Ch: Channel,
        Ch32: From<Ch>,
        Chan: From<Ch>,
    {
        let len =
            audio.len() as f64 * hz as f64 / audio.sample_rate().get() as f64;
        let mut output = Self::with_silence(hz, len.ceil() as usize);
        let mut stream = Stream::new(hz);
        let mut sink = crate::SinkTo::<_, Chan, _, CH, N>::new(output.sink());
        stream.pipe(audio, &mut sink);
        stream.flush(&mut sink);
        output
    }

    /// Get an audio frame.
    #[inline(always)]
    pub fn get(&self, index: usize) -> Option<Frame<Chan, CH>> {
        self.frames.get(index).cloned()
    }

    /// Get a mutable reference to an audio frame.
    #[inline(always)]
    pub fn get_mut(&mut self, index: usize) -> Option<&mut Frame<Chan, CH>> {
        self.frames.get_mut(index)
    }

    /// Get a slice of all audio frames.
    #[inline(always)]
    pub fn as_slice(&self) -> &[Frame<Chan, CH>] {
        &*self.frames
    }

    /// Get a slice of all audio frames.
    #[inline(always)]
    pub fn as_mut_slice(&mut self) -> &mut [Frame<Chan, CH>] {
        &mut *self.frames
    }

    /// Returns an iterator over the audio frames.
    #[inline(always)]
    pub fn iter(&self) -> Iter<'_, Frame<Chan, CH>> {
        self.frames.iter()
    }

    /// Returns an iterator that allows modifying each audio frame.
    #[inline(always)]
    pub fn iter_mut(&mut self) -> IterMut<'_, Frame<Chan, CH>> {
        self.frames.iter_mut()
    }

    /// Get the sample rate of this audio buffer.
    #[inline(always)]
    pub fn sample_rate(&self) -> NonZeroU32 {
        self.sample_rate
    }

    /// Get the length of the `Audio` buffer.
    #[inline(always)]
    pub fn len(&self) -> usize {
        self.frames.len()
    }

    /// Check if `Audio` buffer is empty.
    #[inline(always)]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Silence the audio buffer.
    #[inline(always)]
    pub fn silence(&mut self) {
        for f in self.frames.iter_mut() {
            *f = Frame::<Chan, CH>::default()
        }
    }

    /// Sink audio into this audio buffer from a `Stream`.
    #[inline(always)]
    pub fn sink(&mut self) -> AudioSink<'_, Chan, CH> {
        AudioSink {
            index: 0,
            audio: self,
        }
    }
}

/// Returned from [`Audio::sink()`](crate::Audio::sink).
#[derive(Debug)]
pub struct AudioSink<'a, Chan: Channel, const CH: usize> {
    index: usize,
    audio: &'a mut Audio<Chan, CH>,
}

// Using '_ results in reserved lifetime error.
#[allow(single_use_lifetimes)]
impl<'a, Chan: Channel, const CH: usize> Sink<Chan, CH>
    for AudioSink<'a, Chan, CH>
{
    #[inline(always)]
    fn sample_rate(&self) -> NonZeroU32 {
        self.audio.sample_rate()
    }

    #[inline(always)]
    fn len(&self) -> usize {
        self.audio.len()
    }

    #[inline(always)]
    fn sink_with(&mut self, iter: &mut dyn Iterator<Item = Frame<Chan, CH>>) {
        let mut this = self;
        Sink::<Chan, CH>::sink_with(&mut this, iter)
    }
}

impl<Chan: Channel, const CH: usize> Sink<Chan, CH>
    for &mut AudioSink<'_, Chan, CH>
{
    #[inline(always)]
    fn sample_rate(&self) -> NonZeroU32 {
        self.audio.sample_rate()
    }

    #[inline(always)]
    fn len(&self) -> usize {
        self.audio.len()
    }

    #[inline(always)]
    fn sink_with(&mut self, iter: &mut dyn Iterator<Item = Frame<Chan, CH>>) {
        for frame in self.audio.iter_mut().skip(self.index) {
            *frame = if let Some(frame) = iter.next() {
                frame
            } else {
                break;
            };
            self.index += 1;
        }
    }
}

impl<const CH: usize> Audio<Ch16, CH> {
    /// Construct an `Audio` buffer from an `i16` buffer.
    #[allow(unsafe_code)]
    pub fn with_i16_buffer<B>(hz: u32, buffer: B) -> Self
    where
        B: Into<Box<[i16]>>,
    {
        let buffer: Box<[i16]> = buffer.into();
        let bytes = buffer.len() * size_of::<i16>();
        let len = bytes / size_of::<Frame<Ch16, CH>>();
        assert_eq!(0, bytes % size_of::<Frame<Ch16, CH>>());
        let slice = Box::<[i16]>::into_raw(buffer);
        let frames: Box<[Frame<Ch16, CH>]> = unsafe {
            let ptr = (*slice).as_mut_ptr() as *mut Frame<Ch16, CH>;
            Box::from_raw(from_raw_parts_mut(ptr, len))
        };
        let frames: Vec<Frame<Ch16, CH>> = frames.into();
        Audio::with_frames(hz, frames)
    }

    /// Get view of samples as an `i16` slice.
    #[allow(unsafe_code)]
    pub fn as_i16_slice(&mut self) -> &mut [i16] {
        let frames = self.as_mut_slice();
        unsafe {
            let (prefix, v, suffix) = frames.align_to_mut::<i16>();
            debug_assert!(prefix.is_empty());
            debug_assert!(suffix.is_empty());
            v
        }
    }
}

impl<const CH: usize> Audio<Ch24, CH> {
    /// Construct an `Audio` buffer from an `u8` buffer.
    #[allow(unsafe_code)]
    pub fn with_u8_buffer<B>(hz: u32, buffer: B) -> Self
    where
        B: Into<Box<[u8]>>,
    {
        let buffer: Box<[u8]> = buffer.into();
        let bytes = buffer.len() * size_of::<i16>();
        let len = bytes / size_of::<Frame<Ch16, CH>>();
        assert_eq!(0, bytes % size_of::<Frame<Ch16, CH>>());
        let slice = Box::<[u8]>::into_raw(buffer);
        let frames: Box<[Frame<Ch24, CH>]> = unsafe {
            let ptr = (*slice).as_mut_ptr() as *mut Frame<Ch24, CH>;
            Box::from_raw(from_raw_parts_mut(ptr, len))
        };
        let frames: Vec<Frame<Ch24, CH>> = frames.into();
        Audio::with_frames(hz, frames)
    }

    /// Get view of samples as an `u8` slice.
    #[allow(unsafe_code)]
    pub fn as_u8_slice(&mut self) -> &mut [u8] {
        let frames = self.as_mut_slice();
        unsafe {
            let (prefix, v, suffix) = frames.align_to_mut::<u8>();
            debug_assert!(prefix.is_empty());
            debug_assert!(suffix.is_empty());
            v
        }
    }
}

impl<const CH: usize> Audio<Ch32, CH> {
    /// Construct an `Audio` buffer from an `f32` buffer.
    #[allow(unsafe_code)]
    pub fn with_f32_buffer<B>(hz: u32, buffer: B) -> Self
    where
        B: Into<Box<[f32]>>,
    {
        let buffer: Box<[f32]> = buffer.into();
        let bytes = buffer.len() * size_of::<f32>();
        let len = bytes / size_of::<Frame<Ch32, CH>>();
        assert_eq!(0, bytes % size_of::<Frame<Ch32, CH>>());
        let slice = Box::<[f32]>::into_raw(buffer);
        let frames: Box<[Frame<Ch32, CH>]> = unsafe {
            let ptr = (*slice).as_mut_ptr() as *mut Frame<Ch32, CH>;
            Box::from_raw(from_raw_parts_mut(ptr, len))
        };
        let frames: Vec<Frame<Ch32, CH>> = frames.into();
        Audio::with_frames(hz, frames)
    }

    /// Get view of samples as an `f32` slice.
    #[allow(unsafe_code)]
    pub fn as_f32_slice(&mut self) -> &mut [f32] {
        let frames = self.as_mut_slice();
        unsafe {
            let (prefix, v, suffix) = frames.align_to_mut::<f32>();
            debug_assert!(prefix.is_empty());
            debug_assert!(suffix.is_empty());
            v
        }
    }
}

impl<const CH: usize> Audio<Ch64, CH> {
    /// Construct an `Audio` buffer from an `f64` buffer.
    #[allow(unsafe_code)]
    pub fn with_f64_buffer<B>(hz: u32, buffer: B) -> Self
    where
        B: Into<Box<[f64]>>,
    {
        let buffer: Box<[f64]> = buffer.into();
        let bytes = buffer.len() * size_of::<f64>();
        let len = bytes / size_of::<Frame<Ch64, CH>>();
        assert_eq!(0, bytes % size_of::<Frame<Ch64, CH>>());
        let slice = Box::<[f64]>::into_raw(buffer);
        let frames: Box<[Frame<Ch64, CH>]> = unsafe {
            let ptr = (*slice).as_mut_ptr() as *mut Frame<Ch64, CH>;
            Box::from_raw(from_raw_parts_mut(ptr, len))
        };
        let frames: Vec<Frame<Ch64, CH>> = frames.into();
        Audio::with_frames(hz, frames)
    }

    /// Get view of samples as an `f64` slice.
    #[allow(unsafe_code)]
    pub fn as_f64_slice(&mut self) -> &mut [f64] {
        let frames = self.as_mut_slice();
        unsafe {
            let (prefix, v, suffix) = frames.align_to_mut::<f64>();
            debug_assert!(prefix.is_empty());
            debug_assert!(suffix.is_empty());
            v
        }
    }
}

impl<Chan, const CH: usize> From<Audio<Chan, CH>> for Vec<Frame<Chan, CH>>
where
    Chan: Channel,
{
    /// Get internal sample data as `Vec` of audio frames.
    fn from(audio: Audio<Chan, CH>) -> Self {
        audio.frames.into()
    }
}

impl<Chan: Channel, const CH: usize> From<Audio<Chan, CH>>
    for Box<[Frame<Chan, CH>]>
{
    /// Get internal sample data as `Vec` of audio frames.
    fn from(audio: Audio<Chan, CH>) -> Self {
        let audio: Vec<Frame<Chan, CH>> = audio.frames.into();
        audio.into()
    }
}

impl<const CH: usize> From<Audio<Ch16, CH>> for Box<[i16]> {
    /// Get internal sample data as boxed slice of *i16*.
    #[allow(unsafe_code)]
    fn from(audio: Audio<Ch16, CH>) -> Self {
        let mut frames: Vec<Frame<Ch16, CH>> = audio.frames.into();
        let capacity = frames.len() * size_of::<Frame<Ch16, CH>>() / 2;
        let buffer: Box<[i16]> = unsafe {
            let ptr = frames.as_mut_ptr() as *mut i16;
            Box::from_raw(from_raw_parts_mut(ptr, capacity))
        };
        buffer
    }
}

impl<const CH: usize> From<Audio<Ch24, CH>> for Box<[u8]> {
    /// Get internal sample data as boxed slice of *u8*.
    #[allow(unsafe_code)]
    fn from(audio: Audio<Ch24, CH>) -> Self {
        let mut frames: Vec<Frame<Ch24, CH>> = audio.frames.into();
        let capacity = frames.len() * size_of::<Frame<Ch24, CH>>() / 3;
        let buffer: Box<[u8]> = unsafe {
            let ptr = frames.as_mut_ptr() as *mut u8;
            Box::from_raw(from_raw_parts_mut(ptr, capacity))
        };
        buffer
    }
}

impl<const CH: usize> From<Audio<Ch32, CH>> for Box<[f32]> {
    /// Get internal sample data as boxed slice of *f32*.
    #[allow(unsafe_code)]
    fn from(audio: Audio<Ch32, CH>) -> Self {
        let mut frames: Vec<Frame<Ch32, CH>> = audio.frames.into();
        let capacity = frames.len() * size_of::<Frame<Ch32, CH>>() / 4;
        let buffer: Box<[f32]> = unsafe {
            let ptr = frames.as_mut_ptr() as *mut f32;
            Box::from_raw(from_raw_parts_mut(ptr, capacity))
        };
        buffer
    }
}

impl<const CH: usize> From<Audio<Ch64, CH>> for Box<[f64]> {
    /// Get internal sample data as boxed slice of *f64*.
    #[allow(unsafe_code)]
    fn from(audio: Audio<Ch64, CH>) -> Self {
        let mut frames: Vec<Frame<Ch64, CH>> = audio.frames.into();
        let capacity = frames.len() * size_of::<Frame<Ch64, CH>>() / 8;
        let buffer: Box<[f64]> = unsafe {
            let ptr = frames.as_mut_ptr() as *mut f64;
            Box::from_raw(from_raw_parts_mut(ptr, capacity))
        };
        buffer
    }
}