forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

lib.rs178 lines, 6.5 KiBHistoryRawDownload
1//! MP3 — MPEG-1/2/2.5 Layer III — decoding and encoding for the edith_codecs
2//! family, plus Layer I and II (MP1/MP2) decoding.
3//!
4//! Three ways in, smallest first:
5//!
6//! - [`Mp3Reader`] over a byte stream: push bytes, take frames. It skips ID3v2
7//! and the Xing/gapless/VBRI header frame, resyncs over junk, and keeps the bit
8//! reservoir across frames.
9//! - [`Mp3Decoder`], the [`ec_core::Decoder`] contract, for a container that
10//! hands out one Layer III frame per packet.
11//! - [`Mp3Encoder`]: interleaved PCM in, CBR Layer III frames out, with a
12//! Xing/Info header carrying the encoder delay and padding — so a decoder
13//! that honours it hands back exactly the samples that went in, with no
14//! leading or trailing silence.
15//!
16//! **Where the constants came from.** Layer III's Huffman code tables and its
17//! 512-tap polyphase window are normative data no formula produces. Rather
18//! than copy them out of an existing implementation, `scripts/mp3-tables/`
19//! *measures* them: it writes legal frames whose main-data bits it chooses,
20//! decodes them with the oracle, and reads the answer back through a model of the
21//! decode chain. Every code tree is walked to a leaf, checked for a Kraft sum
22//! of exactly 1 and for complete, duplicate-free coverage of its value grid;
23//! the window is least-squares fitted to a residual of 1.6e-6. The measured
24//! scalefactor band widths agreed with the published MPEG-1 layouts exactly,
25//! which is the cross-check that the rig itself was right.
26//!
27//! Everything else — side info, the bit reservoir, requantisation, stereo
28//! coupling, the block windows, the psychoacoustic model — is written from the
29//! standards (ISO/IEC 11172-3 and 13818-3).
30//!
31//! **Layers I and II.** The same [`Mp3Reader`], [`Mp3Decode`] and [`Mp3Decoder`]
32//! decode MPEG-1/2/2.5 Layer I and II frames (selected by the header, so a
33//! stream may even mix them), through the same polyphase bank run in f64 with the
34//! exact `D[i]` window. Layer II's allocation tables were measured from an oracle
35//! like the Layer III ones (`scripts/mp2-tables/`). Joint-stereo intensity bound
36//! and CRC are honoured; the MPEG-2 multichannel extension is ignored (the
37//! stereo base is decoded). There is no Layer I/II encoder.
38//!
39//! Free-format streams are refused by name rather than guessed at, since their
40//! frame length is only knowable by scanning to the next sync word.
41
42#![forbid(unsafe_code)]
43#![warn(missing_docs)]
44
45pub mod decode;
46pub mod encode;
47pub mod header;
48
49mod filterbank;
50mod huffman;
51mod huffman_tables;
52mod layer12;
53mod tables;
54mod window;
55
56pub use decode::{DecodedFrame, Mp3Decode, Mp3Reader};
57pub use encode::{Mp3Encode, Mp3Encoder, Mp3EncoderConfig};
58pub use header::{ChannelMode, FrameHeader, Version};
59
60use ec_core::error::{Error, Result};
61use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};
62use ec_core::packet::{Buf, Packet};
63use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters};
64
65/// The [`ec_core::Decoder`] seat for MP3: one packet is one or more Layer III
66/// frames, which is how Matroska, MP4 and the family's own probe deliver them.
67#[derive(Debug)]
68pub struct Mp3Decoder {
69 params: CodecParameters,
70 reader: Mp3Reader,
71 pending: Vec<AudioFrame>,
72 drained: bool,
73}
74
75impl Mp3Decoder {
76 /// A decoder for a stream of Layer III packets.
77 pub fn new(params: CodecParameters) -> Result<Mp3Decoder> {
78 Ok(Mp3Decoder {
79 params,
80 reader: Mp3Reader::new(),
81 pending: Vec::new(),
82 drained: false,
83 })
84 }
85
86 // Drains every complete frame the reservoir will yield. `NeedMore`/`Eof`
87 // just mean "nothing left to take yet" and end the loop quietly; any
88 // other error (corrupt CRC, unsupported layer) is real and must reach
89 // the caller rather than vanish here.
90 fn take(&mut self) -> Result<()> {
91 loop {
92 let frame = match self.reader.next_frame() {
93 Ok(frame) => frame,
94 Err(e) if e.is_need_more() || e.is_eof() => return Ok(()),
95 Err(e) => return Err(e),
96 };
97 if frame.samples.is_empty() {
98 continue;
99 }
100 let layout = ChannelLayout::from_count(frame.channels);
101 let mut bytes = Vec::with_capacity(frame.samples.len() * 4);
102 for sample in &frame.samples {
103 bytes.extend_from_slice(&sample.to_ne_bytes());
104 }
105 let samples = frame.samples.len() / frame.channels;
106 if let MediaParameters::Audio(audio) = &mut self.params.media {
107 audio.sample_rate = frame.sample_rate;
108 audio.layout = layout.clone();
109 audio.format = Some(SampleFormat::F32);
110 }
111 if let Ok(audio) = AudioFrame::try_new(
112 SampleFormat::F32,
113 false,
114 layout,
115 frame.sample_rate,
116 samples,
117 vec![Buf::from(bytes)],
118 ) {
119 self.pending.push(audio);
120 }
121 }
122 }
123}
124
125impl Decoder for Mp3Decoder {
126 fn codec_parameters(&self) -> &CodecParameters {
127 &self.params
128 }
129
130 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
131 self.reader.push(packet.data.as_ref());
132 self.take()
133 }
134
135 fn receive_frame(&mut self) -> Result<Frame> {
136 if self.pending.is_empty() {
137 return Err(if self.drained {
138 Error::Eof
139 } else {
140 Error::NeedMore
141 });
142 }
143 Ok(Frame::Audio(self.pending.remove(0)))
144 }
145
146 fn flush(&mut self) -> Result<()> {
147 self.take()?;
148 self.drained = true;
149 Ok(())
150 }
151
152 fn reset(&mut self) {
153 self.reader.reset();
154 self.pending.clear();
155 self.drained = false;
156 }
157}
158
159/// Codec parameters for a Layer III stream of this shape.
160pub fn codec_parameters(sample_rate: u32, channels: usize) -> CodecParameters {
161 layer_codec_parameters(3, sample_rate, channels)
162}
163
164/// Codec parameters for a Layer I (`1`), II (`2`) or III (anything else) stream.
165pub fn layer_codec_parameters(layer: u8, sample_rate: u32, channels: usize) -> CodecParameters {
166 let mut params = CodecParameters::new(match layer {
167 1 => CodecId::Mp1,
168 2 => CodecId::Mp2,
169 _ => CodecId::Mp3,
170 });
171 params.media = MediaParameters::Audio(AudioParameters {
172 sample_rate,
173 layout: ChannelLayout::from_count(channels),
174 format: Some(SampleFormat::F32),
175 bits_per_sample: None,
176 });
177 params
178}