symphonium 0.9.2

An unofficial easy-to-use wrapper around Symphonia for loading audio files
Documentation
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
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
use std::num::NonZeroU32;
use symphonia::core::{conv::FromSample, sample::u24};

/// A resource of raw f32 audio samples stored in deinterleaved format.
///
/// This struct stores samples
/// in their native sample format when possible to save memory.
#[derive(Clone)]
pub struct DecodedAudioF32 {
    pub data: Vec<Vec<f32>>,
    /// The sample rate of this audio resource.
    pub sample_rate: NonZeroU32,
    /// The sample rate of the audio resource before it was resampled
    /// (if it was resampled).
    pub original_sample_rate: NonZeroU32,
}

impl DecodedAudioF32 {
    /// Construct a new `DecedAudioF32` resource.
    ///
    /// * `data` - The deinterleaved audio data.
    /// * `sample_rate` - The sample rate of this resource.
    /// * `original_sample_rate` - The sample rate of the audio resource before
    ///   it was resampled (if it was resampled).
    pub fn new(
        data: Vec<Vec<f32>>,
        sample_rate: NonZeroU32,
        original_sample_rate: NonZeroU32,
    ) -> Self {
        let frames = data[0].len();

        for ch in data.iter().skip(1) {
            assert_eq!(ch.len(), frames);
        }

        Self {
            data,
            sample_rate,
            original_sample_rate,
        }
    }

    /// The number of channels in this resource.
    pub fn channels(&self) -> usize {
        self.data.len()
    }

    /// The length of this resource in frames (length of a single channel in
    /// samples).
    pub fn frames(&self) -> usize {
        self.data[0].len()
    }
}

impl std::fmt::Debug for DecodedAudioF32 {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "DecodedAudioF32 {{ channels: {}, frames: {}, sample_rate: {} }}",
            self.data.len(),
            self.data[0].len(),
            self.sample_rate
        )
    }
}

impl From<DecodedAudioF32> for DecodedAudio {
    fn from(value: DecodedAudioF32) -> Self {
        let channels = value.channels();
        let frames = value.frames();

        DecodedAudio {
            resource_type: DecodedAudioType::F32(value.data),
            sample_rate: value.sample_rate,
            original_sample_rate: value.original_sample_rate,
            channels,
            frames,
        }
    }
}

/// A resource of raw audio samples stored in deinterleaved format.
///
/// This struct stores samples
/// in their native sample format when possible to save memory.
#[derive(Debug, Clone)]
pub struct DecodedAudio {
    resource_type: DecodedAudioType,
    sample_rate: NonZeroU32,
    original_sample_rate: NonZeroU32,
    channels: usize,
    frames: usize,
}

/// The format of the raw audio samples stored in deinterleaved format.
///
/// Note that there is no option for U32/I32. This is because in processing
/// we ultimately use `f32` for everything anyway. We only store the other
/// types to save memory.
///
/// Also note there is no option for `I24` (signed 24 bit). This is because
/// converting two's compliment numbers from 32 bit to 24 bit and vice-versa
/// is tricky and less performant. Instead, just convert the data into `u24`
/// format.
#[derive(Clone)]
pub enum DecodedAudioType {
    U8(Vec<Vec<u8>>),
    U16(Vec<Vec<u16>>),
    /// The endianness of the samples must be the native endianness of the
    /// target platform.
    U24(Vec<Vec<[u8; 3]>>),
    S8(Vec<Vec<i8>>),
    S16(Vec<Vec<i16>>),
    F32(Vec<Vec<f32>>),
    F64(Vec<Vec<f64>>),
}

impl DecodedAudio {
    /// Construct a new `DecodedAudio` resource.
    ///
    /// * `resource_type` - The deinterleaved audio data.
    /// * `sample_rate` - The sample rate of this resource.
    /// * `original_sample_rate` - The sample rate of the audio resource before
    ///   it was resampled (if it was resampled).
    pub fn new(
        resource_type: DecodedAudioType,
        sample_rate: NonZeroU32,
        original_sample_rate: NonZeroU32,
    ) -> Self {
        let (channels, frames) = match &resource_type {
            DecodedAudioType::U8(b) => {
                let len = b[0].len();

                for ch in b.iter().skip(1) {
                    assert_eq!(ch.len(), len);
                }

                (b.len(), len)
            }
            DecodedAudioType::U16(b) => {
                let len = b[0].len();

                for ch in b.iter().skip(1) {
                    assert_eq!(ch.len(), len);
                }

                (b.len(), len)
            }
            DecodedAudioType::U24(b) => {
                let len = b[0].len();

                for ch in b.iter().skip(1) {
                    assert_eq!(ch.len(), len);
                }

                (b.len(), len)
            }
            DecodedAudioType::S8(b) => {
                let len = b[0].len();

                for ch in b.iter().skip(1) {
                    assert_eq!(ch.len(), len);
                }

                (b.len(), len)
            }
            DecodedAudioType::S16(b) => {
                let len = b[0].len();

                for ch in b.iter().skip(1) {
                    assert_eq!(ch.len(), len);
                }

                (b.len(), len)
            }
            DecodedAudioType::F32(b) => {
                let len = b[0].len();

                for ch in b.iter().skip(1) {
                    assert_eq!(ch.len(), len);
                }

                (b.len(), len)
            }
            DecodedAudioType::F64(b) => {
                let len = b[0].len();

                for ch in b.iter().skip(1) {
                    assert_eq!(ch.len(), len);
                }

                (b.len(), len)
            }
        };

        Self {
            resource_type,
            sample_rate,
            original_sample_rate,
            channels,
            frames,
        }
    }

