forge
Explore
Log in

Don't you dare go Hollow

Layer III decoder and encoder, tables measured not copied

Browse files at this commit

13251078aaefe9ae8fb0e45f6f9c4d0f7a3279baAhmet Kaan GümüşParent: 2d69f73
  • feat
    • Layer III decoder and encoder, tables measured not copied
Show full message
feat(mp3): Layer III decoder and encoder, tables measured not copied

ec-mp3 decodes MPEG-1, MPEG-2 LSF and MPEG-2.5 Layer III and encodes CBR
MPEG-1 Layer III, and shims/rusty_mp3 carries the incumbent's name, version
and call shape over it.

Layer III's Huffman code tables and its 512-tap polyphase window are
normative data no formula produces. Instead of copying them out of an
existing implementation, scripts/mp3-tables measures them against a
reference decoder: it writes legal frames whose main-data bits it chooses,
decodes them with ffmpeg, and reads the answer back through a model of the
decode chain. Every code tree is walked to its leaves and checked for a
Kraft sum of exactly 1, complete coverage of its value grid and no
duplicates; the window is least-squares fitted to a 1.6e-6 residual, the
f32 noise floor of the decoder measured. The same rig produced the MPEG-1
long scalefactor band widths, which came out equal to the published
layouts, and it corrected two things a description would not have: the
MPEG-2.5 11.025 and 12 kHz short-block layouts are the 16 kHz ones, and the
short-block region boundary is three scalefactor bands rather than the
fixed 36 lines that only holds where those bands are four wide.

Decoder: header and CRC, side info, scalefactors (MPEG-1 with scfsi and the
LSF partition scheme), all Huffman tables, requantisation, mid/side and
intensity stereo, short-block reorder, alias reduction, IMDCT with the four
block windows, and a DCT-based polyphase bank from ec-dsp. ID3v2 and the
Xing/LAME/VBRI header frame are skipped, junk is resynced over, and
free-format is refused by name rather than guessed at.

Encoder: polyphase analysis (the synthesis bank's adjoint, reconstructing
to its -85 dB design limit), MDCT with block switching, an FFT-based
masking model whose gaps are stated in the module docs, inner rate and
outer distortion loops, Huffman table and region selection, and a bit
reservoir that emits frames one behind so a granule can start inside the
previous frame's payload.

Measured, all against ffmpeg:
- decode: 47 fixtures (nine sample rates, mono/stereo/joint/simple, CBR and
  VBR) at correlation 1.000000, 333-3232x realtime
- encode: at or above rusty_mp3 0.6.1 on the same corpus and metric at
  128/192/320 kbit/s, mono and stereo, every stream decoding without an
  ffmpeg warning
