forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdd00c7cTahinli3 months ago169 commits

lib.rs152 lines, 5.2 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, 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 ffmpeg, 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 fn take(&mut self) {
78 while let Ok(frame) = self.reader.next_frame() {
79 if frame.samples.is_empty() {
80 continue;
81 }
82 let layout = ChannelLayout::from_count(frame.channels);
83 let mut bytes = Vec::with_capacity(frame.samples.len() * 4);
84 for sample in &frame.samples {
85 bytes.extend_from_slice(&sample.to_ne_bytes());
86 }
87 let samples = frame.samples.len() / frame.channels;
88 if let MediaParameters::Audio(audio) = &mut self.params.media {
89 audio.sample_rate = frame.sample_rate;
90 audio.layout = layout.clone();
91 audio.format = Some(SampleFormat::F32);
92 }
93 if let Ok(audio) = AudioFrame::try_new(
94 SampleFormat::F32,
95 false,
96 layout,
97 frame.sample_rate,
98 samples,
99 vec![Buf::from(bytes)],
100 ) {
101 self.pending.push(audio);
102 }
103 }
104 }
105}
106
107impl Decoder for Mp3Decoder {
108 fn codec_parameters(&self) -> &CodecParameters {
109 &self.params
110 }
111
112 fn send_packet(&mut self, packet: &Packet) -> Result<()> {
113 self.reader.push(packet.data.as_ref());
114 self.take();
115 Ok(())
116 }
117
118 fn receive_frame(&mut self) -> Result<Frame> {
119 if self.pending.is_empty() {
120 return Err(if self.drained {
121 Error::Eof
122 } else {
123 Error::NeedMore
124 });
125 }
126 Ok(Frame::Audio(self.pending.remove(0)))
127 }
128
129 fn flush(&mut self) -> Result<()> {
130 self.take();
131 self.drained = true;
132 Ok(())
133 }
134
135 fn reset(&mut self) {
136 self.reader.reset();
137 self.pending.clear();
138 self.drained = false;
139 }
140}
141
142/// Codec parameters for a Layer III stream of this shape.
143pub fn codec_parameters(sample_rate: u32, channels: usize) -> CodecParameters {
144 let mut params = CodecParameters::new(CodecId::Mp3);
145 params.media = MediaParameters::Audio(AudioParameters {
146 sample_rate,
147 layout: ChannelLayout::from_count(channels),
148 format: Some(SampleFormat::F32),
149 bits_per_sample: None,
150 });
151 params
152}