    /// The number of channels in this resource.
    pub fn channels(&self) -> usize {
        self.channels
    }

    /// The length of this resource in frames (length of a single channel in
    /// samples).
    pub fn frames(&self) -> usize {
        self.frames
    }

    /// The sample rate of this resource in samples per second.
    pub fn sample_rate(&self) -> NonZeroU32 {
        self.sample_rate
    }

    /// The sample rate of the audio resource before it was resampled
    /// (if it was resampled).
    pub fn original_sample_rate(&self) -> NonZeroU32 {
        self.original_sample_rate
    }

    pub fn get(&self) -> &DecodedAudioType {
        &self.resource_type
    }

    /// Fill the buffer with samples from the given `channel`, starting from the
    /// given `frame`.
    ///
    /// If the length of the buffer exceeds the length of the PCM resource, then
    /// the remaining samples will be filled with zeros.
    ///
    /// This returns the number of frames that were copied into the buffer. (If
    /// this number is less than the length of `buf`, then it means that the
    /// remaining samples were filled with zeros.)
    ///
    /// The will return an error if the given channel does not exist.
    pub fn fill_channel(
        &self,
        channel: usize,
        frame: usize,
        buf: &mut [f32],
    ) -> Result<usize, FillChannelError> {
        if channel >= self.channels {
            return Err(FillChannelError {
                got_index: channel,
                num_channels: self.channels,
            });
        }

        if frame >= self.frames {
            // Out of range, fill with zeros instead.
            buf.fill(0.0);
            return Ok(0);
        }

        let fill_frames = if frame + buf.len() > self.frames {
            // Fill the out-of-range part with zeros.
            let fill_frames = self.frames - frame;
            buf[fill_frames..].fill(0.0);
            fill_frames
        } else {
            buf.len()
        };

        let buf_part = &mut buf[0..fill_frames];

        match &self.resource_type {
            DecodedAudioType::U8(pcm) => {
                let pcm_part = &pcm[channel][frame..frame + fill_frames];

                for i in 0..fill_frames {
                    buf_part[i] = FromSample::from_sample(pcm_part[i]);
                }
            }
            DecodedAudioType::U16(pcm) => {
                let pcm_part = &pcm[channel][frame..frame + fill_frames];

                for i in 0..fill_frames {
                    buf_part[i] = FromSample::from_sample(pcm_part[i]);
                }
            }
            DecodedAudioType::U24(pcm) => {
                let pcm_part = &pcm[channel][frame..frame + fill_frames];

                for i in 0..fill_frames {
                    let b = &pcm_part[i];

                    let s = if cfg!(target_endian = "little") {
                        // In little-endian the MSB is the last byte.
                        u24(u32::from_le_bytes([b[0], b[1], b[2], 0]))
                    } else {
                        // In big-endian the MSB is the first byte.
                        u24(u32::from_be_bytes([0, b[0], b[1], b[2]]))
                    };

                    buf_part[i] = FromSample::from_sample(s);
                }
            }
            DecodedAudioType::S8(pcm) => {
                let pcm_part = &pcm[channel][frame..frame + fill_frames];

                for i in 0..fill_frames {
                    buf_part[i] = FromSample::from_sample(pcm_part[i]);
                }
            }
            DecodedAudioType::S16(pcm) => {
                let pcm_part = &pcm[channel][frame..frame + fill_frames];

                for i in 0..fill_frames {
                    buf_part[i] = FromSample::from_sample(pcm_part[i]);
                }
            }
            DecodedAudioType::F32(pcm) => {
                let pcm_part = &pcm[channel][frame..frame + fill_frames];

                buf_part.copy_from_slice(pcm_part);
            }
            DecodedAudioType::F64(pcm) => {
                let pcm_part = &pcm[channel][frame..frame + fill_frames];

                for i in 0..fill_frames {
                    buf_part[i] = pcm_part[i] as f32;
                }
            }
        }

        Ok(fill_frames)
    }

