audio_samples_io 0.1.10

A Rust library for audio input and output operations.
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
489
490
491
492
493
494
495
use core::fmt::{Debug, Display, Formatter, Result as FmtResult};
use core::str::FromStr;
use std::borrow::{Borrow, Cow};
use std::fs::File;
use std::io;
use std::num::{NonZeroU32, NonZeroUsize};
use std::ops::Deref;
use std::path::{Path, PathBuf};
use std::time::Duration;

use audio_samples::SampleType;
use memmap2::Mmap;

use crate::error::AudioIOError;
use crate::traits::AudioInfoMarker;

/// Meant to reflect the SampleType enum but only allow valid sample types for audio files, everthing but unknown
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum ValidatedSampleType {
    U8,
    I16,
    I24,
    I32,
    F32,
    F64,
}

impl ValidatedSampleType {
    pub const fn bits_per_sample(&self) -> NonZeroUsize {
        match self {
            ValidatedSampleType::U8 => audio_samples::nzu!(8),
            ValidatedSampleType::I16 => audio_samples::nzu!(16),
            ValidatedSampleType::I24 => audio_samples::nzu!(24),
            ValidatedSampleType::I32 | ValidatedSampleType::F32 => audio_samples::nzu!(32),
            ValidatedSampleType::F64 => audio_samples::nzu!(64),
        }
    }

    pub const fn bytes_per_sample(&self) -> NonZeroUsize {
        self.bits_per_sample().div_ceil(audio_samples::nzu!(8))
    }
}

impl TryFrom<SampleType> for ValidatedSampleType {
    type Error = AudioIOError;

    fn try_from(value: SampleType) -> Result<Self, Self::Error> {
        match value {
            SampleType::U8 => Ok(ValidatedSampleType::U8),
            SampleType::I16 => Ok(ValidatedSampleType::I16),
            SampleType::I24 => Ok(ValidatedSampleType::I24),
            SampleType::I32 => Ok(ValidatedSampleType::I32),
            SampleType::F32 => Ok(ValidatedSampleType::F32),
            SampleType::F64 => Ok(ValidatedSampleType::F64),
            _ => Err(AudioIOError::unsupported_format(format!(
                "Unsupported sample type: {value:?}"
            ))),
        }
    }
}

impl From<ValidatedSampleType> for SampleType {
    fn from(val: ValidatedSampleType) -> Self {
        match val {
            ValidatedSampleType::U8 => SampleType::U8,
            ValidatedSampleType::I16 => SampleType::I16,
            ValidatedSampleType::I24 => SampleType::I24,
            ValidatedSampleType::I32 => SampleType::I32,
            ValidatedSampleType::F32 => SampleType::F32,
            ValidatedSampleType::F64 => SampleType::F64,
        }
    }
}

#[derive(Debug, Clone, PartialEq)]
pub struct AudioInfo<I: AudioInfoMarker> {
    pub fp: PathBuf,
    pub base_info: BaseAudioInfo,
    pub specific_info: I,
}

/// Audio file container format types
#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash)]
#[non_exhaustive]
pub enum FileType {
    /// WAV container
    #[default]
    WAV,
    /// MP3 container
    MP3,
    /// OGG container
    OGG,
    /// FLAC container
    FLAC,
    /// AIFF container
    AIFF,
    /// Unknown or unsupported container
    Unknown,
}

impl FileType {
    /// Canonical lowercase file extension
    pub const fn as_str(self) -> &'static str {
        match self {
            FileType::WAV => "wav",
            FileType::MP3 => "mp3",
            FileType::OGG => "ogg",
            FileType::FLAC => "flac",
            FileType::AIFF => "aiff",
            FileType::Unknown => "unknown",
        }
    }

    /// Human-readable descriptive name
    pub const fn description(self) -> &'static str {
        match self {
            FileType::WAV => "Waveform Audio File Format",
            FileType::MP3 => "MPEG-1 Audio Layer III",
            FileType::OGG => "Ogg Vorbis Container",
            FileType::FLAC => "Free Lossless Audio Codec",
            FileType::AIFF => "Audio Interchange File Format",
            FileType::Unknown => "Unknown or unsupported audio container",
        }
    }

    /// True if this container is compressed
    pub const fn is_compressed(self) -> bool {
        matches!(self, FileType::MP3 | FileType::OGG | FileType::FLAC)
    }

    /// True if this container is lossless
    pub const fn is_lossless(self) -> bool {
        matches!(self, FileType::WAV | FileType::FLAC | FileType::AIFF)
    }

    /// Detect file type from path extension without allocating
    pub fn from_path<P: AsRef<Path>>(path: P) -> Self {
        let Some(ext) = path.as_ref().extension().and_then(|e| e.to_str()) else {
            return FileType::Unknown;
        };

        ext.parse().unwrap_or(FileType::Unknown)
    }
}

impl Display for FileType {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        if f.alternate() {
            // "{:#}" → human-readable container name
            write!(f, "{}", self.description())
        } else {
            // "{}" → canonical extension
            write!(f, "{}", self.as_str())
        }
    }
}

