forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB30d372eTahinli3 months ago42 commits

lib.rs149 lines, 5.0 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/LAME/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.
12//!
13//! **Where the constants came from.** Layer III's Huffman code tables and its
14//! 512-tap polyphase window are normative data no formula produces. Rather
15//! than copy them out of an existing implementation, `scripts/mp3-tables/`
16//! *measures* them: it writes legal frames whose main-data bits it chooses,
17//! decodes them with ffmpeg, and reads the answer back through a model of the
18//! decode chain. Every code tree is walked to a leaf, checked for a Kraft sum
19//! of exactly 1 and for complete, duplicate-free coverage of its value grid;
20//! the window is least-squares fitted to a residual of 1.6e-6. The measured
21//! scalefactor band widths agreed with the published MPEG-1 layouts exactly,
22//! which is the cross-check that the rig itself was right.
23//!
24//! Everything else — side info, the bit reservoir, requantisation, stereo
25//! coupling, the block windows, the psychoacoustic model — is written from the
26//! standards (ISO/IEC 11172-3 and 13818-3).
27//!
28//! Free-format streams are refused by name rather than guessed at, since their
29//! frame length is only knowable by scanning to the next sync word.
30
31#![forbid(unsafe_code)]
32#![warn(missing_docs)]
33
34pub mod decode;
35pub mod encode;
36pub mod header;
37
38mod filterbank;
39mod huffman;
40mod huffman_tables;
41mod tables;
42mod window;
43
44pub use decode::{DecodedFrame, Mp3Decode, Mp3Reader};
45pub use encode::{Mp3Encode, Mp3Encoder, Mp3EncoderConfig};
46pub use header::{ChannelMode, FrameHeader, Version};
47
48use ec_core::error::{Error, Result};
49use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};
50use ec_core::packet::{Buf, Packet};
51use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters};
52
53/// The [`ec_core::Decoder`] seat for MP3: one packet is one or more Layer III
54/// frames, which is how Matroska, MP4 and the family's own probe deliver them.
55#[derive(Debug)]
56pub struct Mp3Decoder {
57 params: CodecParameters,
58 reader: Mp3Reader,
59 pending: Vec<AudioFrame>,
60 drained: bool,
61}
62
63impl Mp3Decoder {
64 /// A decoder for a stream of Layer III packets.
65 pub fn new(params: CodecParameters) -> Result<Mp3Decoder> {
66 Ok(Mp3Decoder {
67 params,
68 reader: Mp3Reader::new(),
69 pending: Vec::new(),
70 drained: false,
71 })
72 }
73
74 fn take(&mut self) {
75 while let Ok(frame) = self.reader.next_frame() {
76 if frame.samples.is_empty() {
77 continue;
78 }
79 let layout = ChannelLayout::from_count(frame.channels);
80 let mut bytes = Vec::with_capacity(frame.samples.len() * 4);
81 for sample in &frame.samples {
82 bytes.extend_from_slice(&sample.to_ne_bytes());
83 }
84 let samples = frame.samples.len() / frame.channels;
85 if let MediaParameters::Audio(audio) = &mut self.params.media {
86 audio.sample_rate = frame.sample_rate;
87 audio.layout = layout.clone();
88 audio.format = Some(SampleFormat::F32);
89 }
90 if let Ok(audio) = AudioFrame::try_new(
91 SampleFormat::F32,
92 false,
93 layout,
94 frame.sample_rate,
95 samples,
96 vec![Buf::from(bytes)],
97 ) {
98 self.pending.push(audio);
99 }
100 }
101 }
102}
103
104impl Decoder for Mp3Decoder {
105 fn codec_parameters(&self) -> &CodecParameters {
106 &self.params
107 }
108
109 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
110 self.reader.push(packet.data.as_ref());
111 self.take();
112 Ok(())
113 }
114
115 fn receive_frame(&mut self) -> Result<Frame> {
116 if self.pending.is_empty() {
117 return Err(if self.drained {
118 Error::Eof
119 } else {
120 Error::NeedMore
121 });
122 }
123 Ok(Frame::Audio(self.pending.remove(0)))
124 }
125
126 fn flush(&mut self) -> Result<()> {
127 self.take();
128 self.drained = true;
129 Ok(())
130 }
131
132 fn reset(&mut self) {
133 self.reader.reset();
134 self.pending.clear();
135 self.drained = false;
136 }
137}
138
139/// Codec parameters for a Layer III stream of this shape.
140pub fn codec_parameters(sample_rate: u32, channels: usize) -> CodecParameters {
141 let mut params = CodecParameters::new(CodecId::Mp3);
142 params.media = MediaParameters::Audio(AudioParameters {
143 sample_rate,
144 layout: ChannelLayout::from_count(channels),
145 format: Some(SampleFormat::F32),
146 bits_per_sample: None,
147 });
148 params
149}