forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB8a5feaaTahinli2 months ago3162 commits

lib.rs160 lines, 5.6 KiBHistoryRawDownload
1//! MP3 — MPEG-1/2/2.5 Layer III — decoding and encoding for the edith_codecs
2//! family.
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//! Free-format streams are refused by name rather than guessed at, since their
32//! frame length is only knowable by scanning to the next sync word.
33
34#![forbid(unsafe_code)]
35#![warn(missing_docs)]
36
37pub mod decode;
38pub mod encode;
39pub mod header;
40
41mod filterbank;
42mod huffman;
43mod huffman_tables;
44mod tables;
45mod window;
46
47pub use decode::{DecodedFrame, Mp3Decode, Mp3Reader};
48pub use encode::{Mp3Encode, Mp3Encoder, Mp3EncoderConfig};
49pub use header::{ChannelMode, FrameHeader, Version};
50
51use ec_core::error::{Error, Result};
52use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};
53use ec_core::packet::{Buf, Packet};
54use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters};
55
56/// The [`ec_core::Decoder`] seat for MP3: one packet is one or more Layer III
57/// frames, which is how Matroska, MP4 and the family's own probe deliver them.
58#[derive(Debug)]
59pub struct Mp3Decoder {
60 params: CodecParameters,
61 reader: Mp3Reader,
62 pending: Vec<AudioFrame>,
63 drained: bool,
64}
65
66impl Mp3Decoder {
67 /// A decoder for a stream of Layer III packets.
68 pub fn new(params: CodecParameters) -> Result<Mp3Decoder> {
69 Ok(Mp3Decoder {
70 params,
71 reader: Mp3Reader::new(),
72 pending: Vec::new(),
73 drained: false,
74 })
75 }
76
77 // Drains every complete frame the reservoir will yield. `NeedMore`/`Eof`
78 // just mean "nothing left to take yet" and end the loop quietly; any
79 // other error (corrupt CRC, unsupported layer) is real and must reach
80 // the caller rather than vanish here.
81 fn take(&mut self) -> Result<()> {
82 loop {
83 let frame = match self.reader.next_frame() {
84 Ok(frame) => frame,
85 Err(e) if e.is_need_more() || e.is_eof() => return Ok(()),
86 Err(e) => return Err(e),
87 };
88 if frame.samples.is_empty() {
89 continue;
90 }
91 let layout = ChannelLayout::from_count(frame.channels);
92 let mut bytes = Vec::with_capacity(frame.samples.len() * 4);
93 for sample in &frame.samples {
94 bytes.extend_from_slice(&sample.to_ne_bytes());
95 }
96 let samples = frame.samples.len() / frame.channels;
97 if let MediaParameters::Audio(audio) = &mut self.params.media {
98 audio.sample_rate = frame.sample_rate;
99 audio.layout = layout.clone();
100 audio.format = Some(SampleFormat::F32);
101 }
102 if let Ok(audio) = AudioFrame::try_new(
103 SampleFormat::F32,
104 false,
105 layout,
106 frame.sample_rate,
107 samples,
108 vec![Buf::from(bytes)],
109 ) {
110 self.pending.push(audio);
111 }
112 }
113 }
114}
115
116impl Decoder for Mp3Decoder {
117 fn codec_parameters(&self) -> &CodecParameters {
118 &self.params
119 }
120
121 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
122 self.reader.push(packet.data.as_ref());
123 self.take()
124 }
125
126 fn receive_frame(&mut self) -> Result<Frame> {
127 if self.pending.is_empty() {
128 return Err(if self.drained {
129 Error::Eof
130 } else {
131 Error::NeedMore
132 });
133 }
134 Ok(Frame::Audio(self.pending.remove(0)))
135 }
136
137 fn flush(&mut self) -> Result<()> {
138 self.take()?;
139 self.drained = true;
140 Ok(())
141 }
142
143 fn reset(&mut self) {
144 self.reader.reset();
145 self.pending.clear();
146 self.drained = false;
147 }
148}
149
150/// Codec parameters for a Layer III stream of this shape.
151pub fn codec_parameters(sample_rate: u32, channels: usize) -> CodecParameters {
152 let mut params = CodecParameters::new(CodecId::Mp3);
153 params.media = MediaParameters::Audio(AudioParameters {
154 sample_rate,
155 layout: ChannelLayout::from_count(channels),
156 format: Some(SampleFormat::F32),
157 bits_per_sample: None,
158 });
159 params
160}