impl FromStr for FileType {
    type Err = ();

    fn from_str(s: &str) -> Result<Self, Self::Err> {
        match s {
            "wav" | "WAV" => Ok(FileType::WAV),
            "mp3" | "MP3" => Ok(FileType::MP3),
            "ogg" | "OGG" => Ok(FileType::OGG),
            "flac" | "FLAC" => Ok(FileType::FLAC),
            "aiff" | "aif" | "AIFF" | "AIF" => Ok(FileType::AIFF),
            _ => Err(()),
        }
    }
}

/// Audio file information structure
#[derive(Debug, Copy, Clone, PartialEq)]
pub struct BaseAudioInfo {
    /// Sample rate in Hz
    pub sample_rate: NonZeroU32,
    /// Number of audio channels
    pub channels: u16,
    /// Bits per sample (8, 16, 24, 32)
    pub bits_per_sample: u16,
    /// Bytes per sample
    pub bytes_per_sample: u16,

    /// Byte rate (bytes per second)
    pub byte_rate: u32,
    /// Block align (bytes per sample frame)
    pub block_align: u16,

    /// Total number of samples
    pub total_samples: usize,
    /// Duration in seconds
    pub duration: Duration,
    /// Audio file format
    pub file_type: FileType,
    /// Sample type
    pub sample_type: SampleType,
}

impl BaseAudioInfo {
    pub const fn new(
        sample_rate: NonZeroU32,
        channels: u16,
        bits_per_sample: u16,
        bytes_per_sample: u16,
        byte_rate: u32,
        block_align: u16,
        total_samples: usize,
        duration: Duration,
        file_type: FileType,
        sample_type: SampleType,
    ) -> Self {
        BaseAudioInfo {
            sample_rate,
            channels,
            bits_per_sample,
            bytes_per_sample,
            byte_rate,
            block_align,
            total_samples,
            duration,
            file_type,
            sample_type,
        }
    }
}

impl Display for BaseAudioInfo {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        //
        // -------- COMPACT MODE --------
        //
        if !f.alternate() {
            return write!(
                f,
                "{} {} | {} Hz, {} ch, {}-bit, {:.2} s",
                self.file_type,
                self.sample_type,
                self.sample_rate,
                self.channels,
                self.bits_per_sample,
                self.duration.as_secs_f32()
            );
        }

        //
        // -------- PRETTY MODE --------
        //

        // ============ COLOURED VERSION ============
        #[cfg(feature = "colored")]
        {
            // Helper functions (NOT closures with impl Trait)
            fn label(s: &str) -> ColoredString {
                s.bold().bright_blue()
            }

            fn value<T: ToString>(v: T) -> ColoredString {
                v.to_string().bright_green()
            }

            writeln!(f, "{}", "Audio Info".bold().underline())?;

            writeln!(f, "├─ {}: {}", label("File Type"), value(self.format))?;
            writeln!(
                f,
                "├─ {}: {}",
                label("Sample Type"),
                value(format!("{}", self.sample_type))
            )?;
            writeln!(
                f,
                "├─ {}: {}",
                label("Sample Rate"),
                value(format!("{} Hz", self.sample_rate))
            )?;
            writeln!(f, "├─ {}: {}", label("Channels"), value(self.channels))?;
            writeln!(
                f,
                "├─ {}: {}",
                label("Bits per Sample"),
                value(format!("{}-bit", self.bits_per_sample))
            )?;
            writeln!(
                f,
                "├─ {}: {}",
                label("Bytes per Sample"),
                value(format!("{} bytes", self.bytes_per_sample))
            )?;
            writeln!(
                f,
                "├─ {}: {}",
                label("Total Samples"),
                value(self.n_samples)
            )?;
            writeln!(
                f,
                "└─ {}: {}",
                label("Duration"),
                value(format!("{:.2} s", self.duration.as_secs_f32()))
            )
        }

        // ============ NON-COLOURED VERSION ============
        #[cfg(not(feature = "colored"))]
        {
            writeln!(f, "Audio Info:")?;
            writeln!(f, "├─ File Type: {}", self.file_type)?;
            writeln!(f, "├─ Sample Type: {}", self.sample_type)?;
            writeln!(f, "├─ Sample Rate: {} Hz", self.sample_rate)?;
            writeln!(f, "├─ Channels: {}", self.channels)?;
            writeln!(f, "├─ Bits per Sample: {}-bit", self.bits_per_sample)?;
            writeln!(f, "├─ Bytes per Sample: {} bytes", self.bytes_per_sample)?;
            writeln!(f, "├─ Total Samples: {}", self.total_samples)?;
            writeln!(f, "└─ Duration: {:.2} s", self.duration.as_secs_f32())
        }
    }
}

/// Unified view over audio byte storage
#[non_exhaustive]
pub enum AudioDataSource<'a> {
    /// Owned heap-allocated byte buffer
    Owned(Vec<u8>),

    /// Memory-mapped file (zero-copy, OS-backed)
    MemoryMapped(Mmap),

    /// Borrowed byte slice
    Borrowed(&'a [u8]),
}