    /// Fill the stereo buffer with samples, starting from the given `frame`.
    ///
    /// If this resource has only one channel, then both channels will be
    /// filled with the same data.
    ///
    /// If the length of the buffer exceeds the length of the PCM resource, then
    /// the remaining samples will be filled with zeros.
    ///
    /// This returns the number of frames that were copied into the buffer. (If
    /// this number is less than the length of `buf`, then it means that the
    /// remaining samples were filled with zeros.)
    pub fn fill_stereo(&self, frame: usize, buf_l: &mut [f32], buf_r: &mut [f32]) -> usize {
        let buf_len = buf_l.len().min(buf_r.len());
        let buf_l = &mut buf_l[..buf_len];
        let buf_r = &mut buf_r[..buf_len];

        let fill_frames = if self.channels > 0 {
            self.fill_channel(0, frame, buf_l).unwrap()
        } else {
            return 0;
        };

        if self.channels > 1 {
            self.fill_channel(1, frame, buf_r).unwrap();
        } else {
            buf_r.copy_from_slice(buf_l);
        }

        fill_frames
    }

    /// Consume this resource and return the raw samples.
    pub fn into_raw(self) -> DecodedAudioType {
        self.resource_type
    }
}

impl std::fmt::Debug for DecodedAudioType {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            Self::U8(c) => write!(
                f,
                "DecodedAudioType::U8 {{ channels: {}, frames: {} }}",
                c.len(),
                c[0].len()
            ),
            Self::U16(c) => write!(
                f,
                "DecodedAudioType::U16 {{ channels: {}, frames: {} }}",
                c.len(),
                c[0].len()
            ),
            Self::U24(c) => write!(
                f,
                "DecodedAudioType::U24 {{ channels: {}, frames: {} }}",
                c.len(),
                c[0].len()
            ),
            Self::S8(c) => write!(
                f,
                "DecodedAudioType::S8 {{ channels: {}, frames: {} }}",
                c.len(),
                c[0].len()
            ),
            Self::S16(c) => write!(
                f,
                "DecodedAudioType::S16 {{ channels: {}, frames: {} }}",
                c.len(),
                c[0].len()
            ),
            Self::F32(c) => write!(
                f,
                "DecodedAudioType::F32 {{ channels: {}, frames: {} }}",
                c.len(),
                c[0].len()
            ),
            Self::F64(c) => write!(
                f,
                "DecodedAudioType::F64 {{ channels: {}, frames: {} }}",
                c.len(),
                c[0].len()
            ),
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn pcm_fill_range_test() {
        let test_pcm = DecodedAudio::new(
            DecodedAudioType::F32(vec![vec![1.0, 2.0, 3.0, 4.0]]),
            NonZeroU32::new(44100).unwrap(),
            NonZeroU32::new(44100).unwrap(),
        );

        let mut out_buf: [f32; 8] = [10.0; 8];

        let fill_frames = test_pcm.fill_channel(0, 0, &mut out_buf[0..4]);
        assert_eq!(fill_frames, Ok(4));
        assert_eq!(&out_buf[0..4], &[1.0, 2.0, 3.0, 4.0]);

        out_buf = [10.0; 8];
        let fill_frames = test_pcm.fill_channel(0, 0, &mut out_buf[0..5]);
        assert_eq!(fill_frames, Ok(4));
        assert_eq!(&out_buf[0..5], &[1.0, 2.0, 3.0, 4.0, 0.0]);

        out_buf = [10.0; 8];
        let fill_frames = test_pcm.fill_channel(0, 2, &mut out_buf[0..4]);
        assert_eq!(fill_frames, Ok(2));
        assert_eq!(&out_buf[0..4], &[3.0, 4.0, 0.0, 0.0]);

        out_buf = [10.0; 8];
        let fill_frames = test_pcm.fill_channel(0, 3, &mut out_buf[0..4]);
        assert_eq!(fill_frames, Ok(1));
        assert_eq!(&out_buf[0..4], &[4.0, 0.0, 0.0, 0.0]);

        out_buf = [10.0; 8];
        let fill_frames = test_pcm.fill_channel(0, 4, &mut out_buf[0..4]);
        assert_eq!(fill_frames, Ok(0));
        assert_eq!(&out_buf[0..4], &[0.0, 0.0, 0.0, 0.0]);

        out_buf = [10.0; 8];
        let fill_frames = test_pcm.fill_channel(0, 1, &mut out_buf[0..2]);
        assert_eq!(fill_frames, Ok(2));
        assert_eq!(&out_buf[0..2], &[2.0, 3.0]);

        out_buf = [10.0; 8];
        let fill_frames = test_pcm.fill_channel(0, 1, &mut out_buf[0..4]);
        assert_eq!(fill_frames, Ok(3));
        assert_eq!(&out_buf[0..4], &[2.0, 3.0, 4.0, 0.0]);
    }
}

/// An error occured while using [`DecodedAudio::fill_channel`].
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct FillChannelError {
    pub got_index: usize,
    pub num_channels: usize,
}

impl std::error::Error for FillChannelError {}

impl std::fmt::Display for FillChannelError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        write!(
            f,
            "channel index {} out of bounds for DecodedAudio with {} channels",
            self.got_index, self.num_channels
        )
    }
}