forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB79a4e31Tahinli2 months ago3812 commits

lib.rs217 lines, 6.5 KiBHistoryRawDownload
1//! `rusty_mp3` 0.6.1's surface, over [`ec_mp3`].
2//!
3//! This crate exists to be swapped in by `[patch.crates-io]`: it carries the
4//! incumbent's name and version so a consumer's `use rusty_mp3::…` compiles
5//! unchanged. Only what edith consumes plus the streaming decoder beside it is
6//! here — [`Mp3Encoder`] with [`Mp3EncoderConfig`], [`Mp3Decoder`] with
7//! [`DecodedAudio`], and an [`Error`] carrying the incumbent's `Eof`/`Again`
8//! contract — because a shim that grows a surface nobody calls is a second
9//! implementation to keep honest.
10//!
11//! Behaviour difference from the incumbent, stated: the encoder writes the
12//! `Xing`/`Info` header frame first, and `vbr_quality` runs true variable
13//! bitrate — per-frame bitrate indices chosen to carry the coded granules
14//! (see [`ec_mp3::encode::Mp3EncoderConfig`]).
15
16#![forbid(unsafe_code)]
17#![warn(missing_docs)]
18
19use std::collections::VecDeque;
20use std::fmt;
21
22/// The incumbent's error type.
23#[derive(Debug)]
24pub enum Error {
25 /// No more frames will arrive.
26 Eof,
27 /// Not enough data buffered yet; push more and retry.
28 Again,
29 /// The bitstream is malformed, or the configuration is not codable.
30 Format(String),
31}
32
33impl fmt::Display for Error {
34 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
35 match self {
36 Error::Eof => write!(f, "end of stream"),
37 Error::Again => write!(f, "need more data"),
38 Error::Format(why) => write!(f, "mp3: {why}"),
39 }
40 }
41}
42
43impl std::error::Error for Error {}
44
45impl From<ec_core::error::Error> for Error {
46 fn from(error: ec_core::error::Error) -> Error {
47 match error {
48 ec_core::error::Error::Eof => Error::Eof,
49 ec_core::error::Error::NeedMore => Error::Again,
50 other => Error::Format(other.to_string()),
51 }
52 }
53}
54
55/// The incumbent's result alias.
56pub type Result<T> = std::result::Result<T, Error>;
57
58/// One decoded frame of audio.
59#[derive(Debug, Clone)]
60pub struct DecodedAudio {
61 /// Sample rate in Hz.
62 pub sample_rate: u32,
63 /// Channel count.
64 pub channels: u16,
65 /// Interleaved samples in `[-1, 1]`.
66 pub samples: Vec<f32>,
67}
68
69/// A streaming MP3 decoder.
70#[derive(Debug, Default)]
71pub struct Mp3Decoder {
72 reader: ec_mp3::Mp3Reader,
73 queue: VecDeque<DecodedAudio>,
74 eof: bool,
75}
76
77impl Mp3Decoder {
78 /// A decoder with nothing buffered.
79 pub fn new() -> Mp3Decoder {
80 Mp3Decoder::default()
81 }
82
83 /// Buffers bytes and decodes whatever whole frames they complete.
84 pub fn push(&mut self, bytes: &[u8]) {
85 self.reader.push(bytes);
86 while let Ok(frame) = self.reader.next_frame() {
87 self.queue.push_back(DecodedAudio {
88 sample_rate: frame.sample_rate,
89 channels: frame.channels as u16,
90 samples: frame.samples,
91 });
92 }
93 }
94
95 /// The next decoded frame, [`Error::Again`] until one is complete and
96 /// [`Error::Eof`] once [`Mp3Decoder::flush`] has been called and drained.
97 pub fn next_frame(&mut self) -> Result<DecodedAudio> {
98 match self.queue.pop_front() {
99 Some(frame) => Ok(frame),
100 None if self.eof => Err(Error::Eof),
101 None => Err(Error::Again),
102 }
103 }
104
105 /// Marks the end of input.
106 pub fn flush(&mut self) {
107 self.eof = true;
108 }
109}
110
111/// Encoder settings, field for field as the incumbent declares them.
112#[derive(Debug, Clone, Default)]
113pub struct Mp3EncoderConfig {
114 /// Constant bitrate in kbit/s.
115 pub bitrate_kbps: u32,
116 /// Quality on a normalised `[0, 1]` scale instead of a bitrate.
117 pub vbr_quality: Option<f32>,
118}
119
120/// The incumbent's quality-to-bitrate curve, in kbit/s.
121pub fn vbr_quality_index(q: f32) -> f32 {
122 ec_mp3::encode::bitrate_for_quality(q) as f32
123}
124
125/// A streaming MP3 encoder.
126#[derive(Debug)]
127pub struct Mp3Encoder {
128 inner: ec_mp3::Mp3Encoder,
129}
130
131impl Mp3Encoder {
132 /// An encoder that configures itself from the first PCM it is given.
133 pub fn new(config: Mp3EncoderConfig) -> Mp3Encoder {
134 Mp3Encoder {
135 inner: ec_mp3::Mp3Encoder::new(ec_mp3::Mp3EncoderConfig {
136 bitrate_kbps: config.bitrate_kbps,
137 vbr_quality: config.vbr_quality,
138 }),
139 }
140 }
141
142 /// Feeds interleaved `f32` samples.
143 pub fn push_pcm_f32(
144 &mut self,
145 interleaved: &[f32],
146 channels: u16,
147 sample_rate: u32,
148 ) -> Result<()> {
149 Ok(self
150 .inner
151 .push_pcm_f32(interleaved, channels, sample_rate)?)
152 }
153
154 /// Feeds interleaved 16-bit samples.
155 pub fn push_pcm_s16(
156 &mut self,
157 interleaved: &[i16],
158 channels: u16,
159 sample_rate: u32,
160 ) -> Result<()> {
161 Ok(self
162 .inner
163 .push_pcm_s16(interleaved, channels, sample_rate)?)
164 }
165
166 /// Ends the stream and flushes the tail.
167 pub fn finish(&mut self) {
168 self.inner.finish();
169 }
170
171 /// The next complete frame; [`Error::Eof`] once drained after
172 /// [`Mp3Encoder::finish`].
173 pub fn next_packet(&mut self) -> Result<Vec<u8>> {
174 Ok(self.inner.next_packet()?)
175 }
176}
177
178#[cfg(test)]
179mod tests {
180 use super::*;
181
182 /// The call shape edith uses, end to end: config in, frames out, and our
183 /// own decoder reads them back.
184 #[test]
185 fn encodes_and_decodes_through_the_incumbent_surface() {
186 let rate = 44100;
187 let pcm: Vec<i16> = (0..rate * 2 / 4)
188 .map(|i| ((i as f32 * 0.05).sin() * 8000.0) as i16)
189 .collect();
190 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
191 bitrate_kbps: 192,
192 vbr_quality: None,
193 });
194 encoder.push_pcm_s16(&pcm, 2, rate as u32).unwrap();
195 encoder.finish();
196 let mut bytes = Vec::new();
197 while let Ok(frame) = encoder.next_packet() {
198 bytes.extend_from_slice(&frame);
199 }
200 assert!(bytes.len() > 1000, "wrote {} bytes", bytes.len());
201
202 let mut decoder = Mp3Decoder::new();
203 decoder.push(&bytes);
204 decoder.flush();
205 let mut frames = 0;
206 let mut samples = 0;
207 while let Ok(frame) = decoder.next_frame() {
208 assert_eq!(frame.sample_rate, rate as u32);
209 assert_eq!(frame.channels, 2);
210 frames += 1;
211 samples += frame.samples.len();
212 }
213 assert!(frames > 5, "decoded {frames} frames");
214 assert!(samples >= pcm.len() / 2, "decoded {samples} samples");
215 assert!(matches!(decoder.next_frame(), Err(Error::Eof)));
216 }
217}