impl<'a> AudioDataSource<'a> {
    /// Returns the audio data as a contiguous byte slice
    #[inline]
    pub fn as_bytes(&'a self) -> &'a [u8] {
        match self {
            AudioDataSource::Owned(data) => data.as_slice(),
            AudioDataSource::MemoryMapped(mmap) => mmap.as_ref(),
            AudioDataSource::Borrowed(slice) => slice,
        }
    }

    /// Returns the length of the buffer in bytes
    #[inline]
    pub fn len(&self) -> usize {
        self.as_bytes().len()
    }

    /// Returns true if the buffer is empty
    #[inline]
    pub fn is_empty(&self) -> bool {
        self.len() == 0
    }

    /// Returns a borrowed view if possible, otherwise allocates
    pub fn to_cow(&'a self) -> Cow<'a, [u8]> {
        match self {
            AudioDataSource::Borrowed(slice) => Cow::Borrowed(slice),
            AudioDataSource::Owned(vec) => Cow::Borrowed(vec.as_slice()),
            AudioDataSource::MemoryMapped(mmap) => Cow::Borrowed(mmap.as_ref()),
        }
    }

    /// Forces this source into an owned buffer
    pub fn into_owned(self) -> Vec<u8> {
        match self {
            AudioDataSource::Owned(data) => data,
            AudioDataSource::Borrowed(slice) => slice.to_vec(),
            AudioDataSource::MemoryMapped(mmap) => mmap.as_ref().to_vec(),
        }
    }

    /// Create a memory-mapped source from a file
    pub fn from_file(file: &File) -> io::Result<Self> {
        let mmap = unsafe { Mmap::map(file)? };
        Ok(AudioDataSource::MemoryMapped(mmap))
    }
}

impl<'a> Deref for AudioDataSource<'a> {
    type Target = [u8];

    #[inline]
    fn deref(&self) -> &Self::Target {
        self.as_bytes()
    }
}

impl<'a> From<Vec<u8>> for AudioDataSource<'a> {
    fn from(value: Vec<u8>) -> Self {
        AudioDataSource::Owned(value)
    }
}

impl<'a> From<&'a [u8]> for AudioDataSource<'a> {
    fn from(value: &'a [u8]) -> Self {
        AudioDataSource::Borrowed(value)
    }
}

impl<'a> From<Mmap> for AudioDataSource<'a> {
    fn from(value: Mmap) -> Self {
        AudioDataSource::MemoryMapped(value)
    }
}

impl<'a> From<AudioDataSource<'a>> for Vec<u8> {
    fn from(value: AudioDataSource<'a>) -> Self {
        value.into_owned()
    }
}

impl<'a> AsRef<[u8]> for AudioDataSource<'a> {
    #[inline]
    fn as_ref(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl<'a> Borrow<[u8]> for AudioDataSource<'a> {
    #[inline]
    fn borrow(&self) -> &[u8] {
        self.as_bytes()
    }
}

impl<'a> IntoIterator for &'a AudioDataSource<'a> {
    type Item = u8;
    type IntoIter = std::iter::Copied<std::slice::Iter<'a, u8>>;

    fn into_iter(self) -> Self::IntoIter {
        self.as_bytes().iter().copied()
    }
}

impl<'a> PartialEq<[u8]> for AudioDataSource<'a> {
    fn eq(&self, other: &[u8]) -> bool {
        self.as_bytes() == other
    }
}

impl<'a> PartialEq<AudioDataSource<'a>> for [u8] {
    fn eq(&self, other: &AudioDataSource<'a>) -> bool {
        self == other.as_bytes()
    }
}

impl<'a> From<Cow<'a, [u8]>> for AudioDataSource<'a> {
    fn from(value: Cow<'a, [u8]>) -> Self {
        match value {
            Cow::Borrowed(slice) => AudioDataSource::Borrowed(slice),
            Cow::Owned(vec) => AudioDataSource::Owned(vec),
        }
    }
}

impl<'a> Debug for AudioDataSource<'a> {
    fn fmt(&self, f: &mut Formatter<'_>) -> FmtResult {
        match self {
            AudioDataSource::Owned(data) => f
                .debug_struct("AudioDataSource::Owned")
                .field("len", &data.len())
                .finish(),
            AudioDataSource::MemoryMapped(mmap) => f
                .debug_struct("AudioDataSource::MemoryMapped")
                .field("len", &mmap.len())
                .finish(),
            AudioDataSource::Borrowed(slice) => f
                .debug_struct("AudioDataSource::Borrowed")
                .field("len", &slice.len())
                .finish(),
        }
    }
}

#[derive(Debug, Clone, Copy)]
pub struct OpenOptions {
    pub use_memory_map: bool,
}

impl Default for OpenOptions {
    fn default() -> Self {
        OpenOptions {
            use_memory_map: true,
        }
    }
}

#[allow(dead_code)]
const fn _assert_send_sync()
where
    AudioDataSource<'static>: Send + Sync,
{
}