Skip to main content

nanomp3/
load.rs

1//! Decoding a whole stream into memory (`mp3dec_load_*` in minimp3_ex).
2
3use alloc::vec::Vec;
4
5use crate::frames::raw_info;
6use crate::reader::Options;
7use crate::tags::strip_tags_impl;
8use crate::vbr::check_vbrtag;
9use crate::{Channels, Decoder, Sample, VbrTag, MAX_SAMPLES_PER_FRAME};
10use nanomp3_core::__private::{self as core_private, find_frame, FrameInfo as RawInfo, Header};
11
12/// A decoded stream, from [`decode_all`].
13#[derive(Debug, Clone)]
14#[non_exhaustive]
15pub struct Decoded<S> {
16    /// Interleaved samples, with the encoder delay and padding trimmed when
17    /// the stream has a LAME/Lavc tag.
18    pub samples: Vec<S>,
19    /// Channels of the stream; `None` if there was no audio, or the stream
20    /// switched between mono and stereo (see
21    /// [`Options::allow_mono_stereo_transition`]).
22    pub channels: Option<Channels>,
23    /// Sample rate in Hz (0 if there was no audio).
24    pub sample_rate: u32,
25    /// MPEG layer (1, 2 or 3; 0 if there was no audio).
26    pub layer: u8,
27    /// Average of the frame bitrates, in kbps.
28    pub avg_bitrate_kbps: u32,
29    /// Decoding stopped early because the sample rate, layer or (unless
30    /// allowed) channel count changed; `samples` holds the audio before that.
31    pub format_changed: bool,
32}
33
34impl<S> Decoded<S> {
35    pub(crate) fn empty() -> Self {
36        Self { samples: Vec::new(), channels: None, sample_rate: 0, layer: 0, avg_bitrate_kbps: 0, format_changed: false }
37    }
38}
39
40/// Decodes all of `data` (`mp3dec_load_buf`). Tags are skipped, and the
41/// encoder delay and padding are trimmed when the stream has a LAME/Lavc tag.
42pub fn decode_all<S: Sample>(data: &[u8]) -> Decoded<S> {
43    decode_all_with(data, Options::default())
44}
45
46/// [`decode_all`] with options. [`Options::skip_scan`] has no effect.
47pub fn decode_all_with<S: Sample>(data: &[u8], options: Options) -> Decoded<S> {
48    let compat = options.minimp3_compat;
49    let mut out = Decoded::empty();
50    let mut buf = strip_tags_impl(data, compat);
51    if buf.is_empty() {
52        return out;
53    }
54
55    // Find the first frame and check it for a VBR tag.
56    let mut to_skip = 0;
57    let mut detected = 0;
58    let mut frame_info;
59    loop {
60        let (i, frame_size) = find_frame(buf, &mut 0);
61        buf = &buf[i..];
62        if i != 0 && frame_size == 0 {
63            continue;
64        }
65        if frame_size == 0 {
66            return out;
67        }
68        frame_info = raw_info(Header::read(buf), frame_size);
69        if frame_info.layer != 3 {
70            break;
71        }
72        let tag = check_vbrtag(buf, frame_size);
73        if let Some(tag @ VbrTag { frames: Some(frames), .. }) = tag {
74            let samples = u64::from(Header::read(buf).frame_samples()) * u64::from(frame_info.channels);
75            let channels = i32::from(frame_info.channels);
76            let (delay, padding) = tag.delay_padding();
77            let padding = padding * channels;
78            to_skip = delay * channels;
79            detected = samples * u64::from(frames);
80            if detected >= to_skip as u64 {
81                detected -= to_skip as u64;
82            }
83            if padding > 0 && detected >= padding as u64 {
84                detected -= padding as u64;
85            }
86            if detected == 0 {
87                return out;
88            }
89        }
90        if tag.is_some() {
91            buf = &buf[frame_size..];
92        }
93        break;
94    }
95
96    let mut decoder = if compat { Decoder::new_minimp3_compat() } else { Decoder::new() };
97    load_body(&mut out, &mut decoder, &mut frame_info, to_skip, detected, options, |dec, pcm, info| {
98        let n = core_private::decode_frame(dec, &buf[..buf.len().min(i32::MAX as usize)], Some(pcm), info);
99        buf = &buf[info.frame_bytes..];
100        Some(n)
101    });
102    out
103}
104
105/// The decode loop shared by [`decode_all`] and
106/// [`decode_all_reader`](crate::decode_all_reader). `decode` decodes the next
107/// frame into `pcm`, or returns `None` to stop (on an I/O error).
108pub(crate) fn load_body<S: Sample>(
109    out: &mut Decoded<S>,
110    dec: &mut Decoder,
111    frame_info: &mut RawInfo,
112    mut to_skip: i32,
113    detected: u64,
114    options: Options,
115    mut decode: impl FnMut(&mut Decoder, &mut [S], &mut RawInfo) -> Option<usize>,
116) {
117    let mut channels = frame_info.channels;
118    out.sample_rate = frame_info.hz;
119    out.layer = frame_info.layer;
120    let (mut len, mut bitrate_sum, mut frames) = (0usize, 0u64, 0u64);
121    let zero = S::from_synth(0.0, false);
122    loop {
123        if out.samples.len() < len + MAX_SAMPLES_PER_FRAME {
124            out.samples.resize(len + MAX_SAMPLES_PER_FRAME, zero);
125        }
126        let Some(samples) = decode(dec, &mut out.samples[len..], frame_info) else {
127            break;
128        };
129        if samples != 0 {
130            if out.sample_rate != frame_info.hz || out.layer != frame_info.layer {
131                out.format_changed = true;
132                break;
133            }
134            if channels != 0 && channels != frame_info.channels {
135                if options.allow_mono_stereo_transition {
136                    channels = 0; // mark the stream as mixed
137                } else {
138                    out.format_changed = true;
139                    break;
140                }
141            }
142            let mut samples = samples * usize::from(frame_info.channels);
143            if to_skip > 0 {
144                let skip = samples.min(to_skip as usize);
145                to_skip -= skip as i32;
146                samples -= skip;
147                // minimp3 moves the rest to the very start of the buffer, which
148                // is where it belongs: nothing is kept while skipping.
149                out.samples.copy_within(len + skip..len + skip + samples, 0);
150            }
151            len += samples;
152            bitrate_sum += u64::from(frame_info.bitrate_kbps);
153            frames += 1;
154        }
155        if frame_info.frame_bytes == 0 {
156            break;
157        }
158    }
159    if detected != 0 && len as u64 > detected {
160        len = detected as usize; // cut the padding
161    }
162    out.samples.truncate(len);
163    out.channels = match channels {
164        1 => Some(Channels::Mono),
165        2 => Some(Channels::Stereo),
166        _ => None,
167    };
168    if let Some(avg) = bitrate_sum.checked_div(frames) {
169        out.avg_bitrate_kbps = avg as u32;
170    }
171}