nanomp3_core/lib.rs
1//! The MPEG audio frame decoder behind [nanomp3](https://docs.rs/nanomp3): a
2//! safe Rust port of [minimp3](https://github.com/lieff/minimp3) whose output
3//! is bit-identical to upstream's.
4//!
5//! It's `no_std`, allocates nothing and does no buffering: [`Decoder::decode`]
6//! finds and decodes one frame at a time from the bytes you give it. Because a
7//! frame only counts once the frames after it are seen to be consistent, keep
8//! several frames of input available (16 KiB is plenty) and refill as it
9//! drains.
10//!
11//! ```
12//! # let data: &[u8] = &[];
13//! use nanomp3_core::{DecodeError, Decoder, MAX_SAMPLES_PER_FRAME};
14//!
15//! let mut decoder = Decoder::new();
16//! let mut pcm = [0f32; MAX_SAMPLES_PER_FRAME]; // or i16, u8, i32, ...
17//! let mut mp3 = data;
18//! while !mp3.is_empty() {
19//! let (consumed, result) = decoder.decode(mp3, &mut pcm);
20//! mp3 = &mp3[consumed..];
21//! match result {
22//! Ok(info) => {
23//! let samples = &pcm[..info.samples_produced * info.channels.num() as usize];
24//! // ... interleaved samples at info.sample_rate
25//! }
26//! // Normal while starting up or after a seek; later frames decode.
27//! Err(DecodeError::ReservoirUnavailable(_)) => {}
28//! Err(e) => eprintln!("skipped: {e}"),
29//! }
30//! }
31//! ```
32//!
33//! Most users want the `nanomp3` crate, which re-exports this one and adds a
34//! seekable reader with its own buffering, gapless playback, and tag handling.
35//!
36//! # Features
37//!
38//! - `wide` (default): explicit SIMD via the `wide` crate. Without it, the
39//! same kernels run on plain arrays and rely on LLVM's auto-vectorizer.
40//! - `layer12` (default): decode MPEG Layer I and II frames too. Without it
41//! they are reported as [`DecodeError::UnsupportedLayer`], like minimp3
42//! built with `MINIMP3_ONLY_MP3`.
43
44#![no_std]
45#![forbid(unsafe_code)]
46
47mod minimp3;
48
49pub use minimp3::Sample;
50
51#[doc(hidden)]
52pub mod __private {
53 //! Internals shared with the `nanomp3` crate, which pins an exact version
54 //! of this one. Not public API: no semver guarantees.
55 pub use crate::minimp3::{l3_side_info, mp3d_find_frame as find_frame, FrameInfo, Header};
56 use crate::{minimp3, Decoder, Sample};
57
58 /// `mp3dec_decode_frame` with C's `info` semantics: when no frame is
59 /// found, only `frame_bytes` is written.
60 pub fn decode_frame<S: Sample>(
61 dec: &mut Decoder,
62 mp3: &[u8],
63 pcm: Option<&mut [S]>,
64 info: &mut FrameInfo,
65 ) -> usize {
66 minimp3::mp3dec_decode_frame(&mut dec.dec, mp3, pcm, info, dec.minimp3_compat)
67 }
68
69 /// `mp3dec_init`.
70 pub fn init(dec: &mut Decoder) {
71 minimp3::mp3dec_init(&mut dec.dec);
72 }
73}
74
75#[cfg(test)]
76mod tests;
77
78/// The minimum length of the PCM output buffer, in samples.
79pub const MAX_SAMPLES_PER_FRAME: usize = 1152*2;
80
81/// The core MP3 decoder, with no internal buffering.
82///
83/// The decoder is about 22 KiB: it holds the filterbank state between frames
84/// and the working memory for decoding one. Nothing is allocated.
85#[derive(Clone)]
86pub struct Decoder {
87 dec: minimp3::Mp3Dec,
88 minimp3_compat: bool,
89}
90
91
92/// The channel formats that may be encoded in an MP3 frame.
93#[derive(Debug, Clone, Copy, PartialEq, Eq, PartialOrd, Ord)]
94pub enum Channels {
95 Mono = 1,
96 Stereo
97}
98
99impl Channels {
100 /// Returns the corresponding number of channels for `self`.
101 pub fn num(self) -> u8 {
102 self as u8
103 }
104}
105
106/// Information about a frame found by [`Decoder::decode`].
107#[derive(Debug, Clone, Copy, PartialEq, Eq)]
108#[non_exhaustive]
109pub struct FrameInfo {
110 /// The number of PCM samples produced per channel (0 when the frame
111 /// produced no audio).
112 pub samples_produced: usize,
113 /// The number of channels in this frame.
114 pub channels: Channels,
115 /// Sample rate of this frame, in Hz.
116 pub sample_rate: u32,
117 /// The frame's bitrate, in kilobits per second (0 for free-format streams).
118 pub bitrate: u32,
119 /// The MPEG layer: 1, 2 or 3 (MP1, MP2 or MP3).
120 pub layer: u8,
121}
122
123/// Why [`Decoder::decode`] produced no audio.
124///
125/// Every variant except `NoFrame` carries the frame's header information.
126/// `NoFrame` at the end of the input and `ReservoirUnavailable` right after
127/// starting or seeking are part of normal decoding.
128#[derive(Debug, Clone, Copy, PartialEq, Eq)]
129#[non_exhaustive]
130pub enum DecodeError {
131 /// The input holds no complete frame, so the consumed bytes (all of the
132 /// input, unless it was empty) were skipped as tags or junk. At the end of
133 /// a stream this means there's nothing left; mid-stream, the input was
134 /// cut short or corrupt.
135 NoFrame,
136 /// The frame uses bit-reservoir data from earlier frames that weren't
137 /// decoded, as happens for the first frame or two after starting in the
138 /// middle of a stream or seeking. Later frames decode normally.
139 ReservoirUnavailable(FrameInfo),
140 /// The frame is corrupt and was skipped.
141 Corrupt(FrameInfo),
142 /// The frame is Layer I or II and the `layer12` feature is disabled.
143 UnsupportedLayer(FrameInfo),
144}
145
146impl DecodeError {
147 /// The header information of the skipped frame, if there was one.
148 pub fn frame_info(&self) -> Option<&FrameInfo> {
149 match self {
150 DecodeError::NoFrame => None,
151 DecodeError::ReservoirUnavailable(info)
152 | DecodeError::Corrupt(info)
153 | DecodeError::UnsupportedLayer(info) => Some(info),
154 }
155 }
156}
157
158impl core::fmt::Display for DecodeError {
159 fn fmt(&self, f: &mut core::fmt::Formatter<'_>) -> core::fmt::Result {
160 f.write_str(match self {
161 DecodeError::NoFrame => "no complete MPEG audio frame in the input",
162 DecodeError::ReservoirUnavailable(_) => "frame depends on bit reservoir data that wasn't decoded",
163 DecodeError::Corrupt(_) => "corrupt frame",
164 DecodeError::UnsupportedLayer(_) => "Layer I/II frame (the layer12 feature is disabled)",
165 })
166 }
167}
168
169impl core::error::Error for DecodeError {}
170
171impl Decoder {
172 /// Instantiates a `Decoder`.
173 pub const fn new() -> Self {
174 Self { dec: minimp3::Mp3Dec::new(), minimp3_compat: false }
175 }
176
177 /// Instantiates a `Decoder` whose output is bit-identical to minimp3's,
178 /// including quirks nanomp3 otherwise corrects. Currently that only
179 /// affects `i16` output, where minimp3 rounds samples in (−1.5, −0.5] to
180 /// 0 instead of −1 (see [`Sample`]).
181 pub const fn new_minimp3_compat() -> Self {
182 Self { dec: minimp3::Mp3Dec::new(), minimp3_compat: true }
183 }
184
185 /// Decodes the next frame of `mp3` into `pcm`. Returns how many bytes of
186 /// `mp3` were consumed (always advance past them, whatever the result) and
187 /// either the decoded frame's information or why no audio came out.
188 ///
189 /// `mp3` should hold several frames' worth of data (16 KiB is plenty):
190 /// frames are only recognized once the frames after them are seen, and a
191 /// frame cut off at the end of the input is skipped as junk.
192 ///
193 /// Samples are interleaved. `pcm` can hold `f32` samples (nominally in
194 /// `[-1.0, 1.0]`, not clipped) or signed or unsigned 8-, 16- or 32-bit
195 /// integers; see [`Sample`] for the conversions.
196 ///
197 /// # Panics
198 ///
199 /// Panics if `pcm` is less than [`MAX_SAMPLES_PER_FRAME`] long.
200 pub fn decode<S: Sample>(&mut self, mp3: &[u8], pcm: &mut [S]) -> (usize, Result<FrameInfo, DecodeError>) {
201 assert!(pcm.len() >= MAX_SAMPLES_PER_FRAME, "pcm buffer too small");
202
203 let mut info = minimp3::FrameInfo::default();
204 let samples = minimp3::mp3dec_decode_frame(&mut self.dec, mp3, Some(pcm), &mut info, self.minimp3_compat);
205 let frame = FrameInfo {
206 samples_produced: samples,
207 channels: if info.channels == 1 { Channels::Mono } else { Channels::Stereo },
208 sample_rate: info.hz,
209 bitrate: info.bitrate_kbps,
210 layer: info.layer,
211 };
212 let result = match info.status {
213 minimp3::Status::Decoded => Ok(frame),
214 minimp3::Status::NoFrame | minimp3::Status::HeaderOnly => Err(DecodeError::NoFrame),
215 minimp3::Status::Corrupt => Err(DecodeError::Corrupt(frame)),
216 minimp3::Status::ReservoirUnavailable => Err(DecodeError::ReservoirUnavailable(frame)),
217 minimp3::Status::UnsupportedLayer => Err(DecodeError::UnsupportedLayer(frame)),
218 };
219 (info.frame_bytes, result)
220 }
221}
222
223impl Default for Decoder {
224 fn default() -> Self {
225 Self::new()
226 }
227}