Skip to main content

threers_codec/
audio_file.rs

1//! One entry point for audio files, decoded the way libsndfile
2//! (`soundfile.read`) returns them: planar float, signed integers scaled by
3//! `1 / 2^(bits-1)`. Formats: WAV/RF64, AIFF/AIFF-C, FLAC (native and in
4//! Ogg), Vorbis in Ogg and MP3, plus AAC in MP4/M4A and Opus in
5//! WebM/Matroska (which libsndfile cannot read; decoded as ffmpeg 7.1 does).
6//! Recognised by content, not extension.
7//!
8//! ```no_run
9//! let pcm = threers_codec::audio_file::read(&std::fs::read("take.m4a").unwrap()).unwrap();
10//! println!("{:.2}s of {}-channel audio", pcm.duration(), pcm.channels.len());
11//! ```
12
13use super::pcm::Pcm;
14
15/// What kind of file `data` holds.
16#[derive(Debug, Clone, Copy, PartialEq, Eq)]
17pub enum Kind {
18    /// RIFF WAVE or RF64.
19    Wav,
20    /// AIFF or AIFF-C.
21    Aiff,
22    /// Native FLAC (`fLaC`).
23    Flac,
24    /// An Ogg stream: FLAC or Vorbis.
25    Ogg,
26    /// MPEG audio Layer III, with or without an ID3v2 tag.
27    Mp3,
28    /// ISO base media (MP4/M4A) carrying AAC.
29    Mp4,
30    /// Matroska or WebM carrying Opus.
31    Matroska,
32    /// None of the above.
33    Unknown,
34}
35
36/// What kind of file `data` holds, judged from its first bytes.
37pub fn sniff(data: &[u8]) -> Kind {
38    let h = |s: &[u8]| data.starts_with(s);
39    if h(b"RIFF") || h(b"RF64") {
40        Kind::Wav
41    } else if h(b"FORM") {
42        Kind::Aiff
43    } else if h(b"fLaC") {
44        Kind::Flac
45    } else if h(b"OggS") {
46        Kind::Ogg
47    } else if h(b"ID3") {
48        // ID3v2 in front of FLAC or MPEG audio.
49        let sz = data.get(6..10).map_or(0, |b| {
50            b.iter()
51                .fold(0usize, |a, &x| (a << 7) | (x & 0x7f) as usize)
52        });
53        if data.get(10 + sz..14 + sz) == Some(b"fLaC".as_slice()) {
54            Kind::Flac
55        } else {
56            Kind::Mp3
57        }
58    } else if h(&[0x1a, 0x45, 0xdf, 0xa3]) {
59        Kind::Matroska
60    } else if matches!(
61        data.get(4..8),
62        Some(b"ftyp" | b"moov" | b"mdat" | b"wide" | b"free")
63    ) {
64        Kind::Mp4
65    } else if (data.len() > 2 && data[0] == 0xff && data[1] & 0xe0 == 0xe0)
66        || super::mp3::probe(data)
67    {
68        Kind::Mp3
69    } else {
70        Kind::Unknown
71    }
72}
73
74/// Decode an audio file to planar float.
75pub fn read(data: &[u8]) -> Result<Pcm, String> {
76    match sniff(data) {
77        Kind::Wav => super::pcm::read_wav(data),
78        Kind::Aiff => super::pcm::read_aiff(data),
79        Kind::Flac => {
80            let f = super::flac::decode(data)?;
81            Ok(Pcm {
82                sample_rate: f.info.sample_rate,
83                channels: f.to_f32(),
84            })
85        }
86        Kind::Mp4 => {
87            let a = super::aac::decode_mp4(data).map_err(|e| e.to_string())?;
88            Ok(Pcm {
89                sample_rate: a.sample_rate,
90                channels: a.planes,
91            })
92        }
93        Kind::Matroska => {
94            let d = super::opus::decode_matroska(data)?.ok_or("no audio track")?;
95            Ok(Pcm {
96                sample_rate: d.sample_rate,
97                channels: d.planes,
98            })
99        }
100        Kind::Ogg => {
101            if super::ogg::packets(data)?
102                .0
103                .first()
104                .is_some_and(|p| p.data.starts_with(b"\x7fFLAC"))
105            {
106                let f = super::ogg::decode_flac(data)?;
107                Ok(Pcm {
108                    sample_rate: f.info.sample_rate,
109                    channels: f.to_f32(),
110                })
111            } else {
112                let v = super::vorbis::decode_ogg(data)?;
113                Ok(Pcm {
114                    sample_rate: v.sample_rate,
115                    channels: v.channels,
116                })
117            }
118        }
119        Kind::Mp3 => {
120            let m = super::mp3::decode(data)?;
121            let n = m.channels;
122            let channels = (0..n)
123                .map(|c| m.samples.iter().skip(c).step_by(n).copied().collect())
124                .collect();
125            Ok(Pcm {
126                sample_rate: m.sample_rate,
127                channels,
128            })
129        }
130        Kind::Unknown => Err("unrecognised audio format".into()),
131    }
132}