Cargo.tomlmodified+1 -0
@@ -16,6 +16,7 @@ ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" }
1616 ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" }
1717 ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" }
1818 ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" }
19+ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" }
1920 ec-mp4 = { path = "crates/ec-mp4", version = "0.1.0" }
2021 ec-riff = { path = "crates/ec-riff", version = "0.1.0" }
2122 ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" }
crates/ec-mp3/Cargo.tomladded+11 -0
@@ -0,0 +1,11 @@
1+[package]
2+name = "ec-mp3"
3+description = "MPEG-1/2/2.5 Layer III (MP3) decoder and encoder, built on the edith_codecs IR."
4+version.workspace = true
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-core = { workspace = true }
11+ec-dsp = { workspace = true }
crates/ec-mp3/src/decode.rsadded+776 -0
@@ -0,0 +1,776 @@
1+//! Layer III decoding: side info, scalefactors, spectrum, stereo, and the
2+//! filterbank that turns 576 coefficients back into PCM.
3+
4+use crate::filterbank::{Imdct, Synthesis, alias_reduce};
5+use crate::header::{ChannelMode, FrameHeader, Version, crc16};
6+use crate::huffman;
7+use crate::tables::{
8+ LSF_PARTITIONS, MAX_QUANT, PRETAB, SLEN, long_starts, power43, short_starts, short_widths,
9+};
10+use ec_core::bitio::BitReader;
11+use ec_core::error::{Error, Result};
12+
13+/// One decoded frame: interleaved `f32` samples in `[-1, 1]`.
14+#[derive(Clone, Debug, Default, PartialEq)]
15+pub struct DecodedFrame {
16+ /// Sample rate in Hz.
17+ pub sample_rate: u32,
18+ /// Channel count, 1 or 2.
19+ pub channels: usize,
20+ /// Interleaved samples, `channels * samples_per_frame` of them.
21+ pub samples: Vec<f32>,
22+}
23+
24+#[derive(Clone, Copy, Debug, Default)]
25+struct GranuleInfo {
26+ part2_3_length: u32,
27+ big_values: u32,
28+ global_gain: u32,
29+ scalefac_compress: u32,
30+ window_switching: bool,
31+ block_type: u8,
32+ mixed_block: bool,
33+ table_select: [u8; 3],
34+ subblock_gain: [u32; 3],
35+ region0_count: u32,
36+ region1_count: u32,
37+ preflag: bool,
38+ scalefac_scale: bool,
39+ count1table_select: bool,
40+}
41+
42+#[derive(Clone, Copy, Debug, Default)]
43+struct SideInfo {
44+ main_data_begin: u32,
45+ scfsi: [[bool; 4]; 2],
46+ granules: [[GranuleInfo; 2]; 2],
47+}
48+
49+fn parse_side_info(header: &FrameHeader, bytes: &[u8]) -> Result<SideInfo> {
50+ let channels = header.channels();
51+ let lsf = header.version != Version::Mpeg1;
52+ let mut r = BitReader::new(bytes);
53+ let mut side = SideInfo {
54+ main_data_begin: r.read_bits(if lsf { 8 } else { 9 })?,
55+ ..SideInfo::default()
56+ };
57+ let private = match (lsf, channels) {
58+ (true, 1) => 1,
59+ (true, _) => 2,
60+ (false, 1) => 5,
61+ (false, _) => 3,
62+ };
63+ r.skip_bits(private)?;
64+ if !lsf {
65+ for ch in 0..channels {
66+ for band in 0..4 {
67+ side.scfsi[ch][band] = r.read_bit()?;
68+ }
69+ }
70+ }
71+ for gr in 0..header.granules() {
72+ for ch in 0..channels {
73+ let mut g = GranuleInfo {
74+ part2_3_length: r.read_bits(12)?,
75+ big_values: r.read_bits(9)?,
76+ global_gain: r.read_bits(8)?,
77+ scalefac_compress: r.read_bits(if lsf { 9 } else { 4 })?,
78+ window_switching: r.read_bit()?,
79+ ..GranuleInfo::default()
80+ };
81+ if g.big_values > 288 {
82+ return Err(Error::corrupt(format!(
83+ "mp3: big_values {} exceeds 288",
84+ g.big_values
85+ )));
86+ }
87+ if g.window_switching {
88+ g.block_type = r.read_bits(2)? as u8;
89+ g.mixed_block = r.read_bit()?;
90+ for slot in &mut g.table_select[..2] {
91+ *slot = r.read_bits(5)? as u8;
92+ }
93+ for slot in &mut g.subblock_gain {
94+ *slot = r.read_bits(3)?;
95+ }
96+ g.region0_count = if g.block_type == 2 && !g.mixed_block {
97+ 8
98+ } else {
99+ 7
100+ };
101+ g.region1_count = 20 - g.region0_count;
102+ if g.block_type == 0 {
103+ return Err(Error::corrupt(
104+ "mp3: window switching with normal block type",
105+ ));
106+ }
107+ } else {
108+ for slot in &mut g.table_select {
109+ *slot = r.read_bits(5)? as u8;
110+ }
111+ g.region0_count = r.read_bits(4)?;
112+ g.region1_count = r.read_bits(3)?;
113+ }
114+ if !lsf {
115+ g.preflag = r.read_bit()?;
116+ }
117+ g.scalefac_scale = r.read_bit()?;
118+ g.count1table_select = r.read_bit()?;
119+ side.granules[gr][ch] = g;
120+ }
121+ }
122+ Ok(side)
123+}
124+
125+/// The stateful half of the decoder: one frame in, one frame of PCM out.
126+///
127+/// State that crosses frames — the bit reservoir, the IMDCT overlap and the
128+/// polyphase window history — lives here, so [`Mp3Decode::reset`] after a seek
129+/// is the whole story.
130+#[derive(Debug)]
131+pub struct Mp3Decode {
132+ imdct: Imdct,
133+ synthesis: [Synthesis; 2],
134+ overlap: [Box<[[f32; 18]; 32]>; 2],
135+ reservoir: Vec<u8>,
136+ is: [Box<[i32; 576]>; 2],
137+ xr: [Box<[f32; 576]>; 2],
138+ scalefac_l: [[u8; 23]; 2],
139+ scalefac_s: [[[u8; 3]; 13]; 2],
140+}
141+
142+impl Default for Mp3Decode {
143+ fn default() -> Mp3Decode {
144+ Mp3Decode {
145+ imdct: Imdct::default(),
146+ synthesis: [Synthesis::default(), Synthesis::default()],
147+ overlap: [Box::new([[0.0; 18]; 32]), Box::new([[0.0; 18]; 32])],
148+ reservoir: Vec::with_capacity(2048),
149+ is: [Box::new([0; 576]), Box::new([0; 576])],
150+ xr: [Box::new([0.0; 576]), Box::new([0.0; 576])],
151+ scalefac_l: [[0; 23]; 2],
152+ scalefac_s: [[[0; 3]; 13]; 2],
153+ }
154+ }
155+}
156+
157+impl Mp3Decode {
158+ /// A decoder with an empty reservoir and silent history.
159+ pub fn new() -> Mp3Decode {
160+ Mp3Decode::default()
161+ }
162+
163+ /// Drops the reservoir and the filterbank history, as a seek requires.
164+ pub fn reset(&mut self) {
165+ self.reservoir.clear();
166+ for synth in &mut self.synthesis {
167+ synth.reset();
168+ }
169+ for overlap in &mut self.overlap {
170+ overlap.iter_mut().for_each(|sb| sb.fill(0.0));
171+ }
172+ }
173+
174+ /// Decodes one complete frame, header included.
175+ ///
176+ /// A frame whose main data has not arrived yet — the bit reservoir points
177+ /// further back than we have seen, which is normal for the first frames
178+ /// after a seek — decodes as silence rather than as an error, because that
179+ /// is what the reservoir mechanism means.
180+ pub fn decode_frame(&mut self, frame: &[u8]) -> Result<DecodedFrame> {
181+ let header = FrameHeader::parse(frame)?;
182+ if header.layer != 3 {
183+ return Err(Error::unsupported(
184+ format!("MPEG audio layer {}", header.layer),
185+ "only Layer III is implemented in ec-mp3",
186+ ));
187+ }
188+ let Some(frame_len) = header.frame_len() else {
189+ return Err(Error::unsupported(
190+ "free-format MPEG audio",
191+ "no bitrate index, so the frame length is only knowable by scanning",
192+ ));
193+ };
194+ if frame.len() < frame_len {
195+ return Err(Error::NeedMore);
196+ }
197+ let side_len = header.side_info_len();
198+ let crc_len = usize::from(header.crc) * 2;
199+ let side_start = 4 + crc_len;
200+ if header.crc {
201+ let stored = u16::from_be_bytes([frame[4], frame[5]]);
202+ let computed = crc16(
203+ &[frame[0], frame[1], frame[2], frame[3]],
204+ &frame[side_start..side_start + side_len],
205+ );
206+ if stored != computed {
207+ return Err(Error::corrupt(format!(
208+ "mp3: side info CRC {computed:#06x} != {stored:#06x}"
209+ )));
210+ }
211+ }
212+ let side = parse_side_info(&header, &frame[side_start..side_start + side_len])?;
213+ let main = &frame[side_start + side_len..frame_len];
214+
215+ let begin = side.main_data_begin as usize;
216+ let have = self.reservoir.len();
217+ self.reservoir.extend_from_slice(main);
218+ let channels = header.channels();
219+ let mut samples = vec![0.0f32; header.samples_per_frame() * channels];
220+ if begin > have {
221+ // The reservoir does not reach back that far: this frame's own
222+ // spectrum is unreadable, so emit silence and keep the bytes for
223+ // the frames that follow.
224+ self.trim_reservoir();
225+ return Ok(DecodedFrame {
226+ sample_rate: header.sample_rate,
227+ channels,
228+ samples,
229+ });
230+ }
231+ let start = have - begin;
232+ let data = self.reservoir[start..].to_vec();
233+ let mut bit = 0u64;
234+ for gr in 0..header.granules() {
235+ for ch in 0..channels {
236+ self.decode_granule(&header, &side, gr, ch, &data, bit)?;
237+ bit += u64::from(side.granules[gr][ch].part2_3_length);
238+ }
239+ self.stereo(&header, &side, gr);
240+ for ch in 0..channels {
241+ let granule = side.granules[gr][ch];
242+ self.synthesise(&granule, ch, gr, channels, &mut samples);
243+ }
244+ }
245+ self.trim_reservoir();
246+ Ok(DecodedFrame {
247+ sample_rate: header.sample_rate,
248+ channels,
249+ samples,
250+ })
251+ }
252+
253+ fn trim_reservoir(&mut self) {
254+ // 511 bytes is the largest `main_data_begin` a frame can name.
255+ const KEEP: usize = 511;
256+ if self.reservoir.len() > KEEP {
257+ let drop = self.reservoir.len() - KEEP;
258+ self.reservoir.drain(..drop);
259+ }
260+ }
261+
262+ fn decode_granule(
263+ &mut self,
264+ header: &FrameHeader,
265+ side: &SideInfo,
266+ gr: usize,
267+ ch: usize,
268+ data: &[u8],
269+ start_bit: u64,
270+ ) -> Result<()> {
271+ let granule = side.granules[gr][ch];
272+ let reader = &mut BitReader::new(data);
273+ reader.skip_bits(start_bit)?;
274+ let end_bit = start_bit + u64::from(granule.part2_3_length);
275+ if header.version == Version::Mpeg1 {
276+ self.read_scalefactors_v1(side, gr, ch, reader)?;
277+ } else {
278+ self.read_scalefactors_lsf(header, &granule, ch, reader)?;
279+ }
280+ let scalefactor_bits = reader.bit_position() - start_bit;
281+ if scalefactor_bits > u64::from(granule.part2_3_length) {
282+ return Err(Error::corrupt("mp3: scalefactors longer than the granule"));
283+ }
284+ // Whatever the granule reserved but did not use is stuffing, and the
285+ // next granule starts at its own offset regardless, so nothing here
286+ // needs to seek to the end.
287+ self.read_spectrum(header, &granule, ch, reader, end_bit)?;
288+ self.requantise(header, &granule, ch);
289+ Ok(())
290+ }
291+
292+ fn read_scalefactors_v1(
293+ &mut self,
294+ side: &SideInfo,
295+ gr: usize,
296+ ch: usize,
297+ reader: &mut BitReader<'_>,
298+ ) -> Result<()> {
299+ let granule = side.granules[gr][ch];
300+ let (slen1, slen2) = SLEN[(granule.scalefac_compress & 15) as usize];
301+ if granule.window_switching && granule.block_type == 2 {
302+ if granule.mixed_block {
303+ for sfb in 0..8 {
304+ self.scalefac_l[ch][sfb] = reader.read_bits(slen1)? as u8;
305+ }
306+ for sfb in 3..6 {
307+ for w in 0..3 {
308+ self.scalefac_s[ch][sfb][w] = reader.read_bits(slen1)? as u8;
309+ }
310+ }
311+ } else {
312+ for sfb in 0..6 {
313+ for w in 0..3 {
314+ self.scalefac_s[ch][sfb][w] = reader.read_bits(slen1)? as u8;
315+ }
316+ }
317+ }
318+ for sfb in 6..12 {
319+ for w in 0..3 {
320+ self.scalefac_s[ch][sfb][w] = reader.read_bits(slen2)? as u8;
321+ }
322+ }
323+ self.scalefac_s[ch][12] = [0; 3];
324+ } else {
325+ const GROUPS: [(usize, usize); 4] = [(0, 6), (6, 11), (11, 16), (16, 21)];
326+ for (group, (from, to)) in GROUPS.into_iter().enumerate() {
327+ if gr == 1 && side.scfsi[ch][group] {
328+ continue; // reuse granule 0's values
329+ }
330+ let slen = if from < 11 { slen1 } else { slen2 };
331+ for sfb in from..to {
332+ self.scalefac_l[ch][sfb] = reader.read_bits(slen)? as u8;
333+ }
334+ }
335+ self.scalefac_l[ch][21] = 0;
336+ self.scalefac_l[ch][22] = 0;
337+ }
338+ Ok(())
339+ }
340+
341+ fn read_scalefactors_lsf(
342+ &mut self,
343+ header: &FrameHeader,
344+ granule: &GranuleInfo,
345+ ch: usize,
346+ reader: &mut BitReader<'_>,
347+ ) -> Result<()> {
348+ let intensity = header.mode == ChannelMode::JointStereo && header.mode_ext & 1 != 0;
349+ let mut sfc = granule.scalefac_compress;
350+ let slen;
351+ let block_number;
352+ if intensity && ch == 1 {
353+ sfc >>= 1;
354+ if sfc < 180 {
355+ slen = [sfc / 36, (sfc % 36) / 6, sfc % 6, 0];
356+ block_number = 3;
357+ } else if sfc < 244 {
358+ sfc -= 180;
359+ slen = [(sfc % 64) >> 4, (sfc % 16) >> 2, sfc % 4, 0];
360+ block_number = 4;
361+ } else {
362+ sfc -= 244;
363+ slen = [sfc / 3, sfc % 3, 0, 0];
364+ block_number = 5;
365+ }
366+ } else if sfc < 400 {
367+ slen = [(sfc >> 4) / 5, (sfc >> 4) % 5, (sfc % 16) >> 2, sfc % 4];
368+ block_number = 0;
369+ } else if sfc < 500 {
370+ sfc -= 400;
371+ slen = [(sfc >> 2) / 5, (sfc >> 2) % 5, sfc % 4, 0];
372+ block_number = 1;
373+ } else {
374+ sfc -= 500;
375+ slen = [sfc / 3, sfc % 3, 0, 0];
376+ block_number = 2;
377+ }
378+ let short = granule.window_switching && granule.block_type == 2;
379+ let kind = if !short {
380+ 0
381+ } else if granule.mixed_block {
382+ 2
383+ } else {
384+ 1
385+ };
386+ let counts = LSF_PARTITIONS[block_number][kind];
387+ self.scalefac_l[ch] = [0; 23];
388+ self.scalefac_s[ch] = [[0; 3]; 13];
389+ let mut band = 0usize;
390+ for (partition, count) in counts.into_iter().enumerate() {
391+ for _ in 0..count {
392+ let value = reader.read_bits(slen[partition])? as u8;
393+ match kind {
394+ 0 => self.scalefac_l[ch][band] = value,
395+ 1 => self.scalefac_s[ch][band / 3][band % 3] = value,
396+ _ if band < 6 => self.scalefac_l[ch][band] = value,
397+ _ => {
398+ let index = band - 6;
399+ self.scalefac_s[ch][3 + index / 3][index % 3] = value;
400+ }
401+ }
402+ band += 1;
403+ }
404+ }
405+ Ok(())
406+ }
407+
408+ fn read_spectrum(
409+ &mut self,
410+ header: &FrameHeader,
411+ granule: &GranuleInfo,
412+ ch: usize,
413+ reader: &mut BitReader<'_>,
414+ end_bit: u64,
415+ ) -> Result<()> {
416+ let is = &mut self.is[ch];
417+ is.fill(0);
418+ let starts = long_starts(header.sample_rate);
419+ let short = granule.window_switching && granule.block_type == 2;
420+ let (region1, region2) = if granule.window_switching {
421+ if short {
422+ // Three short bands, all three windows: 36 lines at every rate
423+ // whose first bands are four wide, but 72 at 8 kHz, where they
424+ // are eight. The fixed 36 that most descriptions quote is that
425+ // coincidence, and 8 kHz is where it stops holding.
426+ (short_starts(header.sample_rate)[3] as usize * 3, 576)
427+ } else {
428+ (starts[8] as usize, 576)
429+ }
430+ } else {
431+ let r0 = (granule.region0_count + 1).min(22) as usize;
432+ let r1 = (granule.region0_count + granule.region1_count + 2).min(22) as usize;
433+ (starts[r0] as usize, starts[r1] as usize)
434+ };
435+ let big = granule.big_values as usize * 2;
436+ let mut index = 0usize;
437+ let mut pair = [0.0f32; 2];
438+ while index < big {
439+ let region = if index < region1 {
440+ 0
441+ } else if index < region2 {
442+ 1
443+ } else {
444+ 2
445+ };
446+ let select = usize::from(granule.table_select[region]);
447+ let table = huffman::big_table(select)?;
448+ if table.codes.is_empty() {
449+ index += 2;
450+ continue;
451+ }
452+ if reader.bit_position() >= end_bit {
453+ break;
454+ }
455+ huffman::decode_pair(reader, select, table, &mut pair)?;
456+ is[index] = pair[0] as i32;
457+ is[index + 1] = pair[1] as i32;
458+ index += 2;
459+ }
460+ let mut quad = [0.0f32; 4];
461+ while index + 4 <= 576 && reader.bit_position() < end_bit {
462+ let before = reader.bit_position();
463+ if huffman::decode_quad(reader, granule.count1table_select, &mut quad).is_err() {
464+ break;
465+ }
466+ if reader.bit_position() > end_bit {
467+ // The last quadruple ran past the granule: encoders are allowed
468+ // to leave it there, and its values are not part of the
469+ // spectrum.
470+ let _ = before;
471+ break;
472+ }
473+ for (slot, value) in is[index..index + 4].iter_mut().zip(quad) {
474+ *slot = value as i32;
475+ }
476+ index += 4;
477+ }
478+ Ok(())
479+ }
480+
481+ fn requantise(&mut self, header: &FrameHeader, granule: &GranuleInfo, ch: usize) {
482+ let power = power43();
483+ let xr = &mut self.xr[ch];
484+ let is = &self.is[ch];
485+ let short = granule.window_switching && granule.block_type == 2;
486+ let multiplier = if granule.scalefac_scale { 1.0 } else { 0.5 };
487+ let base = (granule.global_gain as f32 - 210.0) * 0.25;
488+ let value = |v: i32| -> f32 {
489+ let magnitude = power[(v.unsigned_abs() as usize).min(MAX_QUANT)];
490+ if v < 0 { -magnitude } else { magnitude }
491+ };
492+ xr.fill(0.0);
493+ let long_bands = if !short {
494+ 22
495+ } else if granule.mixed_block {
496+ // Mixed blocks keep the first two subbands long, which is 36
497+ // coefficients: eight bands at an MPEG-1 rate, six at an LSF one.
498+ if header.version == Version::Mpeg1 {
499+ 8
500+ } else {
501+ 6
502+ }
503+ } else {
504+ 0
505+ };
506+ let starts = long_starts(header.sample_rate);
507+ for sfb in 0..long_bands {
508+ let (from, to) = (starts[sfb] as usize, starts[sfb + 1] as usize);
509+ let mut sf = f32::from(self.scalefac_l[ch][sfb]);
510+ if granule.preflag {
511+ sf += f32::from(PRETAB[sfb]);
512+ }
513+ let gain = (base - multiplier * sf).exp2();
514+ for i in from..to.min(576) {
515+ xr[i] = value(is[i]) * gain;
516+ }
517+ }
518+ if short {
519+ // Short blocks arrive band by band, window by window, and land in a
520+ // spectrum whose three windows interleave line by line: bitstream
521+ // index (sfb, window, line) becomes 3 * (band start + line) +
522+ // window, which is the order the short IMDCT reads back.
523+ let widths = short_widths(header.sample_rate);
524+ let starts = short_starts(header.sample_rate);
525+ let first = if granule.mixed_block { 3 } else { 0 };
526+ let mut index = if granule.mixed_block { 36 } else { 0 };
527+ for sfb in first..13 {
528+ let width = widths[sfb] as usize;
529+ let band_start = starts[sfb] as usize;
530+ for window in 0..3 {
531+ let sf = f32::from(self.scalefac_s[ch][sfb][window]);
532+ let gain =
533+ (base - 2.0 * granule.subblock_gain[window] as f32 - multiplier * sf)
534+ .exp2();
535+ for line in 0..width {
536+ if index >= 576 {
537+ break;
538+ }
539+ let target = (band_start + line) * 3 + window;
540+ if target < 576 {
541+ xr[target] = value(is[index]) * gain;
542+ }
543+ index += 1;
544+ }
545+ }
546+ }
547+ }
548+ }
549+
550+ fn stereo(&mut self, header: &FrameHeader, side: &SideInfo, gr: usize) {
551+ if header.channels() != 2 {
552+ return;
553+ }
554+ let joint = header.mode == ChannelMode::JointStereo;
555+ let ms = joint && header.mode_ext & 2 != 0;
556+ let intensity = joint && header.mode_ext & 1 != 0;
557+ let granule = side.granules[gr][0];
558+ let short = granule.window_switching && granule.block_type == 2;
559+ // Intensity coding starts at the first band above the right channel's
560+ // last non-zero line.
561+ let bound = if intensity {
562+ let last = (0..576)
563+ .rev()
564+ .find(|&i| self.is[1][i] != 0)
565+ .map_or(0, |i| i + 1);
566+ let starts = long_starts(header.sample_rate);
567+ starts
568+ .iter()
569+ .find(|&&s| usize::from(s) >= last)
570+ .map_or(576, |s| usize::from(*s))
571+ } else {
572+ 576
573+ };
574+ if ms {
575+ const INV_SQRT2: f32 = std::f32::consts::FRAC_1_SQRT_2;
576+ for i in 0..bound {
577+ let (m, s) = (self.xr[0][i], self.xr[1][i]);
578+ self.xr[0][i] = (m + s) * INV_SQRT2;
579+ self.xr[1][i] = (m - s) * INV_SQRT2;
580+ }
581+ }
582+ if intensity && bound < 576 {
583+ let starts = long_starts(header.sample_rate);
584+ for sfb in 0..22 {
585+ let (from, to) = (starts[sfb] as usize, starts[sfb + 1] as usize);
586+ if from < bound {
587+ continue;
588+ }
589+ let is_pos = if short {
590+ u32::from(self.scalefac_s[1][sfb.min(12)][0])
591+ } else {
592+ u32::from(self.scalefac_l[1][sfb])
593+ };
594+ if is_pos >= 7 {
595+ continue; // 7 is not a legal position; leave the band alone
596+ }
597+ let ratio = (std::f32::consts::PI / 12.0 * is_pos as f32).tan();
598+ let (kl, kr) = (ratio / (1.0 + ratio), 1.0 / (1.0 + ratio));
599+ for i in from..to.min(576) {
600+ let value = self.xr[0][i];
601+ self.xr[0][i] = value * kl;
602+ self.xr[1][i] = value * kr;
603+ }
604+ }
605+ }
606+ }
607+
608+ fn synthesise(
609+ &mut self,
610+ granule: &GranuleInfo,
611+ ch: usize,
612+ gr: usize,
613+ channels: usize,
614+ out: &mut [f32],
615+ ) {
616+ let short = granule.window_switching && granule.block_type == 2;
617+ let alias_bands = if !short {
618+ 32
619+ } else if granule.mixed_block {
620+ 2
621+ } else {
622+ 1
623+ };
624+ alias_reduce(&mut self.xr[ch][..], alias_bands);
625+ let mut block = [0.0f32; 36];
626+ let mut slots = [[0.0f32; 32]; 18];
627+ // The transpose (subband-major in, slot-major out) is the point of
628+ // this loop, so it indexes both ways on purpose.
629+ #[allow(clippy::needless_range_loop)]
630+ for sb in 0..32 {
631+ let coefficients = &self.xr[ch][sb * 18..sb * 18 + 18];
632+ if short && !(granule.mixed_block && sb < 2) {
633+ self.imdct.short(coefficients, &mut block);
634+ } else {
635+ let block_type = if short { 0 } else { granule.block_type };
636+ self.imdct.long(coefficients, block_type, &mut block);
637+ }
638+ let overlap = &mut self.overlap[ch][sb];
639+ for t in 0..18 {
640+ let mut sample = block[t] + overlap[t];
641+ overlap[t] = block[18 + t];
642+ if sb % 2 == 1 && t % 2 == 1 {
643+ sample = -sample;
644+ }
645+ slots[t][sb] = sample;
646+ }
647+ }
648+ let mut pcm = [0.0f32; 32];
649+ for (t, slot) in slots.iter().enumerate() {
650+ self.synthesis[ch].slot(slot, &mut pcm);
651+ let base = (gr * 18 + t) * 32 * channels + ch;
652+ for (j, sample) in pcm.iter().enumerate() {
653+ out[base + j * channels] = *sample;
654+ }
655+ }
656+ }
657+}
658+
659+/// Turns a byte stream into frames: skips ID3v2 and the Xing/LAME/VBRI header
660+/// frame, resyncs over junk, and holds partial data until the rest arrives.
661+#[derive(Debug, Default)]
662+pub struct Mp3Reader {
663+ decoder: Mp3Decode,
664+ buffer: Vec<u8>,
665+ consumed: usize,
666+ started: bool,
667+}
668+
669+impl Mp3Reader {
670+ /// An empty reader.
671+ pub fn new() -> Mp3Reader {
672+ Mp3Reader::default()
673+ }
674+
675+ /// Appends bytes to decode.
676+ pub fn push(&mut self, bytes: &[u8]) {
677+ if self.consumed > 0 {
678+ self.buffer.drain(..self.consumed);
679+ self.consumed = 0;
680+ }
681+ self.buffer.extend_from_slice(bytes);
682+ }
683+
684+ /// Drops buffered input and decoder history.
685+ pub fn reset(&mut self) {
686+ self.buffer.clear();
687+ self.consumed = 0;
688+ self.started = false;
689+ self.decoder.reset();
690+ }
691+
692+ /// The next frame, or [`Error::NeedMore`] when the buffer holds only part
693+ /// of one.
694+ pub fn next_frame(&mut self) -> Result<DecodedFrame> {
695+ loop {
696+ let data = &self.buffer[self.consumed..];
697+ if data.len() < 4 {
698+ return Err(Error::NeedMore);
699+ }
700+ if !self.started && data.starts_with(b"ID3") {
701+ if data.len() < 10 {
702+ return Err(Error::NeedMore);
703+ }
704+ let size = data[6..10]
705+ .iter()
706+ .fold(0usize, |acc, b| (acc << 7) | usize::from(b & 0x7F));
707+ let total = 10 + size;
708+ if data.len() < total {
709+ return Err(Error::NeedMore);
710+ }
711+ self.consumed += total;
712+ continue;
713+ }
714+ let Ok(header) = FrameHeader::parse(data) else {
715+ self.consumed += 1;
716+ continue;
717+ };
718+ let Some(frame_len) = header.frame_len() else {
719+ return Err(Error::unsupported(
720+ "free-format MPEG audio",
721+ "no bitrate index, so the frame length is only knowable by scanning",
722+ ));
723+ };
724+ if header.layer != 3 {
725+ self.consumed += 1;
726+ continue;
727+ }
728+ if data.len() < frame_len {
729+ return Err(Error::NeedMore);
730+ }
731+ let frame = &data[..frame_len];
732+ if !self.started && is_info_frame(&header, frame) {
733+ self.started = true;
734+ self.consumed += frame_len;
735+ continue;
736+ }
737+ self.started = true;
738+ let decoded = self.decoder.decode_frame(frame);
739+ self.consumed += frame_len;
740+ return decoded;
741+ }
742+ }
743+
744+ /// Decodes everything buffered, stopping at the first incomplete frame.
745+ pub fn decode_all(&mut self) -> Vec<DecodedFrame> {
746+ let mut out = Vec::new();
747+ while let Ok(frame) = self.next_frame() {
748+ out.push(frame);
749+ }
750+ out
751+ }
752+}
753+
754+/// True for the Xing/Info/VBRI header frame every VBR encoder puts first: it
755+/// carries a tag rather than audio, and decoding it would prepend a frame of
756+/// silence no other decoder emits.
757+fn is_info_frame(header: &FrameHeader, frame: &[u8]) -> bool {
758+ let side = 4 + usize::from(header.crc) * 2 + header.side_info_len();
759+ let tagged = |at: usize, tag: &[u8]| frame.len() >= at + 4 && &frame[at..at + 4] == tag;
760+ tagged(side, b"Xing") || tagged(side, b"Info") || tagged(36, b"VBRI")
761+}
762+
763+#[cfg(test)]
764+mod tests {
765+ use super::*;
766+
767+ #[test]
768+ fn id3v2_and_junk_are_skipped_before_the_first_frame() {
769+ let mut reader = Mp3Reader::new();
770+ let mut stream = b"ID3\x04\x00\x00\x00\x00\x00\x05hello".to_vec();
771+ stream.extend_from_slice(&[0x00, 0x11, 0x22]); // junk before sync
772+ assert!(reader.next_frame().is_err());
773+ reader.push(&stream);
774+ assert!(matches!(reader.next_frame(), Err(Error::NeedMore)));
775+ }
776+}
crates/ec-mp3/src/encode.rsadded+1207 -0
@@ -0,0 +1,1207 @@
1+//! Layer III encoding: analysis filterbank, MDCT with block switching, a
2+//! masking model, the two quantisation loops and the bit reservoir.
3+//!
4+//! **The psychoacoustic model, stated plainly.** Per granule and channel it
5+//! takes one 1024-point real FFT of the sine-windowed input, sums the power
6+//! spectrum into the granule's scalefactor bands, spreads that energy across
7+//! neighbouring bands with a one-sided exponential (about 25 dB/band up, 10
8+//! dB/band down), and sets each band's allowed noise to the spread energy
9+//! minus a signal-to-mask offset that follows a spectral-flatness tonality
10+//! estimate — 21 dB where the band looks tonal, 6 dB where it looks like
11+//! noise — floored by an absolute-threshold curve. It has no temporal
12+//! spreading, no pre-echo control beyond block switching, and no inter-channel
13+//! masking; those are the honest gaps against a full ISO Model 2.
14+//!
15+//! The outer (distortion) loop amplifies the scalefactors of bands whose
16+//! quantisation noise exceeds that threshold; the inner (rate) loop raises
17+//! `global_gain` until the Huffman-coded granule fits the bits the reservoir
18+//! makes available.
19+
20+use crate::filterbank::{Analysis, alias_expand};
21+use crate::header::{ChannelMode, FrameHeader, Version};
22+use crate::huffman::{self, Table};
23+use crate::tables::{MAX_QUANT, SLEN, long_starts, power43, short_starts, windows};
24+use ec_core::bitio::BitWriter;
25+use ec_core::error::{Error, Result};
26+use ec_dsp::{RealFft, Window};
27+
28+/// Encoder settings.
29+///
30+/// The field names match the incumbent `rusty_mp3` shim's, because the replica
31+/// swaps one for the other without touching call sites.
32+#[derive(Clone, Copy, Debug, Default, PartialEq)]
33+pub struct Mp3EncoderConfig {
34+ /// Target bitrate in kbit/s, snapped to the nearest legal Layer III rate.
35+ pub bitrate_kbps: u32,
36+ /// Quality on a 0..1 scale instead of a bitrate.
37+ ///
38+ /// corner-cut: this picks a constant bitrate from the quality rather than
39+ /// varying the rate per frame — the streams are legal and decode
40+ /// everywhere, they just do not spend fewer bits on easy frames. Upgrade
41+ /// path is a per-frame bitrate index chosen after the rate loop, which the
42+ /// frame writer here already supports (it writes the header last).
43+ pub vbr_quality: Option<f32>,
44+}
45+
46+const BITRATES_V1: [u32; 14] = [
47+ 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
48+];
49+const BITRATES_V2: [u32; 14] = [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
50+
51+/// The legal Layer III bitrate nearest to `kbps` for this stream.
52+pub fn snap_bitrate(version: Version, kbps: u32) -> u32 {
53+ let table: &[u32] = if version == Version::Mpeg1 {
54+ &BITRATES_V1
55+ } else {
56+ &BITRATES_V2
57+ };
58+ *table
59+ .iter()
60+ .min_by_key(|&&r| r.abs_diff(kbps))
61+ .expect("bitrate table is not empty")
62+}
63+
64+/// The bitrate a `vbr_quality` in `[0, 1]` asks for, in kbit/s.
65+pub fn bitrate_for_quality(quality: f32) -> u32 {
66+ let q = quality.clamp(0.0, 1.0);
67+ // 0.0 -> 96 kbit/s, 0.5 -> 192, 1.0 -> 320.
68+ (96.0 + q * 224.0).round() as u32
69+}
70+
71+const SFB_LONG: usize = 21;
72+
73+/// One granule's worth of coded spectrum plus the side info describing it.
74+#[derive(Clone, Debug)]
75+struct CodedGranule {
76+ bits: Vec<bool>,
77+ part2_3_length: u32,
78+ big_values: u32,
79+ global_gain: u32,
80+ scalefac_compress: u32,
81+ block_type: u8,
82+ table_select: [u8; 3],
83+ region0_count: u32,
84+ region1_count: u32,
85+ scalefac_scale: bool,
86+ count1table_select: bool,
87+}
88+
89+/// The stateful encoder core: PCM in, Layer III frames out.
90+#[derive(Debug)]
91+pub struct Mp3Encode {
92+ sample_rate: u32,
93+ channels: usize,
94+ bitrate_kbps: u32,
95+ version: Version,
96+ mode: ChannelMode,
97+ analysis: Vec<Analysis>,
98+ /// Subband slots waiting for their MDCT, per channel.
99+ slots: Vec<Vec<[f32; 32]>>,
100+ /// The previous granule's subband slots, for the 36-sample MDCT window.
101+ history: Vec<[[f32; 32]; 18]>,
102+ /// Window type chosen for the granule we are holding back.
103+ pending: Vec<PendingGranule>,
104+ fft: RealFft<f32>,
105+ fft_window: Window<f32>,
106+ psy_history: Vec<Vec<f32>>,
107+ /// The main-data byte stream and how much of it frames have carried.
108+ stream: Vec<u8>,
109+ used: usize,
110+ /// Stream bytes already assigned to a frame's payload, decided or not.
111+ assigned: usize,
112+ /// Stream bytes already written out in a frame.
113+ written: usize,
114+ /// Frames whose header and side info are decided but whose payload is
115+ /// still being filled: the bit reservoir means a frame's payload carries
116+ /// the *next* frame's granule data, so emission runs one frame behind.
117+ queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>)>,
118+ ready: std::collections::VecDeque<Vec<u8>>,
119+ frames: u32,
120+}
121+
122+#[derive(Clone, Debug)]
123+struct PendingGranule {
124+ subband: Vec<[f32; 32]>,
125+ energy: f32,
126+ threshold: Vec<f32>,
127+}
128+
129+impl Mp3Encode {
130+ /// An encoder for this stream shape. Rates outside 8..48 kHz have no Layer
131+ /// III frame and are refused by name.
132+ pub fn new(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Result<Mp3Encode> {
133+ let version = match sample_rate {
134+ 32000 | 44100 | 48000 => Version::Mpeg1,
135+ 16000 | 22050 | 24000 => Version::Mpeg2,
136+ 8000 | 11025 | 12000 => Version::Mpeg25,
137+ other => {
138+ return Err(Error::unsupported(
139+ format!("{other} Hz MPEG audio"),
140+ "Layer III frames exist only for 8, 11.025, 12, 16, 22.05, 24, 32, 44.1 and 48 kHz",
141+ ));
142+ }
143+ };
144+ if channels == 0 || channels > 2 {
145+ return Err(Error::unsupported(
146+ format!("{channels}-channel MP3"),
147+ "Layer III carries one or two channels",
148+ ));
149+ }
150+ Ok(Mp3Encode {
151+ sample_rate,
152+ channels,
153+ bitrate_kbps: snap_bitrate(version, bitrate_kbps),
154+ version,
155+ mode: if channels == 2 {
156+ ChannelMode::JointStereo
157+ } else {
158+ ChannelMode::Mono
159+ },
160+ analysis: (0..channels).map(|_| Analysis::default()).collect(),
161+ slots: vec![Vec::new(); channels],
162+ history: vec![[[0.0; 32]; 18]; channels],
163+ pending: Vec::new(),
164+ fft: RealFft::new(1024),
165+ fft_window: Window::sine(1024),
166+ psy_history: vec![vec![0.0; 1024]; channels],
167+ stream: Vec::new(),
168+ used: 0,
169+ assigned: 0,
170+ written: 0,
171+ queued: std::collections::VecDeque::new(),
172+ ready: std::collections::VecDeque::new(),
173+ frames: 0,
174+ })
175+ }
176+
177+ /// The header every frame of this stream carries.
178+ fn header(&self) -> FrameHeader {
179+ FrameHeader {
180+ version: self.version,
181+ layer: 3,
182+ crc: false,
183+ bitrate_kbps: self.bitrate_kbps,
184+ sample_rate: self.sample_rate,
185+ padding: false,
186+ private: false,
187+ mode: self.mode,
188+ mode_ext: 0,
189+ copyright: false,
190+ original: true,
191+ emphasis: 0,
192+ }
193+ }
194+
195+ /// Granules per frame for this stream.
196+ pub fn granules(&self) -> usize {
197+ self.header().granules()
198+ }
199+
200+ /// Samples per channel one frame codes.
201+ pub fn frame_samples(&self) -> usize {
202+ self.granules() * 576
203+ }
204+}
205+
206+/// Interleaved PCM in, complete frames out.
207+#[derive(Debug)]
208+pub struct Mp3Encoder {
209+ core: Option<Mp3Encode>,
210+ config: Mp3EncoderConfig,
211+ pcm: Vec<f32>,
212+ frames: std::collections::VecDeque<Vec<u8>>,
213+ finished: bool,
214+ header_written: bool,
215+ total_samples: u64,
216+}
217+
218+impl Mp3Encoder {
219+ /// An encoder that configures itself from the first PCM it is given.
220+ pub fn new(config: Mp3EncoderConfig) -> Mp3Encoder {
221+ Mp3Encoder {
222+ core: None,
223+ config,
224+ pcm: Vec::new(),
225+ frames: std::collections::VecDeque::new(),
226+ finished: false,
227+ header_written: false,
228+ total_samples: 0,
229+ }
230+ }
231+
232+ /// Feeds interleaved `f32` samples in `[-1, 1]`.
233+ pub fn push_pcm_f32(
234+ &mut self,
235+ interleaved: &[f32],
236+ channels: u16,
237+ sample_rate: u32,
238+ ) -> Result<()> {
239+ if self.core.is_none() {
240+ let bitrate = match self.config.vbr_quality {
241+ Some(q) => bitrate_for_quality(q),
242+ None => self.config.bitrate_kbps.max(8),
243+ };
244+ self.core = Some(Mp3Encode::new(sample_rate, usize::from(channels), bitrate)?);
245+ }
246+ self.pcm.extend_from_slice(interleaved);
247+ self.total_samples += (interleaved.len() / usize::from(channels.max(1))) as u64;
248+ self.drain(false);
249+ Ok(())
250+ }
251+
252+ /// Feeds interleaved 16-bit samples, scaled the way every decoder here
253+ /// scales them.
254+ pub fn push_pcm_s16(
255+ &mut self,
256+ interleaved: &[i16],
257+ channels: u16,
258+ sample_rate: u32,
259+ ) -> Result<()> {
260+ let floats: Vec<f32> = interleaved
261+ .iter()
262+ .map(|s| f32::from(*s) / 32768.0)
263+ .collect();
264+ self.push_pcm_f32(&floats, channels, sample_rate)
265+ }
266+
267+ /// Ends the stream: pads the tail to a whole frame and flushes.
268+ pub fn finish(&mut self) {
269+ if let Some(core) = &self.core {
270+ let channels = core.channels;
271+ // The filterbank runs fifteen slots behind, and the MDCT one
272+ // granule behind that; feed silence so the last real samples come
273+ // out the other end.
274+ let tail = vec![0.0f32; channels * (576 * 2 + 480)];
275+ self.pcm.extend_from_slice(&tail);
276+ }
277+ self.drain(true);
278+ self.finished = true;
279+ }
280+
281+ fn drain(&mut self, flush: bool) {
282+ let Some(core) = self.core.as_mut() else {
283+ return;
284+ };
285+ let channels = core.channels;
286+ let need = core.frame_samples() * channels;
287+ while self.pcm.len() >= need {
288+ let block: Vec<f32> = self.pcm.drain(..need).collect();
289+ core.encode_block(&block);
290+ }
291+ if flush {
292+ if !self.pcm.is_empty() {
293+ let mut block = std::mem::take(&mut self.pcm);
294+ block.resize(need, 0.0);
295+ core.encode_block(&block);
296+ }
297+ core.flush_frames();
298+ }
299+ while let Some(frame) = core.ready.pop_front() {
300+ self.frames.push_back(frame);
301+ }
302+ }
303+
304+ /// The next complete frame, [`Error::Eof`] once drained after
305+ /// [`Mp3Encoder::finish`], [`Error::NeedMore`] before that.
306+ pub fn next_packet(&mut self) -> Result<Vec<u8>> {
307+ if !self.header_written && (self.finished || !self.frames.is_empty()) {
308+ self.header_written = true;
309+ if let Some(core) = &self.core {
310+ return Ok(info_frame(core, self.total_samples));
311+ }
312+ }
313+ match self.frames.pop_front() {
314+ Some(frame) => Ok(frame),
315+ None if self.finished => Err(Error::Eof),
316+ None => Err(Error::NeedMore),
317+ }
318+ }
319+}
320+
321+/// The Xing/Info header frame every player expects first: a silent frame whose
322+/// main data is the tag, so a decoder that does not know the tag still decodes
323+/// a legal (silent) frame rather than choking.
324+fn info_frame(core: &Mp3Encode, samples: u64) -> Vec<u8> {
325+ let header = core.header();
326+ let frame_len = header.frame_len().unwrap_or(417);
327+ let mut out = vec![0u8; frame_len];
328+ out[..4].copy_from_slice(&header.to_bytes());
329+ let at = 4 + header.side_info_len();
330+ let tag: &[u8] = b"Info";
331+ out[at..at + 4].copy_from_slice(tag);
332+ out[at + 4..at + 8].copy_from_slice(&1u32.to_be_bytes()); // frames field present
333+ let frames = samples.div_ceil(header.samples_per_frame() as u64) as u32;
334+ out[at + 8..at + 12].copy_from_slice(&frames.to_be_bytes());
335+ out
336+}
337+
338+impl Mp3Encode {
339+ /// Encodes one frame's worth of interleaved PCM.
340+ fn encode_block(&mut self, pcm: &[f32]) {
341+ let channels = self.channels;
342+ let granules = self.granules();
343+ // Polyphase analysis, one channel at a time.
344+ for ch in 0..channels {
345+ let mut mono: Vec<f32> = Vec::with_capacity(pcm.len() / channels);
346+ for frame in pcm.chunks(channels) {
347+ mono.push(frame[ch]);
348+ }
349+ for chunk in mono.chunks(32) {
350+ if chunk.len() < 32 {
351+ break;
352+ }
353+ if let Some(slot) = self.analysis[ch].push(chunk) {
354+ self.slots[ch].push(slot);
355+ }
356+ }
357+ self.psy_push(ch, &mono);
358+ }
359+ // A granule is 18 slots; hold one back so block switching can look
360+ // ahead at the next granule's energy.
361+ let ready = self.slots[0].len() / 18;
362+ if ready == 0 {
363+ return;
364+ }
365+ for _ in 0..ready {
366+ for ch in 0..channels {
367+ let subband: Vec<[f32; 32]> = self.slots[ch].drain(..18).collect();
368+ let energy: f32 = subband
369+ .iter()
370+ .flat_map(|slot| slot.iter())
371+ .map(|v| v * v)
372+ .sum();
373+ let threshold = self.psy_threshold(ch);
374+ self.pending.push(PendingGranule {
375+ subband,
376+ energy,
377+ threshold,
378+ });
379+ }
380+ }
381+ // Emit whole frames while a lookahead granule remains.
382+ let per_frame = granules * channels;
383+ while self.pending.len() >= per_frame + channels {
384+ self.emit_frame();
385+ }
386+ }
387+
388+ /// One FFT per granule of input, kept for the masking model.
389+ fn psy_push(&mut self, ch: usize, mono: &[f32]) {
390+ let n = 1024.min(mono.len());
391+ let history = &mut self.psy_history[ch];
392+ history.copy_within(n.., 0);
393+ let keep = 1024 - n;
394+ history[keep..].copy_from_slice(&mono[mono.len() - n..]);
395+ }
396+
397+ /// Allowed noise per long scalefactor band, from the masking model.
398+ fn psy_threshold(&mut self, ch: usize) -> Vec<f32> {
399+ let mut block: Vec<f32> = self.psy_history[ch].clone();
400+ self.fft_window.apply(&mut block);
401+ let mut spectrum = vec![ec_dsp::Complex::<f32>::ZERO; 513];
402+ self.fft.forward(&block, &mut spectrum);
403+ let starts = long_starts(self.sample_rate);
404+ let mut energy = vec![0.0f32; SFB_LONG];
405+ for (band, slot) in energy.iter_mut().enumerate() {
406+ // The 576 coefficients of a granule map onto 512 FFT bins.
407+ let from = usize::from(starts[band]) * 512 / 576;
408+ let to = (usize::from(starts[band + 1]) * 512 / 576).max(from + 1);
409+ let mut sum = 0.0f32;
410+ let mut log_sum = 0.0f32;
411+ let mut count = 0.0f32;
412+ for bin in &spectrum[from..to.min(512)] {
413+ let power = bin.norm_sqr() + 1e-30;
414+ sum += power;
415+ log_sum += power.ln();
416+ count += 1.0;
417+ }
418+ // Spectral flatness as a tonality proxy: a flat band is noise-like
419+ // and masks less.
420+ let flatness = if count > 0.0 {
421+ ((log_sum / count).exp() / (sum / count)).clamp(0.0, 1.0)
422+ } else {
423+ 1.0
424+ };
425+ let offset_db = 6.0 + 15.0 * (1.0 - flatness);
426+ *slot = sum * 10f32.powf(-offset_db / 10.0);
427+ }
428+ // Spreading: masking leaks upward strongly and downward weakly.
429+ let mut spread = energy.clone();
430+ for band in 1..SFB_LONG {
431+ let leak = spread[band - 1] * 0.0032; // about -25 dB per band
432+ spread[band] = spread[band].max(leak);
433+ }
434+ for band in (0..SFB_LONG - 1).rev() {
435+ let leak = spread[band + 1] * 0.1; // about -10 dB per band
436+ spread[band] = spread[band].max(leak);
437+ }
438+ // Absolute threshold, coarse: hearing is least sensitive at the ends.
439+ for (band, slot) in spread.iter_mut().enumerate() {
440+ let rel = band as f32 / SFB_LONG as f32;
441+ let floor = 1e-9 * (1.0 + 400.0 * (rel - 0.35).max(0.0).powi(2));
442+ *slot = slot.max(floor);
443+ }
444+ spread
445+ }
446+
447+ fn emit_frame(&mut self) {
448+ let channels = self.channels;
449+ let granules = self.granules();
450+ let header = self.header();
451+ let frame_len = header.frame_len().unwrap_or(0);
452+ let capacity = frame_len - 4 - header.side_info_len();
453+
454+ // Window types: a granule whose successor is much louder starts the
455+ // switch, the loud one is short, and the one after stops it.
456+ let mut types = vec![0u8; granules * channels];
457+ for gr in 0..granules {
458+ for ch in 0..channels {
459+ let index = gr * channels + ch;
460+ let next = index + channels;
461+ let here = self.pending[index].energy;
462+ let there = self.pending.get(next).map_or(here, |g| g.energy);
463+ if there > here * 8.0 + 1e-6 {
464+ types[index] = 1; // start
465+ }
466+ }
467+ }
468+ for gr in 0..granules {
469+ for ch in 0..channels {
470+ let index = gr * channels + ch;
471+ if index >= channels && types[index - channels] == 1 {
472+ types[index] = 2; // short
473+ } else if index >= 2 * channels && types[index - 2 * channels] == 2 {
474+ types[index] = 3; // stop
475+ }
476+ }
477+ }
478+
479+ let begin = self.assigned - self.used;
480+ let budget_bits = (self.assigned + capacity - self.used) * 8;
481+ let mut coded: Vec<CodedGranule> = Vec::with_capacity(granules * channels);
482+ let share = budget_bits / (granules * channels).max(1);
483+ for gr in 0..granules {
484+ for ch in 0..channels {
485+ let index = gr * channels + ch;
486+ let granule = self.pending[index].clone();
487+ let xr = self.mdct(ch, &granule.subband, types[index]);
488+ let spent: usize = coded.iter().map(|c| c.part2_3_length as usize).sum();
489+ let left = budget_bits.saturating_sub(spent);
490+ let target = share.min(left).min(4095);
491+ coded.push(quantise_granule(
492+ &xr,
493+ types[index],
494+ target as u32,
495+ &granule.threshold,
496+ self.sample_rate,
497+ ));
498+ }
499+ }
500+ self.pending.drain(..granules * channels);
501+
502+ // Assemble the frame: header, side info, and this frame's window on
503+ // the main-data stream.
504+ let mut side = BitWriter::new();
505+ side.write_bits(
506+ begin as u32,
507+ if self.version == Version::Mpeg1 { 9 } else { 8 },
508+ );
509+ let private = match (self.version == Version::Mpeg1, channels) {
510+ (true, 1) => 5,
511+ (true, _) => 3,
512+ (false, 1) => 1,
513+ (false, _) => 2,
514+ };
515+ side.write_bits(0, private);
516+ if self.version == Version::Mpeg1 {
517+ side.write_bits(0, 4 * channels as u32); // scfsi: never reuse
518+ }
519+ for granule in &coded {
520+ side.write_bits(granule.part2_3_length, 12);
521+ side.write_bits(granule.big_values, 9);
522+ side.write_bits(granule.global_gain, 8);
523+ side.write_bits(
524+ granule.scalefac_compress,
525+ if self.version == Version::Mpeg1 { 4 } else { 9 },
526+ );
527+ if granule.block_type == 0 {
528+ side.write_bit(false);
529+ for table in granule.table_select {
530+ side.write_bits(u32::from(table), 5);
531+ }
532+ side.write_bits(granule.region0_count, 4);
533+ side.write_bits(granule.region1_count, 3);
534+ } else {
535+ side.write_bit(true);
536+ side.write_bits(u32::from(granule.block_type), 2);
537+ side.write_bit(false); // mixed_block_flag
538+ for table in &granule.table_select[..2] {
539+ side.write_bits(u32::from(*table), 5);
540+ }
541+ side.write_bits(0, 9); // subblock_gain
542+ }
543+ if self.version == Version::Mpeg1 {
544+ side.write_bit(false); // preflag
545+ }
546+ side.write_bit(granule.scalefac_scale);
547+ side.write_bit(granule.count1table_select);
548+ }
549+ side.align_to_byte();
550+ let side_bytes = side.into_bytes();
551+ debug_assert_eq!(side_bytes.len(), header.side_info_len());
552+
553+ // Append the granule data to the stream at `used`, byte aligned.
554+ let mut main = BitWriter::new();
555+ for granule in &coded {
556+ for bit in &granule.bits {
557+ main.write_bit(*bit);
558+ }
559+ }
560+ main.align_to_byte();
561+ let main_bytes = main.into_bytes();
562+ // Stream positions the reservoir cap skipped over are stuffing, not
563+ // data, so they are zeros rather than a shorter stream.
564+ if self.stream.len() < self.used {
565+ self.stream.resize(self.used, 0);
566+ }
567+ self.stream.truncate(self.used);
568+ self.stream.extend_from_slice(&main_bytes);
569+ self.used += main_bytes.len();
570+
571+ self.queued
572+ .push_back((header.to_bytes().to_vec(), side_bytes));
573+ self.assigned += capacity;
574+ // A queued frame can only go out once real granule data covers its
575+ // whole payload; padding it early is what would strand the next
576+ // frame's `main_data_begin` in bytes that were already written.
577+ while !self.queued.is_empty() && self.stream.len() >= self.written + capacity {
578+ let (head, side) = self.queued.pop_front().expect("queue is not empty");
579+ let mut frame = Vec::with_capacity(frame_len);
580+ frame.extend_from_slice(&head);
581+ frame.extend_from_slice(&side);
582+ frame.extend_from_slice(&self.stream[self.written..self.written + capacity]);
583+ self.written += capacity;
584+ self.ready.push_back(frame);
585+ self.frames += 1;
586+ }
587+ // main_data_begin is nine bits, so the reservoir cannot reach further
588+ // back than 511 bytes; anything older is dropped rather than pointed at.
589+ if self.assigned > self.used + 511 {
590+ self.used = self.assigned - 511;
591+ }
592+ }
593+
594+ /// Writes out whatever frames are still queued, padding the stream so the
595+ /// last frame is complete.
596+ fn flush_frames(&mut self) {
597+ let header = self.header();
598+ let frame_len = header.frame_len().unwrap_or(0);
599+ let capacity = frame_len - 4 - header.side_info_len();
600+ while let Some((head, side)) = self.queued.pop_front() {
601+ if self.stream.len() < self.written + capacity {
602+ self.stream.resize(self.written + capacity, 0);
603+ }
604+ let mut frame = Vec::with_capacity(frame_len);
605+ frame.extend_from_slice(&head);
606+ frame.extend_from_slice(&side);
607+ frame.extend_from_slice(&self.stream[self.written..self.written + capacity]);
608+ self.written += capacity;
609+ self.ready.push_back(frame);
610+ self.frames += 1;
611+ }
612+ }
613+
614+ /// One granule of subband samples to 576 spectral lines.
615+ fn mdct(&mut self, ch: usize, subband: &[[f32; 32]], block_type: u8) -> Vec<f32> {
616+ let mut xr = vec![0.0f32; 576];
617+ let history = self.history[ch];
618+ for sb in 0..32 {
619+ // The transform window is the previous granule's 18 samples
620+ // followed by this granule's, with the frequency inversion the
621+ // decoder applies undone first.
622+ let mut input = [0.0f32; 36];
623+ for t in 0..18 {
624+ let sign = if sb % 2 == 1 && t % 2 == 1 { -1.0 } else { 1.0 };
625+ input[t] = history[t][sb] * sign;
626+ input[18 + t] = subband[t][sb] * sign;
627+ }
628+ let out = &mut xr[sb * 18..sb * 18 + 18];
629+ if block_type == 2 {
630+ mdct_short(&input, out);
631+ } else {
632+ mdct_long(&input, block_type, out);
633+ }
634+ }
635+ if block_type != 2 {
636+ alias_expand(&mut xr, 32);
637+ }
638+ let mut store = [[0.0f32; 32]; 18];
639+ store[..18].copy_from_slice(&subband[..18]);
640+ self.history[ch] = store;
641+ xr
642+ }
643+}
644+
645+/// Forward MDCT, 36 samples to 18 coefficients, scaled so the decoder's
646+/// unscaled inverse reconstructs the input under overlap-add.
647+fn mdct_long(input: &[f32; 36], block_type: u8, out: &mut [f32]) {
648+ let window = &windows()[usize::from(block_type)];
649+ let mut windowed = [0.0f32; 36];
650+ for i in 0..36 {
651+ windowed[i] = input[i] * window[i];
652+ }
653+ for (k, slot) in out.iter_mut().enumerate() {
654+ let mut sum = 0.0f64;
655+ for (n, value) in windowed.iter().enumerate() {
656+ let angle = std::f64::consts::PI / 72.0 * ((2 * n + 19) * (2 * k + 1)) as f64;
657+ sum += f64::from(*value) * angle.cos();
658+ }
659+ *slot = (sum / 9.0) as f32;
660+ }
661+}
662+
663+/// Forward MDCT for a short block: three 12-sample transforms, interleaved
664+/// into the spectrum the way the decoder reads them back.
665+fn mdct_short(input: &[f32; 36], out: &mut [f32]) {
666+ let window = &windows()[2];
667+ for w in 0..3 {
668+ for k in 0..6 {
669+ let mut sum = 0.0f64;
670+ for n in 0..12 {
671+ let sample = input[6 + 6 * w + n] * window[n];
672+ let angle = std::f64::consts::PI / 24.0 * ((2 * n + 7) * (2 * k + 1)) as f64;
673+ sum += f64::from(sample) * angle.cos();
674+ }
675+ out[k * 3 + w] = (sum / 3.0) as f32;
676+ }
677+ }
678+}
679+
680+/// Quantises one granule: the rate loop inside the distortion loop.
681+fn quantise_granule(
682+ xr: &[f32],
683+ block_type: u8,
684+ target_bits: u32,
685+ threshold: &[f32],
686+ sample_rate: u32,
687+) -> CodedGranule {
688+ let mut scalefac = [0u8; SFB_LONG];
689+ let mut best: Option<(CodedGranule, f64)> = None;
690+ // The distortion loop. Two things end it: every band is under its masking
691+ // threshold *and* the bits are spent, or no band can be amplified further.
692+ // Spending the bits matters as much as the threshold does — a granule that
693+ // stops early leaves the extra bitrate on the floor, which is what makes an
694+ // encoder's quality flat across 128 and 320 kbit/s.
695+ for _round in 0..20 {
696+ let (granule, noise) = code_with(xr, block_type, target_bits, &scalefac, sample_rate);
697+ let ratios: Vec<f64> = (0..SFB_LONG)
698+ .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30))
699+ .collect();
700+ let score: f64 = ratios.iter().sum();
701+ let spent = granule.part2_3_length;
702+ if best.as_ref().is_none_or(|(_, s)| score < *s) {
703+ best = Some((granule, score));
704+ }
705+ if block_type == 2 {
706+ break; // short blocks carry no long scalefactors here
707+ }
708+ if spent * 20 > target_bits * 19 {
709+ break; // the budget is spent; amplifying now only coarsens
710+ }
711+ // Amplify the bands that are worst against their threshold.
712+ let mut order: Vec<usize> = (0..SFB_LONG).filter(|&b| scalefac[b] < 15).collect();
713+ order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a]));
714+ let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect();
715+ let chosen: Vec<usize> = if over.is_empty() {
716+ order.iter().copied().take(3).collect()
717+ } else {
718+ over
719+ };
720+ if chosen.is_empty() {
721+ break;
722+ }
723+ for band in chosen {
724+ scalefac[band] += 1;
725+ }
726+ }
727+ best.expect("at least one round runs").0
728+}
729+
730+/// Quantises with a fixed scalefactor set, running the rate loop on
731+/// `global_gain`, and reports the noise each band ends up with.
732+fn code_with(
733+ xr: &[f32],
734+ block_type: u8,
735+ budget_bits: u32,
736+ scalefac: &[u8; SFB_LONG],
737+ sample_rate: u32,
738+) -> (CodedGranule, [f32; SFB_LONG]) {
739+ let (slen1, slen2, compress) = scalefac_compress(scalefac);
740+ // The scalefactors come out of the same budget as the spectrum does.
741+ let scalefac_bits = if block_type == 2 {
742+ 0
743+ } else {
744+ slen1 * 11 + slen2 * 10
745+ };
746+ let target_bits = budget_bits.saturating_sub(scalefac_bits);
747+ let peak = xr.iter().fold(0.0f32, |acc, v| acc.max(v.abs()));
748+ // A starting gain that puts the loudest line near the top of the coded
749+ // range: |xr| / 2^((g-210)/4) raised to 3/4 should land around 8000.
750+ let start = if peak > 1e-20 {
751+ (210.0 + 4.0 * (peak.log2() - 13.0 / 0.75)).round() as i32
752+ } else {
753+ 210
754+ };
755+ let mut gain = start.clamp(0, 255);
756+ let mut ix = vec![0i32; 576];
757+ let mut coded;
758+ // The rate loop runs both ways: down while there are bits to spare, up
759+ // while the granule is too big for them. A line that saturates the coding
760+ // range is not "cheap", it is clipped, so that check comes first.
761+ let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191);
762+ quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
763+ coded = code_spectrum(&ix, block_type, sample_rate);
764+ loop {
765+ if (saturated(&ix) || coded.0 > target_bits) && gain < 255 {
766+ gain += 1;
767+ quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
768+ coded = code_spectrum(&ix, block_type, sample_rate);
769+ continue;
770+ }
771+ if saturated(&ix) || coded.0 > target_bits || gain == 0 {
772+ break;
773+ }
774+ // Try one step quieter; keep it only if it still fits and stays
775+ // inside the coding range.
776+ let mut trial = ix.clone();
777+ quantise(xr, gain - 1, scalefac, sample_rate, block_type, &mut trial);
778+ let trial_coded = code_spectrum(&trial, block_type, sample_rate);
779+ if trial_coded.0 > target_bits || saturated(&trial) {
780+ break;
781+ }
782+ gain -= 1;
783+ ix = trial;
784+ coded = trial_coded;
785+ }
786+ // Last resort: if even the quietest legal gain will not fit the bits we
787+ // were given, drop the top of the spectrum until it does. A granule that
788+ // overruns its budget would corrupt the reservoir for every frame after
789+ // it, which is far worse than a low-passed one.
790+ let mut limit = 576usize;
791+ while coded.0 > target_bits && limit > 4 {
792+ limit = limit * 3 / 4;
793+ for slot in ix.iter_mut().skip(limit) {
794+ *slot = 0;
795+ }
796+ coded = code_spectrum(&ix, block_type, sample_rate);
797+ }
798+ let (_, big_values, tables, region0, region1, count1_select, bits) = coded;
799+ let mut noise = [0.0f32; SFB_LONG];
800+ let starts = long_starts(sample_rate);
801+ let power = power43();
802+ for band in 0..SFB_LONG {
803+ let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1]));
804+ let scale = band_gain(gain, scalefac[band], block_type);
805+ let mut sum = 0.0f32;
806+ for i in from..to.min(576) {
807+ let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scale;
808+ let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude };
809+ sum += (xr[i] - reconstructed).powi(2);
810+ }
811+ noise[band] = sum;
812+ }
813+ let mut out = BitWriter::new();
814+ for (band, value) in scalefac.iter().enumerate() {
815+ let slen = if band < 11 { slen1 } else { slen2 };
816+ if block_type != 2 {
817+ out.write_bits(u32::from(*value), slen);
818+ }
819+ }
820+ let scalefac_bits = out.bit_len() as u32;
821+ let mut bits_out: Vec<bool> = Vec::with_capacity((scalefac_bits + bits.len() as u32) as usize);
822+ let bytes = out.into_bytes();
823+ for i in 0..scalefac_bits as usize {
824+ bits_out.push((bytes[i / 8] >> (7 - i % 8)) & 1 == 1);
825+ }
826+ bits_out.extend_from_slice(&bits);
827+ let granule = CodedGranule {
828+ part2_3_length: bits_out.len() as u32,
829+ bits: bits_out,
830+ big_values,
831+ global_gain: gain as u32,
832+ scalefac_compress: compress,
833+ block_type,
834+ table_select: tables,
835+ region0_count: region0,
836+ region1_count: region1,
837+ scalefac_scale: false,
838+ count1table_select: count1_select,
839+ };
840+ (granule, noise)
841+}
842+
843+fn band_gain(gain: i32, scalefac: u8, block_type: u8) -> f32 {
844+ let base = (gain as f32 - 210.0) * 0.25;
845+ if block_type == 2 {
846+ base.exp2()
847+ } else {
848+ (base - 0.5 * f32::from(scalefac)).exp2()
849+ }
850+}
851+
852+/// The spectrum as integers, per the decoder's requantisation read backwards.
853+fn quantise(
854+ xr: &[f32],
855+ gain: i32,
856+ scalefac: &[u8; SFB_LONG],
857+ sample_rate: u32,
858+ block_type: u8,
859+ ix: &mut [i32],
860+) {
861+ let starts = long_starts(sample_rate);
862+ // 22 bands, not 21: the topmost band carries no transmitted scalefactor,
863+ // but it does carry audio — zeroing it low-passes the encoder at 16 kHz.
864+ for band in 0..22 {
865+ let (from, to) = (
866+ usize::from(starts[band]),
867+ usize::from(starts[band + 1]).min(576),
868+ );
869+ let scalefac = if band < SFB_LONG { scalefac[band] } else { 0 };
870+ let scale = 1.0 / band_gain(gain, scalefac, block_type);
871+ for i in from..to {
872+ let value = (xr[i].abs() * scale).powf(0.75);
873+ let magnitude = (value + 0.4054).min(MAX_QUANT as f32) as i32;
874+ ix[i] = if xr[i] < 0.0 { -magnitude } else { magnitude };
875+ }
876+ }
877+}
878+
879+/// Chooses the region split, the tables and the count1 boundary, and writes the
880+/// spectrum. Returns the bit cost first so the rate loop can stop early.
881+#[allow(clippy::type_complexity)]
882+fn code_spectrum(
883+ ix: &[i32],
884+ block_type: u8,
885+ sample_rate: u32,
886+) -> (u32, u32, [u8; 3], u32, u32, bool, Vec<bool>) {
887+ // Trailing zeros are not coded at all; before them, a run of values in
888+ // -1..=1 is coded four at a time.
889+ let mut rzero = 576;
890+ while rzero > 0 && ix[rzero - 1] == 0 {
891+ rzero -= 1;
892+ }
893+ let count1_end = (rzero.div_ceil(4) * 4).min(576);
894+ let mut count1_start = count1_end;
895+ while count1_start >= 4
896+ && ix[count1_start - 4..count1_start]
897+ .iter()
898+ .all(|v| v.abs() <= 1)
899+ {
900+ count1_start -= 4;
901+ }
902+ let big_end = count1_start;
903+
904+ let starts = long_starts(sample_rate);
905+ let short = block_type == 2;
906+ // Region boundaries land on band edges. Splitting the big-value region in
907+ // three roughly equal parts is what makes the three tables specialise;
908+ // searching every legal split costs far more than it saves.
909+ let (region0, region1, bounds) = if short {
910+ let first = usize::from(short_starts(sample_rate)[3]) * 3;
911+ (8u32, 12u32, [first.min(big_end), big_end, big_end])
912+ } else {
913+ let band_at = |target: usize| -> usize {
914+ (0..21)
915+ .min_by_key(|&b| usize::from(starts[b + 1]).abs_diff(target))
916+ .unwrap_or(7)
917+ };
918+ let r0 = band_at(big_end / 3).min(15);
919+ let r1 = band_at(big_end * 2 / 3).saturating_sub(r0 + 1).min(7);
920+ let a = usize::from(starts[(r0 + 1).min(21)]).min(big_end);
921+ let b = usize::from(starts[(r0 + r1 + 2).min(21)]).min(big_end);
922+ (r0 as u32, r1 as u32, [a, b.max(a), big_end])
923+ };
924+
925+ let mut tables = [0u8; 3];
926+ let mut writer = BitWriter::new();
927+ let mut from = 0usize;
928+ for (region, to) in bounds.iter().enumerate() {
929+ let to = (*to).min(big_end);
930+ if to > from {
931+ let select = best_table(ix, from, to);
932+ tables[region] = select;
933+ let table = huffman::big_table(usize::from(select)).expect("table exists");
934+ let mut i = from;
935+ while i + 1 < to {
936+ huffman::write_pair(&mut writer, table, ix[i], ix[i + 1]);
937+ i += 2;
938+ }
939+ }
940+ from = to;
941+ }
942+ // count1: try both tables, keep the cheaper.
943+ let quads: Vec<[i32; 4]> = (big_end..count1_end)
944+ .step_by(4)
945+ .filter(|i| i + 4 <= 576)
946+ .map(|i| [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]])
947+ .collect();
948+ let cost = |select: bool| -> u32 {
949+ quads
950+ .iter()
951+ .map(|quad| huffman::quad_bits(select, *quad))
952+ .sum()
953+ };
954+ let count1_select = cost(true) < cost(false);
955+ for quad in &quads {
956+ huffman::write_quad(&mut writer, count1_select, *quad);
957+ }
958+ let bit_len = writer.bit_len() as usize;
959+ let bytes = writer.into_bytes();
960+ let mut bits = Vec::with_capacity(bit_len);
961+ for i in 0..bit_len {
962+ bits.push((bytes[i / 8] >> (7 - i % 8)) & 1 == 1);
963+ }
964+ (
965+ bits.len() as u32,
966+ (big_end / 2) as u32,
967+ tables,
968+ region0,
969+ region1,
970+ count1_select,
971+ bits,
972+ )
973+}
974+
975+/// Tables that can code a region whose largest magnitude is `max`, cheapest
976+/// candidates first. Anything above 15 needs an escape-coded table, and the
977+/// escape tables differ only in how many linbits they spend.
978+fn candidates(max: u32) -> &'static [u8] {
979+ match max {
980+ 0..=1 => &[1, 2, 3, 5, 6, 7, 8, 9],
981+ 2 => &[2, 3, 5, 6, 7, 8, 9, 10],
982+ 3 => &[5, 6, 7, 8, 9, 10, 11, 12],
983+ 4..=5 => &[7, 8, 9, 10, 11, 12, 13, 15],
984+ 6..=7 => &[10, 11, 12, 13, 15],
985+ 8..=15 => &[13, 15, 16, 24],
986+ 16..=16 => &[16, 17, 18, 19, 20, 21, 22, 23, 24],
987+ 17..=18 => &[17, 18, 19, 20, 21, 22, 23, 24, 25],
988+ 19..=30 => &[18, 19, 20, 21, 22, 23, 25, 26, 27],
989+ 31..=78 => &[20, 21, 22, 23, 26, 27, 28, 29],
990+ 79..=270 => &[21, 22, 23, 28, 29, 30, 31],
991+ 271..=1038 => &[22, 23, 30, 31],
992+ _ => &[23, 31],
993+ }
994+}
995+
996+/// The cheapest table for one region.
997+fn best_table(ix: &[i32], from: usize, to: usize) -> u8 {
998+ let max = ix[from..to]
999+ .iter()
1000+ .map(|v| v.unsigned_abs())
1001+ .max()
1002+ .unwrap_or(0);
1003+ let mut best = (u32::MAX, 0u8);
1004+ for &select in candidates(max) {
1005+ let Ok(table) = huffman::big_table(usize::from(select)) else {
1006+ continue;
1007+ };
1008+ if let Some(cost) = table_cost(ix, from, to, table)
1009+ && cost < best.0
1010+ {
1011+ best = (cost, select);
1012+ }
1013+ }
1014+ if best.1 == 0 {
1015+ // Nothing in the shortlist fits, which only a value above the coding
1016+ // range can cause; fall back to the widest escape table.
1017+ return 23;
1018+ }
1019+ best.1
1020+}
1021+
1022+fn table_cost(ix: &[i32], from: usize, to: usize, table: Table) -> Option<u32> {
1023+ let mut sum = 0;
1024+ let mut i = from;
1025+ while i + 1 < to {
1026+ sum += huffman::pair_bits(table, ix[i].unsigned_abs(), ix[i + 1].unsigned_abs())?;
1027+ i += 2;
1028+ }
1029+ Some(sum)
1030+}
1031+
1032+/// The `scalefac_compress` index whose two lengths hold these scalefactors.
1033+fn scalefac_compress(scalefac: &[u8; SFB_LONG]) -> (u32, u32, u32) {
1034+ let bits_for = |slice: &[u8]| -> u32 {
1035+ let max = slice.iter().copied().max().unwrap_or(0);
1036+ (0..=4u32).find(|n| max < (1 << n)).unwrap_or(4)
1037+ };
1038+ let need1 = bits_for(&scalefac[..11]);
1039+ let need2 = bits_for(&scalefac[11..]);
1040+ let mut best = (u32::MAX, 0u32, 0u32, 0u32);
1041+ for (index, (slen1, slen2)) in SLEN.iter().enumerate() {
1042+ if *slen1 >= need1 && *slen2 >= need2 {
1043+ let cost = slen1 * 11 + slen2 * 10;
1044+ if cost < best.0 {
1045+ best = (cost, *slen1, *slen2, index as u32);
1046+ }
1047+ }
1048+ }
1049+ (best.1, best.2, best.3)
1050+}
1051+
1052+#[cfg(test)]
1053+mod tests {
1054+ use super::*;
1055+
1056+ #[test]
1057+ fn bitrates_snap_to_legal_values() {
1058+ assert_eq!(snap_bitrate(Version::Mpeg1, 128), 128);
1059+ assert_eq!(snap_bitrate(Version::Mpeg1, 130), 128);
1060+ assert_eq!(snap_bitrate(Version::Mpeg1, 1000), 320);
1061+ assert_eq!(snap_bitrate(Version::Mpeg2, 128), 128);
1062+ assert_eq!(snap_bitrate(Version::Mpeg2, 320), 160);
1063+ }
1064+
1065+ #[test]
1066+ fn unsupported_rates_are_refused_by_name() {
1067+ let err = Mp3Encode::new(96000, 2, 128).unwrap_err();
1068+ assert!(format!("{err}").contains("96000 Hz"), "{err}");
1069+ }
1070+
1071+ /// The encoder's whole analysis chain against the decoder's whole
1072+ /// synthesis chain, quantisation left out: what comes back is what went
1073+ /// in, delayed by the filterbank.
1074+ #[test]
1075+ fn analysis_chain_round_trips_through_the_decoder() {
1076+ use crate::filterbank::{Imdct, Synthesis, alias_reduce};
1077+ let imdct = Imdct::default();
1078+ let mut analysis = Analysis::default();
1079+ let mut synthesis = Synthesis::default();
1080+ let n = 32 * 32 * 24;
1081+ let input: Vec<f32> = (0..n)
1082+ .map(|i| {
1083+ let t = i as f32;
1084+ 0.4 * (t * 0.05).sin() + 0.2 * (t * 0.31).cos()
1085+ })
1086+ .collect();
1087+ let mut slots: Vec<[f32; 32]> = Vec::new();
1088+ for chunk in input.chunks(32) {
1089+ if let Some(slot) = analysis.push(chunk) {
1090+ slots.push(slot);
1091+ }
1092+ }
1093+ let granules = slots.len() / 18;
1094+ let mut history = [[0.0f32; 32]; 18];
1095+ let mut overlap = [[0.0f32; 18]; 32];
1096+ let mut output: Vec<f32> = Vec::new();
1097+ for g in 0..granules {
1098+ let granule = &slots[g * 18..g * 18 + 18];
1099+ let mut xr = vec![0.0f32; 576];
1100+ for sb in 0..32 {
1101+ let mut window = [0.0f32; 36];
1102+ for t in 0..18 {
1103+ let sign = if sb % 2 == 1 && t % 2 == 1 { -1.0 } else { 1.0 };
1104+ window[t] = history[t][sb] * sign;
1105+ window[18 + t] = granule[t][sb] * sign;
1106+ }
1107+ mdct_long(&window, 0, &mut xr[sb * 18..sb * 18 + 18]);
1108+ }
1109+ alias_expand(&mut xr, 32);
1110+ history.copy_from_slice(granule);
1111+ // decoder side
1112+ alias_reduce(&mut xr, 32);
1113+ let mut out_slots = [[0.0f32; 32]; 18];
1114+ let mut block = [0.0f32; 36];
1115+ for sb in 0..32 {
1116+ imdct.long(&xr[sb * 18..sb * 18 + 18], 0, &mut block);
1117+ for t in 0..18 {
1118+ let mut sample = block[t] + overlap[sb][t];
1119+ overlap[sb][t] = block[18 + t];
1120+ if sb % 2 == 1 && t % 2 == 1 {
1121+ sample = -sample;
1122+ }
1123+ out_slots[t][sb] = sample;
1124+ }
1125+ }
1126+ let mut pcm = [0.0f32; 32];
1127+ for slot in &out_slots {
1128+ synthesis.slot(slot, &mut pcm);
1129+ output.extend_from_slice(&pcm);
1130+ }
1131+ }
1132+ // Find the delay, then check the reconstruction is faithful. The
1133+ // comparison starts past the filterbank's ramp-up, which is silence
1134+ // sliding into the window rather than anything the transform got wrong.
1135+ let (from, len) = (4096usize, 8192usize);
1136+ let mut best = (f64::MIN, 0usize);
1137+ for delay in 0..output.len().min(2048) {
1138+ if delay + from + len > output.len() || from + len > input.len() {
1139+ break;
1140+ }
1141+ let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
1142+ for i in from..from + len {
1143+ let (x, y) = (output[delay + i] as f64, input[i] as f64);
1144+ ab += x * y;
1145+ aa += x * x;
1146+ bb += y * y;
1147+ }
1148+ let corr = ab / (aa * bb).sqrt().max(1e-30);
1149+ if corr > best.0 {
1150+ best = (corr, delay);
1151+ }
1152+ }
1153+ assert!(
1154+ best.0 > 0.99999,
1155+ "analysis/synthesis correlation {:.6} at delay {}",
1156+ best.0,
1157+ best.1
1158+ );
1159+ }
1160+
1161+ /// The forward MDCT and the decoder's inverse are a reconstructing pair:
1162+ /// two overlapped granules of a signal come back as themselves.
1163+ #[test]
1164+ fn mdct_round_trips_under_overlap_add() {
1165+ use crate::filterbank::Imdct;
1166+ let imdct = Imdct::default();
1167+ let signal: Vec<f32> = (0..72)
1168+ .map(|i| ((i as f32) * 0.37).sin() + 0.3 * ((i as f32) * 1.1).cos())
1169+ .collect();
1170+ let mut output = vec![0.0f32; 72];
1171+ let mut previous = [0.0f32; 18];
1172+ for granule in 0..3 {
1173+ let mut input = [0.0f32; 36];
1174+ for (i, slot) in input.iter_mut().enumerate() {
1175+ let index = granule * 18 + i;
1176+ if index < signal.len() {
1177+ *slot = signal[index];
1178+ }
1179+ }
1180+ let mut spectrum = [0.0f32; 18];
1181+ mdct_long(&input, 0, &mut spectrum);
1182+ let mut block = [0.0f32; 36];
1183+ imdct.long(&spectrum, 0, &mut block);
1184+ for t in 0..18 {
1185+ let index = granule * 18 + t;
1186+ if index < output.len() {
1187+ output[index] = block[t] + previous[t];
1188+ }
1189+ }
1190+ previous.copy_from_slice(&block[18..]);
1191+ }
1192+ // The first granule has no predecessor, so compare from the second.
1193+ let mut worst = 0.0f32;
1194+ for i in 18..54 {
1195+ worst = worst.max((output[i] - signal[i]).abs());
1196+ }
1197+ println!("mdct round trip worst absolute error {worst:e}");
1198+ for i in 18..54 {
1199+ assert!(
1200+ (output[i] - signal[i]).abs() < 1e-5,
1201+ "sample {i}: {} vs {}",
1202+ output[i],
1203+ signal[i]
1204+ );
1205+ }
1206+ }
1207+}
crates/ec-mp3/src/filterbank.rsadded+314 -0
@@ -0,0 +1,314 @@
1+//! The two transforms every Layer III sample passes through: the 36/12-point
2+//! IMDCT with its alias butterflies, and the 32-band polyphase bank.
3+//!
4+//! The polyphase matrixing is a 32-point DCT from `ec-dsp` in both directions —
5+//! DCT-II going out, DCT-III coming in — after folding the 64 (or 80) cosine
6+//! arguments onto the 32 the transform actually computes. That is what keeps
7+//! synthesis at 512 window multiplies and one short DCT per 32 output samples
8+//! instead of a 32x64 product.
9+//!
10+//! The IMDCT sizes (36 and 12) are not powers of two, so `ec-dsp`'s MDCT plan
11+//! does not apply. They are computed instead from the transform's own two
12+//! symmetries — `y[17-n] = -y[n]` and `y[35-m] = y[18+m]` — which halve a
13+//! fixed-size product that costs under 1 % of decode time either way; the
14+//! polyphase bank below is where the time actually goes.
15+
16+use crate::tables::{alias_coefficients, windows};
17+use crate::window::WINDOW;
18+use ec_dsp::Dct;
19+
20+/// Precomputed IMDCT bases, shared by the decoder and the encoder.
21+#[derive(Clone, Debug)]
22+pub(crate) struct Imdct {
23+ long: [[f32; 18]; 18],
24+ short: [[f32; 6]; 6],
25+}
26+
27+impl Default for Imdct {
28+ fn default() -> Imdct {
29+ let mut long = [[0.0f32; 18]; 18];
30+ for (row, out) in long.iter_mut().enumerate() {
31+ let n = if row < 9 { row } else { row + 9 };
32+ for (k, slot) in out.iter_mut().enumerate() {
33+ let angle = std::f64::consts::PI / 72.0 * ((2 * n + 19) * (2 * k + 1)) as f64;
34+ *slot = angle.cos() as f32;
35+ }
36+ }
37+ let mut short = [[0.0f32; 6]; 6];
38+ for (row, out) in short.iter_mut().enumerate() {
39+ let n = if row < 3 { row } else { row + 3 };
40+ for (k, slot) in out.iter_mut().enumerate() {
41+ let angle = std::f64::consts::PI / 24.0 * ((2 * n + 7) * (2 * k + 1)) as f64;
42+ *slot = angle.cos() as f32;
43+ }
44+ }
45+ Imdct { long, short }
46+ }
47+}
48+
49+impl Imdct {
50+ /// 18 coefficients to 36 samples, windowed with `block_type`'s window.
51+ pub(crate) fn long(&self, x: &[f32], block_type: u8, out: &mut [f32; 36]) {
52+ let mut half = [0.0f32; 18];
53+ for (row, slot) in self.long.iter().zip(half.iter_mut()) {
54+ *slot = row.iter().zip(x).map(|(c, v)| c * v).sum();
55+ }
56+ for n in 0..9 {
57+ out[n] = half[n];
58+ out[17 - n] = -half[n];
59+ out[18 + n] = half[9 + n];
60+ out[35 - n] = half[9 + n];
61+ }
62+ let window = &windows()[usize::from(block_type)];
63+ for (slot, w) in out.iter_mut().zip(window) {
64+ *slot *= w;
65+ }
66+ }
67+
68+ /// Three 6-coefficient short blocks to one 36-sample overlap buffer.
69+ pub(crate) fn short(&self, x: &[f32], out: &mut [f32; 36]) {
70+ out.fill(0.0);
71+ let window = &windows()[2];
72+ for w in 0..3 {
73+ let mut half = [0.0f32; 6];
74+ for (row, slot) in self.short.iter().zip(half.iter_mut()) {
75+ *slot = (0..6).map(|k| row[k] * x[k * 3 + w]).sum();
76+ }
77+ let mut block = [0.0f32; 12];
78+ for n in 0..3 {
79+ block[n] = half[n];
80+ block[5 - n] = -half[n];
81+ block[6 + n] = half[3 + n];
82+ block[11 - n] = half[3 + n];
83+ }
84+ for (i, value) in block.iter().enumerate() {
85+ out[6 + 6 * w + i] += value * window[i];
86+ }
87+ }
88+ }
89+}
90+
91+/// The decoder's alias reduction: eight butterflies each side of every long
92+/// subband boundary.
93+pub(crate) fn alias_reduce(xr: &mut [f32], bands: usize) {
94+ let coeffs = alias_coefficients();
95+ for sb in 1..bands {
96+ for (i, (cs, ca)) in coeffs.iter().enumerate() {
97+ let lo = sb * 18 - 1 - i;
98+ let hi = sb * 18 + i;
99+ let (a, b) = (xr[lo], xr[hi]);
100+ xr[lo] = a * cs - b * ca;
101+ xr[hi] = b * cs + a * ca;
102+ }
103+ }
104+}
105+
106+/// The encoder's inverse of [`alias_reduce`], applied before quantisation so
107+/// that the decoder's butterflies undo it exactly.
108+pub(crate) fn alias_expand(xr: &mut [f32], bands: usize) {
109+ let coeffs = alias_coefficients();
110+ for sb in 1..bands {
111+ for (i, (cs, ca)) in coeffs.iter().enumerate() {
112+ let lo = sb * 18 - 1 - i;
113+ let hi = sb * 18 + i;
114+ let (a, b) = (xr[lo], xr[hi]);
115+ xr[lo] = a * cs + b * ca;
116+ xr[hi] = b * cs - a * ca;
117+ }
118+ }
119+}
120+
121+/// Folds the 64 matrixing rows onto the 32 a DCT-II computes.
122+fn unfold(g: &[f32; 32], v: &mut [f32; 64]) {
123+ for (b, slot) in v.iter_mut().enumerate() {
124+ *slot = match b {
125+ 0..=15 => g[b + 16],
126+ 16 => 0.0,
127+ 17..=47 => -g[48 - b],
128+ _ => -g[b - 48],
129+ };
130+ }
131+}
132+
133+/// The synthesis polyphase bank for one channel.
134+#[derive(Clone, Debug)]
135+pub(crate) struct Synthesis {
136+ blocks: Box<[[f32; 64]; 16]>,
137+ pos: usize,
138+ dct: Dct<f32>,
139+}
140+
141+impl Default for Synthesis {
142+ fn default() -> Synthesis {
143+ Synthesis {
144+ blocks: Box::new([[0.0f32; 64]; 16]),
145+ pos: 0,
146+ dct: Dct::new(32),
147+ }
148+ }
149+}
150+
151+impl Synthesis {
152+ /// Forgets the window history — what a seek needs.
153+ pub(crate) fn reset(&mut self) {
154+ self.blocks.iter_mut().for_each(|b| b.fill(0.0));
155+ self.pos = 0;
156+ }
157+
158+ /// One slot: 32 subband samples in, 32 PCM samples out.
159+ pub(crate) fn slot(&mut self, subband: &[f32; 32], out: &mut [f32]) {
160+ let mut g = *subband;
161+ self.dct.dct2(&mut g);
162+ self.pos = (self.pos + 15) % 16;
163+ unfold(&g, &mut self.blocks[self.pos]);
164+ for (j, sample) in out.iter_mut().enumerate() {
165+ let mut acc = 0.0f32;
166+ for i in 0..16 {
167+ let b = if i % 2 == 0 { j } else { j + 32 };
168+ acc += WINDOW[j + 32 * i] * self.blocks[(self.pos + i) % 16][b];
169+ }
170+ *sample = acc;
171+ }
172+ }
173+}
174+
175+/// The analysis polyphase bank: the adjoint of [`Synthesis`], so that an
176+/// encode/decode pair reconstructs to the filterbank's own -85 dB limit.
177+///
178+/// One subband slot needs the sixteen PCM slots starting at it, so the bank
179+/// runs fifteen slots behind the samples fed to it — the filterbank delay every
180+/// Layer III encoder has.
181+#[derive(Clone, Debug)]
182+pub(crate) struct Analysis {
183+ pcm: Box<[[f32; 32]; 16]>,
184+ pos: usize,
185+ filled: usize,
186+ dct: Dct<f32>,
187+}
188+
189+impl Default for Analysis {
190+ fn default() -> Analysis {
191+ Analysis {
192+ pcm: Box::new([[0.0f32; 32]; 16]),
193+ pos: 0,
194+ filled: 0,
195+ dct: Dct::new(32),
196+ }
197+ }
198+}
199+
200+impl Analysis {
201+ /// Pushes 32 PCM samples; yields the subband slot that became complete.
202+ pub(crate) fn push(&mut self, pcm: &[f32]) -> Option<[f32; 32]> {
203+ self.pcm[self.pos].copy_from_slice(pcm);
204+ self.pos = (self.pos + 1) % 16;
205+ if self.filled < 15 {
206+ self.filled += 1;
207+ return None;
208+ }
209+ let mut r = [0.0f32; 32];
210+ for j in 0..32 {
211+ let mut even = 0.0f32;
212+ let mut odd = 0.0f32;
213+ for i in 0..16 {
214+ let sample = self.pcm[(self.pos + i) % 16][j] * WINDOW[j + 32 * i];
215+ if i % 2 == 0 {
216+ even += sample;
217+ } else {
218+ odd += sample;
219+ }
220+ }
221+ // fold b = j (even taps) and b = j + 32 (odd taps) onto 0..31
222+ match j {
223+ 0..=15 => r[j + 16] += even,
224+ 16 => {}
225+ _ => r[48 - j] -= even,
226+ }
227+ let b = j + 32;
228+ match b {
229+ 32..=47 => r[48 - b] -= odd,
230+ _ => r[b - 48] -= odd,
231+ }
232+ }
233+ // `Dct::dct3` halves its zeroth term; the matrixing wants it whole.
234+ r[0] *= 2.0;
235+ self.dct.dct3(&mut r);
236+ for slot in &mut r {
237+ *slot /= 32.0;
238+ }
239+ Some(r)
240+ }
241+}
242+
243+#[cfg(test)]
244+mod tests {
245+ use super::*;
246+
247+ #[test]
248+ fn alias_butterflies_are_exactly_invertible() {
249+ let mut xr: Vec<f32> = (0..576).map(|i| ((i * 37 % 101) as f32) - 50.0).collect();
250+ let original = xr.clone();
251+ alias_expand(&mut xr, 32);
252+ alias_reduce(&mut xr, 32);
253+ for (a, b) in xr.iter().zip(&original) {
254+ assert!((a - b).abs() < 1e-3, "{a} vs {b}");
255+ }
256+ }
257+
258+ /// Analysis into synthesis is the pseudo-QMF's round trip: a pure delay of
259+ /// 15 slots and -80 dB of residual, which is the bank's design limit.
260+ #[test]
261+ fn filterbank_round_trip_reconstructs() {
262+ let mut analysis = Analysis::default();
263+ let mut synthesis = Synthesis::default();
264+ let n = 64 * 32;
265+ let input: Vec<f32> = (0..n)
266+ .map(|i| {
267+ let t = i as f32;
268+ (t * 0.031).sin() * 0.4 + (t * 0.21).sin() * 0.2 + (t * 0.7).cos() * 0.1
269+ })
270+ .collect();
271+ let mut output = vec![0.0f32; n];
272+ let mut slot_out = 0usize;
273+ for chunk in input.chunks(32) {
274+ if let Some(subband) = analysis.push(chunk) {
275+ let (start, end) = (slot_out * 32, slot_out * 32 + 32);
276+ synthesis.slot(&subband, &mut output[start..end]);
277+ slot_out += 1;
278+ }
279+ }
280+ // The bank reconstructs in place: subband slot t is the sixteen PCM
281+ // slots from t, and synthesising it lands back on PCM slot t. Only the
282+ // first fifteen slots are a ramp, so the comparison starts past them.
283+ let (from, to) = (20 * 32, 40 * 32);
284+ let mut error = 0.0f64;
285+ let mut energy = 0.0f64;
286+ for i in from..to {
287+ let want = input[i] as f64;
288+ let got = output[i] as f64;
289+ error += (want - got).powi(2);
290+ energy += want.powi(2);
291+ }
292+ let snr = 10.0 * (energy / error).log10();
293+ assert!(snr > 80.0, "filterbank round trip snr {snr:.1} dB");
294+ }
295+
296+ #[test]
297+ fn imdct_matches_its_definition() {
298+ let imdct = Imdct::default();
299+ let x: Vec<f32> = (0..18).map(|k| ((k * 13 % 7) as f32) - 3.0).collect();
300+ let mut got = [0.0f32; 36];
301+ imdct.long(&x, 0, &mut got);
302+ let window = &windows()[0];
303+ for (n, value) in got.iter().enumerate() {
304+ let want: f64 = (0..18)
305+ .map(|k| {
306+ x[k] as f64
307+ * (std::f64::consts::PI / 72.0 * ((2 * n + 19) * (2 * k + 1)) as f64).cos()
308+ })
309+ .sum::<f64>()
310+ * window[n] as f64;
311+ assert!((want - *value as f64).abs() < 1e-3, "n={n} {want} {value}");
312+ }
313+ }
314+}
crates/ec-mp3/src/header.rsadded+317 -0
@@ -0,0 +1,317 @@
1+//! The four-byte MPEG audio frame header, its CRC, and the frame geometry
2+//! every other module reads off it.
3+
4+use ec_core::error::{Error, Result};
5+
6+/// Which MPEG audio generation a frame belongs to. The three differ in sample
7+/// rate range, granule count and side-info layout, not in the codec itself.
8+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
9+pub enum Version {
10+ /// MPEG-1 (ISO/IEC 11172-3): 32/44.1/48 kHz, two granules per frame.
11+ Mpeg1,
12+ /// MPEG-2 LSF (ISO/IEC 13818-3): 16/22.05/24 kHz, one granule.
13+ Mpeg2,
14+ /// MPEG-2.5, the de-facto extension to 8/11.025/12 kHz.
15+ Mpeg25,
16+}
17+
18+/// The channel arrangement a frame declares.
19+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
20+pub enum ChannelMode {
21+ /// Two independent channels coded as a stereo pair.
22+ Stereo,
23+ /// Stereo with mid/side and/or intensity coupling, per `mode_extension`.
24+ JointStereo,
25+ /// Two unrelated mono programmes in one stream.
26+ DualChannel,
27+ /// A single channel.
28+ Mono,
29+}
30+
31+impl ChannelMode {
32+ /// Channels carried by the frame.
33+ pub fn channels(self) -> usize {
34+ match self {
35+ ChannelMode::Mono => 1,
36+ _ => 2,
37+ }
38+ }
39+}
40+
41+const BITRATES_V1: [u32; 15] = [
42+ 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
43+];
44+const BITRATES_V2: [u32; 15] = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
45+const RATES_V1: [u32; 3] = [44100, 48000, 32000];
46+
47+/// Everything the header declares, decoded into usable units.
48+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
49+pub struct FrameHeader {
50+ /// MPEG generation.
51+ pub version: Version,
52+ /// Layer number, 1..=3. Only Layer III is decodable here.
53+ pub layer: u8,
54+ /// True when a 16-bit CRC follows the header.
55+ pub crc: bool,
56+ /// Declared bitrate in kbit/s; 0 means free format.
57+ pub bitrate_kbps: u32,
58+ /// Sample rate in Hz.
59+ pub sample_rate: u32,
60+ /// True when the frame carries one extra byte.
61+ pub padding: bool,
62+ /// The private bit, carried through untouched.
63+ pub private: bool,
64+ /// Channel arrangement.
65+ pub mode: ChannelMode,
66+ /// Joint-stereo mode extension: bit 0 intensity, bit 1 mid/side.
67+ pub mode_ext: u8,
68+ /// Copyright flag.
69+ pub copyright: bool,
70+ /// Original-media flag.
71+ pub original: bool,
72+ /// De-emphasis selector, 0 = none.
73+ pub emphasis: u8,
74+}
75+
76+impl FrameHeader {
77+ /// Parses a header from four bytes.
78+ ///
79+ /// Reserved encodings are refused rather than guessed at: a "bad" bitrate
80+ /// index, a reserved sample rate, layer 0 and the reserved MPEG version are
81+ /// all [`Error::Corrupt`], which is what lets [`crate::decode::Mp3Reader`]
82+ /// treat a failed parse as "this was not a frame start" and resync.
83+ pub fn parse(b: &[u8]) -> Result<FrameHeader> {
84+ if b.len() < 4 {
85+ return Err(Error::NeedMore);
86+ }
87+ if b[0] != 0xFF || (b[1] & 0xE0) != 0xE0 {
88+ return Err(Error::corrupt("mp3: no frame sync"));
89+ }
90+ let version = match (b[1] >> 3) & 3 {
91+ 0 => Version::Mpeg25,
92+ 2 => Version::Mpeg2,
93+ 3 => Version::Mpeg1,
94+ _ => return Err(Error::corrupt("mp3: reserved MPEG version id")),
95+ };
96+ let layer = match (b[1] >> 1) & 3 {
97+ 1 => 3,
98+ 2 => 2,
99+ 3 => 1,
100+ _ => return Err(Error::corrupt("mp3: reserved layer id")),
101+ };
102+ let crc = (b[1] & 1) == 0;
103+ let bitrate_index = (b[2] >> 4) as usize;
104+ if bitrate_index == 15 {
105+ return Err(Error::corrupt("mp3: bitrate index 15"));
106+ }
107+ let table = if version == Version::Mpeg1 {
108+ &BITRATES_V1
109+ } else {
110+ &BITRATES_V2
111+ };
112+ let bitrate_kbps = table[bitrate_index];
113+ let rate_index = ((b[2] >> 2) & 3) as usize;
114+ if rate_index == 3 {
115+ return Err(Error::corrupt("mp3: reserved sampling frequency"));
116+ }
117+ let sample_rate = match version {
118+ Version::Mpeg1 => RATES_V1[rate_index],
119+ Version::Mpeg2 => RATES_V1[rate_index] / 2,
120+ Version::Mpeg25 => RATES_V1[rate_index] / 4,
121+ };
122+ let mode = match (b[3] >> 6) & 3 {
123+ 0 => ChannelMode::Stereo,
124+ 1 => ChannelMode::JointStereo,
125+ 2 => ChannelMode::DualChannel,
126+ _ => ChannelMode::Mono,
127+ };
128+ Ok(FrameHeader {
129+ version,
130+ layer,
131+ crc,
132+ bitrate_kbps,
133+ sample_rate,
134+ padding: (b[2] >> 1) & 1 == 1,
135+ private: b[2] & 1 == 1,
136+ mode,
137+ mode_ext: (b[3] >> 4) & 3,
138+ copyright: (b[3] >> 3) & 1 == 1,
139+ original: (b[3] >> 2) & 1 == 1,
140+ emphasis: b[3] & 3,
141+ })
142+ }
143+
144+ /// The header as four bytes, for the encoder and for round-trip tests.
145+ pub fn to_bytes(&self) -> [u8; 4] {
146+ let version_id = match self.version {
147+ Version::Mpeg25 => 0,
148+ Version::Mpeg2 => 2,
149+ Version::Mpeg1 => 3,
150+ };
151+ let layer_id = match self.layer {
152+ 3 => 1,
153+ 2 => 2,
154+ _ => 3,
155+ };
156+ let table = if self.version == Version::Mpeg1 {
157+ &BITRATES_V1
158+ } else {
159+ &BITRATES_V2
160+ };
161+ let bitrate_index = table
162+ .iter()
163+ .position(|&k| k == self.bitrate_kbps)
164+ .unwrap_or(0) as u8;
165+ let base = match self.version {
166+ Version::Mpeg1 => self.sample_rate,
167+ Version::Mpeg2 => self.sample_rate * 2,
168+ Version::Mpeg25 => self.sample_rate * 4,
169+ };
170+ let rate_index = RATES_V1.iter().position(|&r| r == base).unwrap_or(0) as u8;
171+ let mode_id = match self.mode {
172+ ChannelMode::Stereo => 0,
173+ ChannelMode::JointStereo => 1,
174+ ChannelMode::DualChannel => 2,
175+ ChannelMode::Mono => 3,
176+ };
177+ [
178+ 0xFF,
179+ 0xE0 | (version_id << 3) | (layer_id << 1) | u8::from(!self.crc),
180+ (bitrate_index << 4)
181+ | (rate_index << 2)
182+ | (u8::from(self.padding) << 1)
183+ | u8::from(self.private),
184+ (mode_id << 6)
185+ | (self.mode_ext << 4)
186+ | (u8::from(self.copyright) << 3)
187+ | (u8::from(self.original) << 2)
188+ | self.emphasis,
189+ ]
190+ }
191+
192+ /// Channels carried by this frame.
193+ pub fn channels(&self) -> usize {
194+ self.mode.channels()
195+ }
196+
197+ /// Granules per frame: two for MPEG-1, one for the low sampling frequency
198+ /// extensions.
199+ pub fn granules(&self) -> usize {
200+ if self.version == Version::Mpeg1 { 2 } else { 1 }
201+ }
202+
203+ /// PCM samples per channel produced by this frame.
204+ pub fn samples_per_frame(&self) -> usize {
205+ self.granules() * 576
206+ }
207+
208+ /// Side-information bytes between the header (plus CRC) and the main data.
209+ pub fn side_info_len(&self) -> usize {
210+ match (self.version, self.channels()) {
211+ (Version::Mpeg1, 1) => 17,
212+ (Version::Mpeg1, _) => 32,
213+ (_, 1) => 9,
214+ (_, _) => 17,
215+ }
216+ }
217+
218+ /// Total frame length in bytes, header included, or `None` for free format
219+ /// (where the length is only knowable by scanning to the next sync word).
220+ pub fn frame_len(&self) -> Option<usize> {
221+ if self.bitrate_kbps == 0 {
222+ return None;
223+ }
224+ let bits = self.bitrate_kbps as usize * 1000;
225+ let rate = self.sample_rate as usize;
226+ let pad = usize::from(self.padding);
227+ Some(match self.layer {
228+ 1 => (12 * bits / rate + pad) * 4,
229+ 2 => 144 * bits / rate + pad,
230+ _ if self.version == Version::Mpeg1 => 144 * bits / rate + pad,
231+ _ => 72 * bits / rate + pad,
232+ })
233+ }
234+
235+ /// Bytes of main data this frame carries: everything after the header, the
236+ /// optional CRC and the side info.
237+ pub fn main_data_len(&self) -> Option<usize> {
238+ let len = self.frame_len()?;
239+ let overhead = 4 + usize::from(self.crc) * 2 + self.side_info_len();
240+ Some(len.saturating_sub(overhead))
241+ }
242+
243+ /// True when two headers describe the same stream configuration — the test
244+ /// a resync uses to tell a real frame from a byte pattern that looked like
245+ /// one.
246+ pub fn same_stream(&self, other: &FrameHeader) -> bool {
247+ self.version == other.version
248+ && self.layer == other.layer
249+ && self.sample_rate == other.sample_rate
250+ && self.mode.channels() == other.mode.channels()
251+ }
252+}
253+
254+/// CRC-16 as Layer III specifies it: polynomial 0x8005, seeded with all ones,
255+/// over the last two header bytes followed by the whole side info.
256+pub fn crc16(header: &[u8; 4], side_info: &[u8]) -> u16 {
257+ let mut crc = 0xFFFFu16;
258+ for &byte in header[2..].iter().chain(side_info) {
259+ crc ^= u16::from(byte) << 8;
260+ for _ in 0..8 {
261+ crc = if crc & 0x8000 != 0 {
262+ (crc << 1) ^ 0x8005
263+ } else {
264+ crc << 1
265+ };
266+ }
267+ }
268+ crc
269+}
270+
271+#[cfg(test)]
272+mod tests {
273+ use super::*;
274+
275+ #[test]
276+ fn parses_and_rebuilds_a_128k_stereo_header() {
277+ let bytes = [0xFF, 0xFB, 0x90, 0x00];
278+ let h = FrameHeader::parse(&bytes).unwrap();
279+ assert_eq!(h.version, Version::Mpeg1);
280+ assert_eq!(h.layer, 3);
281+ assert_eq!(h.bitrate_kbps, 128);
282+ assert_eq!(h.sample_rate, 44100);
283+ assert_eq!(h.mode, ChannelMode::Stereo);
284+ assert_eq!(h.frame_len(), Some(417));
285+ assert_eq!(h.side_info_len(), 32);
286+ assert_eq!(h.to_bytes(), bytes);
287+ }
288+
289+ #[test]
290+ fn low_sampling_frequency_geometry() {
291+ // MPEG-2, 24 kHz, 64 kbit/s, mono.
292+ let bytes = [0xFF, 0xF3, 0x84, 0xC0];
293+ let h = FrameHeader::parse(&bytes).unwrap();
294+ assert_eq!(h.version, Version::Mpeg2);
295+ assert_eq!(h.sample_rate, 24000);
296+ assert_eq!(h.granules(), 1);
297+ assert_eq!(h.samples_per_frame(), 576);
298+ assert_eq!(h.side_info_len(), 9);
299+ assert_eq!(h.frame_len(), Some(72 * 64000 / 24000));
300+ assert_eq!(h.to_bytes(), bytes);
301+ }
302+
303+ #[test]
304+ fn reserved_fields_are_refused() {
305+ assert!(FrameHeader::parse(&[0xFF, 0xFB, 0xF0, 0x00]).is_err()); // bitrate 15
306+ assert!(FrameHeader::parse(&[0xFF, 0xFB, 0x9C, 0x00]).is_err()); // rate 3
307+ assert!(FrameHeader::parse(&[0xFF, 0xE9, 0x90, 0x00]).is_err()); // layer 0
308+ assert!(FrameHeader::parse(&[0x00, 0x00, 0x00, 0x00]).is_err()); // no sync
309+ }
310+
311+ #[test]
312+ fn free_format_has_no_computable_length() {
313+ let h = FrameHeader::parse(&[0xFF, 0xFB, 0x00, 0x00]).unwrap();
314+ assert_eq!(h.bitrate_kbps, 0);
315+ assert_eq!(h.frame_len(), None);
316+ }
317+}
crates/ec-mp3/src/huffman.rsadded+345 -0
@@ -0,0 +1,345 @@
1+//! Layer III Huffman coding: the table registry, a decode tree built once per
2+//! process, and the encoder's cost/write side.
3+
4+use crate::huffman_tables::*;
5+use ec_core::bitio::{BitReader, BitWriter};
6+use ec_core::error::{Error, Result};
7+use std::sync::OnceLock;
8+
9+/// One code table as the bitstream refers to it.
10+#[derive(Clone, Copy, Debug)]
11+pub(crate) struct Table {
12+ /// `(length, code)` indexed by `x * dim + y`.
13+ pub codes: &'static [(u8, u16)],
14+ /// Values per axis; `x` and `y` run `0..dim`, the top one being an escape
15+ /// when `linbits` is non-zero.
16+ pub dim: u16,
17+ /// Extra magnitude bits read when a value is `dim - 1`.
18+ pub linbits: u8,
19+}
20+
21+/// The 32 big-value table slots. 4 and 14 are not assigned by the standard;
22+/// 16..=23 and 24..=31 share one code table each and differ only in `linbits`.
23+pub(crate) fn big_table(select: usize) -> Result<Table> {
24+ let t = |codes: &'static [(u8, u16)], dim: u16, linbits: u8| Table {
25+ codes,
26+ dim,
27+ linbits,
28+ };
29+ Ok(match select {
30+ 0 => t(&[], 0, 0),
31+ 1 => t(&T1, 2, 0),
32+ 2 => t(&T2, 3, 0),
33+ 3 => t(&T3, 3, 0),
34+ 5 => t(&T5, 4, 0),
35+ 6 => t(&T6, 4, 0),
36+ 7 => t(&T7, 6, 0),
37+ 8 => t(&T8, 6, 0),
38+ 9 => t(&T9, 6, 0),
39+ 10 => t(&T10, 8, 0),
40+ 11 => t(&T11, 8, 0),
41+ 12 => t(&T12, 8, 0),
42+ 13 => t(&T13, 16, 0),
43+ 15 => t(&T15, 16, 0),
44+ 16..=23 => t(&T16, 16, LINBITS_16[select - 16]),
45+ 24..=31 => t(&T24, 16, LINBITS_24[select - 24]),
46+ _ => {
47+ return Err(Error::corrupt(format!(
48+ "mp3: Huffman table {select} is not assigned"
49+ )));
50+ }
51+ })
52+}
53+
54+const LINBITS_16: [u8; 8] = [1, 2, 3, 4, 6, 8, 10, 13];
55+const LINBITS_24: [u8; 8] = [4, 5, 6, 7, 8, 9, 11, 13];
56+
57+/// The two count1 (quadruple) tables, selected by `count1table_select`.
58+pub(crate) fn count1_table(select: bool) -> &'static [(u8, u16)] {
59+ if select { &C1 } else { &C0 }
60+}
61+
62+/// A decode tree: two child slots per node, a negative slot being
63+/// `-(value_index + 1)`.
64+type Tree = Vec<[i32; 2]>;
65+
66+fn build_tree(codes: &[(u8, u16)]) -> Tree {
67+ let mut tree: Tree = vec![[0, 0]];
68+ for (index, &(len, code)) in codes.iter().enumerate() {
69+ let mut node = 0usize;
70+ let code = u32::from(code);
71+ for bit in (0..u32::from(len)).rev() {
72+ let branch = ((code >> bit) & 1) as usize;
73+ if bit == 0 {
74+ tree[node][branch] = -(index as i32 + 1);
75+ } else {
76+ if tree[node][branch] == 0 {
77+ tree.push([0, 0]);
78+ tree[node][branch] = (tree.len() - 1) as i32;
79+ }
80+ node = tree[node][branch] as usize;
81+ }
82+ }
83+ }
84+ tree
85+}
86+
87+struct Trees {
88+ big: Vec<Option<Tree>>,
89+ count1: [Tree; 2],
90+}
91+
92+fn trees() -> &'static Trees {
93+ static TREES: OnceLock<Trees> = OnceLock::new();
94+ TREES.get_or_init(|| {
95+ let mut big = Vec::with_capacity(32);
96+ for select in 0..32 {
97+ big.push(match big_table(select) {
98+ Ok(t) if !t.codes.is_empty() => Some(build_tree(t.codes)),
99+ _ => None,
100+ });
101+ }
102+ Trees {
103+ big,
104+ count1: [build_tree(&C0), build_tree(&C1)],
105+ }
106+ })
107+}
108+
109+fn walk(tree: &Tree, reader: &mut BitReader<'_>) -> Result<usize> {
110+ let mut node = 0usize;
111+ loop {
112+ let branch = usize::from(reader.read_bit()?);
113+ let next = tree[node][branch];
114+ if next < 0 {
115+ return Ok((-next - 1) as usize);
116+ }
117+ if next == 0 {
118+ return Err(Error::corrupt("mp3: Huffman code not in table"));
119+ }
120+ node = next as usize;
121+ }
122+}
123+
124+/// Decodes one big-value pair into `out`, sign bits and linbits included.
125+pub(crate) fn decode_pair(
126+ reader: &mut BitReader<'_>,
127+ select: usize,
128+ table: Table,
129+ out: &mut [f32; 2],
130+) -> Result<()> {
131+ let tree = trees().big[select]
132+ .as_ref()
133+ .ok_or_else(|| Error::corrupt(format!("mp3: Huffman table {select} is not assigned")))?;
134+ let index = walk(tree, reader)?;
135+ let values = [
136+ (index as u16 / table.dim) as u32,
137+ (index as u16 % table.dim) as u32,
138+ ];
139+ // Order matters and is per value, not per pair: escape bits then sign for
140+ // x, then the same for y. Grouping them costs the same number of bits,
141+ // which is why only the samples go wrong.
142+ for (slot, mut value) in out.iter_mut().zip(values) {
143+ if table.linbits > 0 && value == u32::from(table.dim) - 1 {
144+ value += reader.read_bits(u32::from(table.linbits))?;
145+ }
146+ *slot = if value == 0 {
147+ 0.0
148+ } else if reader.read_bit()? {
149+ -(value as f32)
150+ } else {
151+ value as f32
152+ };
153+ }
154+ Ok(())
155+}
156+
157+/// Decodes one count1 quadruple: four values of 0 or +-1.
158+pub(crate) fn decode_quad(
159+ reader: &mut BitReader<'_>,
160+ select: bool,
161+ out: &mut [f32; 4],
162+) -> Result<()> {
163+ let tree = &trees().count1[usize::from(select)];
164+ let index = walk(tree, reader)?;
165+ for (slot, shift) in out.iter_mut().zip([3, 2, 1, 0]) {
166+ let value = (index >> shift) & 1;
167+ *slot = if value == 0 {
168+ 0.0
169+ } else if reader.read_bit()? {
170+ -1.0
171+ } else {
172+ 1.0
173+ };
174+ }
175+ Ok(())
176+}
177+
178+/// Bits one pair costs in `table`, or `None` when the pair is out of range.
179+pub(crate) fn pair_bits(table: Table, x: u32, y: u32) -> Option<u32> {
180+ let max = u32::from(table.dim) - 1;
181+ let escape = u32::from(table.linbits) > 0;
182+ let (ix, iy) = (x.min(max), y.min(max));
183+ if (x > max && !escape) || (y > max && !escape) {
184+ return None;
185+ }
186+ if escape && (x > max + (1 << table.linbits) - 1 || y > max + (1 << table.linbits) - 1) {
187+ return None;
188+ }
189+ let (len, _) = table.codes[(ix * u32::from(table.dim) + iy) as usize];
190+ if len == 0 && !(x == 0 && y == 0) {
191+ return None;
192+ }
193+ let mut bits = u32::from(len);
194+ for value in [x, y] {
195+ if value >= max && escape {
196+ bits += u32::from(table.linbits);
197+ }
198+ if value != 0 {
199+ bits += 1;
200+ }
201+ }
202+ Some(bits)
203+}
204+
205+/// Writes one pair; the caller has already checked it fits the table.
206+pub(crate) fn write_pair(writer: &mut BitWriter, table: Table, x: i32, y: i32) {
207+ let max = u32::from(table.dim) - 1;
208+ let escape = table.linbits > 0;
209+ let (ax, ay) = (x.unsigned_abs(), y.unsigned_abs());
210+ let (ix, iy) = (ax.min(max), ay.min(max));
211+ let (len, code) = table.codes[(ix * u32::from(table.dim) + iy) as usize];
212+ writer.write_bits(u32::from(code), u32::from(len));
213+ for (value, abs) in [(x, ax), (y, ay)] {
214+ if abs >= max && escape {
215+ writer.write_bits(abs - max, u32::from(table.linbits));
216+ }
217+ if abs != 0 {
218+ writer.write_bit(value < 0);
219+ }
220+ }
221+}
222+
223+/// Bits one count1 quadruple costs.
224+pub(crate) fn quad_bits(select: bool, quad: [i32; 4]) -> u32 {
225+ let index = quad
226+ .iter()
227+ .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0));
228+ let (len, _) = count1_table(select)[index];
229+ u32::from(len) + quad.iter().filter(|v| **v != 0).count() as u32
230+}
231+
232+/// Writes one count1 quadruple.
233+pub(crate) fn write_quad(writer: &mut BitWriter, select: bool, quad: [i32; 4]) {
234+ let index = quad
235+ .iter()
236+ .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0));
237+ let (len, code) = count1_table(select)[index];
238+ writer.write_bits(u32::from(code), u32::from(len));
239+ for value in quad {
240+ if value != 0 {
241+ writer.write_bit(value < 0);
242+ }
243+ }
244+}
245+
246+#[cfg(test)]
247+mod tests {
248+ use super::*;
249+
250+ /// Every table is a complete prefix code over its whole value grid: the
251+ /// property the measurement rig checked before these numbers were written,
252+ /// re-checked here so a hand edit cannot break it unnoticed.
253+ #[test]
254+ fn tables_are_complete_prefix_codes() {
255+ let mut seen = 0;
256+ for select in 0..32 {
257+ let Ok(table) = big_table(select) else {
258+ continue;
259+ };
260+ if table.codes.is_empty() {
261+ continue;
262+ }
263+ seen += 1;
264+ assert_eq!(
265+ table.codes.len(),
266+ usize::from(table.dim) * usize::from(table.dim)
267+ );
268+ let kraft: f64 = table
269+ .codes
270+ .iter()
271+ .map(|(len, _)| 2f64.powi(-i32::from(*len)))
272+ .sum();
273+ assert!(
274+ (kraft - 1.0).abs() < 1e-12,
275+ "table {select}: Kraft sum {kraft}"
276+ );
277+ let tree = build_tree(table.codes);
278+ assert_eq!(
279+ tree.iter().flatten().filter(|n| **n < 0).count(),
280+ table.codes.len()
281+ );
282+ }
283+ assert_eq!(seen, 29, "tables 0..31 minus the four unassigned slots");
284+ for select in [false, true] {
285+ let codes = count1_table(select);
286+ let kraft: f64 = codes
287+ .iter()
288+ .map(|(len, _)| 2f64.powi(-i32::from(*len)))
289+ .sum();
290+ assert!((kraft - 1.0).abs() < 1e-12);
291+ }
292+ }
293+
294+ #[test]
295+ fn pairs_round_trip_through_every_table() {
296+ for select in (1..32).filter(|s| big_table(*s).is_ok()) {
297+ let table = big_table(select).unwrap();
298+ if table.codes.is_empty() {
299+ continue;
300+ }
301+ let max = u32::from(table.dim) - 1;
302+ let mut writer = BitWriter::new();
303+ let mut wanted = Vec::new();
304+ for x in 0..=max {
305+ for y in 0..=max {
306+ let (sx, sy) = (x as i32, -(y as i32));
307+ write_pair(&mut writer, table, sx, sy);
308+ wanted.push([sx as f32, sy as f32]);
309+ }
310+ }
311+ let bytes = writer.into_bytes();
312+ let mut reader = BitReader::new(&bytes);
313+ for want in wanted {
314+ let mut got = [0.0f32; 2];
315+ decode_pair(&mut reader, select, table, &mut got).unwrap();
316+ assert_eq!(got, want, "table {select}");
317+ }
318+ }
319+ }
320+
321+ #[test]
322+ fn quads_round_trip() {
323+ for select in [false, true] {
324+ let mut writer = BitWriter::new();
325+ let mut wanted = Vec::new();
326+ for index in 0..16 {
327+ let quad = [
328+ (index >> 3) & 1,
329+ -((index >> 2) & 1),
330+ (index >> 1) & 1,
331+ -(index & 1),
332+ ];
333+ write_quad(&mut writer, select, quad);
334+ wanted.push(quad.map(|v| v as f32));
335+ }
336+ let bytes = writer.into_bytes();
337+ let mut reader = BitReader::new(&bytes);
338+ for want in wanted {
339+ let mut got = [0.0f32; 4];
340+ decode_quad(&mut reader, select, &mut got).unwrap();
341+ assert_eq!(got, want);
342+ }
343+ }
344+ }
345+}
crates/ec-mp3/src/huffman_tables.rsadded+1468 -0
@@ -0,0 +1,1468 @@
1+//! Layer III Huffman code tables.
2+//!
3+//! Every entry here was *measured*, not transcribed: `scripts/mp3-tables/`
4+//! writes legal Layer III frames whose main-data bits it chooses, decodes them
5+//! with ffmpeg, and walks each code tree by asking whether all continuations of
6+//! a bit prefix decode to the same pair. The result is checked for a Kraft sum
7+//! of exactly 1, for full coverage of the value grid, and for uniqueness before
8+//! it is written out, so a wrong entry cannot reach this file silently.
9+//!
10+//! `(length, code)` indexed by `x * dim + y`, where `x` and `y` are the two
11+//! (or four, for the count1 tables) values the codeword yields, in the order
12+//! they are written to the spectrum.
13+
14+pub(crate) static T1: [(u8, u16); 4] = [(1, 1), (3, 1), (2, 1), (3, 0)];
15+
16+pub(crate) static T2: [(u8, u16); 9] = [
17+ (1, 1),
18+ (3, 2),
19+ (6, 1),
20+ (3, 3),
21+ (3, 1),
22+ (5, 1),
23+ (5, 3),
24+ (5, 2),
25+ (6, 0),
26+];
27+
28+pub(crate) static T3: [(u8, u16); 9] = [
29+ (2, 3),
30+ (2, 2),
31+ (6, 1),
32+ (3, 1),
33+ (2, 1),
34+ (5, 1),
35+ (5, 3),
36+ (5, 2),
37+ (6, 0),
38+];
39+
40+pub(crate) static T5: [(u8, u16); 16] = [
41+ (1, 1),
42+ (3, 2),
43+ (6, 6),
44+ (7, 5),
45+ (3, 3),
46+ (3, 1),
47+ (6, 4),
48+ (7, 4),
49+ (6, 7),
50+ (6, 5),
51+ (7, 7),
52+ (8, 1),
53+ (7, 6),
54+ (6, 1),
55+ (7, 1),
56+ (8, 0),
57+];
58+
59+pub(crate) static T6: [(u8, u16); 16] = [
60+ (3, 7),
61+ (3, 3),
62+ (5, 5),
63+ (7, 1),
64+ (3, 6),
65+ (2, 2),
66+ (4, 3),
67+ (5, 2),
68+ (4, 5),
69+ (4, 4),
70+ (5, 4),
71+ (6, 1),
72+ (6, 3),
73+ (5, 3),
74+ (6, 2),
75+ (7, 0),
76+];
77+
78+pub(crate) static T7: [(u8, u16); 36] = [
79+ (1, 1),
80+ (3, 2),
81+ (6, 10),
82+ (8, 19),
83+ (8, 16),
84+ (9, 10),
85+ (3, 3),
86+ (4, 3),
87+ (6, 7),
88+ (7, 10),
89+ (7, 5),
90+ (8, 3),
91+ (6, 11),
92+ (5, 4),
93+ (7, 13),
94+ (8, 17),
95+ (8, 8),
96+ (9, 4),
97+ (7, 12),
98+ (7, 11),
99+ (8, 18),
100+ (9, 15),
101+ (9, 11),
102+ (9, 2),
103+ (7, 7),
104+ (7, 6),
105+ (8, 9),
106+ (9, 14),
107+ (9, 3),
108+ (10, 1),
109+ (8, 6),
110+ (8, 4),
111+ (9, 5),
112+ (10, 3),
113+ (10, 2),
114+ (10, 0),
115+];
116+
117+pub(crate) static T8: [(u8, u16); 36] = [
118+ (2, 3),
119+ (3, 4),
120+ (6, 6),
121+ (8, 18),
122+ (8, 12),
123+ (9, 5),
124+ (3, 5),
125+ (2, 1),
126+ (4, 2),
127+ (8, 16),
128+ (8, 9),
129+ (8, 3),
130+ (6, 7),
131+ (4, 3),
132+ (6, 5),
133+ (8, 14),
134+ (8, 7),
135+ (9, 3),
136+ (8, 19),
137+ (8, 17),
138+ (8, 15),
139+ (9, 13),
140+ (9, 10),
141+ (10, 4),
142+ (8, 13),
143+ (7, 5),
144+ (8, 8),
145+ (9, 11),
146+ (10, 5),
147+ (10, 1),
148+ (9, 12),
149+ (8, 4),
150+ (9, 4),
151+ (9, 1),
152+ (11, 1),
153+ (11, 0),
154+];
155+
156+pub(crate) static T9: [(u8, u16); 36] = [
157+ (3, 7),
158+ (3, 5),
159+ (5, 9),
160+ (6, 14),
161+ (8, 15),
162+ (9, 7),
163+ (3, 6),
164+ (3, 4),
165+ (4, 5),
166+ (5, 5),
167+ (6, 6),
168+ (8, 7),
169+ (4, 7),
170+ (4, 6),
171+ (5, 8),
172+ (6, 8),
173+ (7, 8),
174+ (8, 5),
175+ (6, 15),
176+ (5, 6),
177+ (6, 9),
178+ (7, 10),
179+ (7, 5),
180+ (8, 1),
181+ (7, 11),
182+ (6, 7),
183+ (7, 9),
184+ (7, 6),
185+ (8, 4),
186+ (9, 1),
187+ (8, 14),
188+ (7, 4),
189+ (8, 6),
190+ (8, 2),
191+ (9, 6),
192+ (9, 0),
193+];
194+
195+pub(crate) static T10: [(u8, u16); 64] = [
196+ (1, 1),
197+ (3, 2),
198+ (6, 10),
199+ (8, 23),
200+ (9, 35),
201+ (9, 30),
202+ (9, 12),
203+ (10, 17),
204+ (3, 3),
205+ (4, 3),
206+ (6, 8),
207+ (7, 12),
208+ (8, 18),
209+ (9, 21),
210+ (8, 12),
211+ (8, 7),
212+ (6, 11),
213+ (6, 9),
214+ (7, 15),
215+ (8, 21),
216+ (9, 32),
217+ (10, 40),
218+ (9, 19),
219+ (9, 6),
220+ (7, 14),
221+ (7, 13),
222+ (8, 22),
223+ (9, 34),
224+ (10, 46),
225+ (10, 23),
226+ (9, 18),
227+ (10, 7),
228+ (8, 20),
229+ (8, 19),
230+ (9, 33),
231+ (10, 47),
232+ (10, 27),
233+ (10, 22),
234+ (10, 9),
235+ (10, 3),
236+ (9, 31),
237+ (9, 22),
238+ (10, 41),
239+ (10, 26),
240+ (11, 21),
241+ (11, 20),
242+ (10, 5),
243+ (11, 3),
244+ (8, 14),
245+ (8, 13),
246+ (9, 10),
247+ (10, 11),
248+ (10, 16),
249+ (10, 6),
250+ (11, 5),
251+ (11, 1),
252+ (9, 9),
253+ (8, 8),
254+ (9, 7),
255+ (10, 8),
256+ (10, 4),
257+ (11, 4),
258+ (11, 2),
259+ (11, 0),
260+];
261+
262+pub(crate) static T11: [(u8, u16); 64] = [
263+ (2, 3),
264+ (3, 4),
265+ (5, 10),
266+ (7, 24),
267+ (8, 34),
268+ (9, 33),
269+ (8, 21),
270+ (9, 15),
271+ (3, 5),
272+ (3, 3),
273+ (4, 4),
274+ (6, 10),
275+ (8, 32),
276+ (8, 17),
277+ (7, 11),
278+ (8, 10),
279+ (5, 11),
280+ (5, 7),
281+ (6, 13),
282+ (7, 18),
283+ (8, 30),
284+ (9, 31),
285+ (8, 20),
286+ (8, 5),
287+ (7, 25),
288+ (6, 11),
289+ (7, 19),
290+ (9, 59),
291+ (8, 27),
292+ (10, 18),
293+ (8, 12),
294+ (9, 5),
295+ (8, 35),
296+ (8, 33),
297+ (8, 31),
298+ (9, 58),
299+ (9, 30),
300+ (10, 16),
301+ (9, 7),
302+ (10, 5),
303+ (8, 28),
304+ (8, 26),
305+ (9, 32),
306+ (10, 19),
307+ (10, 17),
308+ (11, 15),
309+ (10, 8),
310+ (11, 14),
311+ (8, 14),
312+ (7, 12),
313+ (7, 9),
314+ (8, 13),
315+ (9, 14),
316+ (10, 9),
317+ (10, 4),
318+ (10, 1),
319+ (8, 11),
320+ (7, 4),
321+ (8, 6),
322+ (9, 6),
323+ (10, 6),
324+ (10, 3),
325+ (10, 2),
326+ (10, 0),
327+];
328+
329+pub(crate) static T12: [(u8, u16); 64] = [
330+ (4, 9),
331+ (3, 6),
332+ (5, 16),
333+ (7, 33),
334+ (8, 41),
335+ (9, 39),
336+ (9, 38),
337+ (9, 26),
338+ (3, 7),
339+ (3, 5),
340+ (4, 6),
341+ (5, 9),
342+ (7, 23),
343+ (7, 16),
344+ (8, 26),
345+ (8, 11),
346+ (5, 17),
347+ (4, 7),
348+ (5, 11),
349+ (6, 14),
350+ (7, 21),
351+ (8, 30),
352+ (7, 10),
353+ (8, 7),
354+ (6, 17),
355+ (5, 10),
356+ (6, 15),
357+ (6, 12),
358+ (7, 18),
359+ (8, 28),
360+ (8, 14),
361+ (8, 5),
362+ (7, 32),
363+ (6, 13),
364+ (7, 22),
365+ (7, 19),
366+ (8, 18),
367+ (8, 16),
368+ (8, 9),
369+ (9, 5),
370+ (8, 40),
371+ (7, 17),
372+ (8, 31),
373+ (8, 29),
374+ (8, 17),
375+ (9, 13),
376+ (8, 4),
377+ (9, 2),
378+ (8, 27),
379+ (7, 12),
380+ (7, 11),
381+ (8, 15),
382+ (8, 10),
383+ (9, 7),
384+ (9, 4),
385+ (10, 1),
386+ (9, 27),
387+ (8, 12),
388+ (8, 8),
389+ (9, 12),
390+ (9, 6),
391+ (9, 3),
392+ (9, 1),
393+ (10, 0),
394+];
395+
396+pub(crate) static T13: [(u8, u16); 256] = [
397+ (1, 1),
398+ (4, 5),
399+ (6, 14),
400+ (7, 21),
401+ (8, 34),
402+ (9, 51),
403+ (9, 46),
404+ (10, 71),
405+ (9, 42),
406+ (10, 52),
407+ (11, 68),
408+ (11, 52),
409+ (12, 67),
410+ (12, 44),
411+ (13, 43),
412+ (13, 19),
413+ (3, 3),
414+ (4, 4),
415+ (6, 12),
416+ (7, 19),
417+ (8, 31),
418+ (8, 26),
419+ (9, 44),
420+ (9, 33),
421+ (9, 31),
422+ (9, 24),
423+ (10, 32),
424+ (10, 24),
425+ (11, 31),
426+ (12, 35),
427+ (12, 22),
428+ (12, 14),
429+ (6, 15),
430+ (6, 13),
431+ (7, 23),
432+ (8, 36),
433+ (9, 59),
434+ (9, 49),
435+ (10, 77),
436+ (10, 65),
437+ (9, 29),
438+ (10, 40),
439+ (10, 30),
440+ (11, 40),
441+ (11, 27),
442+ (12, 33),
443+ (13, 42),
444+ (13, 16),
445+ (7, 22),
446+ (7, 20),
447+ (8, 37),
448+ (9, 61),
449+ (9, 56),
450+ (10, 79),
451+ (10, 73),
452+ (10, 64),
453+ (10, 43),
454+ (11, 76),
455+ (11, 56),
456+ (11, 37),
457+ (11, 26),
458+ (12, 31),
459+ (13, 25),
460+ (13, 14),
461+ (8, 35),
462+ (7, 16),
463+ (9, 60),
464+ (9, 57),
465+ (10, 97),
466+ (10, 75),
467+ (11, 114),
468+ (11, 91),
469+ (10, 54),
470+ (11, 73),
471+ (11, 55),
472+ (12, 41),
473+ (12, 48),
474+ (13, 53),
475+ (13, 23),
476+ (14, 24),
477+ (9, 58),
478+ (8, 27),
479+ (9, 50),
480+ (10, 96),
481+ (10, 76),
482+ (10, 70),
483+ (11, 93),
484+ (11, 84),
485+ (11, 77),
486+ (11, 58),
487+ (12, 79),
488+ (11, 29),
489+ (13, 74),
490+ (13, 49),
491+ (14, 41),
492+ (14, 17),
493+ (9, 47),
494+ (9, 45),
495+ (10, 78),
496+ (10, 74),
497+ (11, 115),
498+ (11, 94),
499+ (11, 90),
500+ (11, 79),
501+ (11, 69),
502+ (12, 83),
503+ (12, 71),
504+ (12, 50),
505+ (13, 59),
506+ (13, 38),
507+ (14, 36),
508+ (14, 15),
509+ (10, 72),
510+ (9, 34),
511+ (10, 56),
512+ (11, 95),
513+ (11, 92),
514+ (11, 85),
515+ (12, 91),
516+ (12, 90),
517+ (12, 86),
518+ (12, 73),
519+ (13, 77),
520+ (13, 65),
521+ (13, 51),
522+ (14, 44),
523+ (16, 43),
524+ (16, 42),
525+ (9, 43),
526+ (8, 20),
527+ (9, 30),
528+ (10, 44),
529+ (10, 55),
530+ (11, 78),
531+ (11, 72),
532+ (12, 87),
533+ (12, 78),
534+ (12, 61),
535+ (12, 46),
536+ (13, 54),
537+ (13, 37),
538+ (14, 30),
539+ (15, 20),
540+ (15, 16),
541+ (10, 53),
542+ (9, 25),
543+ (10, 41),
544+ (10, 37),
545+ (11, 44),
546+ (11, 59),
547+ (11, 54),
548+ (13, 81),
549+ (12, 66),
550+ (13, 76),
551+ (13, 57),
552+ (14, 54),
553+ (14, 37),
554+ (14, 18),
555+ (16, 39),
556+ (15, 11),
557+ (10, 35),
558+ (10, 33),
559+ (10, 31),
560+ (11, 57),
561+ (11, 42),
562+ (12, 82),
563+ (12, 72),
564+ (13, 80),
565+ (12, 47),
566+ (13, 58),
567+ (14, 55),
568+ (13, 21),
569+ (14, 22),
570+ (15, 26),
571+ (16, 38),
572+ (17, 22),
573+ (11, 53),
574+ (10, 25),
575+ (10, 23),
576+ (11, 38),
577+ (12, 70),
578+ (12, 60),
579+ (12, 51),
580+ (12, 36),
581+ (13, 55),
582+ (13, 26),
583+ (13, 34),
584+ (14, 23),
585+ (15, 27),
586+ (15, 14),
587+ (15, 9),
588+ (16, 7),
589+ (11, 34),
590+ (11, 32),
591+ (11, 28),
592+ (12, 39),
593+ (12, 49),
594+ (13, 75),
595+ (12, 30),
596+ (13, 52),
597+ (14, 48),
598+ (14, 40),
599+ (15, 52),
600+ (15, 28),
601+ (15, 18),
602+ (16, 17),
603+ (16, 9),
604+ (16, 5),
605+ (12, 45),
606+ (11, 21),
607+ (12, 34),
608+ (13, 64),
609+ (13, 56),
610+ (13, 50),
611+ (14, 49),
612+ (14, 45),
613+ (14, 31),
614+ (14, 19),
615+ (14, 12),
616+ (15, 15),
617+ (16, 10),
618+ (15, 7),
619+ (16, 6),
620+ (16, 3),
621+ (13, 48),
622+ (12, 23),
623+ (12, 20),
624+ (13, 39),
625+ (13, 36),
626+ (13, 35),
627+ (15, 53),
628+ (14, 21),
629+ (14, 16),
630+ (17, 23),
631+ (15, 13),
632+ (15, 10),
633+ (15, 6),
634+ (17, 1),
635+ (16, 4),
636+ (16, 2),
637+ (12, 16),
638+ (12, 15),
639+ (13, 17),
640+ (14, 27),
641+ (14, 25),
642+ (14, 20),
643+ (15, 29),
644+ (14, 11),
645+ (15, 17),
646+ (15, 12),
647+ (16, 16),
648+ (16, 8),
649+ (19, 1),
650+ (18, 1),
651+ (19, 0),
652+ (16, 1),
653+];
654+
655+pub(crate) static T15: [(u8, u16); 256] = [
656+ (3, 7),
657+ (4, 12),
658+ (5, 18),
659+ (7, 53),
660+ (7, 47),
661+ (8, 76),
662+ (9, 124),
663+ (9, 108),
664+ (9, 89),
665+ (10, 123),
666+ (10, 108),
667+ (11, 119),
668+ (11, 107),
669+ (11, 81),
670+ (12, 122),
671+ (13, 63),
672+ (4, 13),
673+ (3, 5),
674+ (5, 16),
675+ (6, 27),
676+ (7, 46),
677+ (7, 36),
678+ (8, 61),
679+ (8, 51),
680+ (8, 42),
681+ (9, 70),
682+ (9, 52),
683+ (10, 83),
684+ (10, 65),
685+ (10, 41),
686+ (11, 59),
687+ (11, 36),
688+ (5, 19),
689+ (5, 17),
690+ (5, 15),
691+ (6, 24),
692+ (7, 41),
693+ (7, 34),
694+ (8, 59),
695+ (8, 48),
696+ (8, 40),
697+ (9, 64),
698+ (9, 50),
699+ (10, 78),
700+ (10, 62),
701+ (11, 80),
702+ (11, 56),
703+ (11, 33),
704+ (6, 29),
705+ (6, 28),
706+ (6, 25),
707+ (7, 43),
708+ (7, 39),
709+ (8, 63),
710+ (8, 55),
711+ (9, 93),
712+ (9, 76),
713+ (9, 59),
714+ (10, 93),
715+ (10, 72),
716+ (10, 54),
717+ (11, 75),
718+ (11, 50),
719+ (11, 29),
720+ (7, 52),
721+ (6, 22),
722+ (7, 42),
723+ (7, 40),
724+ (8, 67),
725+ (8, 57),
726+ (9, 95),
727+ (9, 79),
728+ (9, 72),
729+ (9, 57),
730+ (10, 89),
731+ (10, 69),
732+ (10, 49),
733+ (11, 66),
734+ (11, 46),
735+ (11, 27),
736+ (8, 77),
737+ (7, 37),
738+ (7, 35),
739+ (8, 66),
740+ (8, 58),
741+ (8, 52),
742+ (9, 91),
743+ (9, 74),
744+ (9, 62),
745+ (9, 48),
746+ (10, 79),
747+ (10, 63),
748+ (11, 90),
749+ (11, 62),
750+ (11, 40),
751+ (12, 38),
752+ (9, 125),
753+ (7, 32),
754+ (8, 60),
755+ (8, 56),
756+ (8, 50),
757+ (9, 92),
758+ (9, 78),
759+ (9, 65),
760+ (9, 55),
761+ (10, 87),
762+ (10, 71),
763+ (10, 51),
764+ (11, 73),
765+ (11, 51),
766+ (12, 70),
767+ (12, 30),
768+ (9, 109),
769+ (8, 53),
770+ (8, 49),
771+ (9, 94),
772+ (9, 88),
773+ (9, 75),
774+ (9, 66),
775+ (10, 122),
776+ (10, 91),
777+ (10, 73),
778+ (10, 56),
779+ (10, 42),
780+ (11, 64),
781+ (11, 44),
782+ (11, 21),
783+ (12, 25),
784+ (9, 90),
785+ (8, 43),
786+ (8, 41),
787+ (9, 77),
788+ (9, 73),
789+ (9, 63),
790+ (9, 56),
791+ (10, 92),
792+ (10, 77),
793+ (10, 66),
794+ (10, 47),
795+ (11, 67),
796+ (11, 48),
797+ (12, 53),
798+ (12, 36),
799+ (12, 20),
800+ (9, 71),
801+ (8, 34),
802+ (9, 67),
803+ (9, 60),
804+ (9, 58),
805+ (9, 49),
806+ (10, 88),
807+ (10, 76),
808+ (10, 67),
809+ (11, 106),
810+ (11, 71),
811+ (11, 54),
812+ (11, 38),
813+ (12, 39),
814+ (12, 23),
815+ (12, 15),
816+ (10, 109),
817+ (9, 53),
818+ (9, 51),
819+ (9, 47),
820+ (10, 90),
821+ (10, 82),
822+ (10, 58),
823+ (10, 57),
824+ (10, 48),
825+ (11, 72),
826+ (11, 57),
827+ (11, 41),
828+ (11, 23),
829+ (12, 27),
830+ (13, 62),
831+ (12, 9),
832+ (10, 86),
833+ (9, 42),
834+ (9, 40),
835+ (9, 37),
836+ (10, 70),
837+ (10, 64),
838+ (10, 52),
839+ (10, 43),
840+ (11, 70),
841+ (11, 55),
842+ (11, 42),
843+ (11, 25),
844+ (12, 29),
845+ (12, 18),
846+ (12, 11),
847+ (13, 11),
848+ (11, 118),
849+ (10, 68),
850+ (9, 30),
851+ (10, 55),
852+ (10, 50),
853+ (10, 46),
854+ (11, 74),
855+ (11, 65),
856+ (11, 49),
857+ (11, 39),
858+ (11, 24),
859+ (11, 16),
860+ (12, 22),
861+ (12, 13),
862+ (13, 14),
863+ (13, 7),
864+ (11, 91),
865+ (10, 44),
866+ (10, 39),
867+ (10, 38),
868+ (10, 34),
869+ (11, 63),
870+ (11, 52),
871+ (11, 45),
872+ (11, 31),
873+ (12, 52),
874+ (12, 28),
875+ (12, 19),
876+ (12, 14),
877+ (12, 8),
878+ (13, 9),
879+ (13, 3),
880+ (12, 123),
881+ (11, 60),
882+ (11, 58),
883+ (11, 53),
884+ (11, 47),
885+ (11, 43),
886+ (11, 32),
887+ (11, 22),
888+ (12, 37),
889+ (12, 24),
890+ (12, 17),
891+ (12, 12),
892+ (13, 15),
893+ (13, 10),
894+ (12, 2),
895+ (13, 1),
896+ (12, 71),
897+ (11, 37),
898+ (11, 34),
899+ (11, 30),
900+ (11, 28),
901+ (11, 20),
902+ (11, 17),
903+ (12, 26),
904+ (12, 21),
905+ (12, 16),
906+ (12, 10),
907+ (12, 6),
908+ (13, 8),
909+ (13, 6),
910+ (13, 2),
911+ (13, 0),
912+];
913+
914+pub(crate) static T16: [(u8, u16); 256] = [
915+ (1, 1),
916+ (4, 5),
917+ (6, 14),
918+ (8, 44),
919+ (9, 74),
920+ (9, 63),
921+ (10, 110),
922+ (10, 93),
923+ (11, 172),
924+ (11, 149),
925+ (11, 138),
926+ (12, 242),
927+ (12, 225),
928+ (12, 195),
929+ (13, 376),
930+ (9, 17),
931+ (3, 3),
932+ (4, 4),
933+ (6, 12),
934+ (7, 20),
935+ (8, 35),
936+ (9, 62),
937+ (9, 53),
938+ (9, 47),
939+ (10, 83),
940+ (10, 75),
941+ (10, 68),
942+ (11, 119),
943+ (12, 201),
944+ (11, 107),
945+ (12, 207),
946+ (8, 9),
947+ (6, 15),
948+ (6, 13),
949+ (7, 23),
950+ (8, 38),
951+ (9, 67),
952+ (9, 58),
953+ (10, 103),
954+ (10, 90),
955+ (11, 161),
956+ (10, 72),
957+ (11, 127),
958+ (11, 117),
959+ (11, 110),
960+ (12, 209),
961+ (12, 206),
962+ (9, 16),
963+ (8, 45),
964+ (7, 21),
965+ (8, 39),
966+ (9, 69),
967+ (9, 64),
968+ (10, 114),
969+ (10, 99),
970+ (10, 87),
971+ (11, 158),
972+ (11, 140),
973+ (12, 252),
974+ (12, 212),
975+ (12, 199),
976+ (13, 387),
977+ (13, 365),
978+ (10, 26),
979+ (9, 75),
980+ (8, 36),
981+ (9, 68),
982+ (9, 65),
983+ (10, 115),
984+ (10, 101),
985+ (11, 179),
986+ (11, 164),
987+ (11, 155),
988+ (12, 264),
989+ (12, 246),
990+ (12, 226),
991+ (13, 395),
992+ (13, 382),
993+ (13, 362),
994+ (9, 9),
995+ (9, 66),
996+ (8, 30),
997+ (9, 59),
998+ (9, 56),
999+ (10, 102),
1000+ (11, 185),
1001+ (11, 173),
1002+ (12, 265),
1003+ (11, 142),
1004+ (12, 253),
1005+ (12, 232),
1006+ (13, 400),
1007+ (13, 388),
1008+ (13, 378),
1009+ (14, 445),
1010+ (10, 16),
1011+ (10, 111),
1012+ (9, 54),
1013+ (9, 52),
1014+ (10, 100),
1015+ (11, 184),
1016+ (11, 178),
1017+ (11, 160),
1018+ (11, 133),
1019+ (12, 257),
1020+ (12, 244),
1021+ (12, 228),
1022+ (12, 217),
1023+ (13, 385),
1024+ (13, 366),
1025+ (14, 715),
1026+ (10, 10),
1027+ (10, 98),
1028+ (9, 48),
1029+ (10, 91),
1030+ (10, 88),
1031+ (11, 165),
1032+ (11, 157),
1033+ (11, 148),
1034+ (12, 261),
1035+ (12, 248),
1036+ (13, 407),
1037+ (13, 397),
1038+ (13, 372),
1039+ (13, 380),
1040+ (15, 889),
1041+ (15, 884),
1042+ (10, 8),
1043+ (10, 85),
1044+ (10, 84),
1045+ (10, 81),
1046+ (11, 159),
1047+ (11, 156),
1048+ (11, 143),
1049+ (12, 260),
1050+ (12, 249),
1051+ (13, 427),
1052+ (13, 401),
1053+ (13, 392),
1054+ (13, 383),
1055+ (14, 727),
1056+ (14, 713),
1057+ (14, 708),
1058+ (10, 7),
1059+ (11, 154),
1060+ (10, 76),
1061+ (10, 73),
1062+ (11, 141),
1063+ (11, 131),
1064+ (12, 256),
1065+ (12, 245),
1066+ (13, 426),
1067+ (13, 406),
1068+ (13, 394),
1069+ (13, 384),
1070+ (14, 735),
1071+ (13, 359),
1072+ (14, 710),
1073+ (13, 352),
1074+ (11, 11),
1075+ (11, 139),
1076+ (11, 129),
1077+ (10, 67),
1078+ (11, 125),
1079+ (12, 247),
1080+ (12, 233),
1081+ (12, 229),
1082+ (12, 219),
1083+ (13, 393),
1084+ (14, 743),
1085+ (14, 737),
1086+ (14, 720),
1087+ (15, 885),
1088+ (15, 882),
1089+ (14, 439),
1090+ (10, 4),
1091+ (12, 243),
1092+ (11, 120),
1093+ (11, 118),
1094+ (11, 115),
1095+ (12, 227),
1096+ (12, 223),
1097+ (13, 396),
1098+ (14, 746),
1099+ (14, 742),
1100+ (14, 736),
1101+ (14, 721),
1102+ (14, 712),
1103+ (14, 706),
1104+ (13, 223),
1105+ (14, 436),
1106+ (11, 6),
1107+ (12, 202),
1108+ (12, 224),
1109+ (12, 222),
1110+ (12, 218),
1111+ (12, 216),
1112+ (13, 389),
1113+ (13, 386),
1114+ (13, 381),
1115+ (13, 364),
1116+ (15, 888),
1117+ (14, 443),
1118+ (14, 707),
1119+ (14, 440),
1120+ (14, 437),
1121+ (16, 1728),
1122+ (11, 4),
1123+ (14, 747),
1124+ (12, 211),
1125+ (12, 210),
1126+ (12, 208),
1127+ (13, 370),
1128+ (13, 379),
1129+ (14, 734),
1130+ (14, 723),
1131+ (14, 714),
1132+ (16, 1735),
1133+ (15, 883),
1134+ (15, 877),
1135+ (15, 876),
1136+ (17, 3459),
1137+ (15, 865),
1138+ (11, 2),
1139+ (13, 377),
1140+ (13, 369),
1141+ (11, 102),
1142+ (12, 187),
1143+ (14, 726),
1144+ (14, 722),
1145+ (13, 358),
1146+ (14, 711),
1147+ (14, 709),
1148+ (15, 866),
1149+ (16, 1734),
1150+ (15, 871),
1151+ (17, 3458),
1152+ (15, 870),
1153+ (14, 434),
1154+ (11, 0),
1155+ (9, 12),
1156+ (8, 10),
1157+ (8, 7),
1158+ (9, 11),
1159+ (9, 10),
1160+ (10, 17),
1161+ (10, 11),
1162+ (10, 9),
1163+ (11, 13),
1164+ (11, 12),
1165+ (11, 10),
1166+ (11, 7),
1167+ (11, 5),
1168+ (11, 3),
1169+ (11, 1),
1170+ (8, 3),
1171+];
1172+
1173+pub(crate) static T24: [(u8, u16); 256] = [
1174+ (4, 15),
1175+ (4, 13),
1176+ (6, 46),
1177+ (7, 80),
1178+ (8, 146),
1179+ (9, 262),
1180+ (9, 248),
1181+ (10, 434),
1182+ (10, 426),
1183+ (11, 669),
1184+ (11, 653),
1185+ (11, 649),
1186+ (11, 621),
1187+ (11, 517),
1188+ (12, 1032),
1189+ (9, 88),
1190+ (4, 14),
1191+ (4, 12),
1192+ (5, 21),
1193+ (6, 38),
1194+ (7, 71),
1195+ (8, 130),
1196+ (8, 122),
1197+ (9, 216),
1198+ (9, 209),
1199+ (9, 198),
1200+ (10, 327),
1201+ (10, 345),
1202+ (10, 319),
1203+ (10, 297),
1204+ (10, 279),
1205+ (8, 42),
1206+ (6, 47),
1207+ (5, 22),
1208+ (6, 41),
1209+ (7, 74),
1210+ (7, 68),
1211+ (8, 128),
1212+ (8, 120),
1213+ (9, 221),
1214+ (9, 207),
1215+ (9, 194),
1216+ (9, 182),
1217+ (10, 340),
1218+ (10, 315),
1219+ (10, 295),
1220+ (11, 541),
1221+ (7, 18),
1222+ (7, 81),
1223+ (6, 39),
1224+ (7, 75),
1225+ (7, 70),
1226+ (8, 134),
1227+ (8, 125),
1228+ (8, 116),
1229+ (9, 220),
1230+ (9, 204),
1231+ (9, 190),
1232+ (9, 178),
1233+ (10, 325),
1234+ (10, 311),
1235+ (10, 293),
1236+ (10, 271),
1237+ (7, 16),
1238+ (8, 147),
1239+ (7, 72),
1240+ (7, 69),
1241+ (8, 135),
1242+ (8, 127),
1243+ (8, 118),
1244+ (8, 112),
1245+ (9, 210),
1246+ (9, 200),
1247+ (9, 188),
1248+ (10, 352),
1249+ (10, 323),
1250+ (10, 306),
1251+ (10, 285),
1252+ (11, 540),
1253+ (7, 14),
1254+ (9, 263),
1255+ (7, 66),
1256+ (8, 129),
1257+ (8, 126),
1258+ (8, 119),
1259+ (8, 114),
1260+ (9, 214),
1261+ (9, 202),
1262+ (9, 192),
1263+ (9, 180),
1264+ (10, 341),
1265+ (10, 317),
1266+ (10, 301),
1267+ (10, 281),
1268+ (10, 262),
1269+ (7, 12),
1270+ (9, 249),
1271+ (8, 123),
1272+ (8, 121),
1273+ (8, 117),
1274+ (8, 113),
1275+ (9, 215),
1276+ (9, 206),
1277+ (9, 195),
1278+ (9, 185),
1279+ (10, 347),
1280+ (10, 330),
1281+ (10, 308),
1282+ (10, 291),
1283+ (10, 272),
1284+ (11, 520),
1285+ (7, 10),
1286+ (10, 435),
1287+ (8, 115),
1288+ (8, 111),
1289+ (8, 109),
1290+ (9, 211),
1291+ (9, 203),
1292+ (9, 196),
1293+ (9, 187),
1294+ (10, 353),
1295+ (10, 332),
1296+ (10, 313),
1297+ (10, 298),
1298+ (10, 283),
1299+ (11, 531),
1300+ (11, 381),
1301+ (8, 17),
1302+ (10, 427),
1303+ (9, 212),
1304+ (9, 208),
1305+ (9, 205),
1306+ (9, 201),
1307+ (9, 193),
1308+ (9, 186),
1309+ (9, 177),
1310+ (9, 169),
1311+ (10, 320),
1312+ (10, 303),
1313+ (10, 286),
1314+ (10, 268),
1315+ (11, 514),
1316+ (11, 377),
1317+ (8, 16),
1318+ (10, 335),
1319+ (9, 199),
1320+ (9, 197),
1321+ (9, 191),
1322+ (9, 189),
1323+ (9, 181),
1324+ (9, 174),
1325+ (10, 333),
1326+ (10, 321),
1327+ (10, 305),
1328+ (10, 289),
1329+ (10, 275),
1330+ (11, 521),
1331+ (11, 379),
1332+ (11, 371),
1333+ (8, 11),
1334+ (11, 668),
1335+ (9, 184),
1336+ (9, 183),
1337+ (9, 179),
1338+ (9, 175),
1339+ (10, 344),
1340+ (10, 331),
1341+ (10, 314),
1342+ (10, 304),
1343+ (10, 290),
1344+ (10, 277),
1345+ (11, 530),
1346+ (11, 383),
1347+ (11, 373),
1348+ (11, 366),
1349+ (8, 10),
1350+ (11, 652),
1351+ (10, 346),
1352+ (9, 171),
1353+ (9, 168),
1354+ (9, 164),
1355+ (10, 318),
1356+ (10, 309),
1357+ (10, 299),
1358+ (10, 287),
1359+ (10, 276),
1360+ (10, 263),
1361+ (11, 513),
1362+ (11, 375),
1363+ (11, 368),
1364+ (11, 362),
1365+ (8, 6),
1366+ (11, 648),
1367+ (10, 322),
1368+ (10, 316),
1369+ (10, 312),
1370+ (10, 307),
1371+ (10, 302),
1372+ (10, 292),
1373+ (10, 284),
1374+ (10, 269),
1375+ (10, 261),
1376+ (11, 512),
1377+ (11, 376),
1378+ (11, 370),
1379+ (11, 364),
1380+ (11, 359),
1381+ (8, 4),
1382+ (11, 620),
1383+ (10, 300),
1384+ (10, 296),
1385+ (10, 294),
1386+ (10, 288),
1387+ (10, 282),
1388+ (10, 273),
1389+ (10, 266),
1390+ (11, 515),
1391+ (11, 380),
1392+ (11, 374),
1393+ (11, 369),
1394+ (11, 365),
1395+ (11, 361),
1396+ (11, 357),
1397+ (8, 2),
1398+ (12, 1033),
1399+ (10, 280),
1400+ (10, 278),
1401+ (10, 274),
1402+ (10, 267),
1403+ (10, 264),
1404+ (10, 259),
1405+ (11, 382),
1406+ (11, 378),
1407+ (11, 372),
1408+ (11, 367),
1409+ (11, 363),
1410+ (11, 360),
1411+ (11, 358),
1412+ (11, 356),
1413+ (8, 0),
1414+ (8, 43),
1415+ (7, 20),
1416+ (7, 19),
1417+ (7, 17),
1418+ (7, 15),
1419+ (7, 13),
1420+ (7, 11),
1421+ (7, 9),
1422+ (7, 7),
1423+ (7, 6),
1424+ (7, 4),
1425+ (8, 7),
1426+ (8, 5),
1427+ (8, 3),
1428+ (8, 1),
1429+ (4, 3),
1430+];
1431+
1432+pub(crate) static C0: [(u8, u16); 16] = [
1433+ (1, 1),
1434+ (4, 5),
1435+ (4, 4),
1436+ (5, 5),
1437+ (4, 6),
1438+ (6, 5),
1439+ (5, 4),
1440+ (6, 4),
1441+ (4, 7),
1442+ (5, 3),
1443+ (5, 6),
1444+ (6, 0),
1445+ (5, 7),
1446+ (6, 2),
1447+ (6, 3),
1448+ (6, 1),
1449+];
1450+
1451+pub(crate) static C1: [(u8, u16); 16] = [
1452+ (4, 15),
1453+ (4, 14),
1454+ (4, 13),
1455+ (4, 12),
1456+ (4, 11),
1457+ (4, 10),
1458+ (4, 9),
1459+ (4, 8),
1460+ (4, 7),
1461+ (4, 6),
1462+ (4, 5),
1463+ (4, 4),
1464+ (4, 3),
1465+ (4, 2),
1466+ (4, 1),
1467+ (4, 0),
1468+];
crates/ec-mp3/src/lib.rsadded+149 -0
@@ -0,0 +1,149 @@
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+
34+pub mod decode;
35+pub mod encode;
36+pub mod header;
37+
38+mod filterbank;
39+mod huffman;
40+mod huffman_tables;
41+mod tables;
42+mod window;
43+
44+pub use decode::{DecodedFrame, Mp3Decode, Mp3Reader};
45+pub use encode::{Mp3Encode, Mp3Encoder, Mp3EncoderConfig};
46+pub use header::{ChannelMode, FrameHeader, Version};
47+
48+use ec_core::error::{Error, Result};
49+use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat};
50+use ec_core::packet::{Buf, Packet};
51+use 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)]
56+pub struct Mp3Decoder {
57+ params: CodecParameters,
58+ reader: Mp3Reader,
59+ pending: Vec<AudioFrame>,
60+ drained: bool,
61+}
62+
63+impl 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+
104+impl 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.
140+pub 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+}
crates/ec-mp3/src/tables.rsadded+204 -0
@@ -0,0 +1,204 @@
1+//! The constant tables Layer III needs besides the Huffman codes: scalefactor
2+//! band layouts, the pre-emphasis table, and the two lazily built power tables
3+//! requantisation runs on.
4+//!
5+//! The three MPEG-1 long-block layouts here were measured against a reference
6+//! decoder the same way the Huffman tables were (`scripts/mp3-tables/`, one
7+//! band attenuated at a time), which is also why they are stated as widths: a
8+//! width table cannot silently disagree with itself about where 576 ends.
9+
10+use std::sync::OnceLock;
11+
12+/// Widths of the 22 long scalefactor bands, by sample rate.
13+pub(crate) fn long_widths(sample_rate: u32) -> &'static [u16; 22] {
14+ match sample_rate {
15+ 44100 => &[
16+ 4, 4, 4, 4, 4, 4, 6, 6, 8, 8, 10, 12, 16, 20, 24, 28, 34, 42, 50, 54, 76, 158,
17+ ],
18+ 48000 => &[
19+ 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 10, 12, 16, 18, 22, 28, 34, 40, 46, 54, 54, 192,
20+ ],
21+ 32000 => &[
22+ 4, 4, 4, 4, 4, 4, 6, 6, 8, 10, 12, 16, 20, 24, 30, 38, 46, 56, 68, 84, 102, 26,
23+ ],
24+ 22050 | 16000 | 11025 | 12000 => &[
25+ 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54,
26+ ],
27+ 24000 => &[
28+ 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 18, 22, 26, 32, 38, 46, 54, 62, 70, 76, 36,
29+ ],
30+ // 8 kHz is the odd one out: five two-wide bands at the top rather than
31+ // one wide one.
32+ _ => &[
33+ 12, 12, 12, 12, 12, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 76, 90, 2, 2, 2, 2, 2,
34+ ],
35+ }
36+}
37+
38+/// Widths of the 13 short scalefactor bands (per window), by sample rate.
39+pub(crate) fn short_widths(sample_rate: u32) -> &'static [u16; 13] {
40+ match sample_rate {
41+ 44100 => &[4, 4, 4, 4, 6, 8, 10, 12, 14, 18, 22, 30, 56],
42+ 48000 => &[4, 4, 4, 4, 6, 6, 10, 12, 14, 16, 20, 26, 66],
43+ 32000 => &[4, 4, 4, 4, 6, 8, 12, 16, 20, 26, 34, 42, 12],
44+ 22050 => &[4, 4, 4, 6, 6, 8, 10, 14, 18, 26, 32, 42, 18],
45+ 24000 => &[4, 4, 4, 6, 8, 10, 12, 14, 18, 24, 32, 44, 12],
46+ // Measured: the MPEG-2.5 rates 11.025 and 12 kHz share the 16 kHz
47+ // layout rather than the LSF rate they halve.
48+ 16000 | 11025 | 12000 => &[4, 4, 4, 6, 8, 10, 12, 14, 18, 24, 30, 40, 18],
49+ _ => &[8, 8, 8, 12, 16, 20, 24, 28, 36, 2, 2, 2, 26],
50+ }
51+}
52+
53+/// Start offset of each long band, plus 576 as the last entry.
54+pub(crate) fn long_starts(sample_rate: u32) -> [u16; 23] {
55+ let mut out = [0u16; 23];
56+ let mut acc = 0;
57+ for (i, w) in long_widths(sample_rate).iter().enumerate() {
58+ out[i] = acc;
59+ acc += w;
60+ }
61+ out[22] = acc;
62+ out
63+}
64+
65+/// Start offset of each short band within one window, plus 192.
66+pub(crate) fn short_starts(sample_rate: u32) -> [u16; 14] {
67+ let mut out = [0u16; 14];
68+ let mut acc = 0;
69+ for (i, w) in short_widths(sample_rate).iter().enumerate() {
70+ out[i] = acc;
71+ acc += w;
72+ }
73+ out[13] = acc;
74+ out
75+}
76+
77+/// Additional high-frequency scalefactor applied when `preflag` is set.
78+pub(crate) const PRETAB: [u8; 22] = [
79+ 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 2, 0,
80+];
81+
82+/// `slen1`/`slen2` for the MPEG-1 `scalefac_compress` index.
83+pub(crate) const SLEN: [(u32, u32); 16] = [
84+ (0, 0),
85+ (0, 1),
86+ (0, 2),
87+ (0, 3),
88+ (3, 0),
89+ (1, 1),
90+ (1, 2),
91+ (1, 3),
92+ (2, 1),
93+ (2, 2),
94+ (2, 3),
95+ (3, 1),
96+ (3, 2),
97+ (3, 3),
98+ (4, 2),
99+ (4, 3),
100+];
101+
102+/// Scalefactor band counts per partition for the MPEG-2 LSF scalefactor
103+/// scheme, indexed `[block number][0 = long, 1 = short, 2 = mixed]`.
104+pub(crate) const LSF_PARTITIONS: [[[u8; 4]; 3]; 6] = [
105+ [[6, 5, 5, 5], [9, 9, 9, 9], [6, 9, 9, 9]],
106+ [[6, 5, 7, 3], [9, 9, 12, 6], [6, 9, 12, 6]],
107+ [[11, 10, 0, 0], [18, 18, 0, 0], [15, 18, 0, 0]],
108+ [[7, 7, 7, 0], [12, 12, 12, 0], [6, 15, 12, 0]],
109+ [[6, 6, 6, 3], [12, 9, 9, 6], [6, 12, 9, 6]],
110+ [[8, 8, 5, 0], [15, 12, 9, 0], [6, 18, 9, 0]],
111+];
112+
113+/// The largest quantised magnitude Layer III can code (15 plus 13 linbits).
114+pub(crate) const MAX_QUANT: usize = 8206;
115+
116+/// `|is|^(4/3)`, the requantisation curve, tabulated once.
117+pub(crate) fn power43() -> &'static [f32; MAX_QUANT + 1] {
118+ static TABLE: OnceLock<Box<[f32; MAX_QUANT + 1]>> = OnceLock::new();
119+ TABLE.get_or_init(|| {
120+ let mut table = Box::new([0.0f32; MAX_QUANT + 1]);
121+ for (i, slot) in table.iter_mut().enumerate() {
122+ *slot = (i as f64).powf(4.0 / 3.0) as f32;
123+ }
124+ table
125+ })
126+}
127+
128+/// The four Layer III block windows: normal, start, short, stop.
129+pub(crate) fn windows() -> &'static [[f32; 36]; 4] {
130+ static WINDOWS: OnceLock<[[f32; 36]; 4]> = OnceLock::new();
131+ WINDOWS.get_or_init(|| {
132+ let mut w = [[0.0f32; 36]; 4];
133+ let sin36 = |i: usize| (std::f64::consts::PI / 36.0 * (i as f64 + 0.5)).sin() as f32;
134+ let sin12 = |i: usize| (std::f64::consts::PI / 12.0 * (i as f64 + 0.5)).sin() as f32;
135+ for (i, slot) in w[0].iter_mut().enumerate() {
136+ *slot = sin36(i);
137+ }
138+ for (i, slot) in w[1].iter_mut().enumerate() {
139+ *slot = match i {
140+ 0..=17 => sin36(i),
141+ 18..=23 => 1.0,
142+ 24..=29 => sin12(i - 18),
143+ _ => 0.0,
144+ };
145+ }
146+ for (i, slot) in w[2].iter_mut().enumerate().take(12) {
147+ *slot = sin12(i);
148+ }
149+ for (i, slot) in w[3].iter_mut().enumerate() {
150+ *slot = match i {
151+ 0..=5 => 0.0,
152+ 6..=11 => sin12(i - 6),
153+ 12..=17 => 1.0,
154+ _ => sin36(i),
155+ };
156+ }
157+ w
158+ })
159+}
160+
161+/// Alias-reduction butterfly coefficients, `(cs, ca)` for the eight lines each
162+/// side of a subband boundary.
163+pub(crate) fn alias_coefficients() -> &'static [(f32, f32); 8] {
164+ static COEFFS: OnceLock<[(f32, f32); 8]> = OnceLock::new();
165+ COEFFS.get_or_init(|| {
166+ let ci = [
167+ -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037,
168+ ];
169+ let mut out = [(0.0f32, 0.0f32); 8];
170+ for (slot, c) in out.iter_mut().zip(ci) {
171+ let norm = (1.0f64 + c * c).sqrt();
172+ *slot = ((1.0 / norm) as f32, (c / norm) as f32);
173+ }
174+ out
175+ })
176+}
177+
178+#[cfg(test)]
179+mod tests {
180+ use super::*;
181+
182+ #[test]
183+ fn every_band_layout_spans_its_granule() {
184+ for rate in [44100, 48000, 32000, 24000, 22050, 16000, 12000, 11025, 8000] {
185+ let long: u16 = long_widths(rate).iter().sum();
186+ let short: u16 = short_widths(rate).iter().sum();
187+ assert_eq!(long, 576, "long bands at {rate} Hz");
188+ assert_eq!(short * 3, 576, "short bands at {rate} Hz");
189+ assert_eq!(long_starts(rate)[22], 576);
190+ assert_eq!(short_starts(rate)[13], 192);
191+ }
192+ }
193+
194+ #[test]
195+ fn lsf_partitions_cover_their_band_counts() {
196+ for (block, entry) in LSF_PARTITIONS.iter().enumerate() {
197+ let sums: Vec<u32> = entry
198+ .iter()
199+ .map(|p| p.iter().map(|v| u32::from(*v)).sum())
200+ .collect();
201+ assert_eq!(sums, vec![21, 36, 33], "block number {block}");
202+ }
203+ }
204+}
crates/ec-mp3/src/window.rsadded+527 -0
@@ -0,0 +1,527 @@
1+//! The Layer III polyphase window, measured from a reference decoder.
2+//!
3+//! `scripts/mp3-tables/` feeds frames whose spectrum it chooses through
4+//! ffmpeg and least-squares fits the 512 window taps to the PCM that comes
5+//! back; the fit residual is 1.6e-6 relative, i.e. the f32 noise floor of the
6+//! decoder that was measured. The same taps serve the encoder's analysis
7+//! filterbank (scaled by 1/32), which reconstructs to -85 dB -- the
8+//! pseudo-QMF's own design limit, not an approximation of ours.
9+//!
10+//! The eight taps at index `p % 64 == 16` multiply a matrixing row that is
11+//! identically zero, so they are unobservable and unused; they are zero here.
12+
13+/// The 512-tap prototype filter shared by the analysis and synthesis banks.
14+pub(crate) static WINDOW: [f32; 512] = [
15+ 0.000000011415852,
16+ -0.000015267362,
17+ -0.000015203146,
18+ -0.0000151986715,
19+ -0.00001516934,
20+ -0.000015331996,
21+ -0.000015299296,
22+ -0.000030369547,
23+ -0.00003051874,
24+ -0.000030387224,
25+ -0.00003047262,
26+ -0.00004553826,
27+ -0.000045790093,
28+ -0.00006033324,
29+ -0.00006074798,
30+ -0.00007623177,
31+ 0.0000000000000007771561,
32+ -0.00009158812,
33+ -0.00010707284,
34+ -0.00010752892,
35+ -0.00012210483,
36+ -0.0001375902,
37+ -0.00015264975,
38+ -0.00016808163,
39+ -0.000198351,
40+ -0.00021326676,
41+ -0.00024415043,
42+ -0.00025923923,
43+ -0.00028996877,
44+ -0.00032021772,
45+ -0.00036640486,
46+ -0.00039679479,
47+ -0.00044255037,
48+ -0.00047290753,
49+ -0.00053397013,
50+ -0.00057965296,
51+ -0.00062562595,
52+ -0.00068629114,
53+ -0.00074790895,
54+ -0.00080878945,
55+ -0.00088501174,
56+ -0.00096131716,
57+ -0.0010379666,
58+ -0.0011140599,
59+ -0.0012055617,
60+ -0.0012974035,
61+ -0.001388574,
62+ -0.0014802893,
63+ -0.0015868805,
64+ -0.0016939237,
65+ -0.0017852938,
66+ -0.0019078987,
67+ -0.0020141946,
68+ -0.0021213335,
69+ -0.0022432955,
70+ -0.0023501269,
71+ -0.0024565875,
72+ -0.0025787377,
73+ -0.0026854768,
74+ -0.00279207,
75+ -0.0028991497,
76+ -0.0029907583,
77+ -0.0030822374,
78+ -0.0031738034,
79+ 0.003250133,
80+ 0.0033262433,
81+ 0.00338757,
82+ 0.0034334313,
83+ 0.0034637738,
84+ 0.0034788004,
85+ 0.0034790176,
86+ 0.0034639053,
87+ 0.0034180349,
88+ 0.0033721782,
89+ 0.0032808688,
90+ 0.0031739867,
91+ 0.003051756,
92+ 0.0028841344,
93+ 0.0027005575,
94+ 0.0024872634,
95+ 0.0000000000000012733496,
96+ 0.0019376706,
97+ 0.0016176497,
98+ 0.0012662442,
99+ 0.00086979714,
100+ 0.00044235107,
101+ -0.000030705753,
102+ -0.0005494556,
103+ -0.001098628,
104+ -0.0016938953,
105+ -0.0023345852,
106+ -0.0030061814,
107+ -0.0037231992,
108+ -0.004486055,
109+ -0.0052950876,
110+ -0.0061187474,
111+ -0.0070038103,
112+ -0.0079192305,
113+ -0.008865455,
114+ -0.009841983,
115+ -0.010849041,
116+ -0.011887125,
117+ -0.012939475,
118+ -0.014022803,
119+ -0.015121499,
120+ -0.01623552,
121+ -0.01734931,
122+ -0.018463053,
123+ -0.019577023,
124+ -0.02069092,
125+ -0.021789964,
126+ -0.022857735,
127+ -0.023910528,
128+ -0.024933018,
129+ -0.0259098,
130+ -0.02684026,
131+ -0.027725205,
132+ -0.028533855,
133+ -0.029281769,
134+ -0.029937815,
135+ -0.030532835,
136+ -0.031005554,
137+ -0.03138714,
138+ -0.03166223,
139+ -0.031814594,
140+ -0.031844933,
141+ -0.03173854,
142+ -0.031478826,
143+ 0.031082166,
144+ 0.0305177,
145+ 0.029785281,
146+ 0.02888459,
147+ 0.027801497,
148+ 0.0265352,
149+ 0.025085581,
150+ 0.023422332,
151+ 0.021575933,
152+ 0.019531135,
153+ 0.017257782,
154+ 0.014800756,
155+ 0.0121154785,
156+ 0.009231564,
157+ 0.006134068,
158+ 0.0028228818,
159+ -0.000000000000000644611,
160+ -0.0043945615,
161+ -0.008316075,
162+ -0.012420815,
163+ -0.01670837,
164+ -0.021178978,
165+ -0.025818132,
166+ -0.030609008,
167+ -0.035552945,
168+ -0.040634155,
169+ -0.045837644,
170+ -0.05113255,
171+ -0.056533795,
172+ -0.061996475,
173+ -0.06752017,
174+ -0.07305916,
175+ -0.0786286,
176+ -0.0841829,
177+ -0.089706406,
178+ -0.095169336,
179+ -0.10054016,
180+ -0.10581998,
181+ -0.11094653,
182+ -0.115921035,
183+ -0.12069705,
184+ -0.12525961,
185+ -0.12956229,
186+ -0.13359062,
187+ -0.13729873,
188+ -0.1406705,
189+ -0.14367695,
190+ -0.1462553,
191+ -0.14842229,
192+ -0.1501159,
193+ -0.15130647,
194+ -0.15196219,
195+ -0.1520692,
196+ -0.15159595,
197+ -0.15049735,
198+ -0.14877312,
199+ -0.14636232,
200+ -0.14326483,
201+ -0.13944978,
202+ -0.13488811,
203+ -0.12957762,
204+ -0.12347438,
205+ -0.11657697,
206+ -0.108856454,
207+ 0.10031129,
208+ 0.090927154,
209+ 0.080688596,
210+ 0.06959536,
211+ 0.057617296,
212+ 0.04478508,
213+ 0.031082308,
214+ 0.01651004,
215+ 0.0010681328,
216+ -0.015228168,
217+ -0.03237904,
218+ -0.050354324,
219+ -0.069168,
220+ -0.08877562,
221+ -0.109161384,
222+ -0.13031028,
223+ -0.00000000000000026023126,
224+ -0.17478941,
225+ -0.19805925,
226+ -0.22198515,
227+ -0.24650589,
228+ -0.27159062,
229+ -0.29721087,
230+ -0.32331842,
231+ -0.34986892,
232+ -0.3768008,
233+ -0.40408376,
234+ -0.43165684,
235+ -0.45947304,
236+ -0.48747197,
237+ -0.5156101,
238+ -0.5438234,
239+ -0.5720369,
240+ -0.60021967,
241+ -0.62829626,
242+ -0.6562196,
243+ -0.68391407,
244+ -0.7113179,
245+ -0.7383724,
246+ -0.76502967,
247+ -0.7912138,
248+ -0.8168645,
249+ -0.84194964,
250+ -0.86636347,
251+ -0.89009124,
252+ -0.91305554,
253+ -0.93519616,
254+ -0.9564821,
255+ -0.9768524,
256+ -0.99624646,
257+ -1.0146182,
258+ -1.0319365,
259+ -1.0481571,
260+ -1.0632175,
261+ -1.0771183,
262+ -1.0897832,
263+ -1.1012113,
264+ -1.1113733,
265+ -1.1202233,
266+ -1.1277452,
267+ -1.1339263,
268+ -1.1387645,
269+ -1.1422124,
270+ -1.1442869,
271+ 1.1449894,
272+ 1.1442884,
273+ 1.1422125,
274+ 1.1387625,
275+ 1.133927,
276+ 1.1277479,
277+ 1.1202255,
278+ 1.1113749,
279+ 1.1012119,
280+ 1.0897831,
281+ 1.077118,
282+ 1.0632172,
283+ 1.048157,
284+ 1.0319374,
285+ 1.0146184,
286+ 0.9962471,
287+ 0.0000000000000007964717,
288+ 0.95648247,
289+ 0.93519664,
290+ 0.9130558,
291+ 0.8900912,
292+ 0.8663634,
293+ 0.84194976,
294+ 0.81686413,
295+ 0.7912142,
296+ 0.76503056,
297+ 0.7383738,
298+ 0.7113198,
299+ 0.68391466,
300+ 0.6562191,
301+ 0.6282958,
302+ 0.6002202,
303+ 0.5720369,
304+ 0.54382306,
305+ 0.51561016,
306+ 0.48747298,
307+ 0.45947272,
308+ 0.43165582,
309+ 0.40408316,
310+ 0.37680054,
311+ 0.34986863,
312+ 0.32331842,
313+ 0.29721078,
314+ 0.27159154,
315+ 0.24650584,
316+ 0.2219845,
317+ 0.19805893,
318+ 0.17478915,
319+ 0.1522064,
320+ 0.13030985,
321+ 0.10916119,
322+ 0.088775314,
323+ 0.06916808,
324+ 0.050354168,
325+ 0.03237904,
326+ 0.015228211,
327+ -0.0010681684,
328+ -0.016510095,
329+ -0.031082127,
330+ -0.04478449,
331+ -0.05761706,
332+ -0.06959555,
333+ -0.08068876,
334+ -0.09092727,
335+ 0.10031129,
336+ 0.10885651,
337+ 0.11657729,
338+ 0.123474106,
339+ 0.12957765,
340+ 0.13488798,
341+ 0.1394502,
342+ 0.14326526,
343+ 0.14636232,
344+ 0.14877336,
345+ 0.15049754,
346+ 0.15159558,
347+ 0.15206915,
348+ 0.15196228,
349+ 0.15130645,
350+ 0.15011622,
351+ 0.0000000000000002206003,
352+ 0.14625533,
353+ 0.14367671,
354+ 0.14067101,
355+ 0.13729863,
356+ 0.1335911,
357+ 0.12956247,
358+ 0.12525932,
359+ 0.120697,
360+ 0.115920916,
361+ 0.11094674,
362+ 0.10581983,
363+ 0.100540325,
364+ 0.095169336,
365+ 0.089706264,
366+ 0.08418277,
367+ 0.07862859,
368+ 0.073058985,
369+ 0.067519896,
370+ 0.061996456,
371+ 0.05653381,
372+ 0.051132552,
373+ 0.0458371,
374+ 0.040634338,
375+ 0.035553053,
376+ 0.030609237,
377+ 0.02581771,
378+ 0.021179507,
379+ 0.01670833,
380+ 0.012420671,
381+ 0.008315938,
382+ 0.004394627,
383+ 0.0006866427,
384+ -0.0028229149,
385+ -0.006134143,
386+ -0.009231619,
387+ -0.012115582,
388+ -0.014800927,
389+ -0.017258044,
390+ -0.019531146,
391+ -0.021575898,
392+ -0.023422075,
393+ -0.025085574,
394+ -0.026534922,
395+ -0.027801469,
396+ -0.028885014,
397+ -0.029785192,
398+ -0.03051723,
399+ 0.031082176,
400+ 0.03147878,
401+ 0.031738393,
402+ 0.03184512,
403+ 0.031814706,
404+ 0.03166176,
405+ 0.031387117,
406+ 0.031005694,
407+ 0.030532828,
408+ 0.029937604,
409+ 0.029281935,
410+ 0.02853383,
411+ 0.027725317,
412+ 0.026840411,
413+ 0.02590936,
414+ 0.024932835,
415+ -0.0000000000000014298339,
416+ 0.022857612,
417+ 0.021789733,
418+ 0.020690892,
419+ 0.019577093,
420+ 0.018462965,
421+ 0.017348979,
422+ 0.016235009,
423+ 0.015121544,
424+ 0.014023043,
425+ 0.0129397465,
426+ 0.011886712,
427+ 0.010849021,
428+ 0.009841979,
429+ 0.008865594,
430+ 0.007919409,
431+ 0.007003773,
432+ 0.0061188545,
433+ 0.0052949484,
434+ 0.0044858786,
435+ 0.003723058,
436+ 0.0030056525,
437+ 0.0023346553,
438+ 0.0016937256,
439+ 0.0010986148,
440+ 0.0005493129,
441+ 0.00003062855,
442+ -0.00044273847,
443+ -0.00086982694,
444+ -0.0012664495,
445+ -0.0016174339,
446+ -0.001937911,
447+ -0.0022277806,
448+ -0.0024872052,
449+ -0.0027008213,
450+ -0.0028840094,
451+ -0.003051711,
452+ -0.0031738107,
453+ -0.0032806862,
454+ -0.0033721055,
455+ -0.0034179622,
456+ -0.0034639246,
457+ -0.00347904,
458+ -0.00347909,
459+ -0.003463723,
460+ -0.0034331984,
461+ -0.0033875592,
462+ -0.0033261578,
463+ 0.0032501116,
464+ 0.0031737192,
465+ 0.0030822048,
466+ 0.0029911308,
467+ 0.0028991015,
468+ 0.0027921288,
469+ 0.0026856647,
470+ 0.0025788378,
471+ 0.002456706,
472+ 0.0023499262,
473+ 0.0022431447,
474+ 0.002120262,
475+ 0.0020142195,
476+ 0.0019073315,
477+ 0.001785405,
478+ 0.001693759,
479+ 0.0000000000000009972893,
480+ 0.0014800375,
481+ 0.0013885009,
482+ 0.001296985,
483+ 0.0012054051,
484+ 0.0011147871,
485+ 0.0010375459,
486+ 0.0009614164,
487+ 0.0008849344,
488+ 0.00080879295,
489+ 0.00074773876,
490+ 0.0006866758,
491+ 0.0006256105,
492+ 0.0005799012,
493+ 0.00053403573,
494+ 0.00047302843,
495+ 0.00044260576,
496+ 0.00039682162,
497+ 0.0003660489,
498+ 0.00032072325,
499+ 0.00028996973,
500+ 0.00025934313,
501+ 0.00024398624,
502+ 0.00021362594,
503+ 0.00019845674,
504+ 0.00016780205,
505+ 0.00015235315,
506+ 0.0001368079,
507+ 0.00012211184,
508+ 0.00010672097,
509+ 0.000106991814,
510+ 0.00009128963,
511+ 0.000076291864,
512+ 0.00007616151,
513+ 0.00006127107,
514+ 0.000060929906,
515+ 0.00004582208,
516+ 0.000045436722,
517+ 0.000030140414,
518+ 0.000030621795,
519+ 0.000030583265,
520+ 0.000030157482,
521+ 0.000015142228,
522+ 0.0000153379,
523+ 0.00001535084,
524+ 0.000015364727,
525+ 0.000015056947,
526+ 0.000015421143,
527+];
crates/ec-mp3/tests/decode_matrix.rsadded+180 -0
@@ -0,0 +1,180 @@
1+//! Our decoder against ffmpeg's, over every MP3 fixture: same sample count,
2+//! same samples.
3+//!
4+//! Correlation rather than a bit-exact compare, because Layer III's output is
5+//! defined by an inverse transform rather than by an integer recipe; ISO/IEC
6+//! 11172-4 states decoder accuracy the same way. The bar here is 0.999, and
7+//! what the fixtures actually reach is printed.
8+//!
9+//! Run the table:
10+//! cargo test -p ec-mp3 --release --test decode_matrix -- --nocapture
11+
12+use std::path::{Path, PathBuf};
13+use std::process::Command;
14+use std::time::Instant;
15+
16+use ec_mp3::Mp3Reader;
17+
18+fn fixtures() -> PathBuf {
19+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
20+}
21+
22+fn mp3_fixtures() -> Vec<PathBuf> {
23+ let dir = fixtures().join("audio");
24+ let Ok(entries) = std::fs::read_dir(&dir) else {
25+ return Vec::new();
26+ };
27+ let mut out: Vec<PathBuf> = entries
28+ .flatten()
29+ .map(|e| e.path())
30+ .filter(|p| p.extension().is_some_and(|e| e == "mp3"))
31+ .collect();
32+ out.sort();
33+ out
34+}
35+
36+fn ffmpeg_decode(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
37+ let out = Command::new("ffmpeg")
38+ .args(["-v", "error", "-i"])
39+ .arg(path)
40+ .args(["-f", "f32le", "-"])
41+ .output()
42+ .ok()?;
43+ if !out.status.success() {
44+ return None;
45+ }
46+ let samples = out
47+ .stdout
48+ .chunks_exact(4)
49+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
50+ .collect();
51+ let probe = Command::new("ffprobe")
52+ .args([
53+ "-v",
54+ "error",
55+ "-select_streams",
56+ "a:0",
57+ "-show_entries",
58+ "stream=channels,sample_rate",
59+ "-of",
60+ "default=noprint_wrappers=1",
61+ ])
62+ .arg(path)
63+ .output()
64+ .ok()?;
65+ let text = String::from_utf8_lossy(&probe.stdout);
66+ let field = |key: &str| {
67+ text.lines()
68+ .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
69+ .and_then(|v| v.trim().parse::<u32>().ok())
70+ };
71+ Some((samples, field("sample_rate")?, field("channels")? as usize))
72+}
73+
74+fn correlation(a: &[f32], b: &[f32]) -> f64 {
75+ let n = a.len().min(b.len());
76+ let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
77+ for i in 0..n {
78+ let (x, y) = (a[i] as f64, b[i] as f64);
79+ ab += x * y;
80+ aa += x * x;
81+ bb += y * y;
82+ }
83+ if aa == 0.0 || bb == 0.0 {
84+ return f64::from(u8::from(aa == bb));
85+ }
86+ ab / (aa * bb).sqrt()
87+}
88+
89+/// Best correlation over the priming shift ffmpeg applied, and that shift.
90+///
91+/// The score is the whole overlap rather than a window: fixture tones are
92+/// periodic, so a short window correlates almost as well one period out and
93+/// the search would settle on the wrong shift.
94+fn best_alignment(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) {
95+ let mut best = (f64::MIN, 0usize);
96+ let mut offset = 0;
97+ while offset < got.len() && offset <= 2304 * channels {
98+ let n = (got.len() - offset).min(want.len()).min(200_000);
99+ let corr = correlation(&got[offset..offset + n], &want[..n]);
100+ if corr > best.0 {
101+ best = (corr, offset);
102+ }
103+ offset += channels;
104+ }
105+ let (_, offset) = best;
106+ // The first and last frames are the encoder-delay and padding regions that
107+ // gapless trimming exists for: the reservoir the first frame points back
108+ // into predates the stream, and the last frame's tail is padding ffmpeg
109+ // drops. Every frame between them is compared.
110+ let skip = 1152 * channels;
111+ let n = (got.len() - offset)
112+ .min(want.len())
113+ .saturating_sub(2 * skip);
114+ (
115+ correlation(
116+ &got[offset + skip..offset + skip + n],
117+ &want[skip..skip + n],
118+ ),
119+ offset,
120+ )
121+}
122+
123+#[test]
124+fn decodes_every_fixture_like_ffmpeg() {
125+ let files = mp3_fixtures();
126+ if files.is_empty() {
127+ eprintln!("no MP3 fixtures: run scripts/gen-fixtures.sh and scripts/gen-mp3-fixtures.sh");
128+ return;
129+ }
130+ println!(
131+ "{:<34} {:>6} {:>3} {:>9} {:>9} {:>8}",
132+ "fixture", "rate", "ch", "samples", "corr", "x rt"
133+ );
134+ let mut worst = 1.0f64;
135+ let mut failures = Vec::new();
136+ for path in &files {
137+ let bytes = std::fs::read(path).expect("read fixture");
138+ let Some((want, rate, channels)) = ffmpeg_decode(path) else {
139+ panic!("ffmpeg could not decode {}", path.display());
140+ };
141+ let start = Instant::now();
142+ let mut reader = Mp3Reader::new();
143+ reader.push(&bytes);
144+ let frames = reader.decode_all();
145+ let elapsed = start.elapsed().as_secs_f64();
146+ let mut got = Vec::with_capacity(want.len());
147+ for frame in &frames {
148+ got.extend_from_slice(&frame.samples);
149+ }
150+ let name = path.file_name().unwrap().to_string_lossy();
151+ // ffmpeg honours the LAME delay/padding tags and drops the encoder's
152+ // priming samples; we hand back every frame we were given, so the
153+ // comparison finds the shift first. Gapless trimming is a container
154+ // concern, not a decoder one.
155+ let (corr, offset) = best_alignment(&got, &want, channels);
156+ let seconds = got.len() as f64 / (rate as f64 * channels as f64);
157+ let realtime = seconds / elapsed.max(1e-9);
158+ println!(
159+ "{name:<34} {rate:>6} {channels:>3} {:>9} {corr:>9.6} {realtime:>8.0} (+{offset})",
160+ got.len()
161+ );
162+ // A sample count that disagrees by more than the encoder delay plus
163+ // padding means we lost or invented audio, which correlation alone
164+ // would hide. Two frames covers both ends of the gapless trim.
165+ let slack = 2 * 1152 * channels;
166+ if got.len() + slack < want.len() || want.len() + slack < got.len() {
167+ failures.push(format!(
168+ "{name}: {} samples, ffmpeg {} ",
169+ got.len(),
170+ want.len()
171+ ));
172+ }
173+ if corr < 0.999 {
174+ failures.push(format!("{name}: correlation {corr:.6}"));
175+ }
176+ worst = worst.min(corr);
177+ }
178+ println!("worst correlation {worst:.6} over {} fixtures", files.len());
179+ assert!(failures.is_empty(), "{failures:#?}");
180+}
crates/ec-mp3/tests/encode_matrix.rsadded+223 -0
@@ -0,0 +1,223 @@
1+//! Our encoder measured the only way a lossy one can be: encode, decode the
2+//! result with ffmpeg, correlate against the samples that went in.
3+//!
4+//! The bar is the incumbent this crate replaces, `rusty_mp3` 0.6.1, measured on
5+//! the same fixtures and the same metric (see `BAR`, and
6+//! `scripts/mp3-incumbent-bar.md` for how those numbers were produced).
7+//!
8+//! Run the table:
9+//! cargo test -p ec-mp3 --release --test encode_matrix -- --nocapture
10+
11+use std::path::{Path, PathBuf};
12+use std::process::Command;
13+
14+use ec_mp3::{Mp3Encoder, Mp3EncoderConfig};
15+
16+/// Correlation `rusty_mp3` 0.6.1 reaches on this corpus, measured with this
17+/// same alignment and metric (its own encoder, ffmpeg's decoder). The tone
18+/// fixtures reach 1.0 on both encoders and so cannot separate them; the
19+/// `mp3src-*` material — glide, broadband noise and a click every half second —
20+/// is what does.
21+const BAR: [(&str, [f64; 3]); 4] = [
22+ ("mp3src-mono-44100", [0.99920, 0.99983, 0.99999]),
23+ ("mp3src-stereo-44100", [0.99612, 0.99847, 0.99972]),
24+ ("mp3src-mono-48000", [0.99867, 0.99972, 0.99998]),
25+ ("mp3src-stereo-48000", [0.99461, 0.99787, 0.99956]),
26+];
27+const BITRATES: [u32; 3] = [128, 192, 320];
28+
29+/// The incumbent's number for this fixture and bitrate. Fixtures it was not
30+/// measured on (the tones, which both encoders code perfectly) fall back to its
31+/// worst result at that rate.
32+fn bar_for(name: &str, kbps: u32) -> f64 {
33+ let index = BITRATES.iter().position(|k| *k == kbps).unwrap_or(0);
34+ for (fixture, values) in BAR {
35+ if name.starts_with(fixture) {
36+ return values[index];
37+ }
38+ }
39+ BAR.iter()
40+ .map(|(_, v)| v[index])
41+ .fold(f64::INFINITY, f64::min)
42+}
43+
44+fn fixtures() -> PathBuf {
45+ Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures")
46+}
47+
48+fn workdir(test: &str) -> PathBuf {
49+ let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id()));
50+ std::fs::create_dir_all(&dir).expect("create work dir");
51+ dir
52+}
53+
54+/// Reads a WAV fixture as interleaved f32 plus its rate and channel count.
55+fn read_wav(path: &Path) -> Option<(Vec<f32>, u32, usize)> {
56+ let out = Command::new("ffmpeg")
57+ .args(["-v", "error", "-i"])
58+ .arg(path)
59+ .args(["-f", "f32le", "-"])
60+ .output()
61+ .ok()?;
62+ if !out.status.success() {
63+ return None;
64+ }
65+ let samples = out
66+ .stdout
67+ .chunks_exact(4)
68+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
69+ .collect();
70+ let probe = Command::new("ffprobe")
71+ .args([
72+ "-v",
73+ "error",
74+ "-select_streams",
75+ "a:0",
76+ "-show_entries",
77+ "stream=channels,sample_rate",
78+ "-of",
79+ "default=noprint_wrappers=1",
80+ ])
81+ .arg(path)
82+ .output()
83+ .ok()?;
84+ let text = String::from_utf8_lossy(&probe.stdout);
85+ let field = |key: &str| {
86+ text.lines()
87+ .find_map(|l| l.strip_prefix(key)?.strip_prefix('='))
88+ .and_then(|v| v.trim().parse::<u32>().ok())
89+ };
90+ Some((samples, field("sample_rate")?, field("channels")? as usize))
91+}
92+
93+fn correlation(a: &[f32], b: &[f32]) -> f64 {
94+ let n = a.len().min(b.len());
95+ let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
96+ for i in 0..n {
97+ let (x, y) = (a[i] as f64, b[i] as f64);
98+ ab += x * y;
99+ aa += x * x;
100+ bb += y * y;
101+ }
102+ if aa == 0.0 || bb == 0.0 {
103+ return 0.0;
104+ }
105+ ab / (aa * bb).sqrt()
106+}
107+
108+/// Best correlation over the encoder delay, which no MP3 encoder avoids.
109+fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) {
110+ let mut best = (f64::MIN, 0usize);
111+ let mut offset = 0;
112+ while offset + channels < got.len() && offset <= 3000 * channels {
113+ let n = (got.len() - offset).min(want.len());
114+ let skip = 1152 * channels;
115+ if n <= 2 * skip {
116+ break;
117+ }
118+ let corr = correlation(
119+ &got[offset + skip..offset + n - skip],
120+ &want[skip..n - skip],
121+ );
122+ if corr > best.0 {
123+ best = (corr, offset);
124+ }
125+ offset += channels;
126+ }
127+ best
128+}
129+
130+fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
131+ let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
132+ bitrate_kbps: kbps,
133+ vbr_quality: None,
134+ });
135+ encoder
136+ .push_pcm_f32(pcm, channels as u16, rate)
137+ .expect("encoder accepts the fixture");
138+ encoder.finish();
139+ let mut out = Vec::new();
140+ while let Ok(frame) = encoder.next_packet() {
141+ out.extend_from_slice(&frame);
142+ }
143+ out
144+}
145+
146+#[test]
147+fn encodes_above_the_incumbent_bar() {
148+ let dir = fixtures().join("audio");
149+ let mut sources: Vec<PathBuf> = std::fs::read_dir(&dir)
150+ .into_iter()
151+ .flatten()
152+ .flatten()
153+ .map(|e| e.path())
154+ .filter(|p| {
155+ let name = p.file_name().map(|n| n.to_string_lossy().to_string());
156+ name.is_some_and(|n| n.starts_with("wav16-") || n.starts_with("mp3src-"))
157+ && p.extension().is_some_and(|e| e == "wav")
158+ })
159+ .collect();
160+ sources.sort();
161+ sources.retain(|p| {
162+ let name = p.file_name().unwrap().to_string_lossy().to_string();
163+ name.contains("mono") || name.contains("stereo")
164+ });
165+ if sources.is_empty() {
166+ eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
167+ return;
168+ }
169+ let work = workdir("encode");
170+ println!(
171+ "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}",
172+ "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s"
173+ );
174+ let mut failures = Vec::new();
175+ for source in &sources {
176+ let Some((pcm, rate, channels)) = read_wav(source) else {
177+ continue;
178+ };
179+ for kbps in BITRATES {
180+ let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps);
181+ let bytes = encode(&pcm, rate, channels, kbps);
182+ let path = work.join(format!(
183+ "{}-{kbps}.mp3",
184+ source.file_stem().unwrap().to_string_lossy()
185+ ));
186+ std::fs::write(&path, &bytes).expect("write encoded file");
187+ let out = Command::new("ffmpeg")
188+ .args(["-v", "warning", "-i"])
189+ .arg(&path)
190+ .args(["-f", "f32le", "-"])
191+ .output()
192+ .expect("run ffmpeg");
193+ let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string();
194+ if !stderr.is_empty() {
195+ failures.push(format!("{}: ffmpeg said {stderr}", path.display()));
196+ }
197+ let decoded: Vec<f32> = out
198+ .stdout
199+ .chunks_exact(4)
200+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
201+ .collect();
202+ let (corr, _offset) = aligned(&decoded, &pcm, channels);
203+ let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
204+ let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0;
205+ let name = source.file_name().unwrap().to_string_lossy();
206+ println!(
207+ "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}"
208+ );
209+ // Matching counts as passing: at 320 kbit/s both encoders are
210+ // within a part in 10^5 of the source and the difference between
211+ // them is smaller than the metric resolves.
212+ if corr < bar - 1e-5 {
213+ failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}"));
214+ }
215+ if (measured - kbps as f64).abs() > kbps as f64 * 0.05 {
216+ failures.push(format!(
217+ "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s"
218+ ));
219+ }
220+ }
221+ }
222+ assert!(failures.is_empty(), "{failures:#?}");
223+}
scripts/gen-mp3-fixtures.shadded+69 -0
@@ -0,0 +1,69 @@
1+#!/usr/bin/env bash
2+# MP3 fixtures beyond the family matrix in gen-fixtures.sh: every Layer III
3+# sampling frequency (MPEG-1, MPEG-2 LSF and MPEG-2.5), both channel modes,
4+# CBR and VBR, on material that forces block switching and a wide spread of
5+# Huffman tables.
6+#
7+# The family matrix only covers 44.1/48 kHz stereo and mono at one bitrate,
8+# which leaves the LSF side info, the 8 kHz band layout and the short-block
9+# path unexercised — every one of those is a separate table in the decoder.
10+#
11+# Output: fixtures/audio/mp3ext-<mode>-<rate>-<setting>.mp3 (gitignored).
12+set -euo pipefail
13+
14+here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)
15+FIXTURES="$here/../fixtures"
16+mkdir -p "$FIXTURES/audio"
17+
18+src="$FIXTURES/audio/.mp3src.wav"
19+if [ ! -f "$src" ]; then
20+ # A tone with a glide, broadband noise and a click every half second: the
21+ # click is what makes an encoder switch to short blocks, and the noise is
22+ # what makes it reach for the escape-coded Huffman tables.
23+ left="0.35*sin(2*PI*440*t+3*sin(2*PI*1.5*t))+0.12*(random(0)-0.5)+0.7*lt(mod(t\,0.5)\,0.002)"
24+ right="0.30*sin(2*PI*443*t)+0.12*(random(1)-0.5)+0.7*lt(mod(t\,0.5)\,0.002)"
25+ ffmpeg -v error -y -f lavfi -i "aevalsrc='${left}'|'${right}':d=3:s=48000" \
26+ -c:a pcm_s16le "$src"
27+fi
28+
29+# The same material as PCM, mono and stereo, for the encoder's quality table:
30+# a tone fixture cannot tell two encoders apart, and this one can.
31+for rate in 44100 48000; do
32+ for mode in mono stereo; do
33+ channels=1
34+ [ "$mode" = stereo ] && channels=2
35+ ffmpeg -v error -y -i "$src" -ar "$rate" -ac "$channels" -c:a pcm_s16le \
36+ "$FIXTURES/audio/mp3src-${mode}-${rate}.wav"
37+ done
38+done
39+
40+RATES=(48000 44100 32000 24000 22050 16000 12000 11025 8000)
41+made=0
42+for rate in "${RATES[@]}"; do
43+ for mode in mono stereo; do
44+ channels=1
45+ [ "$mode" = stereo ] && channels=2
46+ for setting in cbr128 cbr320 vbr2; do
47+ case "$setting" in
48+ cbr128) opts=(-b:a 128k) ;;
49+ cbr320) opts=(-b:a 320k) ;;
50+ vbr2) opts=(-q:a 2) ;;
51+ esac
52+ # MPEG-2/2.5 rates cap out well below 320 kbit/s.
53+ if [ "$setting" = cbr320 ] && [ "$rate" -lt 32000 ]; then
54+ continue
55+ fi
56+ out="$FIXTURES/audio/mp3ext-${mode}-${rate}-${setting}.mp3"
57+ ffmpeg -v error -y -i "$src" -ar "$rate" -ac "$channels" \
58+ -c:a libmp3lame "${opts[@]}" "$out"
59+ made=$((made + 1))
60+ done
61+ done
62+done
63+# One simple-stereo file: LAME picks joint stereo by default, so the plain
64+# left/right path would otherwise never be decoded.
65+ffmpeg -v error -y -i "$src" -ar 44100 -ac 2 -c:a libmp3lame -b:a 192k \
66+ -joint_stereo 0 "$FIXTURES/audio/mp3ext-simplestereo-44100-cbr192.mp3"
67+made=$((made + 1))
68+
69+echo "wrote $made MP3 fixtures to $FIXTURES/audio"
scripts/mp3-tables/emit_tables.pyadded+53 -0
@@ -0,0 +1,53 @@
1+"""Turn the measured Huffman tables into ec-mp3 source."""
2+
3+import json
4+
5+HDR = '''//! Layer III Huffman code tables.
6+//!
7+//! Every entry here was *measured*, not transcribed: `scripts/mp3-tables.py`
8+//! writes legal Layer III frames whose main-data bits it chooses, decodes them
9+//! with ffmpeg, and walks each code tree by asking whether all continuations of
10+//! a bit prefix decode to the same pair. The result is checked for a Kraft sum
11+//! of exactly 1, for full coverage of the value grid, and for uniqueness before
12+//! it is written out, so a wrong entry cannot reach this file silently.
13+//!
14+//! `(length, code)` indexed by `x * dim + y`, where `x` and `y` are the two
15+//! (or four, for the count1 tables) values the codeword yields, in the order
16+//! they are written to the spectrum.
17+
18+'''
19+
20+
21+def emit_table(name, entries, dim, nvals):
22+ idx = {}
23+ for code, vals in entries.items():
24+ i = 0
25+ for v in vals:
26+ i = i * dim + v
27+ idx[i] = (len(code), int(code, 2) if code else 0)
28+ assert len(idx) == dim ** nvals, (name, len(idx))
29+ body = ", ".join(f"({idx[i][0]}, {idx[i][1]})" for i in range(dim ** nvals))
30+ return f"static {name}: [(u8, u16); {dim ** nvals}] = [{body}];\n"
31+
32+
33+def main():
34+ tabs = json.load(open("huffman.json"))
35+ out = [HDR]
36+ names = {}
37+ for key in ("1", "2", "3", "5", "6", "7", "8", "9", "10", "11", "12",
38+ "13", "15", "16", "24"):
39+ entries = tabs[key]
40+ dim = max(max(v) for v in entries.values()) + 1
41+ name = f"T{key}"
42+ names[key] = name
43+ out.append(emit_table(name, entries, dim, 2))
44+ for sel in (0, 1):
45+ entries = tabs[f"count1_{sel}"]
46+ out.append(emit_table(f"C{sel}", entries, 2, 4))
47+ with open("huffman_tables.rs", "w") as f:
48+ f.write("\n".join(out))
49+ print("wrote huffman_tables.rs")
50+
51+
52+if __name__ == "__main__":
53+ main()
scripts/mp3-tables/learn_huffman.pyadded+95 -0
@@ -0,0 +1,95 @@
1+"""Measure every Layer III Huffman table by walking the code tree against the
2+ffmpeg decoder: a prefix is a codeword exactly when every continuation decodes
3+to the same pair (values clamped at 15, so linbits escapes compare equal)."""
4+
5+import json
6+import sys
7+import numpy as np
8+from probe_engine import Engine, values
9+
10+# (table index used on the wire, entries per axis, linbits, coefficients read)
11+BIG_TABLES = [
12+ (1, 2, 0), (2, 3, 0), (3, 3, 0), (5, 4, 0), (6, 4, 0),
13+ (7, 6, 0), (8, 6, 0), (9, 6, 0), (10, 8, 0), (11, 8, 0), (12, 8, 0),
14+ (13, 16, 0), (15, 16, 0), (16, 16, 1), (24, 16, 4),
15+]
16+MAXDEPTH = 24
17+
18+
19+def learn_table(engine, tsel, dim, quad=False):
20+ """Returns {codeword bits (tuple) : tuple of values}."""
21+ leaves = {}
22+ level = [()]
23+ depth = 0
24+ while level:
25+ depth += 1
26+ if depth > MAXDEPTH:
27+ raise RuntimeError(f"table {tsel}: tree deeper than {MAXDEPTH}")
28+ probes = []
29+ for prefix in level:
30+ for fill in (0, 1):
31+ bits = list(prefix) + [fill] * 48
32+ if quad:
33+ probes.append((bits, 0, 0, tsel))
34+ else:
35+ probes.append((bits, tsel, 1, 0))
36+ got = engine.run(probes)
37+ n = 4 if quad else 2
38+ nxt = []
39+ for i, prefix in enumerate(level):
40+ v0 = np.minimum(values(got[2 * i], n), 15)
41+ v1 = np.minimum(values(got[2 * i + 1], n), 15)
42+ if tuple(v0) == tuple(v1):
43+ leaves[prefix] = tuple(int(x) for x in v0)
44+ else:
45+ nxt.append(prefix + (0,))
46+ nxt.append(prefix + (1,))
47+ level = nxt
48+ return leaves
49+
50+
51+def check(leaves, dim, quad, name):
52+ kraft = sum(2.0 ** -len(c) for c in leaves)
53+ vals = sorted(leaves.values())
54+ expect = dim ** (4 if quad else 2)
55+ ok = True
56+ if abs(kraft - 1.0) > 1e-12:
57+ print(f" !! {name}: kraft = {kraft}")
58+ ok = False
59+ if len(leaves) != expect:
60+ print(f" !! {name}: {len(leaves)} leaves, expected {expect}")
61+ ok = False
62+ if len(set(vals)) != len(vals):
63+ print(f" !! {name}: duplicate values")
64+ ok = False
65+ return ok
66+
67+
68+def main():
69+ Minv = np.load("Minv.npy")
70+ engine = Engine(Minv)
71+ out = {}
72+ allok = True
73+ for tsel, dim, linbits in BIG_TABLES:
74+ leaves = learn_table(engine, tsel, dim)
75+ ok = check(leaves, dim, False, f"table {tsel}")
76+ allok &= ok
77+ maxlen = max(len(c) for c in leaves)
78+ print(f"table {tsel:2d}: {len(leaves):3d} codes, max len {maxlen:2d}, "
79+ f"linbits {linbits}, ok={ok}")
80+ out[str(tsel)] = {"".join(map(str, c)): v for c, v in leaves.items()}
81+ for tsel in (0, 1):
82+ leaves = learn_table(engine, tsel, 2, quad=True)
83+ ok = check(leaves, 2, True, f"count1 {tsel}")
84+ allok &= ok
85+ print(f"count1 {tsel}: {len(leaves)} codes, max len "
86+ f"{max(len(c) for c in leaves)}, ok={ok}")
87+ out[f"count1_{tsel}"] = {"".join(map(str, c)): v for c, v in leaves.items()}
88+ with open("huffman.json", "w") as f:
89+ json.dump(out, f, indent=0)
90+ print("all tables consistent:", allok)
91+ return 0 if allok else 1
92+
93+
94+if __name__ == "__main__":
95+ sys.exit(main())
scripts/mp3-tables/learn_sfb.pyadded+56 -0
@@ -0,0 +1,56 @@
1+"""Measure the MPEG-1 long-block scalefactor band edges: flat spectrum, one
2+band attenuated at a time, read the edges off the recovered coefficients."""
3+
4+import sys
5+import numpy as np
6+from mp3probe import BitWriter, Granule, frame_bytes, ffmpeg_decode
7+from probe_engine import GLOBAL_GAIN, SCALE
8+
9+TABLE1 = [(1, 0b1), (3, 0b001), (2, 0b01), (3, 0b000)]
10+SC = 13 # slen1 = slen2 = 3
11+SLEN = 3
12+NBANDS = 21 # scalefactors transmitted for sfb 0..20
13+
14+
15+def probe_bits(band):
16+ bw = BitWriter()
17+ for b in range(NBANDS):
18+ bw.w(7 if b == band else 0, SLEN)
19+ ln, code = TABLE1[3] # (1,1)
20+ for _ in range(288):
21+ bw.w(code, ln)
22+ bw.w(0, 1)
23+ bw.w(0, 1)
24+ return bw.bits
25+
26+
27+def main():
28+ Minv = np.load("Minv.npy")
29+ for srate_idx, srate in enumerate([44100, 48000, 32000]):
30+ stream = b""
31+ for band in range(NBANDS):
32+ bits = probe_bits(band)
33+ g = Granule(part2_3_length=len(bits), big_values=288,
34+ global_gain=GLOBAL_GAIN, scalefac_compress=SC,
35+ table_select=(1, 1, 1))
36+ stream += frame_bytes([g, Granule()], [bits, []], srate_idx=srate_idx)
37+ stream += frame_bytes([Granule(), Granule()], [[], []], srate_idx=srate_idx)
38+ pcm, err = ffmpeg_decode(stream)
39+ assert not err.strip(), err
40+ edges = [0]
41+ for band in range(NBANDS):
42+ xr = (pcm[band * 2304:(band + 1) * 2304] @ Minv)[:576]
43+ att = np.abs(xr) / SCALE
44+ low = np.where(att < 0.5)[0] # attenuated by 2^-3.5
45+ if len(low) == 0:
46+ print(f" {srate}: band {band} showed no attenuation")
47+ continue
48+ edges.append(int(low[-1]) + 1)
49+ widths = [edges[i + 1] - edges[i] for i in range(len(edges) - 1)]
50+ widths.append(576 - edges[-1])
51+ print(f"{srate} long widths ({sum(widths)}): {widths}")
52+ return 0
53+
54+
55+if __name__ == "__main__":
56+ sys.exit(main())
scripts/mp3-tables/learn_window.pyadded+83 -0
@@ -0,0 +1,83 @@
1+"""Measure the Layer III synthesis window D[512] from the ffmpeg decoder.
2+
3+Probes carry only +-1 spectral values, written with Huffman table 1 (four
4+codewords), so nothing but the header/side-info syntax is assumed. The decode
5+chain up to the synthesis window is modelled exactly, leaving a linear system
6+pcm = A @ D that a least-squares solve inverts.
7+"""
8+
9+import numpy as np
10+import sys
11+from mp3probe import (BitWriter, Granule, frame_bytes, ffmpeg_decode,
12+ granules_to_subband, synthesis_basis)
13+
14+# table 1: (x,y) -> (length, code), index = x*2 + y
15+TABLE1 = [(1, 0b1), (3, 0b001), (2, 0b01), (3, 0b000)]
16+
17+GLOBAL_GAIN = 170 # 2^((gg-210)/4) = 2^-10 spectral scale, far from clipping
18+
19+
20+def write_pairs(pairs):
21+ bw = BitWriter()
22+ for (x, sx), (y, sy) in pairs:
23+ ln, code = TABLE1[x * 2 + y]
24+ bw.w(code, ln)
25+ if x:
26+ bw.w(sx, 1)
27+ if y:
28+ bw.w(sy, 1)
29+ return bw.bits
30+
31+
32+def probe_frames(rng, nframes=6, npairs=288):
33+ """Random +-1 spectra; returns (mp3 bytes, list of granule spectra)."""
34+ stream = b""
35+ spectra = []
36+ for _ in range(nframes):
37+ grans, mains = [], []
38+ for _g in range(2):
39+ vals = rng.integers(0, 2, size=(npairs, 2))
40+ signs = rng.integers(0, 2, size=(npairs, 2))
41+ pairs = [((int(vals[i, 0]), int(signs[i, 0])),
42+ (int(vals[i, 1]), int(signs[i, 1]))) for i in range(npairs)]
43+ bits = write_pairs(pairs)
44+ grans.append(Granule(part2_3_length=len(bits), big_values=npairs,
45+ global_gain=GLOBAL_GAIN, table_select=(1, 1, 1)))
46+ mains.append(bits)
47+ xr = np.zeros(576)
48+ scale = 2.0 ** ((GLOBAL_GAIN - 210) / 4.0)
49+ for i in range(npairs):
50+ for j in range(2):
51+ v = float(vals[i, j])
52+ if signs[i, j]:
53+ v = -v
54+ xr[2 * i + j] = v * scale
55+ spectra.append(xr)
56+ stream += frame_bytes(grans, mains)
57+ return stream, spectra
58+
59+
60+def main():
61+ rng = np.random.default_rng(0xC0DE)
62+ mp3, spectra = probe_frames(rng)
63+ pcm, err = ffmpeg_decode(mp3)
64+ print(f"ffmpeg: {len(pcm)} samples, stderr={err.strip()!r}, peak={np.abs(pcm).max():.6g}")
65+ slots = granules_to_subband(spectra)
66+ A = synthesis_basis(slots)
67+ print(f"model: {A.shape[0]} samples from {len(slots)} slots")
68+ n = min(len(pcm), A.shape[0])
69+ # frame-granularity alignment search
70+ best = None
71+ for off in range(0, len(pcm) - n + 1, 1152 // 2):
72+ D, res, rank, _ = np.linalg.lstsq(A[:n], pcm[off:off + n], rcond=None)
73+ resid = np.linalg.norm(A[:n] @ D - pcm[off:off + n]) / max(np.linalg.norm(pcm[off:off + n]), 1e-30)
74+ if best is None or resid < best[0]:
75+ best = (resid, off, D, rank)
76+ resid, off, D, rank = best
77+ print(f"offset={off} rank={rank} relative residual={resid:.3e}")
78+ print(f"D peak={np.abs(D).max():.6g} D[0..4]={D[:5]}")
79+ np.save("D.npy", D)
80+
81+
82+if __name__ == "__main__":
83+ sys.exit(main())
scripts/mp3-tables/lsf_probe.pyadded+71 -0
@@ -0,0 +1,71 @@
1+"""Short-block reorder probes for the low sampling frequencies: one non-zero
2+coefficient per granule, so the spectral position it lands in reveals the
3+scalefactor band widths."""
4+import numpy as np
5+from mp3probe import BitWriter, Granule
6+from learn_window import TABLE1, GLOBAL_GAIN
7+
8+RATES = {8000: (0, 2), 11025: (0, 0), 12000: (0, 1), 16000: (2, 2), 22050: (2, 0), 24000: (2, 1)}
9+BITRATES_V2 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]
10+
11+
12+def lsf_frame(granule, main_bits, rate, bitrate_idx=14):
13+ version_id, rate_idx = RATES[rate]
14+ frame_len = 72 * BITRATES_V2[bitrate_idx] * 1000 // rate
15+ bw = BitWriter()
16+ bw.w(0x7FF, 11); bw.w(version_id, 2); bw.w(0b01, 2); bw.w(1, 1)
17+ bw.w(bitrate_idx, 4); bw.w(rate_idx, 2); bw.w(0, 1); bw.w(0, 1)
18+ bw.w(0b11, 2); bw.w(0, 2); bw.w(0, 1); bw.w(1, 1); bw.w(0, 2)
19+ bw.w(0, 8) # main_data_begin
20+ bw.w(0, 1) # private
21+ g = granule
22+ bw.w(g.part2_3_length, 12); bw.w(g.big_values, 9); bw.w(g.global_gain, 8)
23+ bw.w(g.scalefac_compress, 9)
24+ bw.w(1 if g.block_type else 0, 1)
25+ if g.block_type:
26+ bw.w(g.block_type, 2); bw.w(g.mixed_block, 1)
27+ for t in g.table_select[:2]:
28+ bw.w(t, 5)
29+ for s in g.subblock_gain:
30+ bw.w(s, 3)
31+ else:
32+ for t in g.table_select:
33+ bw.w(t, 5)
34+ bw.w(g.region0_count, 4); bw.w(g.region1_count, 3)
35+ bw.w(g.scalefac_scale, 1); bw.w(g.count1table_select, 1)
36+ assert len(bw) == 32 + 9 * 8, len(bw)
37+ bw.bits.extend(main_bits)
38+ assert len(bw) <= frame_len * 8, (len(bw), frame_len * 8)
39+ return bw.bytes(pad_to=frame_len)
40+
41+
42+def pair_bits(x, y):
43+ bw = BitWriter()
44+ ln, code = TABLE1[x * 2 + y]
45+ bw.w(code, ln)
46+ if x:
47+ bw.w(0, 1)
48+ if y:
49+ bw.w(0, 1)
50+ return bw.bits
51+
52+
53+def build(rate, positions):
54+ stream = b""
55+ for pos in positions:
56+ bits = []
57+ for i in range(288):
58+ bits += pair_bits(1 if 2 * i == pos else 0, 1 if 2 * i + 1 == pos else 0)
59+ g = Granule(part2_3_length=len(bits), big_values=288, global_gain=GLOBAL_GAIN,
60+ table_select=(1, 1, 1), block_type=2, mixed_block=0)
61+ stream += lsf_frame(g, bits, rate)
62+ stream += lsf_frame(Granule(), [], rate)
63+ return stream
64+
65+
66+if __name__ == "__main__":
67+ import sys
68+ rate = int(sys.argv[1])
69+ positions = list(range(576))
70+ open(f"/tmp/lsf{rate}.mp3", "wb").write(build(rate, positions))
71+ print("wrote", rate, len(positions))
scripts/mp3-tables/mp3op.pyadded+85 -0
@@ -0,0 +1,85 @@
1+"""The linear map (requantised spectrum -> PCM) for one probe frame, and its
2+pseudo-inverse: what turns an ffmpeg decode back into the integers a probe's
3+Huffman bits decoded to."""
4+
5+import math
6+import numpy as np
7+from mp3probe import ALIAS_CS, ALIAS_CA, WIN_NORMAL
8+
9+NSLOTS = 72 # probe frame (36 slots) + trailing silent frame
10+NSAMPLES = NSLOTS * 32
11+
12+
13+def imdct_matrix():
14+ n = 36
15+ return np.array([[math.cos(math.pi / (2 * n) * (2 * i + 1 + n // 2) * (2 * k + 1))
16+ for k in range(18)] for i in range(n)]) * WIN_NORMAL[:, None]
17+
18+
19+def alias_matrix():
20+ ar = np.eye(576)
21+ for sb in range(1, 32):
22+ for i in range(8):
23+ lo, hi = sb * 18 - 1 - i, sb * 18 + i
24+ a, b = ar[lo].copy(), ar[hi].copy()
25+ ar[lo] = a * ALIAS_CS[i] - b * ALIAS_CA[i]
26+ ar[hi] = b * ALIAS_CS[i] + a * ALIAS_CA[i]
27+ return ar
28+
29+
30+def spectrum_to_slots():
31+ """(2 granules x 576) -> (72 slots x 32 subbands), flattened columns."""
32+ imw = imdct_matrix()
33+ ar = alias_matrix()
34+ L = np.zeros((1152, NSLOTS * 32))
35+ for g in range(2):
36+ for sb in range(32):
37+ for k in range(18):
38+ col = np.zeros(NSLOTS * 32)
39+ for i in range(18):
40+ t0 = 18 * g + i
41+ sign = -1.0 if (sb % 2 == 1 and i % 2 == 1) else 1.0
42+ col[t0 * 32 + sb] += imw[i, k] * sign
43+ t1 = 18 * (g + 1) + i
44+ sign = -1.0 if (sb % 2 == 1 and i % 2 == 1) else 1.0
45+ col[t1 * 32 + sb] += imw[18 + i, k] * sign
46+ # the alias butterflies mix coefficients before the imdct
47+ L[g * 576:(g + 1) * 576] += np.outer(ar[sb * 18 + k, :], col)
48+ return L
49+
50+
51+def slots_to_pcm(D):
52+ N = np.array([[math.cos((16 + i) * (2 * k + 1) * math.pi / 64) for k in range(32)]
53+ for i in range(64)])
54+ S = np.zeros((NSLOTS * 32, NSAMPLES))
55+ for i in range(16):
56+ Ci = np.zeros((32, 32))
57+ for j in range(32):
58+ b = j if i % 2 == 0 else j + 32
59+ Ci[j] = D[j + 32 * i] * N[b]
60+ for t in range(NSLOTS):
61+ s = t - i
62+ if s < 0:
63+ continue
64+ S[s * 32:(s + 1) * 32, t * 32:(t + 1) * 32] += Ci.T
65+ return S
66+
67+
68+def build(D):
69+ M = spectrum_to_slots() @ slots_to_pcm(D)
70+ return M, np.linalg.pinv(M)
71+
72+
73+if __name__ == "__main__":
74+ D = np.load("D.npy")
75+ M, Minv = build(D)
76+ np.save("M.npy", M)
77+ np.save("Minv.npy", Minv)
78+ print("M", M.shape, "cond ok")
79+
80+ # self-check: round-trip a random spectrum through the model
81+ rng = np.random.default_rng(7)
82+ c = rng.normal(size=1152) * 1e-3
83+ pcm = c @ M
84+ back = pcm @ Minv
85+ print("model round-trip max err", np.abs(back - c).max())
scripts/mp3-tables/mp3probe.pyadded+211 -0
@@ -0,0 +1,211 @@
1+"""Black-box probe rig for MPEG-1 Layer III.
2+
3+Builds legal Layer III frames whose main data we control bit for bit, decodes
4+them with ffmpeg, and models the decode chain analytically so the spec's
5+constant tables (synthesis window, Huffman codes, scalefactor bands) can be
6+*measured* rather than copied from an implementation.
7+"""
8+
9+import math
10+import subprocess
11+import tempfile
12+import os
13+import numpy as np
14+
15+SRATES = [44100, 48000, 32000]
16+BITRATES = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320]
17+
18+
19+class BitWriter:
20+ def __init__(self):
21+ self.bits = []
22+
23+ def w(self, value, n):
24+ for i in range(n - 1, -1, -1):
25+ self.bits.append((value >> i) & 1)
26+
27+ def __len__(self):
28+ return len(self.bits)
29+
30+ def bytes(self, pad_to=None):
31+ bits = list(self.bits)
32+ if pad_to is not None:
33+ bits += [0] * (pad_to * 8 - len(bits))
34+ while len(bits) % 8:
35+ bits.append(0)
36+ out = bytearray()
37+ for i in range(0, len(bits), 8):
38+ b = 0
39+ for j in range(8):
40+ b = (b << 1) | bits[i + j]
41+ out.append(b)
42+ return bytes(out)
43+
44+
45+class Granule:
46+ """One granule of side info; long blocks only (all the probes need)."""
47+
48+ def __init__(self, part2_3_length=0, big_values=0, global_gain=210,
49+ scalefac_compress=0, table_select=(0, 0, 0), region0_count=15,
50+ region1_count=1, preflag=0, scalefac_scale=0, count1table_select=0,
51+ block_type=0, mixed_block=0, subblock_gain=(0, 0, 0)):
52+ self.block_type = block_type
53+ self.mixed_block = mixed_block
54+ self.subblock_gain = subblock_gain
55+ self.part2_3_length = part2_3_length
56+ self.big_values = big_values
57+ self.global_gain = global_gain
58+ self.scalefac_compress = scalefac_compress
59+ self.table_select = table_select
60+ self.region0_count = region0_count
61+ self.region1_count = region1_count
62+ self.preflag = preflag
63+ self.scalefac_scale = scalefac_scale
64+ self.count1table_select = count1table_select
65+
66+ def write(self, bw):
67+ bw.w(self.part2_3_length, 12)
68+ bw.w(self.big_values, 9)
69+ bw.w(self.global_gain, 8)
70+ bw.w(self.scalefac_compress, 4)
71+ bw.w(1 if self.block_type else 0, 1) # window_switching_flag
72+ if self.block_type:
73+ bw.w(self.block_type, 2)
74+ bw.w(self.mixed_block, 1)
75+ for t in self.table_select[:2]:
76+ bw.w(t, 5)
77+ for g in self.subblock_gain:
78+ bw.w(g, 3)
79+ else:
80+ for t in self.table_select:
81+ bw.w(t, 5)
82+ bw.w(self.region0_count, 4)
83+ bw.w(self.region1_count, 3)
84+ bw.w(self.preflag, 1)
85+ bw.w(self.scalefac_scale, 1)
86+ bw.w(self.count1table_select, 1)
87+
88+
89+def frame_bytes(granules, main_data, srate_idx=0, bitrate_idx=14, padding=0):
90+ """One mono MPEG-1 Layer III frame. `main_data` is a list of bit lists."""
91+ srate = SRATES[srate_idx]
92+ frame_len = 144 * BITRATES[bitrate_idx] * 1000 // srate + padding
93+ bw = BitWriter()
94+ bw.w(0x7FF, 11)
95+ bw.w(0b11, 2) # MPEG-1
96+ bw.w(0b01, 2) # Layer III
97+ bw.w(1, 1) # no CRC
98+ bw.w(bitrate_idx, 4)
99+ bw.w(srate_idx, 2)
100+ bw.w(padding, 1)
101+ bw.w(0, 1)
102+ bw.w(0b11, 2) # mono
103+ bw.w(0, 2)
104+ bw.w(0, 1)
105+ bw.w(1, 1)
106+ bw.w(0, 2)
107+ # side info, mono: 17 bytes
108+ bw.w(0, 9) # main_data_begin
109+ bw.w(0, 5) # private_bits
110+ bw.w(0, 4) # scfsi
111+ for g in granules:
112+ g.write(bw)
113+ assert len(bw) == 32 + 17 * 8, len(bw)
114+ for bits in main_data:
115+ bw.bits.extend(bits)
116+ assert len(bw) <= frame_len * 8, (len(bw), frame_len * 8)
117+ return bw.bytes(pad_to=frame_len)
118+
119+
120+def ffmpeg_decode(mp3: bytes, channels=1):
121+ """Decode with ffmpeg, returning float32 samples (no resampling)."""
122+ with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as f:
123+ f.write(mp3)
124+ path = f.name
125+ try:
126+ p = subprocess.run(
127+ ["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", str(channels), "-"],
128+ capture_output=True, check=True)
129+ return np.frombuffer(p.stdout, dtype=np.float32).astype(np.float64), p.stderr.decode()
130+ finally:
131+ os.unlink(path)
132+
133+
134+# ---------------------------------------------------------------- model side
135+
136+def imdct36(X):
137+ """ISO Layer III IMDCT, n = 36."""
138+ n = 36
139+ out = np.zeros(n)
140+ for i in range(n):
141+ s = 0.0
142+ for k in range(n // 2):
143+ s += X[k] * math.cos(math.pi / (2 * n) * (2 * i + 1 + n // 2) * (2 * k + 1))
144+ out[i] = s
145+ return out
146+
147+
148+WIN_NORMAL = np.array([math.sin(math.pi / 36 * (i + 0.5)) for i in range(36)])
149+
150+ALIAS_CI = [-0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037]
151+ALIAS_CS = np.array([1.0 / math.sqrt(1.0 + c * c) for c in ALIAS_CI])
152+ALIAS_CA = np.array([c / math.sqrt(1.0 + c * c) for c in ALIAS_CI])
153+
154+
155+def alias_reduce(xr):
156+ """In-place butterflies across the 31 long-block subband boundaries."""
157+ xr = xr.copy()
158+ for sb in range(1, 32):
159+ for i in range(8):
160+ lo = sb * 18 - 1 - i
161+ hi = sb * 18 + i
162+ a, b = xr[lo], xr[hi]
163+ xr[lo] = a * ALIAS_CS[i] - b * ALIAS_CA[i]
164+ xr[hi] = b * ALIAS_CS[i] + a * ALIAS_CA[i]
165+ return xr
166+
167+
168+def granules_to_subband(granule_spectra):
169+ """Requantised spectra (long blocks) -> subband samples [slot][32]."""
170+ overlap = np.zeros((32, 18))
171+ slots = []
172+ for xr in granule_spectra:
173+ xr = alias_reduce(xr)
174+ block = np.zeros((18, 32))
175+ for sb in range(32):
176+ y = imdct36(xr[sb * 18: sb * 18 + 18]) * WIN_NORMAL
177+ block[:, sb] = y[:18] + overlap[sb]
178+ overlap[sb] = y[18:]
179+ for t in range(18):
180+ for sb in range(1, 32, 2):
181+ if t % 2 == 1:
182+ block[t, sb] = -block[t, sb]
183+ slots.extend(block)
184+ return np.array(slots)
185+
186+
187+def synthesis_basis(slots):
188+ """Per output sample, the 512 coefficients multiplying D (the window).
189+
190+ Returns an (nsamples, 512) matrix A with pcm = A @ D.
191+ """
192+ nslots = len(slots)
193+ N = np.array([[math.cos((16 + i) * (2 * k + 1) * math.pi / 64) for k in range(32)]
194+ for i in range(64)])
195+ blocks = slots @ N.T # [slot][64] V blocks
196+ A = np.zeros((nslots * 32, 512))
197+ for t in range(nslots):
198+ for j in range(32):
199+ row = A[t * 32 + j]
200+ for i in range(16):
201+ p = j + 32 * i
202+ a, b = divmod(p, 64)
203+ m = 2 * a + (1 if b >= 32 else 0)
204+ s = t - m
205+ if s >= 0:
206+ row[p] = blocks[s][b]
207+ return A
208+
209+
210+def synthesise(slots, D):
211+ return synthesis_basis(slots) @ D
scripts/mp3-tables/probe_engine.pyadded+54 -0
@@ -0,0 +1,54 @@
1+"""Batch probe runner: many one-pair probes per ffmpeg invocation."""
2+
3+import numpy as np
4+from mp3probe import Granule, frame_bytes, ffmpeg_decode
5+
6+GLOBAL_GAIN = 150
7+SCALE = 2.0 ** ((GLOBAL_GAIN - 210) / 4.0)
8+PART2_3 = 48
9+
10+
11+class Engine:
12+ def __init__(self, Minv):
13+ self.Minv = Minv
14+
15+ def run(self, probes):
16+ """probes: list of (bits, table_select, big_values, count1table_select).
17+
18+ Returns one array of 576 requantised coefficients per probe.
19+ """
20+ stream = b""
21+ for i in range(0, len(probes), 2):
22+ pair = probes[i:i + 2]
23+ grans, mains = [], []
24+ for bits, tsel, bigv, c1 in pair:
25+ bits = list(bits) + [0] * (PART2_3 - len(bits))
26+ grans.append(Granule(part2_3_length=PART2_3, big_values=bigv,
27+ global_gain=GLOBAL_GAIN,
28+ table_select=(tsel, tsel, tsel),
29+ count1table_select=c1))
30+ mains.append(bits[:PART2_3])
31+ while len(grans) < 2:
32+ grans.append(Granule())
33+ mains.append([])
34+ stream += frame_bytes(grans, mains)
35+ stream += frame_bytes([Granule(), Granule()], [[], []])
36+ pcm, err = ffmpeg_decode(stream)
37+ nframes = (len(probes) + 1) // 2
38+ assert len(pcm) >= nframes * 2304, (len(pcm), nframes * 2304, err)
39+ windows = np.stack([pcm[i * 2304:(i + 1) * 2304] for i in range(nframes)])
40+ coeffs = windows @ self.Minv # (nframes, 1152)
41+ out = []
42+ for i in range(len(probes)):
43+ out.append(coeffs[i // 2][(i % 2) * 576:((i % 2) + 1) * 576])
44+ return out
45+
46+
47+def values(xr, n):
48+ """First n integer magnitudes of a recovered granule."""
49+ mag = np.abs(xr[:n]) / SCALE
50+ return np.round(np.power(np.maximum(mag, 0.0), 0.75)).astype(np.int64)
51+
52+
53+def signs(xr, n):
54+ return np.sign(xr[:n]).astype(np.int64)
scripts/mp3-tables/run.shadded+30 -0
@@ -0,0 +1,30 @@
1+#!/usr/bin/env bash
2+# Regenerates ec-mp3's measured constant tables.
3+#
4+# Layer III's Huffman codes and its 512-tap polyphase window are normative data
5+# that no formula produces. Rather than copy them out of an existing
6+# implementation, these scripts measure them: they write legal Layer III frames
7+# whose main-data bits they choose, decode them with ffmpeg, and read the answer
8+# back through a model of the decode chain.
9+#
10+# learn_window.py least-squares fits the 512 window taps to the PCM ffmpeg
11+# returns for spectra we chose (residual 1.6e-6, the f32
12+# noise floor of the decoder being measured)
13+# mp3op.py builds the spectrum -> PCM operator and its pseudo-inverse
14+# learn_huffman.py walks every code tree: a bit prefix is a codeword exactly
15+# when all continuations decode to the same pair. Checks a
16+# Kraft sum of 1, full coverage and uniqueness per table
17+# learn_sfb.py MPEG-1 long scalefactor band widths, one band attenuated
18+# at a time (these agreed with the published layouts)
19+# lsf_probe.py short-block reorder at the low sampling frequencies
20+# emit_tables.py writes huffman_tables.rs
21+#
22+# Needs ffmpeg, python3 and numpy. Output lands beside the scripts; copy
23+# huffman_tables.rs and window.rs into crates/ec-mp3/src/.
24+set -euo pipefail
25+cd "$(dirname "${BASH_SOURCE[0]}")"
26+python3 learn_window.py
27+python3 mp3op.py
28+python3 learn_huffman.py
29+python3 learn_sfb.py
30+python3 emit_tables.py
shims/rusty_mp3/Cargo.tomladded+11 -0
@@ -0,0 +1,11 @@
1+[package]
2+name = "rusty_mp3"
3+description = "Compatibility shim: the rusty_mp3 0.6.1 surface, implemented over ec-mp3."
4+version = "0.6.1"
5+edition.workspace = true
6+license.workspace = true
7+authors.workspace = true
8+
9+[dependencies]
10+ec-mp3.workspace = true
11+ec-core.workspace = true
shims/rusty_mp3/src/lib.rsadded+217 -0
@@ -0,0 +1,217 @@
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 differences from the incumbent, all stated: `vbr_quality` picks a
12+//! constant bitrate rather than varying the rate per frame (see
13+//! [`ec_mp3::encode::Mp3EncoderConfig`]), and the encoder writes the `Info`
14+//! header frame first, as the incumbent does.
15+
16+#![forbid(unsafe_code)]
17+#![warn(missing_docs)]
18+
19+use std::collections::VecDeque;
20+use std::fmt;
21+
22+/// The incumbent's error type.
23+#[derive(Debug)]
24+pub 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+
33+impl 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+
43+impl std::error::Error for Error {}
44+
45+impl 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.
56+pub type Result<T> = std::result::Result<T, Error>;
57+
58+/// One decoded frame of audio.
59+#[derive(Debug, Clone)]
60+pub 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)]
71+pub struct Mp3Decoder {
72+ reader: ec_mp3::Mp3Reader,
73+ queue: VecDeque<DecodedAudio>,
74+ eof: bool,
75+}
76+
77+impl 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)]
113+pub 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.
121+pub 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)]
127+pub struct Mp3Encoder {
128+ inner: ec_mp3::Mp3Encoder,
129+}
130+
131+impl 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)]
179+mod 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+}