diff --git a/Cargo.toml b/Cargo.toml index 784b6fea..47248318 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -16,6 +16,7 @@ ec-dsp = { path = "crates/ec-dsp", version = "0.1.0" } ec-h264-syntax = { path = "crates/ec-h264-syntax", version = "0.1.0" } ec-inflate = { path = "crates/ec-inflate", version = "0.1.0" } ec-matroska = { path = "crates/ec-matroska", version = "0.1.0" } +ec-mp3 = { path = "crates/ec-mp3", version = "0.1.0" } ec-mp4 = { path = "crates/ec-mp4", version = "0.1.0" } ec-riff = { path = "crates/ec-riff", version = "0.1.0" } ec-vp9-syntax = { path = "crates/ec-vp9-syntax", version = "0.1.0" } diff --git a/crates/ec-mp3/Cargo.toml b/crates/ec-mp3/Cargo.toml new file mode 100644 index 00000000..fd4a5538 --- /dev/null +++ b/crates/ec-mp3/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "ec-mp3" +description = "MPEG-1/2/2.5 Layer III (MP3) decoder and encoder, built on the edith_codecs IR." +version.workspace = true +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-core = { workspace = true } +ec-dsp = { workspace = true } diff --git a/crates/ec-mp3/src/decode.rs b/crates/ec-mp3/src/decode.rs new file mode 100644 index 00000000..8caf686d --- /dev/null +++ b/crates/ec-mp3/src/decode.rs @@ -0,0 +1,776 @@ +//! Layer III decoding: side info, scalefactors, spectrum, stereo, and the +//! filterbank that turns 576 coefficients back into PCM. + +use crate::filterbank::{Imdct, Synthesis, alias_reduce}; +use crate::header::{ChannelMode, FrameHeader, Version, crc16}; +use crate::huffman; +use crate::tables::{ + LSF_PARTITIONS, MAX_QUANT, PRETAB, SLEN, long_starts, power43, short_starts, short_widths, +}; +use ec_core::bitio::BitReader; +use ec_core::error::{Error, Result}; + +/// One decoded frame: interleaved `f32` samples in `[-1, 1]`. +#[derive(Clone, Debug, Default, PartialEq)] +pub struct DecodedFrame { + /// Sample rate in Hz. + pub sample_rate: u32, + /// Channel count, 1 or 2. + pub channels: usize, + /// Interleaved samples, `channels * samples_per_frame` of them. + pub samples: Vec, +} + +#[derive(Clone, Copy, Debug, Default)] +struct GranuleInfo { + part2_3_length: u32, + big_values: u32, + global_gain: u32, + scalefac_compress: u32, + window_switching: bool, + block_type: u8, + mixed_block: bool, + table_select: [u8; 3], + subblock_gain: [u32; 3], + region0_count: u32, + region1_count: u32, + preflag: bool, + scalefac_scale: bool, + count1table_select: bool, +} + +#[derive(Clone, Copy, Debug, Default)] +struct SideInfo { + main_data_begin: u32, + scfsi: [[bool; 4]; 2], + granules: [[GranuleInfo; 2]; 2], +} + +fn parse_side_info(header: &FrameHeader, bytes: &[u8]) -> Result { + let channels = header.channels(); + let lsf = header.version != Version::Mpeg1; + let mut r = BitReader::new(bytes); + let mut side = SideInfo { + main_data_begin: r.read_bits(if lsf { 8 } else { 9 })?, + ..SideInfo::default() + }; + let private = match (lsf, channels) { + (true, 1) => 1, + (true, _) => 2, + (false, 1) => 5, + (false, _) => 3, + }; + r.skip_bits(private)?; + if !lsf { + for ch in 0..channels { + for band in 0..4 { + side.scfsi[ch][band] = r.read_bit()?; + } + } + } + for gr in 0..header.granules() { + for ch in 0..channels { + let mut g = GranuleInfo { + part2_3_length: r.read_bits(12)?, + big_values: r.read_bits(9)?, + global_gain: r.read_bits(8)?, + scalefac_compress: r.read_bits(if lsf { 9 } else { 4 })?, + window_switching: r.read_bit()?, + ..GranuleInfo::default() + }; + if g.big_values > 288 { + return Err(Error::corrupt(format!( + "mp3: big_values {} exceeds 288", + g.big_values + ))); + } + if g.window_switching { + g.block_type = r.read_bits(2)? as u8; + g.mixed_block = r.read_bit()?; + for slot in &mut g.table_select[..2] { + *slot = r.read_bits(5)? as u8; + } + for slot in &mut g.subblock_gain { + *slot = r.read_bits(3)?; + } + g.region0_count = if g.block_type == 2 && !g.mixed_block { + 8 + } else { + 7 + }; + g.region1_count = 20 - g.region0_count; + if g.block_type == 0 { + return Err(Error::corrupt( + "mp3: window switching with normal block type", + )); + } + } else { + for slot in &mut g.table_select { + *slot = r.read_bits(5)? as u8; + } + g.region0_count = r.read_bits(4)?; + g.region1_count = r.read_bits(3)?; + } + if !lsf { + g.preflag = r.read_bit()?; + } + g.scalefac_scale = r.read_bit()?; + g.count1table_select = r.read_bit()?; + side.granules[gr][ch] = g; + } + } + Ok(side) +} + +/// The stateful half of the decoder: one frame in, one frame of PCM out. +/// +/// State that crosses frames — the bit reservoir, the IMDCT overlap and the +/// polyphase window history — lives here, so [`Mp3Decode::reset`] after a seek +/// is the whole story. +#[derive(Debug)] +pub struct Mp3Decode { + imdct: Imdct, + synthesis: [Synthesis; 2], + overlap: [Box<[[f32; 18]; 32]>; 2], + reservoir: Vec, + is: [Box<[i32; 576]>; 2], + xr: [Box<[f32; 576]>; 2], + scalefac_l: [[u8; 23]; 2], + scalefac_s: [[[u8; 3]; 13]; 2], +} + +impl Default for Mp3Decode { + fn default() -> Mp3Decode { + Mp3Decode { + imdct: Imdct::default(), + synthesis: [Synthesis::default(), Synthesis::default()], + overlap: [Box::new([[0.0; 18]; 32]), Box::new([[0.0; 18]; 32])], + reservoir: Vec::with_capacity(2048), + is: [Box::new([0; 576]), Box::new([0; 576])], + xr: [Box::new([0.0; 576]), Box::new([0.0; 576])], + scalefac_l: [[0; 23]; 2], + scalefac_s: [[[0; 3]; 13]; 2], + } + } +} + +impl Mp3Decode { + /// A decoder with an empty reservoir and silent history. + pub fn new() -> Mp3Decode { + Mp3Decode::default() + } + + /// Drops the reservoir and the filterbank history, as a seek requires. + pub fn reset(&mut self) { + self.reservoir.clear(); + for synth in &mut self.synthesis { + synth.reset(); + } + for overlap in &mut self.overlap { + overlap.iter_mut().for_each(|sb| sb.fill(0.0)); + } + } + + /// Decodes one complete frame, header included. + /// + /// A frame whose main data has not arrived yet — the bit reservoir points + /// further back than we have seen, which is normal for the first frames + /// after a seek — decodes as silence rather than as an error, because that + /// is what the reservoir mechanism means. + pub fn decode_frame(&mut self, frame: &[u8]) -> Result { + let header = FrameHeader::parse(frame)?; + if header.layer != 3 { + return Err(Error::unsupported( + format!("MPEG audio layer {}", header.layer), + "only Layer III is implemented in ec-mp3", + )); + } + let Some(frame_len) = header.frame_len() else { + return Err(Error::unsupported( + "free-format MPEG audio", + "no bitrate index, so the frame length is only knowable by scanning", + )); + }; + if frame.len() < frame_len { + return Err(Error::NeedMore); + } + let side_len = header.side_info_len(); + let crc_len = usize::from(header.crc) * 2; + let side_start = 4 + crc_len; + if header.crc { + let stored = u16::from_be_bytes([frame[4], frame[5]]); + let computed = crc16( + &[frame[0], frame[1], frame[2], frame[3]], + &frame[side_start..side_start + side_len], + ); + if stored != computed { + return Err(Error::corrupt(format!( + "mp3: side info CRC {computed:#06x} != {stored:#06x}" + ))); + } + } + let side = parse_side_info(&header, &frame[side_start..side_start + side_len])?; + let main = &frame[side_start + side_len..frame_len]; + + let begin = side.main_data_begin as usize; + let have = self.reservoir.len(); + self.reservoir.extend_from_slice(main); + let channels = header.channels(); + let mut samples = vec![0.0f32; header.samples_per_frame() * channels]; + if begin > have { + // The reservoir does not reach back that far: this frame's own + // spectrum is unreadable, so emit silence and keep the bytes for + // the frames that follow. + self.trim_reservoir(); + return Ok(DecodedFrame { + sample_rate: header.sample_rate, + channels, + samples, + }); + } + let start = have - begin; + let data = self.reservoir[start..].to_vec(); + let mut bit = 0u64; + for gr in 0..header.granules() { + for ch in 0..channels { + self.decode_granule(&header, &side, gr, ch, &data, bit)?; + bit += u64::from(side.granules[gr][ch].part2_3_length); + } + self.stereo(&header, &side, gr); + for ch in 0..channels { + let granule = side.granules[gr][ch]; + self.synthesise(&granule, ch, gr, channels, &mut samples); + } + } + self.trim_reservoir(); + Ok(DecodedFrame { + sample_rate: header.sample_rate, + channels, + samples, + }) + } + + fn trim_reservoir(&mut self) { + // 511 bytes is the largest `main_data_begin` a frame can name. + const KEEP: usize = 511; + if self.reservoir.len() > KEEP { + let drop = self.reservoir.len() - KEEP; + self.reservoir.drain(..drop); + } + } + + fn decode_granule( + &mut self, + header: &FrameHeader, + side: &SideInfo, + gr: usize, + ch: usize, + data: &[u8], + start_bit: u64, + ) -> Result<()> { + let granule = side.granules[gr][ch]; + let reader = &mut BitReader::new(data); + reader.skip_bits(start_bit)?; + let end_bit = start_bit + u64::from(granule.part2_3_length); + if header.version == Version::Mpeg1 { + self.read_scalefactors_v1(side, gr, ch, reader)?; + } else { + self.read_scalefactors_lsf(header, &granule, ch, reader)?; + } + let scalefactor_bits = reader.bit_position() - start_bit; + if scalefactor_bits > u64::from(granule.part2_3_length) { + return Err(Error::corrupt("mp3: scalefactors longer than the granule")); + } + // Whatever the granule reserved but did not use is stuffing, and the + // next granule starts at its own offset regardless, so nothing here + // needs to seek to the end. + self.read_spectrum(header, &granule, ch, reader, end_bit)?; + self.requantise(header, &granule, ch); + Ok(()) + } + + fn read_scalefactors_v1( + &mut self, + side: &SideInfo, + gr: usize, + ch: usize, + reader: &mut BitReader<'_>, + ) -> Result<()> { + let granule = side.granules[gr][ch]; + let (slen1, slen2) = SLEN[(granule.scalefac_compress & 15) as usize]; + if granule.window_switching && granule.block_type == 2 { + if granule.mixed_block { + for sfb in 0..8 { + self.scalefac_l[ch][sfb] = reader.read_bits(slen1)? as u8; + } + for sfb in 3..6 { + for w in 0..3 { + self.scalefac_s[ch][sfb][w] = reader.read_bits(slen1)? as u8; + } + } + } else { + for sfb in 0..6 { + for w in 0..3 { + self.scalefac_s[ch][sfb][w] = reader.read_bits(slen1)? as u8; + } + } + } + for sfb in 6..12 { + for w in 0..3 { + self.scalefac_s[ch][sfb][w] = reader.read_bits(slen2)? as u8; + } + } + self.scalefac_s[ch][12] = [0; 3]; + } else { + const GROUPS: [(usize, usize); 4] = [(0, 6), (6, 11), (11, 16), (16, 21)]; + for (group, (from, to)) in GROUPS.into_iter().enumerate() { + if gr == 1 && side.scfsi[ch][group] { + continue; // reuse granule 0's values + } + let slen = if from < 11 { slen1 } else { slen2 }; + for sfb in from..to { + self.scalefac_l[ch][sfb] = reader.read_bits(slen)? as u8; + } + } + self.scalefac_l[ch][21] = 0; + self.scalefac_l[ch][22] = 0; + } + Ok(()) + } + + fn read_scalefactors_lsf( + &mut self, + header: &FrameHeader, + granule: &GranuleInfo, + ch: usize, + reader: &mut BitReader<'_>, + ) -> Result<()> { + let intensity = header.mode == ChannelMode::JointStereo && header.mode_ext & 1 != 0; + let mut sfc = granule.scalefac_compress; + let slen; + let block_number; + if intensity && ch == 1 { + sfc >>= 1; + if sfc < 180 { + slen = [sfc / 36, (sfc % 36) / 6, sfc % 6, 0]; + block_number = 3; + } else if sfc < 244 { + sfc -= 180; + slen = [(sfc % 64) >> 4, (sfc % 16) >> 2, sfc % 4, 0]; + block_number = 4; + } else { + sfc -= 244; + slen = [sfc / 3, sfc % 3, 0, 0]; + block_number = 5; + } + } else if sfc < 400 { + slen = [(sfc >> 4) / 5, (sfc >> 4) % 5, (sfc % 16) >> 2, sfc % 4]; + block_number = 0; + } else if sfc < 500 { + sfc -= 400; + slen = [(sfc >> 2) / 5, (sfc >> 2) % 5, sfc % 4, 0]; + block_number = 1; + } else { + sfc -= 500; + slen = [sfc / 3, sfc % 3, 0, 0]; + block_number = 2; + } + let short = granule.window_switching && granule.block_type == 2; + let kind = if !short { + 0 + } else if granule.mixed_block { + 2 + } else { + 1 + }; + let counts = LSF_PARTITIONS[block_number][kind]; + self.scalefac_l[ch] = [0; 23]; + self.scalefac_s[ch] = [[0; 3]; 13]; + let mut band = 0usize; + for (partition, count) in counts.into_iter().enumerate() { + for _ in 0..count { + let value = reader.read_bits(slen[partition])? as u8; + match kind { + 0 => self.scalefac_l[ch][band] = value, + 1 => self.scalefac_s[ch][band / 3][band % 3] = value, + _ if band < 6 => self.scalefac_l[ch][band] = value, + _ => { + let index = band - 6; + self.scalefac_s[ch][3 + index / 3][index % 3] = value; + } + } + band += 1; + } + } + Ok(()) + } + + fn read_spectrum( + &mut self, + header: &FrameHeader, + granule: &GranuleInfo, + ch: usize, + reader: &mut BitReader<'_>, + end_bit: u64, + ) -> Result<()> { + let is = &mut self.is[ch]; + is.fill(0); + let starts = long_starts(header.sample_rate); + let short = granule.window_switching && granule.block_type == 2; + let (region1, region2) = if granule.window_switching { + if short { + // Three short bands, all three windows: 36 lines at every rate + // whose first bands are four wide, but 72 at 8 kHz, where they + // are eight. The fixed 36 that most descriptions quote is that + // coincidence, and 8 kHz is where it stops holding. + (short_starts(header.sample_rate)[3] as usize * 3, 576) + } else { + (starts[8] as usize, 576) + } + } else { + let r0 = (granule.region0_count + 1).min(22) as usize; + let r1 = (granule.region0_count + granule.region1_count + 2).min(22) as usize; + (starts[r0] as usize, starts[r1] as usize) + }; + let big = granule.big_values as usize * 2; + let mut index = 0usize; + let mut pair = [0.0f32; 2]; + while index < big { + let region = if index < region1 { + 0 + } else if index < region2 { + 1 + } else { + 2 + }; + let select = usize::from(granule.table_select[region]); + let table = huffman::big_table(select)?; + if table.codes.is_empty() { + index += 2; + continue; + } + if reader.bit_position() >= end_bit { + break; + } + huffman::decode_pair(reader, select, table, &mut pair)?; + is[index] = pair[0] as i32; + is[index + 1] = pair[1] as i32; + index += 2; + } + let mut quad = [0.0f32; 4]; + while index + 4 <= 576 && reader.bit_position() < end_bit { + let before = reader.bit_position(); + if huffman::decode_quad(reader, granule.count1table_select, &mut quad).is_err() { + break; + } + if reader.bit_position() > end_bit { + // The last quadruple ran past the granule: encoders are allowed + // to leave it there, and its values are not part of the + // spectrum. + let _ = before; + break; + } + for (slot, value) in is[index..index + 4].iter_mut().zip(quad) { + *slot = value as i32; + } + index += 4; + } + Ok(()) + } + + fn requantise(&mut self, header: &FrameHeader, granule: &GranuleInfo, ch: usize) { + let power = power43(); + let xr = &mut self.xr[ch]; + let is = &self.is[ch]; + let short = granule.window_switching && granule.block_type == 2; + let multiplier = if granule.scalefac_scale { 1.0 } else { 0.5 }; + let base = (granule.global_gain as f32 - 210.0) * 0.25; + let value = |v: i32| -> f32 { + let magnitude = power[(v.unsigned_abs() as usize).min(MAX_QUANT)]; + if v < 0 { -magnitude } else { magnitude } + }; + xr.fill(0.0); + let long_bands = if !short { + 22 + } else if granule.mixed_block { + // Mixed blocks keep the first two subbands long, which is 36 + // coefficients: eight bands at an MPEG-1 rate, six at an LSF one. + if header.version == Version::Mpeg1 { + 8 + } else { + 6 + } + } else { + 0 + }; + let starts = long_starts(header.sample_rate); + for sfb in 0..long_bands { + let (from, to) = (starts[sfb] as usize, starts[sfb + 1] as usize); + let mut sf = f32::from(self.scalefac_l[ch][sfb]); + if granule.preflag { + sf += f32::from(PRETAB[sfb]); + } + let gain = (base - multiplier * sf).exp2(); + for i in from..to.min(576) { + xr[i] = value(is[i]) * gain; + } + } + if short { + // Short blocks arrive band by band, window by window, and land in a + // spectrum whose three windows interleave line by line: bitstream + // index (sfb, window, line) becomes 3 * (band start + line) + + // window, which is the order the short IMDCT reads back. + let widths = short_widths(header.sample_rate); + let starts = short_starts(header.sample_rate); + let first = if granule.mixed_block { 3 } else { 0 }; + let mut index = if granule.mixed_block { 36 } else { 0 }; + for sfb in first..13 { + let width = widths[sfb] as usize; + let band_start = starts[sfb] as usize; + for window in 0..3 { + let sf = f32::from(self.scalefac_s[ch][sfb][window]); + let gain = + (base - 2.0 * granule.subblock_gain[window] as f32 - multiplier * sf) + .exp2(); + for line in 0..width { + if index >= 576 { + break; + } + let target = (band_start + line) * 3 + window; + if target < 576 { + xr[target] = value(is[index]) * gain; + } + index += 1; + } + } + } + } + } + + fn stereo(&mut self, header: &FrameHeader, side: &SideInfo, gr: usize) { + if header.channels() != 2 { + return; + } + let joint = header.mode == ChannelMode::JointStereo; + let ms = joint && header.mode_ext & 2 != 0; + let intensity = joint && header.mode_ext & 1 != 0; + let granule = side.granules[gr][0]; + let short = granule.window_switching && granule.block_type == 2; + // Intensity coding starts at the first band above the right channel's + // last non-zero line. + let bound = if intensity { + let last = (0..576) + .rev() + .find(|&i| self.is[1][i] != 0) + .map_or(0, |i| i + 1); + let starts = long_starts(header.sample_rate); + starts + .iter() + .find(|&&s| usize::from(s) >= last) + .map_or(576, |s| usize::from(*s)) + } else { + 576 + }; + if ms { + const INV_SQRT2: f32 = std::f32::consts::FRAC_1_SQRT_2; + for i in 0..bound { + let (m, s) = (self.xr[0][i], self.xr[1][i]); + self.xr[0][i] = (m + s) * INV_SQRT2; + self.xr[1][i] = (m - s) * INV_SQRT2; + } + } + if intensity && bound < 576 { + let starts = long_starts(header.sample_rate); + for sfb in 0..22 { + let (from, to) = (starts[sfb] as usize, starts[sfb + 1] as usize); + if from < bound { + continue; + } + let is_pos = if short { + u32::from(self.scalefac_s[1][sfb.min(12)][0]) + } else { + u32::from(self.scalefac_l[1][sfb]) + }; + if is_pos >= 7 { + continue; // 7 is not a legal position; leave the band alone + } + let ratio = (std::f32::consts::PI / 12.0 * is_pos as f32).tan(); + let (kl, kr) = (ratio / (1.0 + ratio), 1.0 / (1.0 + ratio)); + for i in from..to.min(576) { + let value = self.xr[0][i]; + self.xr[0][i] = value * kl; + self.xr[1][i] = value * kr; + } + } + } + } + + fn synthesise( + &mut self, + granule: &GranuleInfo, + ch: usize, + gr: usize, + channels: usize, + out: &mut [f32], + ) { + let short = granule.window_switching && granule.block_type == 2; + let alias_bands = if !short { + 32 + } else if granule.mixed_block { + 2 + } else { + 1 + }; + alias_reduce(&mut self.xr[ch][..], alias_bands); + let mut block = [0.0f32; 36]; + let mut slots = [[0.0f32; 32]; 18]; + // The transpose (subband-major in, slot-major out) is the point of + // this loop, so it indexes both ways on purpose. + #[allow(clippy::needless_range_loop)] + for sb in 0..32 { + let coefficients = &self.xr[ch][sb * 18..sb * 18 + 18]; + if short && !(granule.mixed_block && sb < 2) { + self.imdct.short(coefficients, &mut block); + } else { + let block_type = if short { 0 } else { granule.block_type }; + self.imdct.long(coefficients, block_type, &mut block); + } + let overlap = &mut self.overlap[ch][sb]; + for t in 0..18 { + let mut sample = block[t] + overlap[t]; + overlap[t] = block[18 + t]; + if sb % 2 == 1 && t % 2 == 1 { + sample = -sample; + } + slots[t][sb] = sample; + } + } + let mut pcm = [0.0f32; 32]; + for (t, slot) in slots.iter().enumerate() { + self.synthesis[ch].slot(slot, &mut pcm); + let base = (gr * 18 + t) * 32 * channels + ch; + for (j, sample) in pcm.iter().enumerate() { + out[base + j * channels] = *sample; + } + } + } +} + +/// Turns a byte stream into frames: skips ID3v2 and the Xing/LAME/VBRI header +/// frame, resyncs over junk, and holds partial data until the rest arrives. +#[derive(Debug, Default)] +pub struct Mp3Reader { + decoder: Mp3Decode, + buffer: Vec, + consumed: usize, + started: bool, +} + +impl Mp3Reader { + /// An empty reader. + pub fn new() -> Mp3Reader { + Mp3Reader::default() + } + + /// Appends bytes to decode. + pub fn push(&mut self, bytes: &[u8]) { + if self.consumed > 0 { + self.buffer.drain(..self.consumed); + self.consumed = 0; + } + self.buffer.extend_from_slice(bytes); + } + + /// Drops buffered input and decoder history. + pub fn reset(&mut self) { + self.buffer.clear(); + self.consumed = 0; + self.started = false; + self.decoder.reset(); + } + + /// The next frame, or [`Error::NeedMore`] when the buffer holds only part + /// of one. + pub fn next_frame(&mut self) -> Result { + loop { + let data = &self.buffer[self.consumed..]; + if data.len() < 4 { + return Err(Error::NeedMore); + } + if !self.started && data.starts_with(b"ID3") { + if data.len() < 10 { + return Err(Error::NeedMore); + } + let size = data[6..10] + .iter() + .fold(0usize, |acc, b| (acc << 7) | usize::from(b & 0x7F)); + let total = 10 + size; + if data.len() < total { + return Err(Error::NeedMore); + } + self.consumed += total; + continue; + } + let Ok(header) = FrameHeader::parse(data) else { + self.consumed += 1; + continue; + }; + let Some(frame_len) = header.frame_len() else { + return Err(Error::unsupported( + "free-format MPEG audio", + "no bitrate index, so the frame length is only knowable by scanning", + )); + }; + if header.layer != 3 { + self.consumed += 1; + continue; + } + if data.len() < frame_len { + return Err(Error::NeedMore); + } + let frame = &data[..frame_len]; + if !self.started && is_info_frame(&header, frame) { + self.started = true; + self.consumed += frame_len; + continue; + } + self.started = true; + let decoded = self.decoder.decode_frame(frame); + self.consumed += frame_len; + return decoded; + } + } + + /// Decodes everything buffered, stopping at the first incomplete frame. + pub fn decode_all(&mut self) -> Vec { + let mut out = Vec::new(); + while let Ok(frame) = self.next_frame() { + out.push(frame); + } + out + } +} + +/// True for the Xing/Info/VBRI header frame every VBR encoder puts first: it +/// carries a tag rather than audio, and decoding it would prepend a frame of +/// silence no other decoder emits. +fn is_info_frame(header: &FrameHeader, frame: &[u8]) -> bool { + let side = 4 + usize::from(header.crc) * 2 + header.side_info_len(); + let tagged = |at: usize, tag: &[u8]| frame.len() >= at + 4 && &frame[at..at + 4] == tag; + tagged(side, b"Xing") || tagged(side, b"Info") || tagged(36, b"VBRI") +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn id3v2_and_junk_are_skipped_before_the_first_frame() { + let mut reader = Mp3Reader::new(); + let mut stream = b"ID3\x04\x00\x00\x00\x00\x00\x05hello".to_vec(); + stream.extend_from_slice(&[0x00, 0x11, 0x22]); // junk before sync + assert!(reader.next_frame().is_err()); + reader.push(&stream); + assert!(matches!(reader.next_frame(), Err(Error::NeedMore))); + } +} diff --git a/crates/ec-mp3/src/encode.rs b/crates/ec-mp3/src/encode.rs new file mode 100644 index 00000000..d94fdc83 --- /dev/null +++ b/crates/ec-mp3/src/encode.rs @@ -0,0 +1,1207 @@ +//! Layer III encoding: analysis filterbank, MDCT with block switching, a +//! masking model, the two quantisation loops and the bit reservoir. +//! +//! **The psychoacoustic model, stated plainly.** Per granule and channel it +//! takes one 1024-point real FFT of the sine-windowed input, sums the power +//! spectrum into the granule's scalefactor bands, spreads that energy across +//! neighbouring bands with a one-sided exponential (about 25 dB/band up, 10 +//! dB/band down), and sets each band's allowed noise to the spread energy +//! minus a signal-to-mask offset that follows a spectral-flatness tonality +//! estimate — 21 dB where the band looks tonal, 6 dB where it looks like +//! noise — floored by an absolute-threshold curve. It has no temporal +//! spreading, no pre-echo control beyond block switching, and no inter-channel +//! masking; those are the honest gaps against a full ISO Model 2. +//! +//! The outer (distortion) loop amplifies the scalefactors of bands whose +//! quantisation noise exceeds that threshold; the inner (rate) loop raises +//! `global_gain` until the Huffman-coded granule fits the bits the reservoir +//! makes available. + +use crate::filterbank::{Analysis, alias_expand}; +use crate::header::{ChannelMode, FrameHeader, Version}; +use crate::huffman::{self, Table}; +use crate::tables::{MAX_QUANT, SLEN, long_starts, power43, short_starts, windows}; +use ec_core::bitio::BitWriter; +use ec_core::error::{Error, Result}; +use ec_dsp::{RealFft, Window}; + +/// Encoder settings. +/// +/// The field names match the incumbent `rusty_mp3` shim's, because the replica +/// swaps one for the other without touching call sites. +#[derive(Clone, Copy, Debug, Default, PartialEq)] +pub struct Mp3EncoderConfig { + /// Target bitrate in kbit/s, snapped to the nearest legal Layer III rate. + pub bitrate_kbps: u32, + /// Quality on a 0..1 scale instead of a bitrate. + /// + /// corner-cut: this picks a constant bitrate from the quality rather than + /// varying the rate per frame — the streams are legal and decode + /// everywhere, they just do not spend fewer bits on easy frames. Upgrade + /// path is a per-frame bitrate index chosen after the rate loop, which the + /// frame writer here already supports (it writes the header last). + pub vbr_quality: Option, +} + +const BITRATES_V1: [u32; 14] = [ + 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, +]; +const BITRATES_V2: [u32; 14] = [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; + +/// The legal Layer III bitrate nearest to `kbps` for this stream. +pub fn snap_bitrate(version: Version, kbps: u32) -> u32 { + let table: &[u32] = if version == Version::Mpeg1 { + &BITRATES_V1 + } else { + &BITRATES_V2 + }; + *table + .iter() + .min_by_key(|&&r| r.abs_diff(kbps)) + .expect("bitrate table is not empty") +} + +/// The bitrate a `vbr_quality` in `[0, 1]` asks for, in kbit/s. +pub fn bitrate_for_quality(quality: f32) -> u32 { + let q = quality.clamp(0.0, 1.0); + // 0.0 -> 96 kbit/s, 0.5 -> 192, 1.0 -> 320. + (96.0 + q * 224.0).round() as u32 +} + +const SFB_LONG: usize = 21; + +/// One granule's worth of coded spectrum plus the side info describing it. +#[derive(Clone, Debug)] +struct CodedGranule { + bits: Vec, + part2_3_length: u32, + big_values: u32, + global_gain: u32, + scalefac_compress: u32, + block_type: u8, + table_select: [u8; 3], + region0_count: u32, + region1_count: u32, + scalefac_scale: bool, + count1table_select: bool, +} + +/// The stateful encoder core: PCM in, Layer III frames out. +#[derive(Debug)] +pub struct Mp3Encode { + sample_rate: u32, + channels: usize, + bitrate_kbps: u32, + version: Version, + mode: ChannelMode, + analysis: Vec, + /// Subband slots waiting for their MDCT, per channel. + slots: Vec>, + /// The previous granule's subband slots, for the 36-sample MDCT window. + history: Vec<[[f32; 32]; 18]>, + /// Window type chosen for the granule we are holding back. + pending: Vec, + fft: RealFft, + fft_window: Window, + psy_history: Vec>, + /// The main-data byte stream and how much of it frames have carried. + stream: Vec, + used: usize, + /// Stream bytes already assigned to a frame's payload, decided or not. + assigned: usize, + /// Stream bytes already written out in a frame. + written: usize, + /// Frames whose header and side info are decided but whose payload is + /// still being filled: the bit reservoir means a frame's payload carries + /// the *next* frame's granule data, so emission runs one frame behind. + queued: std::collections::VecDeque<(Vec, Vec)>, + ready: std::collections::VecDeque>, + frames: u32, +} + +#[derive(Clone, Debug)] +struct PendingGranule { + subband: Vec<[f32; 32]>, + energy: f32, + threshold: Vec, +} + +impl Mp3Encode { + /// An encoder for this stream shape. Rates outside 8..48 kHz have no Layer + /// III frame and are refused by name. + pub fn new(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Result { + let version = match sample_rate { + 32000 | 44100 | 48000 => Version::Mpeg1, + 16000 | 22050 | 24000 => Version::Mpeg2, + 8000 | 11025 | 12000 => Version::Mpeg25, + other => { + return Err(Error::unsupported( + format!("{other} Hz MPEG audio"), + "Layer III frames exist only for 8, 11.025, 12, 16, 22.05, 24, 32, 44.1 and 48 kHz", + )); + } + }; + if channels == 0 || channels > 2 { + return Err(Error::unsupported( + format!("{channels}-channel MP3"), + "Layer III carries one or two channels", + )); + } + Ok(Mp3Encode { + sample_rate, + channels, + bitrate_kbps: snap_bitrate(version, bitrate_kbps), + version, + mode: if channels == 2 { + ChannelMode::JointStereo + } else { + ChannelMode::Mono + }, + analysis: (0..channels).map(|_| Analysis::default()).collect(), + slots: vec![Vec::new(); channels], + history: vec![[[0.0; 32]; 18]; channels], + pending: Vec::new(), + fft: RealFft::new(1024), + fft_window: Window::sine(1024), + psy_history: vec![vec![0.0; 1024]; channels], + stream: Vec::new(), + used: 0, + assigned: 0, + written: 0, + queued: std::collections::VecDeque::new(), + ready: std::collections::VecDeque::new(), + frames: 0, + }) + } + + /// The header every frame of this stream carries. + fn header(&self) -> FrameHeader { + FrameHeader { + version: self.version, + layer: 3, + crc: false, + bitrate_kbps: self.bitrate_kbps, + sample_rate: self.sample_rate, + padding: false, + private: false, + mode: self.mode, + mode_ext: 0, + copyright: false, + original: true, + emphasis: 0, + } + } + + /// Granules per frame for this stream. + pub fn granules(&self) -> usize { + self.header().granules() + } + + /// Samples per channel one frame codes. + pub fn frame_samples(&self) -> usize { + self.granules() * 576 + } +} + +/// Interleaved PCM in, complete frames out. +#[derive(Debug)] +pub struct Mp3Encoder { + core: Option, + config: Mp3EncoderConfig, + pcm: Vec, + frames: std::collections::VecDeque>, + finished: bool, + header_written: bool, + total_samples: u64, +} + +impl Mp3Encoder { + /// An encoder that configures itself from the first PCM it is given. + pub fn new(config: Mp3EncoderConfig) -> Mp3Encoder { + Mp3Encoder { + core: None, + config, + pcm: Vec::new(), + frames: std::collections::VecDeque::new(), + finished: false, + header_written: false, + total_samples: 0, + } + } + + /// Feeds interleaved `f32` samples in `[-1, 1]`. + pub fn push_pcm_f32( + &mut self, + interleaved: &[f32], + channels: u16, + sample_rate: u32, + ) -> Result<()> { + if self.core.is_none() { + let bitrate = match self.config.vbr_quality { + Some(q) => bitrate_for_quality(q), + None => self.config.bitrate_kbps.max(8), + }; + self.core = Some(Mp3Encode::new(sample_rate, usize::from(channels), bitrate)?); + } + self.pcm.extend_from_slice(interleaved); + self.total_samples += (interleaved.len() / usize::from(channels.max(1))) as u64; + self.drain(false); + Ok(()) + } + + /// Feeds interleaved 16-bit samples, scaled the way every decoder here + /// scales them. + pub fn push_pcm_s16( + &mut self, + interleaved: &[i16], + channels: u16, + sample_rate: u32, + ) -> Result<()> { + let floats: Vec = interleaved + .iter() + .map(|s| f32::from(*s) / 32768.0) + .collect(); + self.push_pcm_f32(&floats, channels, sample_rate) + } + + /// Ends the stream: pads the tail to a whole frame and flushes. + pub fn finish(&mut self) { + if let Some(core) = &self.core { + let channels = core.channels; + // The filterbank runs fifteen slots behind, and the MDCT one + // granule behind that; feed silence so the last real samples come + // out the other end. + let tail = vec![0.0f32; channels * (576 * 2 + 480)]; + self.pcm.extend_from_slice(&tail); + } + self.drain(true); + self.finished = true; + } + + fn drain(&mut self, flush: bool) { + let Some(core) = self.core.as_mut() else { + return; + }; + let channels = core.channels; + let need = core.frame_samples() * channels; + while self.pcm.len() >= need { + let block: Vec = self.pcm.drain(..need).collect(); + core.encode_block(&block); + } + if flush { + if !self.pcm.is_empty() { + let mut block = std::mem::take(&mut self.pcm); + block.resize(need, 0.0); + core.encode_block(&block); + } + core.flush_frames(); + } + while let Some(frame) = core.ready.pop_front() { + self.frames.push_back(frame); + } + } + + /// The next complete frame, [`Error::Eof`] once drained after + /// [`Mp3Encoder::finish`], [`Error::NeedMore`] before that. + pub fn next_packet(&mut self) -> Result> { + if !self.header_written && (self.finished || !self.frames.is_empty()) { + self.header_written = true; + if let Some(core) = &self.core { + return Ok(info_frame(core, self.total_samples)); + } + } + match self.frames.pop_front() { + Some(frame) => Ok(frame), + None if self.finished => Err(Error::Eof), + None => Err(Error::NeedMore), + } + } +} + +/// The Xing/Info header frame every player expects first: a silent frame whose +/// main data is the tag, so a decoder that does not know the tag still decodes +/// a legal (silent) frame rather than choking. +fn info_frame(core: &Mp3Encode, samples: u64) -> Vec { + let header = core.header(); + let frame_len = header.frame_len().unwrap_or(417); + let mut out = vec![0u8; frame_len]; + out[..4].copy_from_slice(&header.to_bytes()); + let at = 4 + header.side_info_len(); + let tag: &[u8] = b"Info"; + out[at..at + 4].copy_from_slice(tag); + out[at + 4..at + 8].copy_from_slice(&1u32.to_be_bytes()); // frames field present + let frames = samples.div_ceil(header.samples_per_frame() as u64) as u32; + out[at + 8..at + 12].copy_from_slice(&frames.to_be_bytes()); + out +} + +impl Mp3Encode { + /// Encodes one frame's worth of interleaved PCM. + fn encode_block(&mut self, pcm: &[f32]) { + let channels = self.channels; + let granules = self.granules(); + // Polyphase analysis, one channel at a time. + for ch in 0..channels { + let mut mono: Vec = Vec::with_capacity(pcm.len() / channels); + for frame in pcm.chunks(channels) { + mono.push(frame[ch]); + } + for chunk in mono.chunks(32) { + if chunk.len() < 32 { + break; + } + if let Some(slot) = self.analysis[ch].push(chunk) { + self.slots[ch].push(slot); + } + } + self.psy_push(ch, &mono); + } + // A granule is 18 slots; hold one back so block switching can look + // ahead at the next granule's energy. + let ready = self.slots[0].len() / 18; + if ready == 0 { + return; + } + for _ in 0..ready { + for ch in 0..channels { + let subband: Vec<[f32; 32]> = self.slots[ch].drain(..18).collect(); + let energy: f32 = subband + .iter() + .flat_map(|slot| slot.iter()) + .map(|v| v * v) + .sum(); + let threshold = self.psy_threshold(ch); + self.pending.push(PendingGranule { + subband, + energy, + threshold, + }); + } + } + // Emit whole frames while a lookahead granule remains. + let per_frame = granules * channels; + while self.pending.len() >= per_frame + channels { + self.emit_frame(); + } + } + + /// One FFT per granule of input, kept for the masking model. + fn psy_push(&mut self, ch: usize, mono: &[f32]) { + let n = 1024.min(mono.len()); + let history = &mut self.psy_history[ch]; + history.copy_within(n.., 0); + let keep = 1024 - n; + history[keep..].copy_from_slice(&mono[mono.len() - n..]); + } + + /// Allowed noise per long scalefactor band, from the masking model. + fn psy_threshold(&mut self, ch: usize) -> Vec { + let mut block: Vec = self.psy_history[ch].clone(); + self.fft_window.apply(&mut block); + let mut spectrum = vec![ec_dsp::Complex::::ZERO; 513]; + self.fft.forward(&block, &mut spectrum); + let starts = long_starts(self.sample_rate); + let mut energy = vec![0.0f32; SFB_LONG]; + for (band, slot) in energy.iter_mut().enumerate() { + // The 576 coefficients of a granule map onto 512 FFT bins. + let from = usize::from(starts[band]) * 512 / 576; + let to = (usize::from(starts[band + 1]) * 512 / 576).max(from + 1); + let mut sum = 0.0f32; + let mut log_sum = 0.0f32; + let mut count = 0.0f32; + for bin in &spectrum[from..to.min(512)] { + let power = bin.norm_sqr() + 1e-30; + sum += power; + log_sum += power.ln(); + count += 1.0; + } + // Spectral flatness as a tonality proxy: a flat band is noise-like + // and masks less. + let flatness = if count > 0.0 { + ((log_sum / count).exp() / (sum / count)).clamp(0.0, 1.0) + } else { + 1.0 + }; + let offset_db = 6.0 + 15.0 * (1.0 - flatness); + *slot = sum * 10f32.powf(-offset_db / 10.0); + } + // Spreading: masking leaks upward strongly and downward weakly. + let mut spread = energy.clone(); + for band in 1..SFB_LONG { + let leak = spread[band - 1] * 0.0032; // about -25 dB per band + spread[band] = spread[band].max(leak); + } + for band in (0..SFB_LONG - 1).rev() { + let leak = spread[band + 1] * 0.1; // about -10 dB per band + spread[band] = spread[band].max(leak); + } + // Absolute threshold, coarse: hearing is least sensitive at the ends. + for (band, slot) in spread.iter_mut().enumerate() { + let rel = band as f32 / SFB_LONG as f32; + let floor = 1e-9 * (1.0 + 400.0 * (rel - 0.35).max(0.0).powi(2)); + *slot = slot.max(floor); + } + spread + } + + fn emit_frame(&mut self) { + let channels = self.channels; + let granules = self.granules(); + let header = self.header(); + let frame_len = header.frame_len().unwrap_or(0); + let capacity = frame_len - 4 - header.side_info_len(); + + // Window types: a granule whose successor is much louder starts the + // switch, the loud one is short, and the one after stops it. + let mut types = vec![0u8; granules * channels]; + for gr in 0..granules { + for ch in 0..channels { + let index = gr * channels + ch; + let next = index + channels; + let here = self.pending[index].energy; + let there = self.pending.get(next).map_or(here, |g| g.energy); + if there > here * 8.0 + 1e-6 { + types[index] = 1; // start + } + } + } + for gr in 0..granules { + for ch in 0..channels { + let index = gr * channels + ch; + if index >= channels && types[index - channels] == 1 { + types[index] = 2; // short + } else if index >= 2 * channels && types[index - 2 * channels] == 2 { + types[index] = 3; // stop + } + } + } + + let begin = self.assigned - self.used; + let budget_bits = (self.assigned + capacity - self.used) * 8; + let mut coded: Vec = Vec::with_capacity(granules * channels); + let share = budget_bits / (granules * channels).max(1); + for gr in 0..granules { + for ch in 0..channels { + let index = gr * channels + ch; + let granule = self.pending[index].clone(); + let xr = self.mdct(ch, &granule.subband, types[index]); + let spent: usize = coded.iter().map(|c| c.part2_3_length as usize).sum(); + let left = budget_bits.saturating_sub(spent); + let target = share.min(left).min(4095); + coded.push(quantise_granule( + &xr, + types[index], + target as u32, + &granule.threshold, + self.sample_rate, + )); + } + } + self.pending.drain(..granules * channels); + + // Assemble the frame: header, side info, and this frame's window on + // the main-data stream. + let mut side = BitWriter::new(); + side.write_bits( + begin as u32, + if self.version == Version::Mpeg1 { 9 } else { 8 }, + ); + let private = match (self.version == Version::Mpeg1, channels) { + (true, 1) => 5, + (true, _) => 3, + (false, 1) => 1, + (false, _) => 2, + }; + side.write_bits(0, private); + if self.version == Version::Mpeg1 { + side.write_bits(0, 4 * channels as u32); // scfsi: never reuse + } + for granule in &coded { + side.write_bits(granule.part2_3_length, 12); + side.write_bits(granule.big_values, 9); + side.write_bits(granule.global_gain, 8); + side.write_bits( + granule.scalefac_compress, + if self.version == Version::Mpeg1 { 4 } else { 9 }, + ); + if granule.block_type == 0 { + side.write_bit(false); + for table in granule.table_select { + side.write_bits(u32::from(table), 5); + } + side.write_bits(granule.region0_count, 4); + side.write_bits(granule.region1_count, 3); + } else { + side.write_bit(true); + side.write_bits(u32::from(granule.block_type), 2); + side.write_bit(false); // mixed_block_flag + for table in &granule.table_select[..2] { + side.write_bits(u32::from(*table), 5); + } + side.write_bits(0, 9); // subblock_gain + } + if self.version == Version::Mpeg1 { + side.write_bit(false); // preflag + } + side.write_bit(granule.scalefac_scale); + side.write_bit(granule.count1table_select); + } + side.align_to_byte(); + let side_bytes = side.into_bytes(); + debug_assert_eq!(side_bytes.len(), header.side_info_len()); + + // Append the granule data to the stream at `used`, byte aligned. + let mut main = BitWriter::new(); + for granule in &coded { + for bit in &granule.bits { + main.write_bit(*bit); + } + } + main.align_to_byte(); + let main_bytes = main.into_bytes(); + // Stream positions the reservoir cap skipped over are stuffing, not + // data, so they are zeros rather than a shorter stream. + if self.stream.len() < self.used { + self.stream.resize(self.used, 0); + } + self.stream.truncate(self.used); + self.stream.extend_from_slice(&main_bytes); + self.used += main_bytes.len(); + + self.queued + .push_back((header.to_bytes().to_vec(), side_bytes)); + self.assigned += capacity; + // A queued frame can only go out once real granule data covers its + // whole payload; padding it early is what would strand the next + // frame's `main_data_begin` in bytes that were already written. + while !self.queued.is_empty() && self.stream.len() >= self.written + capacity { + let (head, side) = self.queued.pop_front().expect("queue is not empty"); + let mut frame = Vec::with_capacity(frame_len); + frame.extend_from_slice(&head); + frame.extend_from_slice(&side); + frame.extend_from_slice(&self.stream[self.written..self.written + capacity]); + self.written += capacity; + self.ready.push_back(frame); + self.frames += 1; + } + // main_data_begin is nine bits, so the reservoir cannot reach further + // back than 511 bytes; anything older is dropped rather than pointed at. + if self.assigned > self.used + 511 { + self.used = self.assigned - 511; + } + } + + /// Writes out whatever frames are still queued, padding the stream so the + /// last frame is complete. + fn flush_frames(&mut self) { + let header = self.header(); + let frame_len = header.frame_len().unwrap_or(0); + let capacity = frame_len - 4 - header.side_info_len(); + while let Some((head, side)) = self.queued.pop_front() { + if self.stream.len() < self.written + capacity { + self.stream.resize(self.written + capacity, 0); + } + let mut frame = Vec::with_capacity(frame_len); + frame.extend_from_slice(&head); + frame.extend_from_slice(&side); + frame.extend_from_slice(&self.stream[self.written..self.written + capacity]); + self.written += capacity; + self.ready.push_back(frame); + self.frames += 1; + } + } + + /// One granule of subband samples to 576 spectral lines. + fn mdct(&mut self, ch: usize, subband: &[[f32; 32]], block_type: u8) -> Vec { + let mut xr = vec![0.0f32; 576]; + let history = self.history[ch]; + for sb in 0..32 { + // The transform window is the previous granule's 18 samples + // followed by this granule's, with the frequency inversion the + // decoder applies undone first. + let mut input = [0.0f32; 36]; + for t in 0..18 { + let sign = if sb % 2 == 1 && t % 2 == 1 { -1.0 } else { 1.0 }; + input[t] = history[t][sb] * sign; + input[18 + t] = subband[t][sb] * sign; + } + let out = &mut xr[sb * 18..sb * 18 + 18]; + if block_type == 2 { + mdct_short(&input, out); + } else { + mdct_long(&input, block_type, out); + } + } + if block_type != 2 { + alias_expand(&mut xr, 32); + } + let mut store = [[0.0f32; 32]; 18]; + store[..18].copy_from_slice(&subband[..18]); + self.history[ch] = store; + xr + } +} + +/// Forward MDCT, 36 samples to 18 coefficients, scaled so the decoder's +/// unscaled inverse reconstructs the input under overlap-add. +fn mdct_long(input: &[f32; 36], block_type: u8, out: &mut [f32]) { + let window = &windows()[usize::from(block_type)]; + let mut windowed = [0.0f32; 36]; + for i in 0..36 { + windowed[i] = input[i] * window[i]; + } + for (k, slot) in out.iter_mut().enumerate() { + let mut sum = 0.0f64; + for (n, value) in windowed.iter().enumerate() { + let angle = std::f64::consts::PI / 72.0 * ((2 * n + 19) * (2 * k + 1)) as f64; + sum += f64::from(*value) * angle.cos(); + } + *slot = (sum / 9.0) as f32; + } +} + +/// Forward MDCT for a short block: three 12-sample transforms, interleaved +/// into the spectrum the way the decoder reads them back. +fn mdct_short(input: &[f32; 36], out: &mut [f32]) { + let window = &windows()[2]; + for w in 0..3 { + for k in 0..6 { + let mut sum = 0.0f64; + for n in 0..12 { + let sample = input[6 + 6 * w + n] * window[n]; + let angle = std::f64::consts::PI / 24.0 * ((2 * n + 7) * (2 * k + 1)) as f64; + sum += f64::from(sample) * angle.cos(); + } + out[k * 3 + w] = (sum / 3.0) as f32; + } + } +} + +/// Quantises one granule: the rate loop inside the distortion loop. +fn quantise_granule( + xr: &[f32], + block_type: u8, + target_bits: u32, + threshold: &[f32], + sample_rate: u32, +) -> CodedGranule { + let mut scalefac = [0u8; SFB_LONG]; + let mut best: Option<(CodedGranule, f64)> = None; + // The distortion loop. Two things end it: every band is under its masking + // threshold *and* the bits are spent, or no band can be amplified further. + // Spending the bits matters as much as the threshold does — a granule that + // stops early leaves the extra bitrate on the floor, which is what makes an + // encoder's quality flat across 128 and 320 kbit/s. + for _round in 0..20 { + let (granule, noise) = code_with(xr, block_type, target_bits, &scalefac, sample_rate); + let ratios: Vec = (0..SFB_LONG) + .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30)) + .collect(); + let score: f64 = ratios.iter().sum(); + let spent = granule.part2_3_length; + if best.as_ref().is_none_or(|(_, s)| score < *s) { + best = Some((granule, score)); + } + if block_type == 2 { + break; // short blocks carry no long scalefactors here + } + if spent * 20 > target_bits * 19 { + break; // the budget is spent; amplifying now only coarsens + } + // Amplify the bands that are worst against their threshold. + let mut order: Vec = (0..SFB_LONG).filter(|&b| scalefac[b] < 15).collect(); + order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a])); + let over: Vec = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect(); + let chosen: Vec = if over.is_empty() { + order.iter().copied().take(3).collect() + } else { + over + }; + if chosen.is_empty() { + break; + } + for band in chosen { + scalefac[band] += 1; + } + } + best.expect("at least one round runs").0 +} + +/// Quantises with a fixed scalefactor set, running the rate loop on +/// `global_gain`, and reports the noise each band ends up with. +fn code_with( + xr: &[f32], + block_type: u8, + budget_bits: u32, + scalefac: &[u8; SFB_LONG], + sample_rate: u32, +) -> (CodedGranule, [f32; SFB_LONG]) { + let (slen1, slen2, compress) = scalefac_compress(scalefac); + // The scalefactors come out of the same budget as the spectrum does. + let scalefac_bits = if block_type == 2 { + 0 + } else { + slen1 * 11 + slen2 * 10 + }; + let target_bits = budget_bits.saturating_sub(scalefac_bits); + let peak = xr.iter().fold(0.0f32, |acc, v| acc.max(v.abs())); + // A starting gain that puts the loudest line near the top of the coded + // range: |xr| / 2^((g-210)/4) raised to 3/4 should land around 8000. + let start = if peak > 1e-20 { + (210.0 + 4.0 * (peak.log2() - 13.0 / 0.75)).round() as i32 + } else { + 210 + }; + let mut gain = start.clamp(0, 255); + let mut ix = vec![0i32; 576]; + let mut coded; + // The rate loop runs both ways: down while there are bits to spare, up + // while the granule is too big for them. A line that saturates the coding + // range is not "cheap", it is clipped, so that check comes first. + let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191); + quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix); + coded = code_spectrum(&ix, block_type, sample_rate); + loop { + if (saturated(&ix) || coded.0 > target_bits) && gain < 255 { + gain += 1; + quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix); + coded = code_spectrum(&ix, block_type, sample_rate); + continue; + } + if saturated(&ix) || coded.0 > target_bits || gain == 0 { + break; + } + // Try one step quieter; keep it only if it still fits and stays + // inside the coding range. + let mut trial = ix.clone(); + quantise(xr, gain - 1, scalefac, sample_rate, block_type, &mut trial); + let trial_coded = code_spectrum(&trial, block_type, sample_rate); + if trial_coded.0 > target_bits || saturated(&trial) { + break; + } + gain -= 1; + ix = trial; + coded = trial_coded; + } + // Last resort: if even the quietest legal gain will not fit the bits we + // were given, drop the top of the spectrum until it does. A granule that + // overruns its budget would corrupt the reservoir for every frame after + // it, which is far worse than a low-passed one. + let mut limit = 576usize; + while coded.0 > target_bits && limit > 4 { + limit = limit * 3 / 4; + for slot in ix.iter_mut().skip(limit) { + *slot = 0; + } + coded = code_spectrum(&ix, block_type, sample_rate); + } + let (_, big_values, tables, region0, region1, count1_select, bits) = coded; + let mut noise = [0.0f32; SFB_LONG]; + let starts = long_starts(sample_rate); + let power = power43(); + for band in 0..SFB_LONG { + let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1])); + let scale = band_gain(gain, scalefac[band], block_type); + let mut sum = 0.0f32; + for i in from..to.min(576) { + let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scale; + let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude }; + sum += (xr[i] - reconstructed).powi(2); + } + noise[band] = sum; + } + let mut out = BitWriter::new(); + for (band, value) in scalefac.iter().enumerate() { + let slen = if band < 11 { slen1 } else { slen2 }; + if block_type != 2 { + out.write_bits(u32::from(*value), slen); + } + } + let scalefac_bits = out.bit_len() as u32; + let mut bits_out: Vec = Vec::with_capacity((scalefac_bits + bits.len() as u32) as usize); + let bytes = out.into_bytes(); + for i in 0..scalefac_bits as usize { + bits_out.push((bytes[i / 8] >> (7 - i % 8)) & 1 == 1); + } + bits_out.extend_from_slice(&bits); + let granule = CodedGranule { + part2_3_length: bits_out.len() as u32, + bits: bits_out, + big_values, + global_gain: gain as u32, + scalefac_compress: compress, + block_type, + table_select: tables, + region0_count: region0, + region1_count: region1, + scalefac_scale: false, + count1table_select: count1_select, + }; + (granule, noise) +} + +fn band_gain(gain: i32, scalefac: u8, block_type: u8) -> f32 { + let base = (gain as f32 - 210.0) * 0.25; + if block_type == 2 { + base.exp2() + } else { + (base - 0.5 * f32::from(scalefac)).exp2() + } +} + +/// The spectrum as integers, per the decoder's requantisation read backwards. +fn quantise( + xr: &[f32], + gain: i32, + scalefac: &[u8; SFB_LONG], + sample_rate: u32, + block_type: u8, + ix: &mut [i32], +) { + let starts = long_starts(sample_rate); + // 22 bands, not 21: the topmost band carries no transmitted scalefactor, + // but it does carry audio — zeroing it low-passes the encoder at 16 kHz. + for band in 0..22 { + let (from, to) = ( + usize::from(starts[band]), + usize::from(starts[band + 1]).min(576), + ); + let scalefac = if band < SFB_LONG { scalefac[band] } else { 0 }; + let scale = 1.0 / band_gain(gain, scalefac, block_type); + for i in from..to { + let value = (xr[i].abs() * scale).powf(0.75); + let magnitude = (value + 0.4054).min(MAX_QUANT as f32) as i32; + ix[i] = if xr[i] < 0.0 { -magnitude } else { magnitude }; + } + } +} + +/// Chooses the region split, the tables and the count1 boundary, and writes the +/// spectrum. Returns the bit cost first so the rate loop can stop early. +#[allow(clippy::type_complexity)] +fn code_spectrum( + ix: &[i32], + block_type: u8, + sample_rate: u32, +) -> (u32, u32, [u8; 3], u32, u32, bool, Vec) { + // Trailing zeros are not coded at all; before them, a run of values in + // -1..=1 is coded four at a time. + let mut rzero = 576; + while rzero > 0 && ix[rzero - 1] == 0 { + rzero -= 1; + } + let count1_end = (rzero.div_ceil(4) * 4).min(576); + let mut count1_start = count1_end; + while count1_start >= 4 + && ix[count1_start - 4..count1_start] + .iter() + .all(|v| v.abs() <= 1) + { + count1_start -= 4; + } + let big_end = count1_start; + + let starts = long_starts(sample_rate); + let short = block_type == 2; + // Region boundaries land on band edges. Splitting the big-value region in + // three roughly equal parts is what makes the three tables specialise; + // searching every legal split costs far more than it saves. + let (region0, region1, bounds) = if short { + let first = usize::from(short_starts(sample_rate)[3]) * 3; + (8u32, 12u32, [first.min(big_end), big_end, big_end]) + } else { + let band_at = |target: usize| -> usize { + (0..21) + .min_by_key(|&b| usize::from(starts[b + 1]).abs_diff(target)) + .unwrap_or(7) + }; + let r0 = band_at(big_end / 3).min(15); + let r1 = band_at(big_end * 2 / 3).saturating_sub(r0 + 1).min(7); + let a = usize::from(starts[(r0 + 1).min(21)]).min(big_end); + let b = usize::from(starts[(r0 + r1 + 2).min(21)]).min(big_end); + (r0 as u32, r1 as u32, [a, b.max(a), big_end]) + }; + + let mut tables = [0u8; 3]; + let mut writer = BitWriter::new(); + let mut from = 0usize; + for (region, to) in bounds.iter().enumerate() { + let to = (*to).min(big_end); + if to > from { + let select = best_table(ix, from, to); + tables[region] = select; + let table = huffman::big_table(usize::from(select)).expect("table exists"); + let mut i = from; + while i + 1 < to { + huffman::write_pair(&mut writer, table, ix[i], ix[i + 1]); + i += 2; + } + } + from = to; + } + // count1: try both tables, keep the cheaper. + let quads: Vec<[i32; 4]> = (big_end..count1_end) + .step_by(4) + .filter(|i| i + 4 <= 576) + .map(|i| [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]]) + .collect(); + let cost = |select: bool| -> u32 { + quads + .iter() + .map(|quad| huffman::quad_bits(select, *quad)) + .sum() + }; + let count1_select = cost(true) < cost(false); + for quad in &quads { + huffman::write_quad(&mut writer, count1_select, *quad); + } + let bit_len = writer.bit_len() as usize; + let bytes = writer.into_bytes(); + let mut bits = Vec::with_capacity(bit_len); + for i in 0..bit_len { + bits.push((bytes[i / 8] >> (7 - i % 8)) & 1 == 1); + } + ( + bits.len() as u32, + (big_end / 2) as u32, + tables, + region0, + region1, + count1_select, + bits, + ) +} + +/// Tables that can code a region whose largest magnitude is `max`, cheapest +/// candidates first. Anything above 15 needs an escape-coded table, and the +/// escape tables differ only in how many linbits they spend. +fn candidates(max: u32) -> &'static [u8] { + match max { + 0..=1 => &[1, 2, 3, 5, 6, 7, 8, 9], + 2 => &[2, 3, 5, 6, 7, 8, 9, 10], + 3 => &[5, 6, 7, 8, 9, 10, 11, 12], + 4..=5 => &[7, 8, 9, 10, 11, 12, 13, 15], + 6..=7 => &[10, 11, 12, 13, 15], + 8..=15 => &[13, 15, 16, 24], + 16..=16 => &[16, 17, 18, 19, 20, 21, 22, 23, 24], + 17..=18 => &[17, 18, 19, 20, 21, 22, 23, 24, 25], + 19..=30 => &[18, 19, 20, 21, 22, 23, 25, 26, 27], + 31..=78 => &[20, 21, 22, 23, 26, 27, 28, 29], + 79..=270 => &[21, 22, 23, 28, 29, 30, 31], + 271..=1038 => &[22, 23, 30, 31], + _ => &[23, 31], + } +} + +/// The cheapest table for one region. +fn best_table(ix: &[i32], from: usize, to: usize) -> u8 { + let max = ix[from..to] + .iter() + .map(|v| v.unsigned_abs()) + .max() + .unwrap_or(0); + let mut best = (u32::MAX, 0u8); + for &select in candidates(max) { + let Ok(table) = huffman::big_table(usize::from(select)) else { + continue; + }; + if let Some(cost) = table_cost(ix, from, to, table) + && cost < best.0 + { + best = (cost, select); + } + } + if best.1 == 0 { + // Nothing in the shortlist fits, which only a value above the coding + // range can cause; fall back to the widest escape table. + return 23; + } + best.1 +} + +fn table_cost(ix: &[i32], from: usize, to: usize, table: Table) -> Option { + let mut sum = 0; + let mut i = from; + while i + 1 < to { + sum += huffman::pair_bits(table, ix[i].unsigned_abs(), ix[i + 1].unsigned_abs())?; + i += 2; + } + Some(sum) +} + +/// The `scalefac_compress` index whose two lengths hold these scalefactors. +fn scalefac_compress(scalefac: &[u8; SFB_LONG]) -> (u32, u32, u32) { + let bits_for = |slice: &[u8]| -> u32 { + let max = slice.iter().copied().max().unwrap_or(0); + (0..=4u32).find(|n| max < (1 << n)).unwrap_or(4) + }; + let need1 = bits_for(&scalefac[..11]); + let need2 = bits_for(&scalefac[11..]); + let mut best = (u32::MAX, 0u32, 0u32, 0u32); + for (index, (slen1, slen2)) in SLEN.iter().enumerate() { + if *slen1 >= need1 && *slen2 >= need2 { + let cost = slen1 * 11 + slen2 * 10; + if cost < best.0 { + best = (cost, *slen1, *slen2, index as u32); + } + } + } + (best.1, best.2, best.3) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn bitrates_snap_to_legal_values() { + assert_eq!(snap_bitrate(Version::Mpeg1, 128), 128); + assert_eq!(snap_bitrate(Version::Mpeg1, 130), 128); + assert_eq!(snap_bitrate(Version::Mpeg1, 1000), 320); + assert_eq!(snap_bitrate(Version::Mpeg2, 128), 128); + assert_eq!(snap_bitrate(Version::Mpeg2, 320), 160); + } + + #[test] + fn unsupported_rates_are_refused_by_name() { + let err = Mp3Encode::new(96000, 2, 128).unwrap_err(); + assert!(format!("{err}").contains("96000 Hz"), "{err}"); + } + + /// The encoder's whole analysis chain against the decoder's whole + /// synthesis chain, quantisation left out: what comes back is what went + /// in, delayed by the filterbank. + #[test] + fn analysis_chain_round_trips_through_the_decoder() { + use crate::filterbank::{Imdct, Synthesis, alias_reduce}; + let imdct = Imdct::default(); + let mut analysis = Analysis::default(); + let mut synthesis = Synthesis::default(); + let n = 32 * 32 * 24; + let input: Vec = (0..n) + .map(|i| { + let t = i as f32; + 0.4 * (t * 0.05).sin() + 0.2 * (t * 0.31).cos() + }) + .collect(); + let mut slots: Vec<[f32; 32]> = Vec::new(); + for chunk in input.chunks(32) { + if let Some(slot) = analysis.push(chunk) { + slots.push(slot); + } + } + let granules = slots.len() / 18; + let mut history = [[0.0f32; 32]; 18]; + let mut overlap = [[0.0f32; 18]; 32]; + let mut output: Vec = Vec::new(); + for g in 0..granules { + let granule = &slots[g * 18..g * 18 + 18]; + let mut xr = vec![0.0f32; 576]; + for sb in 0..32 { + let mut window = [0.0f32; 36]; + for t in 0..18 { + let sign = if sb % 2 == 1 && t % 2 == 1 { -1.0 } else { 1.0 }; + window[t] = history[t][sb] * sign; + window[18 + t] = granule[t][sb] * sign; + } + mdct_long(&window, 0, &mut xr[sb * 18..sb * 18 + 18]); + } + alias_expand(&mut xr, 32); + history.copy_from_slice(granule); + // decoder side + alias_reduce(&mut xr, 32); + let mut out_slots = [[0.0f32; 32]; 18]; + let mut block = [0.0f32; 36]; + for sb in 0..32 { + imdct.long(&xr[sb * 18..sb * 18 + 18], 0, &mut block); + for t in 0..18 { + let mut sample = block[t] + overlap[sb][t]; + overlap[sb][t] = block[18 + t]; + if sb % 2 == 1 && t % 2 == 1 { + sample = -sample; + } + out_slots[t][sb] = sample; + } + } + let mut pcm = [0.0f32; 32]; + for slot in &out_slots { + synthesis.slot(slot, &mut pcm); + output.extend_from_slice(&pcm); + } + } + // Find the delay, then check the reconstruction is faithful. The + // comparison starts past the filterbank's ramp-up, which is silence + // sliding into the window rather than anything the transform got wrong. + let (from, len) = (4096usize, 8192usize); + let mut best = (f64::MIN, 0usize); + for delay in 0..output.len().min(2048) { + if delay + from + len > output.len() || from + len > input.len() { + break; + } + let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); + for i in from..from + len { + let (x, y) = (output[delay + i] as f64, input[i] as f64); + ab += x * y; + aa += x * x; + bb += y * y; + } + let corr = ab / (aa * bb).sqrt().max(1e-30); + if corr > best.0 { + best = (corr, delay); + } + } + assert!( + best.0 > 0.99999, + "analysis/synthesis correlation {:.6} at delay {}", + best.0, + best.1 + ); + } + + /// The forward MDCT and the decoder's inverse are a reconstructing pair: + /// two overlapped granules of a signal come back as themselves. + #[test] + fn mdct_round_trips_under_overlap_add() { + use crate::filterbank::Imdct; + let imdct = Imdct::default(); + let signal: Vec = (0..72) + .map(|i| ((i as f32) * 0.37).sin() + 0.3 * ((i as f32) * 1.1).cos()) + .collect(); + let mut output = vec![0.0f32; 72]; + let mut previous = [0.0f32; 18]; + for granule in 0..3 { + let mut input = [0.0f32; 36]; + for (i, slot) in input.iter_mut().enumerate() { + let index = granule * 18 + i; + if index < signal.len() { + *slot = signal[index]; + } + } + let mut spectrum = [0.0f32; 18]; + mdct_long(&input, 0, &mut spectrum); + let mut block = [0.0f32; 36]; + imdct.long(&spectrum, 0, &mut block); + for t in 0..18 { + let index = granule * 18 + t; + if index < output.len() { + output[index] = block[t] + previous[t]; + } + } + previous.copy_from_slice(&block[18..]); + } + // The first granule has no predecessor, so compare from the second. + let mut worst = 0.0f32; + for i in 18..54 { + worst = worst.max((output[i] - signal[i]).abs()); + } + println!("mdct round trip worst absolute error {worst:e}"); + for i in 18..54 { + assert!( + (output[i] - signal[i]).abs() < 1e-5, + "sample {i}: {} vs {}", + output[i], + signal[i] + ); + } + } +} diff --git a/crates/ec-mp3/src/filterbank.rs b/crates/ec-mp3/src/filterbank.rs new file mode 100644 index 00000000..e3867a9d --- /dev/null +++ b/crates/ec-mp3/src/filterbank.rs @@ -0,0 +1,314 @@ +//! The two transforms every Layer III sample passes through: the 36/12-point +//! IMDCT with its alias butterflies, and the 32-band polyphase bank. +//! +//! The polyphase matrixing is a 32-point DCT from `ec-dsp` in both directions — +//! DCT-II going out, DCT-III coming in — after folding the 64 (or 80) cosine +//! arguments onto the 32 the transform actually computes. That is what keeps +//! synthesis at 512 window multiplies and one short DCT per 32 output samples +//! instead of a 32x64 product. +//! +//! The IMDCT sizes (36 and 12) are not powers of two, so `ec-dsp`'s MDCT plan +//! does not apply. They are computed instead from the transform's own two +//! symmetries — `y[17-n] = -y[n]` and `y[35-m] = y[18+m]` — which halve a +//! fixed-size product that costs under 1 % of decode time either way; the +//! polyphase bank below is where the time actually goes. + +use crate::tables::{alias_coefficients, windows}; +use crate::window::WINDOW; +use ec_dsp::Dct; + +/// Precomputed IMDCT bases, shared by the decoder and the encoder. +#[derive(Clone, Debug)] +pub(crate) struct Imdct { + long: [[f32; 18]; 18], + short: [[f32; 6]; 6], +} + +impl Default for Imdct { + fn default() -> Imdct { + let mut long = [[0.0f32; 18]; 18]; + for (row, out) in long.iter_mut().enumerate() { + let n = if row < 9 { row } else { row + 9 }; + for (k, slot) in out.iter_mut().enumerate() { + let angle = std::f64::consts::PI / 72.0 * ((2 * n + 19) * (2 * k + 1)) as f64; + *slot = angle.cos() as f32; + } + } + let mut short = [[0.0f32; 6]; 6]; + for (row, out) in short.iter_mut().enumerate() { + let n = if row < 3 { row } else { row + 3 }; + for (k, slot) in out.iter_mut().enumerate() { + let angle = std::f64::consts::PI / 24.0 * ((2 * n + 7) * (2 * k + 1)) as f64; + *slot = angle.cos() as f32; + } + } + Imdct { long, short } + } +} + +impl Imdct { + /// 18 coefficients to 36 samples, windowed with `block_type`'s window. + pub(crate) fn long(&self, x: &[f32], block_type: u8, out: &mut [f32; 36]) { + let mut half = [0.0f32; 18]; + for (row, slot) in self.long.iter().zip(half.iter_mut()) { + *slot = row.iter().zip(x).map(|(c, v)| c * v).sum(); + } + for n in 0..9 { + out[n] = half[n]; + out[17 - n] = -half[n]; + out[18 + n] = half[9 + n]; + out[35 - n] = half[9 + n]; + } + let window = &windows()[usize::from(block_type)]; + for (slot, w) in out.iter_mut().zip(window) { + *slot *= w; + } + } + + /// Three 6-coefficient short blocks to one 36-sample overlap buffer. + pub(crate) fn short(&self, x: &[f32], out: &mut [f32; 36]) { + out.fill(0.0); + let window = &windows()[2]; + for w in 0..3 { + let mut half = [0.0f32; 6]; + for (row, slot) in self.short.iter().zip(half.iter_mut()) { + *slot = (0..6).map(|k| row[k] * x[k * 3 + w]).sum(); + } + let mut block = [0.0f32; 12]; + for n in 0..3 { + block[n] = half[n]; + block[5 - n] = -half[n]; + block[6 + n] = half[3 + n]; + block[11 - n] = half[3 + n]; + } + for (i, value) in block.iter().enumerate() { + out[6 + 6 * w + i] += value * window[i]; + } + } + } +} + +/// The decoder's alias reduction: eight butterflies each side of every long +/// subband boundary. +pub(crate) fn alias_reduce(xr: &mut [f32], bands: usize) { + let coeffs = alias_coefficients(); + for sb in 1..bands { + for (i, (cs, ca)) in coeffs.iter().enumerate() { + let lo = sb * 18 - 1 - i; + let hi = sb * 18 + i; + let (a, b) = (xr[lo], xr[hi]); + xr[lo] = a * cs - b * ca; + xr[hi] = b * cs + a * ca; + } + } +} + +/// The encoder's inverse of [`alias_reduce`], applied before quantisation so +/// that the decoder's butterflies undo it exactly. +pub(crate) fn alias_expand(xr: &mut [f32], bands: usize) { + let coeffs = alias_coefficients(); + for sb in 1..bands { + for (i, (cs, ca)) in coeffs.iter().enumerate() { + let lo = sb * 18 - 1 - i; + let hi = sb * 18 + i; + let (a, b) = (xr[lo], xr[hi]); + xr[lo] = a * cs + b * ca; + xr[hi] = b * cs - a * ca; + } + } +} + +/// Folds the 64 matrixing rows onto the 32 a DCT-II computes. +fn unfold(g: &[f32; 32], v: &mut [f32; 64]) { + for (b, slot) in v.iter_mut().enumerate() { + *slot = match b { + 0..=15 => g[b + 16], + 16 => 0.0, + 17..=47 => -g[48 - b], + _ => -g[b - 48], + }; + } +} + +/// The synthesis polyphase bank for one channel. +#[derive(Clone, Debug)] +pub(crate) struct Synthesis { + blocks: Box<[[f32; 64]; 16]>, + pos: usize, + dct: Dct, +} + +impl Default for Synthesis { + fn default() -> Synthesis { + Synthesis { + blocks: Box::new([[0.0f32; 64]; 16]), + pos: 0, + dct: Dct::new(32), + } + } +} + +impl Synthesis { + /// Forgets the window history — what a seek needs. + pub(crate) fn reset(&mut self) { + self.blocks.iter_mut().for_each(|b| b.fill(0.0)); + self.pos = 0; + } + + /// One slot: 32 subband samples in, 32 PCM samples out. + pub(crate) fn slot(&mut self, subband: &[f32; 32], out: &mut [f32]) { + let mut g = *subband; + self.dct.dct2(&mut g); + self.pos = (self.pos + 15) % 16; + unfold(&g, &mut self.blocks[self.pos]); + for (j, sample) in out.iter_mut().enumerate() { + let mut acc = 0.0f32; + for i in 0..16 { + let b = if i % 2 == 0 { j } else { j + 32 }; + acc += WINDOW[j + 32 * i] * self.blocks[(self.pos + i) % 16][b]; + } + *sample = acc; + } + } +} + +/// The analysis polyphase bank: the adjoint of [`Synthesis`], so that an +/// encode/decode pair reconstructs to the filterbank's own -85 dB limit. +/// +/// One subband slot needs the sixteen PCM slots starting at it, so the bank +/// runs fifteen slots behind the samples fed to it — the filterbank delay every +/// Layer III encoder has. +#[derive(Clone, Debug)] +pub(crate) struct Analysis { + pcm: Box<[[f32; 32]; 16]>, + pos: usize, + filled: usize, + dct: Dct, +} + +impl Default for Analysis { + fn default() -> Analysis { + Analysis { + pcm: Box::new([[0.0f32; 32]; 16]), + pos: 0, + filled: 0, + dct: Dct::new(32), + } + } +} + +impl Analysis { + /// Pushes 32 PCM samples; yields the subband slot that became complete. + pub(crate) fn push(&mut self, pcm: &[f32]) -> Option<[f32; 32]> { + self.pcm[self.pos].copy_from_slice(pcm); + self.pos = (self.pos + 1) % 16; + if self.filled < 15 { + self.filled += 1; + return None; + } + let mut r = [0.0f32; 32]; + for j in 0..32 { + let mut even = 0.0f32; + let mut odd = 0.0f32; + for i in 0..16 { + let sample = self.pcm[(self.pos + i) % 16][j] * WINDOW[j + 32 * i]; + if i % 2 == 0 { + even += sample; + } else { + odd += sample; + } + } + // fold b = j (even taps) and b = j + 32 (odd taps) onto 0..31 + match j { + 0..=15 => r[j + 16] += even, + 16 => {} + _ => r[48 - j] -= even, + } + let b = j + 32; + match b { + 32..=47 => r[48 - b] -= odd, + _ => r[b - 48] -= odd, + } + } + // `Dct::dct3` halves its zeroth term; the matrixing wants it whole. + r[0] *= 2.0; + self.dct.dct3(&mut r); + for slot in &mut r { + *slot /= 32.0; + } + Some(r) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn alias_butterflies_are_exactly_invertible() { + let mut xr: Vec = (0..576).map(|i| ((i * 37 % 101) as f32) - 50.0).collect(); + let original = xr.clone(); + alias_expand(&mut xr, 32); + alias_reduce(&mut xr, 32); + for (a, b) in xr.iter().zip(&original) { + assert!((a - b).abs() < 1e-3, "{a} vs {b}"); + } + } + + /// Analysis into synthesis is the pseudo-QMF's round trip: a pure delay of + /// 15 slots and -80 dB of residual, which is the bank's design limit. + #[test] + fn filterbank_round_trip_reconstructs() { + let mut analysis = Analysis::default(); + let mut synthesis = Synthesis::default(); + let n = 64 * 32; + let input: Vec = (0..n) + .map(|i| { + let t = i as f32; + (t * 0.031).sin() * 0.4 + (t * 0.21).sin() * 0.2 + (t * 0.7).cos() * 0.1 + }) + .collect(); + let mut output = vec![0.0f32; n]; + let mut slot_out = 0usize; + for chunk in input.chunks(32) { + if let Some(subband) = analysis.push(chunk) { + let (start, end) = (slot_out * 32, slot_out * 32 + 32); + synthesis.slot(&subband, &mut output[start..end]); + slot_out += 1; + } + } + // The bank reconstructs in place: subband slot t is the sixteen PCM + // slots from t, and synthesising it lands back on PCM slot t. Only the + // first fifteen slots are a ramp, so the comparison starts past them. + let (from, to) = (20 * 32, 40 * 32); + let mut error = 0.0f64; + let mut energy = 0.0f64; + for i in from..to { + let want = input[i] as f64; + let got = output[i] as f64; + error += (want - got).powi(2); + energy += want.powi(2); + } + let snr = 10.0 * (energy / error).log10(); + assert!(snr > 80.0, "filterbank round trip snr {snr:.1} dB"); + } + + #[test] + fn imdct_matches_its_definition() { + let imdct = Imdct::default(); + let x: Vec = (0..18).map(|k| ((k * 13 % 7) as f32) - 3.0).collect(); + let mut got = [0.0f32; 36]; + imdct.long(&x, 0, &mut got); + let window = &windows()[0]; + for (n, value) in got.iter().enumerate() { + let want: f64 = (0..18) + .map(|k| { + x[k] as f64 + * (std::f64::consts::PI / 72.0 * ((2 * n + 19) * (2 * k + 1)) as f64).cos() + }) + .sum::() + * window[n] as f64; + assert!((want - *value as f64).abs() < 1e-3, "n={n} {want} {value}"); + } + } +} diff --git a/crates/ec-mp3/src/header.rs b/crates/ec-mp3/src/header.rs new file mode 100644 index 00000000..4fd3337a --- /dev/null +++ b/crates/ec-mp3/src/header.rs @@ -0,0 +1,317 @@ +//! The four-byte MPEG audio frame header, its CRC, and the frame geometry +//! every other module reads off it. + +use ec_core::error::{Error, Result}; + +/// Which MPEG audio generation a frame belongs to. The three differ in sample +/// rate range, granule count and side-info layout, not in the codec itself. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum Version { + /// MPEG-1 (ISO/IEC 11172-3): 32/44.1/48 kHz, two granules per frame. + Mpeg1, + /// MPEG-2 LSF (ISO/IEC 13818-3): 16/22.05/24 kHz, one granule. + Mpeg2, + /// MPEG-2.5, the de-facto extension to 8/11.025/12 kHz. + Mpeg25, +} + +/// The channel arrangement a frame declares. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum ChannelMode { + /// Two independent channels coded as a stereo pair. + Stereo, + /// Stereo with mid/side and/or intensity coupling, per `mode_extension`. + JointStereo, + /// Two unrelated mono programmes in one stream. + DualChannel, + /// A single channel. + Mono, +} + +impl ChannelMode { + /// Channels carried by the frame. + pub fn channels(self) -> usize { + match self { + ChannelMode::Mono => 1, + _ => 2, + } + } +} + +const BITRATES_V1: [u32; 15] = [ + 0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320, +]; +const BITRATES_V2: [u32; 15] = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160]; +const RATES_V1: [u32; 3] = [44100, 48000, 32000]; + +/// Everything the header declares, decoded into usable units. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct FrameHeader { + /// MPEG generation. + pub version: Version, + /// Layer number, 1..=3. Only Layer III is decodable here. + pub layer: u8, + /// True when a 16-bit CRC follows the header. + pub crc: bool, + /// Declared bitrate in kbit/s; 0 means free format. + pub bitrate_kbps: u32, + /// Sample rate in Hz. + pub sample_rate: u32, + /// True when the frame carries one extra byte. + pub padding: bool, + /// The private bit, carried through untouched. + pub private: bool, + /// Channel arrangement. + pub mode: ChannelMode, + /// Joint-stereo mode extension: bit 0 intensity, bit 1 mid/side. + pub mode_ext: u8, + /// Copyright flag. + pub copyright: bool, + /// Original-media flag. + pub original: bool, + /// De-emphasis selector, 0 = none. + pub emphasis: u8, +} + +impl FrameHeader { + /// Parses a header from four bytes. + /// + /// Reserved encodings are refused rather than guessed at: a "bad" bitrate + /// index, a reserved sample rate, layer 0 and the reserved MPEG version are + /// all [`Error::Corrupt`], which is what lets [`crate::decode::Mp3Reader`] + /// treat a failed parse as "this was not a frame start" and resync. + pub fn parse(b: &[u8]) -> Result { + if b.len() < 4 { + return Err(Error::NeedMore); + } + if b[0] != 0xFF || (b[1] & 0xE0) != 0xE0 { + return Err(Error::corrupt("mp3: no frame sync")); + } + let version = match (b[1] >> 3) & 3 { + 0 => Version::Mpeg25, + 2 => Version::Mpeg2, + 3 => Version::Mpeg1, + _ => return Err(Error::corrupt("mp3: reserved MPEG version id")), + }; + let layer = match (b[1] >> 1) & 3 { + 1 => 3, + 2 => 2, + 3 => 1, + _ => return Err(Error::corrupt("mp3: reserved layer id")), + }; + let crc = (b[1] & 1) == 0; + let bitrate_index = (b[2] >> 4) as usize; + if bitrate_index == 15 { + return Err(Error::corrupt("mp3: bitrate index 15")); + } + let table = if version == Version::Mpeg1 { + &BITRATES_V1 + } else { + &BITRATES_V2 + }; + let bitrate_kbps = table[bitrate_index]; + let rate_index = ((b[2] >> 2) & 3) as usize; + if rate_index == 3 { + return Err(Error::corrupt("mp3: reserved sampling frequency")); + } + let sample_rate = match version { + Version::Mpeg1 => RATES_V1[rate_index], + Version::Mpeg2 => RATES_V1[rate_index] / 2, + Version::Mpeg25 => RATES_V1[rate_index] / 4, + }; + let mode = match (b[3] >> 6) & 3 { + 0 => ChannelMode::Stereo, + 1 => ChannelMode::JointStereo, + 2 => ChannelMode::DualChannel, + _ => ChannelMode::Mono, + }; + Ok(FrameHeader { + version, + layer, + crc, + bitrate_kbps, + sample_rate, + padding: (b[2] >> 1) & 1 == 1, + private: b[2] & 1 == 1, + mode, + mode_ext: (b[3] >> 4) & 3, + copyright: (b[3] >> 3) & 1 == 1, + original: (b[3] >> 2) & 1 == 1, + emphasis: b[3] & 3, + }) + } + + /// The header as four bytes, for the encoder and for round-trip tests. + pub fn to_bytes(&self) -> [u8; 4] { + let version_id = match self.version { + Version::Mpeg25 => 0, + Version::Mpeg2 => 2, + Version::Mpeg1 => 3, + }; + let layer_id = match self.layer { + 3 => 1, + 2 => 2, + _ => 3, + }; + let table = if self.version == Version::Mpeg1 { + &BITRATES_V1 + } else { + &BITRATES_V2 + }; + let bitrate_index = table + .iter() + .position(|&k| k == self.bitrate_kbps) + .unwrap_or(0) as u8; + let base = match self.version { + Version::Mpeg1 => self.sample_rate, + Version::Mpeg2 => self.sample_rate * 2, + Version::Mpeg25 => self.sample_rate * 4, + }; + let rate_index = RATES_V1.iter().position(|&r| r == base).unwrap_or(0) as u8; + let mode_id = match self.mode { + ChannelMode::Stereo => 0, + ChannelMode::JointStereo => 1, + ChannelMode::DualChannel => 2, + ChannelMode::Mono => 3, + }; + [ + 0xFF, + 0xE0 | (version_id << 3) | (layer_id << 1) | u8::from(!self.crc), + (bitrate_index << 4) + | (rate_index << 2) + | (u8::from(self.padding) << 1) + | u8::from(self.private), + (mode_id << 6) + | (self.mode_ext << 4) + | (u8::from(self.copyright) << 3) + | (u8::from(self.original) << 2) + | self.emphasis, + ] + } + + /// Channels carried by this frame. + pub fn channels(&self) -> usize { + self.mode.channels() + } + + /// Granules per frame: two for MPEG-1, one for the low sampling frequency + /// extensions. + pub fn granules(&self) -> usize { + if self.version == Version::Mpeg1 { 2 } else { 1 } + } + + /// PCM samples per channel produced by this frame. + pub fn samples_per_frame(&self) -> usize { + self.granules() * 576 + } + + /// Side-information bytes between the header (plus CRC) and the main data. + pub fn side_info_len(&self) -> usize { + match (self.version, self.channels()) { + (Version::Mpeg1, 1) => 17, + (Version::Mpeg1, _) => 32, + (_, 1) => 9, + (_, _) => 17, + } + } + + /// Total frame length in bytes, header included, or `None` for free format + /// (where the length is only knowable by scanning to the next sync word). + pub fn frame_len(&self) -> Option { + if self.bitrate_kbps == 0 { + return None; + } + let bits = self.bitrate_kbps as usize * 1000; + let rate = self.sample_rate as usize; + let pad = usize::from(self.padding); + Some(match self.layer { + 1 => (12 * bits / rate + pad) * 4, + 2 => 144 * bits / rate + pad, + _ if self.version == Version::Mpeg1 => 144 * bits / rate + pad, + _ => 72 * bits / rate + pad, + }) + } + + /// Bytes of main data this frame carries: everything after the header, the + /// optional CRC and the side info. + pub fn main_data_len(&self) -> Option { + let len = self.frame_len()?; + let overhead = 4 + usize::from(self.crc) * 2 + self.side_info_len(); + Some(len.saturating_sub(overhead)) + } + + /// True when two headers describe the same stream configuration — the test + /// a resync uses to tell a real frame from a byte pattern that looked like + /// one. + pub fn same_stream(&self, other: &FrameHeader) -> bool { + self.version == other.version + && self.layer == other.layer + && self.sample_rate == other.sample_rate + && self.mode.channels() == other.mode.channels() + } +} + +/// CRC-16 as Layer III specifies it: polynomial 0x8005, seeded with all ones, +/// over the last two header bytes followed by the whole side info. +pub fn crc16(header: &[u8; 4], side_info: &[u8]) -> u16 { + let mut crc = 0xFFFFu16; + for &byte in header[2..].iter().chain(side_info) { + crc ^= u16::from(byte) << 8; + for _ in 0..8 { + crc = if crc & 0x8000 != 0 { + (crc << 1) ^ 0x8005 + } else { + crc << 1 + }; + } + } + crc +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn parses_and_rebuilds_a_128k_stereo_header() { + let bytes = [0xFF, 0xFB, 0x90, 0x00]; + let h = FrameHeader::parse(&bytes).unwrap(); + assert_eq!(h.version, Version::Mpeg1); + assert_eq!(h.layer, 3); + assert_eq!(h.bitrate_kbps, 128); + assert_eq!(h.sample_rate, 44100); + assert_eq!(h.mode, ChannelMode::Stereo); + assert_eq!(h.frame_len(), Some(417)); + assert_eq!(h.side_info_len(), 32); + assert_eq!(h.to_bytes(), bytes); + } + + #[test] + fn low_sampling_frequency_geometry() { + // MPEG-2, 24 kHz, 64 kbit/s, mono. + let bytes = [0xFF, 0xF3, 0x84, 0xC0]; + let h = FrameHeader::parse(&bytes).unwrap(); + assert_eq!(h.version, Version::Mpeg2); + assert_eq!(h.sample_rate, 24000); + assert_eq!(h.granules(), 1); + assert_eq!(h.samples_per_frame(), 576); + assert_eq!(h.side_info_len(), 9); + assert_eq!(h.frame_len(), Some(72 * 64000 / 24000)); + assert_eq!(h.to_bytes(), bytes); + } + + #[test] + fn reserved_fields_are_refused() { + assert!(FrameHeader::parse(&[0xFF, 0xFB, 0xF0, 0x00]).is_err()); // bitrate 15 + assert!(FrameHeader::parse(&[0xFF, 0xFB, 0x9C, 0x00]).is_err()); // rate 3 + assert!(FrameHeader::parse(&[0xFF, 0xE9, 0x90, 0x00]).is_err()); // layer 0 + assert!(FrameHeader::parse(&[0x00, 0x00, 0x00, 0x00]).is_err()); // no sync + } + + #[test] + fn free_format_has_no_computable_length() { + let h = FrameHeader::parse(&[0xFF, 0xFB, 0x00, 0x00]).unwrap(); + assert_eq!(h.bitrate_kbps, 0); + assert_eq!(h.frame_len(), None); + } +} diff --git a/crates/ec-mp3/src/huffman.rs b/crates/ec-mp3/src/huffman.rs new file mode 100644 index 00000000..66357da3 --- /dev/null +++ b/crates/ec-mp3/src/huffman.rs @@ -0,0 +1,345 @@ +//! Layer III Huffman coding: the table registry, a decode tree built once per +//! process, and the encoder's cost/write side. + +use crate::huffman_tables::*; +use ec_core::bitio::{BitReader, BitWriter}; +use ec_core::error::{Error, Result}; +use std::sync::OnceLock; + +/// One code table as the bitstream refers to it. +#[derive(Clone, Copy, Debug)] +pub(crate) struct Table { + /// `(length, code)` indexed by `x * dim + y`. + pub codes: &'static [(u8, u16)], + /// Values per axis; `x` and `y` run `0..dim`, the top one being an escape + /// when `linbits` is non-zero. + pub dim: u16, + /// Extra magnitude bits read when a value is `dim - 1`. + pub linbits: u8, +} + +/// The 32 big-value table slots. 4 and 14 are not assigned by the standard; +/// 16..=23 and 24..=31 share one code table each and differ only in `linbits`. +pub(crate) fn big_table(select: usize) -> Result { + let t = |codes: &'static [(u8, u16)], dim: u16, linbits: u8| Table { + codes, + dim, + linbits, + }; + Ok(match select { + 0 => t(&[], 0, 0), + 1 => t(&T1, 2, 0), + 2 => t(&T2, 3, 0), + 3 => t(&T3, 3, 0), + 5 => t(&T5, 4, 0), + 6 => t(&T6, 4, 0), + 7 => t(&T7, 6, 0), + 8 => t(&T8, 6, 0), + 9 => t(&T9, 6, 0), + 10 => t(&T10, 8, 0), + 11 => t(&T11, 8, 0), + 12 => t(&T12, 8, 0), + 13 => t(&T13, 16, 0), + 15 => t(&T15, 16, 0), + 16..=23 => t(&T16, 16, LINBITS_16[select - 16]), + 24..=31 => t(&T24, 16, LINBITS_24[select - 24]), + _ => { + return Err(Error::corrupt(format!( + "mp3: Huffman table {select} is not assigned" + ))); + } + }) +} + +const LINBITS_16: [u8; 8] = [1, 2, 3, 4, 6, 8, 10, 13]; +const LINBITS_24: [u8; 8] = [4, 5, 6, 7, 8, 9, 11, 13]; + +/// The two count1 (quadruple) tables, selected by `count1table_select`. +pub(crate) fn count1_table(select: bool) -> &'static [(u8, u16)] { + if select { &C1 } else { &C0 } +} + +/// A decode tree: two child slots per node, a negative slot being +/// `-(value_index + 1)`. +type Tree = Vec<[i32; 2]>; + +fn build_tree(codes: &[(u8, u16)]) -> Tree { + let mut tree: Tree = vec![[0, 0]]; + for (index, &(len, code)) in codes.iter().enumerate() { + let mut node = 0usize; + let code = u32::from(code); + for bit in (0..u32::from(len)).rev() { + let branch = ((code >> bit) & 1) as usize; + if bit == 0 { + tree[node][branch] = -(index as i32 + 1); + } else { + if tree[node][branch] == 0 { + tree.push([0, 0]); + tree[node][branch] = (tree.len() - 1) as i32; + } + node = tree[node][branch] as usize; + } + } + } + tree +} + +struct Trees { + big: Vec>, + count1: [Tree; 2], +} + +fn trees() -> &'static Trees { + static TREES: OnceLock = OnceLock::new(); + TREES.get_or_init(|| { + let mut big = Vec::with_capacity(32); + for select in 0..32 { + big.push(match big_table(select) { + Ok(t) if !t.codes.is_empty() => Some(build_tree(t.codes)), + _ => None, + }); + } + Trees { + big, + count1: [build_tree(&C0), build_tree(&C1)], + } + }) +} + +fn walk(tree: &Tree, reader: &mut BitReader<'_>) -> Result { + let mut node = 0usize; + loop { + let branch = usize::from(reader.read_bit()?); + let next = tree[node][branch]; + if next < 0 { + return Ok((-next - 1) as usize); + } + if next == 0 { + return Err(Error::corrupt("mp3: Huffman code not in table")); + } + node = next as usize; + } +} + +/// Decodes one big-value pair into `out`, sign bits and linbits included. +pub(crate) fn decode_pair( + reader: &mut BitReader<'_>, + select: usize, + table: Table, + out: &mut [f32; 2], +) -> Result<()> { + let tree = trees().big[select] + .as_ref() + .ok_or_else(|| Error::corrupt(format!("mp3: Huffman table {select} is not assigned")))?; + let index = walk(tree, reader)?; + let values = [ + (index as u16 / table.dim) as u32, + (index as u16 % table.dim) as u32, + ]; + // Order matters and is per value, not per pair: escape bits then sign for + // x, then the same for y. Grouping them costs the same number of bits, + // which is why only the samples go wrong. + for (slot, mut value) in out.iter_mut().zip(values) { + if table.linbits > 0 && value == u32::from(table.dim) - 1 { + value += reader.read_bits(u32::from(table.linbits))?; + } + *slot = if value == 0 { + 0.0 + } else if reader.read_bit()? { + -(value as f32) + } else { + value as f32 + }; + } + Ok(()) +} + +/// Decodes one count1 quadruple: four values of 0 or +-1. +pub(crate) fn decode_quad( + reader: &mut BitReader<'_>, + select: bool, + out: &mut [f32; 4], +) -> Result<()> { + let tree = &trees().count1[usize::from(select)]; + let index = walk(tree, reader)?; + for (slot, shift) in out.iter_mut().zip([3, 2, 1, 0]) { + let value = (index >> shift) & 1; + *slot = if value == 0 { + 0.0 + } else if reader.read_bit()? { + -1.0 + } else { + 1.0 + }; + } + Ok(()) +} + +/// Bits one pair costs in `table`, or `None` when the pair is out of range. +pub(crate) fn pair_bits(table: Table, x: u32, y: u32) -> Option { + let max = u32::from(table.dim) - 1; + let escape = u32::from(table.linbits) > 0; + let (ix, iy) = (x.min(max), y.min(max)); + if (x > max && !escape) || (y > max && !escape) { + return None; + } + if escape && (x > max + (1 << table.linbits) - 1 || y > max + (1 << table.linbits) - 1) { + return None; + } + let (len, _) = table.codes[(ix * u32::from(table.dim) + iy) as usize]; + if len == 0 && !(x == 0 && y == 0) { + return None; + } + let mut bits = u32::from(len); + for value in [x, y] { + if value >= max && escape { + bits += u32::from(table.linbits); + } + if value != 0 { + bits += 1; + } + } + Some(bits) +} + +/// Writes one pair; the caller has already checked it fits the table. +pub(crate) fn write_pair(writer: &mut BitWriter, table: Table, x: i32, y: i32) { + let max = u32::from(table.dim) - 1; + let escape = table.linbits > 0; + let (ax, ay) = (x.unsigned_abs(), y.unsigned_abs()); + let (ix, iy) = (ax.min(max), ay.min(max)); + let (len, code) = table.codes[(ix * u32::from(table.dim) + iy) as usize]; + writer.write_bits(u32::from(code), u32::from(len)); + for (value, abs) in [(x, ax), (y, ay)] { + if abs >= max && escape { + writer.write_bits(abs - max, u32::from(table.linbits)); + } + if abs != 0 { + writer.write_bit(value < 0); + } + } +} + +/// Bits one count1 quadruple costs. +pub(crate) fn quad_bits(select: bool, quad: [i32; 4]) -> u32 { + let index = quad + .iter() + .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0)); + let (len, _) = count1_table(select)[index]; + u32::from(len) + quad.iter().filter(|v| **v != 0).count() as u32 +} + +/// Writes one count1 quadruple. +pub(crate) fn write_quad(writer: &mut BitWriter, select: bool, quad: [i32; 4]) { + let index = quad + .iter() + .fold(0usize, |acc, v| acc * 2 + usize::from(*v != 0)); + let (len, code) = count1_table(select)[index]; + writer.write_bits(u32::from(code), u32::from(len)); + for value in quad { + if value != 0 { + writer.write_bit(value < 0); + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// Every table is a complete prefix code over its whole value grid: the + /// property the measurement rig checked before these numbers were written, + /// re-checked here so a hand edit cannot break it unnoticed. + #[test] + fn tables_are_complete_prefix_codes() { + let mut seen = 0; + for select in 0..32 { + let Ok(table) = big_table(select) else { + continue; + }; + if table.codes.is_empty() { + continue; + } + seen += 1; + assert_eq!( + table.codes.len(), + usize::from(table.dim) * usize::from(table.dim) + ); + let kraft: f64 = table + .codes + .iter() + .map(|(len, _)| 2f64.powi(-i32::from(*len))) + .sum(); + assert!( + (kraft - 1.0).abs() < 1e-12, + "table {select}: Kraft sum {kraft}" + ); + let tree = build_tree(table.codes); + assert_eq!( + tree.iter().flatten().filter(|n| **n < 0).count(), + table.codes.len() + ); + } + assert_eq!(seen, 29, "tables 0..31 minus the four unassigned slots"); + for select in [false, true] { + let codes = count1_table(select); + let kraft: f64 = codes + .iter() + .map(|(len, _)| 2f64.powi(-i32::from(*len))) + .sum(); + assert!((kraft - 1.0).abs() < 1e-12); + } + } + + #[test] + fn pairs_round_trip_through_every_table() { + for select in (1..32).filter(|s| big_table(*s).is_ok()) { + let table = big_table(select).unwrap(); + if table.codes.is_empty() { + continue; + } + let max = u32::from(table.dim) - 1; + let mut writer = BitWriter::new(); + let mut wanted = Vec::new(); + for x in 0..=max { + for y in 0..=max { + let (sx, sy) = (x as i32, -(y as i32)); + write_pair(&mut writer, table, sx, sy); + wanted.push([sx as f32, sy as f32]); + } + } + let bytes = writer.into_bytes(); + let mut reader = BitReader::new(&bytes); + for want in wanted { + let mut got = [0.0f32; 2]; + decode_pair(&mut reader, select, table, &mut got).unwrap(); + assert_eq!(got, want, "table {select}"); + } + } + } + + #[test] + fn quads_round_trip() { + for select in [false, true] { + let mut writer = BitWriter::new(); + let mut wanted = Vec::new(); + for index in 0..16 { + let quad = [ + (index >> 3) & 1, + -((index >> 2) & 1), + (index >> 1) & 1, + -(index & 1), + ]; + write_quad(&mut writer, select, quad); + wanted.push(quad.map(|v| v as f32)); + } + let bytes = writer.into_bytes(); + let mut reader = BitReader::new(&bytes); + for want in wanted { + let mut got = [0.0f32; 4]; + decode_quad(&mut reader, select, &mut got).unwrap(); + assert_eq!(got, want); + } + } + } +} diff --git a/crates/ec-mp3/src/huffman_tables.rs b/crates/ec-mp3/src/huffman_tables.rs new file mode 100644 index 00000000..a22a72df --- /dev/null +++ b/crates/ec-mp3/src/huffman_tables.rs @@ -0,0 +1,1468 @@ +//! Layer III Huffman code tables. +//! +//! Every entry here was *measured*, not transcribed: `scripts/mp3-tables/` +//! writes legal Layer III frames whose main-data bits it chooses, decodes them +//! with ffmpeg, and walks each code tree by asking whether all continuations of +//! a bit prefix decode to the same pair. The result is checked for a Kraft sum +//! of exactly 1, for full coverage of the value grid, and for uniqueness before +//! it is written out, so a wrong entry cannot reach this file silently. +//! +//! `(length, code)` indexed by `x * dim + y`, where `x` and `y` are the two +//! (or four, for the count1 tables) values the codeword yields, in the order +//! they are written to the spectrum. + +pub(crate) static T1: [(u8, u16); 4] = [(1, 1), (3, 1), (2, 1), (3, 0)]; + +pub(crate) static T2: [(u8, u16); 9] = [ + (1, 1), + (3, 2), + (6, 1), + (3, 3), + (3, 1), + (5, 1), + (5, 3), + (5, 2), + (6, 0), +]; + +pub(crate) static T3: [(u8, u16); 9] = [ + (2, 3), + (2, 2), + (6, 1), + (3, 1), + (2, 1), + (5, 1), + (5, 3), + (5, 2), + (6, 0), +]; + +pub(crate) static T5: [(u8, u16); 16] = [ + (1, 1), + (3, 2), + (6, 6), + (7, 5), + (3, 3), + (3, 1), + (6, 4), + (7, 4), + (6, 7), + (6, 5), + (7, 7), + (8, 1), + (7, 6), + (6, 1), + (7, 1), + (8, 0), +]; + +pub(crate) static T6: [(u8, u16); 16] = [ + (3, 7), + (3, 3), + (5, 5), + (7, 1), + (3, 6), + (2, 2), + (4, 3), + (5, 2), + (4, 5), + (4, 4), + (5, 4), + (6, 1), + (6, 3), + (5, 3), + (6, 2), + (7, 0), +]; + +pub(crate) static T7: [(u8, u16); 36] = [ + (1, 1), + (3, 2), + (6, 10), + (8, 19), + (8, 16), + (9, 10), + (3, 3), + (4, 3), + (6, 7), + (7, 10), + (7, 5), + (8, 3), + (6, 11), + (5, 4), + (7, 13), + (8, 17), + (8, 8), + (9, 4), + (7, 12), + (7, 11), + (8, 18), + (9, 15), + (9, 11), + (9, 2), + (7, 7), + (7, 6), + (8, 9), + (9, 14), + (9, 3), + (10, 1), + (8, 6), + (8, 4), + (9, 5), + (10, 3), + (10, 2), + (10, 0), +]; + +pub(crate) static T8: [(u8, u16); 36] = [ + (2, 3), + (3, 4), + (6, 6), + (8, 18), + (8, 12), + (9, 5), + (3, 5), + (2, 1), + (4, 2), + (8, 16), + (8, 9), + (8, 3), + (6, 7), + (4, 3), + (6, 5), + (8, 14), + (8, 7), + (9, 3), + (8, 19), + (8, 17), + (8, 15), + (9, 13), + (9, 10), + (10, 4), + (8, 13), + (7, 5), + (8, 8), + (9, 11), + (10, 5), + (10, 1), + (9, 12), + (8, 4), + (9, 4), + (9, 1), + (11, 1), + (11, 0), +]; + +pub(crate) static T9: [(u8, u16); 36] = [ + (3, 7), + (3, 5), + (5, 9), + (6, 14), + (8, 15), + (9, 7), + (3, 6), + (3, 4), + (4, 5), + (5, 5), + (6, 6), + (8, 7), + (4, 7), + (4, 6), + (5, 8), + (6, 8), + (7, 8), + (8, 5), + (6, 15), + (5, 6), + (6, 9), + (7, 10), + (7, 5), + (8, 1), + (7, 11), + (6, 7), + (7, 9), + (7, 6), + (8, 4), + (9, 1), + (8, 14), + (7, 4), + (8, 6), + (8, 2), + (9, 6), + (9, 0), +]; + +pub(crate) static T10: [(u8, u16); 64] = [ + (1, 1), + (3, 2), + (6, 10), + (8, 23), + (9, 35), + (9, 30), + (9, 12), + (10, 17), + (3, 3), + (4, 3), + (6, 8), + (7, 12), + (8, 18), + (9, 21), + (8, 12), + (8, 7), + (6, 11), + (6, 9), + (7, 15), + (8, 21), + (9, 32), + (10, 40), + (9, 19), + (9, 6), + (7, 14), + (7, 13), + (8, 22), + (9, 34), + (10, 46), + (10, 23), + (9, 18), + (10, 7), + (8, 20), + (8, 19), + (9, 33), + (10, 47), + (10, 27), + (10, 22), + (10, 9), + (10, 3), + (9, 31), + (9, 22), + (10, 41), + (10, 26), + (11, 21), + (11, 20), + (10, 5), + (11, 3), + (8, 14), + (8, 13), + (9, 10), + (10, 11), + (10, 16), + (10, 6), + (11, 5), + (11, 1), + (9, 9), + (8, 8), + (9, 7), + (10, 8), + (10, 4), + (11, 4), + (11, 2), + (11, 0), +]; + +pub(crate) static T11: [(u8, u16); 64] = [ + (2, 3), + (3, 4), + (5, 10), + (7, 24), + (8, 34), + (9, 33), + (8, 21), + (9, 15), + (3, 5), + (3, 3), + (4, 4), + (6, 10), + (8, 32), + (8, 17), + (7, 11), + (8, 10), + (5, 11), + (5, 7), + (6, 13), + (7, 18), + (8, 30), + (9, 31), + (8, 20), + (8, 5), + (7, 25), + (6, 11), + (7, 19), + (9, 59), + (8, 27), + (10, 18), + (8, 12), + (9, 5), + (8, 35), + (8, 33), + (8, 31), + (9, 58), + (9, 30), + (10, 16), + (9, 7), + (10, 5), + (8, 28), + (8, 26), + (9, 32), + (10, 19), + (10, 17), + (11, 15), + (10, 8), + (11, 14), + (8, 14), + (7, 12), + (7, 9), + (8, 13), + (9, 14), + (10, 9), + (10, 4), + (10, 1), + (8, 11), + (7, 4), + (8, 6), + (9, 6), + (10, 6), + (10, 3), + (10, 2), + (10, 0), +]; + +pub(crate) static T12: [(u8, u16); 64] = [ + (4, 9), + (3, 6), + (5, 16), + (7, 33), + (8, 41), + (9, 39), + (9, 38), + (9, 26), + (3, 7), + (3, 5), + (4, 6), + (5, 9), + (7, 23), + (7, 16), + (8, 26), + (8, 11), + (5, 17), + (4, 7), + (5, 11), + (6, 14), + (7, 21), + (8, 30), + (7, 10), + (8, 7), + (6, 17), + (5, 10), + (6, 15), + (6, 12), + (7, 18), + (8, 28), + (8, 14), + (8, 5), + (7, 32), + (6, 13), + (7, 22), + (7, 19), + (8, 18), + (8, 16), + (8, 9), + (9, 5), + (8, 40), + (7, 17), + (8, 31), + (8, 29), + (8, 17), + (9, 13), + (8, 4), + (9, 2), + (8, 27), + (7, 12), + (7, 11), + (8, 15), + (8, 10), + (9, 7), + (9, 4), + (10, 1), + (9, 27), + (8, 12), + (8, 8), + (9, 12), + (9, 6), + (9, 3), + (9, 1), + (10, 0), +]; + +pub(crate) static T13: [(u8, u16); 256] = [ + (1, 1), + (4, 5), + (6, 14), + (7, 21), + (8, 34), + (9, 51), + (9, 46), + (10, 71), + (9, 42), + (10, 52), + (11, 68), + (11, 52), + (12, 67), + (12, 44), + (13, 43), + (13, 19), + (3, 3), + (4, 4), + (6, 12), + (7, 19), + (8, 31), + (8, 26), + (9, 44), + (9, 33), + (9, 31), + (9, 24), + (10, 32), + (10, 24), + (11, 31), + (12, 35), + (12, 22), + (12, 14), + (6, 15), + (6, 13), + (7, 23), + (8, 36), + (9, 59), + (9, 49), + (10, 77), + (10, 65), + (9, 29), + (10, 40), + (10, 30), + (11, 40), + (11, 27), + (12, 33), + (13, 42), + (13, 16), + (7, 22), + (7, 20), + (8, 37), + (9, 61), + (9, 56), + (10, 79), + (10, 73), + (10, 64), + (10, 43), + (11, 76), + (11, 56), + (11, 37), + (11, 26), + (12, 31), + (13, 25), + (13, 14), + (8, 35), + (7, 16), + (9, 60), + (9, 57), + (10, 97), + (10, 75), + (11, 114), + (11, 91), + (10, 54), + (11, 73), + (11, 55), + (12, 41), + (12, 48), + (13, 53), + (13, 23), + (14, 24), + (9, 58), + (8, 27), + (9, 50), + (10, 96), + (10, 76), + (10, 70), + (11, 93), + (11, 84), + (11, 77), + (11, 58), + (12, 79), + (11, 29), + (13, 74), + (13, 49), + (14, 41), + (14, 17), + (9, 47), + (9, 45), + (10, 78), + (10, 74), + (11, 115), + (11, 94), + (11, 90), + (11, 79), + (11, 69), + (12, 83), + (12, 71), + (12, 50), + (13, 59), + (13, 38), + (14, 36), + (14, 15), + (10, 72), + (9, 34), + (10, 56), + (11, 95), + (11, 92), + (11, 85), + (12, 91), + (12, 90), + (12, 86), + (12, 73), + (13, 77), + (13, 65), + (13, 51), + (14, 44), + (16, 43), + (16, 42), + (9, 43), + (8, 20), + (9, 30), + (10, 44), + (10, 55), + (11, 78), + (11, 72), + (12, 87), + (12, 78), + (12, 61), + (12, 46), + (13, 54), + (13, 37), + (14, 30), + (15, 20), + (15, 16), + (10, 53), + (9, 25), + (10, 41), + (10, 37), + (11, 44), + (11, 59), + (11, 54), + (13, 81), + (12, 66), + (13, 76), + (13, 57), + (14, 54), + (14, 37), + (14, 18), + (16, 39), + (15, 11), + (10, 35), + (10, 33), + (10, 31), + (11, 57), + (11, 42), + (12, 82), + (12, 72), + (13, 80), + (12, 47), + (13, 58), + (14, 55), + (13, 21), + (14, 22), + (15, 26), + (16, 38), + (17, 22), + (11, 53), + (10, 25), + (10, 23), + (11, 38), + (12, 70), + (12, 60), + (12, 51), + (12, 36), + (13, 55), + (13, 26), + (13, 34), + (14, 23), + (15, 27), + (15, 14), + (15, 9), + (16, 7), + (11, 34), + (11, 32), + (11, 28), + (12, 39), + (12, 49), + (13, 75), + (12, 30), + (13, 52), + (14, 48), + (14, 40), + (15, 52), + (15, 28), + (15, 18), + (16, 17), + (16, 9), + (16, 5), + (12, 45), + (11, 21), + (12, 34), + (13, 64), + (13, 56), + (13, 50), + (14, 49), + (14, 45), + (14, 31), + (14, 19), + (14, 12), + (15, 15), + (16, 10), + (15, 7), + (16, 6), + (16, 3), + (13, 48), + (12, 23), + (12, 20), + (13, 39), + (13, 36), + (13, 35), + (15, 53), + (14, 21), + (14, 16), + (17, 23), + (15, 13), + (15, 10), + (15, 6), + (17, 1), + (16, 4), + (16, 2), + (12, 16), + (12, 15), + (13, 17), + (14, 27), + (14, 25), + (14, 20), + (15, 29), + (14, 11), + (15, 17), + (15, 12), + (16, 16), + (16, 8), + (19, 1), + (18, 1), + (19, 0), + (16, 1), +]; + +pub(crate) static T15: [(u8, u16); 256] = [ + (3, 7), + (4, 12), + (5, 18), + (7, 53), + (7, 47), + (8, 76), + (9, 124), + (9, 108), + (9, 89), + (10, 123), + (10, 108), + (11, 119), + (11, 107), + (11, 81), + (12, 122), + (13, 63), + (4, 13), + (3, 5), + (5, 16), + (6, 27), + (7, 46), + (7, 36), + (8, 61), + (8, 51), + (8, 42), + (9, 70), + (9, 52), + (10, 83), + (10, 65), + (10, 41), + (11, 59), + (11, 36), + (5, 19), + (5, 17), + (5, 15), + (6, 24), + (7, 41), + (7, 34), + (8, 59), + (8, 48), + (8, 40), + (9, 64), + (9, 50), + (10, 78), + (10, 62), + (11, 80), + (11, 56), + (11, 33), + (6, 29), + (6, 28), + (6, 25), + (7, 43), + (7, 39), + (8, 63), + (8, 55), + (9, 93), + (9, 76), + (9, 59), + (10, 93), + (10, 72), + (10, 54), + (11, 75), + (11, 50), + (11, 29), + (7, 52), + (6, 22), + (7, 42), + (7, 40), + (8, 67), + (8, 57), + (9, 95), + (9, 79), + (9, 72), + (9, 57), + (10, 89), + (10, 69), + (10, 49), + (11, 66), + (11, 46), + (11, 27), + (8, 77), + (7, 37), + (7, 35), + (8, 66), + (8, 58), + (8, 52), + (9, 91), + (9, 74), + (9, 62), + (9, 48), + (10, 79), + (10, 63), + (11, 90), + (11, 62), + (11, 40), + (12, 38), + (9, 125), + (7, 32), + (8, 60), + (8, 56), + (8, 50), + (9, 92), + (9, 78), + (9, 65), + (9, 55), + (10, 87), + (10, 71), + (10, 51), + (11, 73), + (11, 51), + (12, 70), + (12, 30), + (9, 109), + (8, 53), + (8, 49), + (9, 94), + (9, 88), + (9, 75), + (9, 66), + (10, 122), + (10, 91), + (10, 73), + (10, 56), + (10, 42), + (11, 64), + (11, 44), + (11, 21), + (12, 25), + (9, 90), + (8, 43), + (8, 41), + (9, 77), + (9, 73), + (9, 63), + (9, 56), + (10, 92), + (10, 77), + (10, 66), + (10, 47), + (11, 67), + (11, 48), + (12, 53), + (12, 36), + (12, 20), + (9, 71), + (8, 34), + (9, 67), + (9, 60), + (9, 58), + (9, 49), + (10, 88), + (10, 76), + (10, 67), + (11, 106), + (11, 71), + (11, 54), + (11, 38), + (12, 39), + (12, 23), + (12, 15), + (10, 109), + (9, 53), + (9, 51), + (9, 47), + (10, 90), + (10, 82), + (10, 58), + (10, 57), + (10, 48), + (11, 72), + (11, 57), + (11, 41), + (11, 23), + (12, 27), + (13, 62), + (12, 9), + (10, 86), + (9, 42), + (9, 40), + (9, 37), + (10, 70), + (10, 64), + (10, 52), + (10, 43), + (11, 70), + (11, 55), + (11, 42), + (11, 25), + (12, 29), + (12, 18), + (12, 11), + (13, 11), + (11, 118), + (10, 68), + (9, 30), + (10, 55), + (10, 50), + (10, 46), + (11, 74), + (11, 65), + (11, 49), + (11, 39), + (11, 24), + (11, 16), + (12, 22), + (12, 13), + (13, 14), + (13, 7), + (11, 91), + (10, 44), + (10, 39), + (10, 38), + (10, 34), + (11, 63), + (11, 52), + (11, 45), + (11, 31), + (12, 52), + (12, 28), + (12, 19), + (12, 14), + (12, 8), + (13, 9), + (13, 3), + (12, 123), + (11, 60), + (11, 58), + (11, 53), + (11, 47), + (11, 43), + (11, 32), + (11, 22), + (12, 37), + (12, 24), + (12, 17), + (12, 12), + (13, 15), + (13, 10), + (12, 2), + (13, 1), + (12, 71), + (11, 37), + (11, 34), + (11, 30), + (11, 28), + (11, 20), + (11, 17), + (12, 26), + (12, 21), + (12, 16), + (12, 10), + (12, 6), + (13, 8), + (13, 6), + (13, 2), + (13, 0), +]; + +pub(crate) static T16: [(u8, u16); 256] = [ + (1, 1), + (4, 5), + (6, 14), + (8, 44), + (9, 74), + (9, 63), + (10, 110), + (10, 93), + (11, 172), + (11, 149), + (11, 138), + (12, 242), + (12, 225), + (12, 195), + (13, 376), + (9, 17), + (3, 3), + (4, 4), + (6, 12), + (7, 20), + (8, 35), + (9, 62), + (9, 53), + (9, 47), + (10, 83), + (10, 75), + (10, 68), + (11, 119), + (12, 201), + (11, 107), + (12, 207), + (8, 9), + (6, 15), + (6, 13), + (7, 23), + (8, 38), + (9, 67), + (9, 58), + (10, 103), + (10, 90), + (11, 161), + (10, 72), + (11, 127), + (11, 117), + (11, 110), + (12, 209), + (12, 206), + (9, 16), + (8, 45), + (7, 21), + (8, 39), + (9, 69), + (9, 64), + (10, 114), + (10, 99), + (10, 87), + (11, 158), + (11, 140), + (12, 252), + (12, 212), + (12, 199), + (13, 387), + (13, 365), + (10, 26), + (9, 75), + (8, 36), + (9, 68), + (9, 65), + (10, 115), + (10, 101), + (11, 179), + (11, 164), + (11, 155), + (12, 264), + (12, 246), + (12, 226), + (13, 395), + (13, 382), + (13, 362), + (9, 9), + (9, 66), + (8, 30), + (9, 59), + (9, 56), + (10, 102), + (11, 185), + (11, 173), + (12, 265), + (11, 142), + (12, 253), + (12, 232), + (13, 400), + (13, 388), + (13, 378), + (14, 445), + (10, 16), + (10, 111), + (9, 54), + (9, 52), + (10, 100), + (11, 184), + (11, 178), + (11, 160), + (11, 133), + (12, 257), + (12, 244), + (12, 228), + (12, 217), + (13, 385), + (13, 366), + (14, 715), + (10, 10), + (10, 98), + (9, 48), + (10, 91), + (10, 88), + (11, 165), + (11, 157), + (11, 148), + (12, 261), + (12, 248), + (13, 407), + (13, 397), + (13, 372), + (13, 380), + (15, 889), + (15, 884), + (10, 8), + (10, 85), + (10, 84), + (10, 81), + (11, 159), + (11, 156), + (11, 143), + (12, 260), + (12, 249), + (13, 427), + (13, 401), + (13, 392), + (13, 383), + (14, 727), + (14, 713), + (14, 708), + (10, 7), + (11, 154), + (10, 76), + (10, 73), + (11, 141), + (11, 131), + (12, 256), + (12, 245), + (13, 426), + (13, 406), + (13, 394), + (13, 384), + (14, 735), + (13, 359), + (14, 710), + (13, 352), + (11, 11), + (11, 139), + (11, 129), + (10, 67), + (11, 125), + (12, 247), + (12, 233), + (12, 229), + (12, 219), + (13, 393), + (14, 743), + (14, 737), + (14, 720), + (15, 885), + (15, 882), + (14, 439), + (10, 4), + (12, 243), + (11, 120), + (11, 118), + (11, 115), + (12, 227), + (12, 223), + (13, 396), + (14, 746), + (14, 742), + (14, 736), + (14, 721), + (14, 712), + (14, 706), + (13, 223), + (14, 436), + (11, 6), + (12, 202), + (12, 224), + (12, 222), + (12, 218), + (12, 216), + (13, 389), + (13, 386), + (13, 381), + (13, 364), + (15, 888), + (14, 443), + (14, 707), + (14, 440), + (14, 437), + (16, 1728), + (11, 4), + (14, 747), + (12, 211), + (12, 210), + (12, 208), + (13, 370), + (13, 379), + (14, 734), + (14, 723), + (14, 714), + (16, 1735), + (15, 883), + (15, 877), + (15, 876), + (17, 3459), + (15, 865), + (11, 2), + (13, 377), + (13, 369), + (11, 102), + (12, 187), + (14, 726), + (14, 722), + (13, 358), + (14, 711), + (14, 709), + (15, 866), + (16, 1734), + (15, 871), + (17, 3458), + (15, 870), + (14, 434), + (11, 0), + (9, 12), + (8, 10), + (8, 7), + (9, 11), + (9, 10), + (10, 17), + (10, 11), + (10, 9), + (11, 13), + (11, 12), + (11, 10), + (11, 7), + (11, 5), + (11, 3), + (11, 1), + (8, 3), +]; + +pub(crate) static T24: [(u8, u16); 256] = [ + (4, 15), + (4, 13), + (6, 46), + (7, 80), + (8, 146), + (9, 262), + (9, 248), + (10, 434), + (10, 426), + (11, 669), + (11, 653), + (11, 649), + (11, 621), + (11, 517), + (12, 1032), + (9, 88), + (4, 14), + (4, 12), + (5, 21), + (6, 38), + (7, 71), + (8, 130), + (8, 122), + (9, 216), + (9, 209), + (9, 198), + (10, 327), + (10, 345), + (10, 319), + (10, 297), + (10, 279), + (8, 42), + (6, 47), + (5, 22), + (6, 41), + (7, 74), + (7, 68), + (8, 128), + (8, 120), + (9, 221), + (9, 207), + (9, 194), + (9, 182), + (10, 340), + (10, 315), + (10, 295), + (11, 541), + (7, 18), + (7, 81), + (6, 39), + (7, 75), + (7, 70), + (8, 134), + (8, 125), + (8, 116), + (9, 220), + (9, 204), + (9, 190), + (9, 178), + (10, 325), + (10, 311), + (10, 293), + (10, 271), + (7, 16), + (8, 147), + (7, 72), + (7, 69), + (8, 135), + (8, 127), + (8, 118), + (8, 112), + (9, 210), + (9, 200), + (9, 188), + (10, 352), + (10, 323), + (10, 306), + (10, 285), + (11, 540), + (7, 14), + (9, 263), + (7, 66), + (8, 129), + (8, 126), + (8, 119), + (8, 114), + (9, 214), + (9, 202), + (9, 192), + (9, 180), + (10, 341), + (10, 317), + (10, 301), + (10, 281), + (10, 262), + (7, 12), + (9, 249), + (8, 123), + (8, 121), + (8, 117), + (8, 113), + (9, 215), + (9, 206), + (9, 195), + (9, 185), + (10, 347), + (10, 330), + (10, 308), + (10, 291), + (10, 272), + (11, 520), + (7, 10), + (10, 435), + (8, 115), + (8, 111), + (8, 109), + (9, 211), + (9, 203), + (9, 196), + (9, 187), + (10, 353), + (10, 332), + (10, 313), + (10, 298), + (10, 283), + (11, 531), + (11, 381), + (8, 17), + (10, 427), + (9, 212), + (9, 208), + (9, 205), + (9, 201), + (9, 193), + (9, 186), + (9, 177), + (9, 169), + (10, 320), + (10, 303), + (10, 286), + (10, 268), + (11, 514), + (11, 377), + (8, 16), + (10, 335), + (9, 199), + (9, 197), + (9, 191), + (9, 189), + (9, 181), + (9, 174), + (10, 333), + (10, 321), + (10, 305), + (10, 289), + (10, 275), + (11, 521), + (11, 379), + (11, 371), + (8, 11), + (11, 668), + (9, 184), + (9, 183), + (9, 179), + (9, 175), + (10, 344), + (10, 331), + (10, 314), + (10, 304), + (10, 290), + (10, 277), + (11, 530), + (11, 383), + (11, 373), + (11, 366), + (8, 10), + (11, 652), + (10, 346), + (9, 171), + (9, 168), + (9, 164), + (10, 318), + (10, 309), + (10, 299), + (10, 287), + (10, 276), + (10, 263), + (11, 513), + (11, 375), + (11, 368), + (11, 362), + (8, 6), + (11, 648), + (10, 322), + (10, 316), + (10, 312), + (10, 307), + (10, 302), + (10, 292), + (10, 284), + (10, 269), + (10, 261), + (11, 512), + (11, 376), + (11, 370), + (11, 364), + (11, 359), + (8, 4), + (11, 620), + (10, 300), + (10, 296), + (10, 294), + (10, 288), + (10, 282), + (10, 273), + (10, 266), + (11, 515), + (11, 380), + (11, 374), + (11, 369), + (11, 365), + (11, 361), + (11, 357), + (8, 2), + (12, 1033), + (10, 280), + (10, 278), + (10, 274), + (10, 267), + (10, 264), + (10, 259), + (11, 382), + (11, 378), + (11, 372), + (11, 367), + (11, 363), + (11, 360), + (11, 358), + (11, 356), + (8, 0), + (8, 43), + (7, 20), + (7, 19), + (7, 17), + (7, 15), + (7, 13), + (7, 11), + (7, 9), + (7, 7), + (7, 6), + (7, 4), + (8, 7), + (8, 5), + (8, 3), + (8, 1), + (4, 3), +]; + +pub(crate) static C0: [(u8, u16); 16] = [ + (1, 1), + (4, 5), + (4, 4), + (5, 5), + (4, 6), + (6, 5), + (5, 4), + (6, 4), + (4, 7), + (5, 3), + (5, 6), + (6, 0), + (5, 7), + (6, 2), + (6, 3), + (6, 1), +]; + +pub(crate) static C1: [(u8, u16); 16] = [ + (4, 15), + (4, 14), + (4, 13), + (4, 12), + (4, 11), + (4, 10), + (4, 9), + (4, 8), + (4, 7), + (4, 6), + (4, 5), + (4, 4), + (4, 3), + (4, 2), + (4, 1), + (4, 0), +]; diff --git a/crates/ec-mp3/src/lib.rs b/crates/ec-mp3/src/lib.rs new file mode 100644 index 00000000..685c1e6e --- /dev/null +++ b/crates/ec-mp3/src/lib.rs @@ -0,0 +1,149 @@ +//! MP3 — MPEG-1/2/2.5 Layer III — decoding and encoding for the edith_codecs +//! family. +//! +//! Three ways in, smallest first: +//! +//! - [`Mp3Reader`] over a byte stream: push bytes, take frames. It skips ID3v2 +//! and the Xing/LAME/VBRI header frame, resyncs over junk, and keeps the bit +//! reservoir across frames. +//! - [`Mp3Decoder`], the [`ec_core::Decoder`] contract, for a container that +//! hands out one Layer III frame per packet. +//! - [`Mp3Encoder`]: interleaved PCM in, CBR Layer III frames out. +//! +//! **Where the constants came from.** Layer III's Huffman code tables and its +//! 512-tap polyphase window are normative data no formula produces. Rather +//! than copy them out of an existing implementation, `scripts/mp3-tables/` +//! *measures* them: 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 a leaf, checked for a Kraft sum +//! of exactly 1 and for complete, duplicate-free coverage of its value grid; +//! the window is least-squares fitted to a residual of 1.6e-6. The measured +//! scalefactor band widths agreed with the published MPEG-1 layouts exactly, +//! which is the cross-check that the rig itself was right. +//! +//! Everything else — side info, the bit reservoir, requantisation, stereo +//! coupling, the block windows, the psychoacoustic model — is written from the +//! standards (ISO/IEC 11172-3 and 13818-3). +//! +//! Free-format streams are refused by name rather than guessed at, since their +//! frame length is only knowable by scanning to the next sync word. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +pub mod decode; +pub mod encode; +pub mod header; + +mod filterbank; +mod huffman; +mod huffman_tables; +mod tables; +mod window; + +pub use decode::{DecodedFrame, Mp3Decode, Mp3Reader}; +pub use encode::{Mp3Encode, Mp3Encoder, Mp3EncoderConfig}; +pub use header::{ChannelMode, FrameHeader, Version}; + +use ec_core::error::{Error, Result}; +use ec_core::frame::{AudioFrame, ChannelLayout, Frame, SampleFormat}; +use ec_core::packet::{Buf, Packet}; +use ec_core::registry::{AudioParameters, CodecId, CodecParameters, Decoder, MediaParameters}; + +/// The [`ec_core::Decoder`] seat for MP3: one packet is one or more Layer III +/// frames, which is how Matroska, MP4 and the family's own probe deliver them. +#[derive(Debug)] +pub struct Mp3Decoder { + params: CodecParameters, + reader: Mp3Reader, + pending: Vec, + drained: bool, +} + +impl Mp3Decoder { + /// A decoder for a stream of Layer III packets. + pub fn new(params: CodecParameters) -> Result { + Ok(Mp3Decoder { + params, + reader: Mp3Reader::new(), + pending: Vec::new(), + drained: false, + }) + } + + fn take(&mut self) { + while let Ok(frame) = self.reader.next_frame() { + if frame.samples.is_empty() { + continue; + } + let layout = ChannelLayout::from_count(frame.channels); + let mut bytes = Vec::with_capacity(frame.samples.len() * 4); + for sample in &frame.samples { + bytes.extend_from_slice(&sample.to_ne_bytes()); + } + let samples = frame.samples.len() / frame.channels; + if let MediaParameters::Audio(audio) = &mut self.params.media { + audio.sample_rate = frame.sample_rate; + audio.layout = layout.clone(); + audio.format = Some(SampleFormat::F32); + } + if let Ok(audio) = AudioFrame::try_new( + SampleFormat::F32, + false, + layout, + frame.sample_rate, + samples, + vec![Buf::from(bytes)], + ) { + self.pending.push(audio); + } + } + } +} + +impl Decoder for Mp3Decoder { + fn codec_parameters(&self) -> &CodecParameters { + &self.params + } + + fn send_packet(&mut self, packet: &Packet) -> Result<()> { + self.reader.push(packet.data.as_ref()); + self.take(); + Ok(()) + } + + fn receive_frame(&mut self) -> Result { + if self.pending.is_empty() { + return Err(if self.drained { + Error::Eof + } else { + Error::NeedMore + }); + } + Ok(Frame::Audio(self.pending.remove(0))) + } + + fn flush(&mut self) -> Result<()> { + self.take(); + self.drained = true; + Ok(()) + } + + fn reset(&mut self) { + self.reader.reset(); + self.pending.clear(); + self.drained = false; + } +} + +/// Codec parameters for a Layer III stream of this shape. +pub fn codec_parameters(sample_rate: u32, channels: usize) -> CodecParameters { + let mut params = CodecParameters::new(CodecId::Mp3); + params.media = MediaParameters::Audio(AudioParameters { + sample_rate, + layout: ChannelLayout::from_count(channels), + format: Some(SampleFormat::F32), + bits_per_sample: None, + }); + params +} diff --git a/crates/ec-mp3/src/tables.rs b/crates/ec-mp3/src/tables.rs new file mode 100644 index 00000000..bd54f882 --- /dev/null +++ b/crates/ec-mp3/src/tables.rs @@ -0,0 +1,204 @@ +//! The constant tables Layer III needs besides the Huffman codes: scalefactor +//! band layouts, the pre-emphasis table, and the two lazily built power tables +//! requantisation runs on. +//! +//! The three MPEG-1 long-block layouts here were measured against a reference +//! decoder the same way the Huffman tables were (`scripts/mp3-tables/`, one +//! band attenuated at a time), which is also why they are stated as widths: a +//! width table cannot silently disagree with itself about where 576 ends. + +use std::sync::OnceLock; + +/// Widths of the 22 long scalefactor bands, by sample rate. +pub(crate) fn long_widths(sample_rate: u32) -> &'static [u16; 22] { + match sample_rate { + 44100 => &[ + 4, 4, 4, 4, 4, 4, 6, 6, 8, 8, 10, 12, 16, 20, 24, 28, 34, 42, 50, 54, 76, 158, + ], + 48000 => &[ + 4, 4, 4, 4, 4, 4, 6, 6, 6, 8, 10, 12, 16, 18, 22, 28, 34, 40, 46, 54, 54, 192, + ], + 32000 => &[ + 4, 4, 4, 4, 4, 4, 6, 6, 8, 10, 12, 16, 20, 24, 30, 38, 46, 56, 68, 84, 102, 26, + ], + 22050 | 16000 | 11025 | 12000 => &[ + 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 20, 24, 28, 32, 38, 46, 52, 60, 68, 58, 54, + ], + 24000 => &[ + 6, 6, 6, 6, 6, 6, 8, 10, 12, 14, 16, 18, 22, 26, 32, 38, 46, 54, 62, 70, 76, 36, + ], + // 8 kHz is the odd one out: five two-wide bands at the top rather than + // one wide one. + _ => &[ + 12, 12, 12, 12, 12, 12, 16, 20, 24, 28, 32, 40, 48, 56, 64, 76, 90, 2, 2, 2, 2, 2, + ], + } +} + +/// Widths of the 13 short scalefactor bands (per window), by sample rate. +pub(crate) fn short_widths(sample_rate: u32) -> &'static [u16; 13] { + match sample_rate { + 44100 => &[4, 4, 4, 4, 6, 8, 10, 12, 14, 18, 22, 30, 56], + 48000 => &[4, 4, 4, 4, 6, 6, 10, 12, 14, 16, 20, 26, 66], + 32000 => &[4, 4, 4, 4, 6, 8, 12, 16, 20, 26, 34, 42, 12], + 22050 => &[4, 4, 4, 6, 6, 8, 10, 14, 18, 26, 32, 42, 18], + 24000 => &[4, 4, 4, 6, 8, 10, 12, 14, 18, 24, 32, 44, 12], + // Measured: the MPEG-2.5 rates 11.025 and 12 kHz share the 16 kHz + // layout rather than the LSF rate they halve. + 16000 | 11025 | 12000 => &[4, 4, 4, 6, 8, 10, 12, 14, 18, 24, 30, 40, 18], + _ => &[8, 8, 8, 12, 16, 20, 24, 28, 36, 2, 2, 2, 26], + } +} + +/// Start offset of each long band, plus 576 as the last entry. +pub(crate) fn long_starts(sample_rate: u32) -> [u16; 23] { + let mut out = [0u16; 23]; + let mut acc = 0; + for (i, w) in long_widths(sample_rate).iter().enumerate() { + out[i] = acc; + acc += w; + } + out[22] = acc; + out +} + +/// Start offset of each short band within one window, plus 192. +pub(crate) fn short_starts(sample_rate: u32) -> [u16; 14] { + let mut out = [0u16; 14]; + let mut acc = 0; + for (i, w) in short_widths(sample_rate).iter().enumerate() { + out[i] = acc; + acc += w; + } + out[13] = acc; + out +} + +/// Additional high-frequency scalefactor applied when `preflag` is set. +pub(crate) const PRETAB: [u8; 22] = [ + 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 3, 3, 3, 2, 0, +]; + +/// `slen1`/`slen2` for the MPEG-1 `scalefac_compress` index. +pub(crate) const SLEN: [(u32, u32); 16] = [ + (0, 0), + (0, 1), + (0, 2), + (0, 3), + (3, 0), + (1, 1), + (1, 2), + (1, 3), + (2, 1), + (2, 2), + (2, 3), + (3, 1), + (3, 2), + (3, 3), + (4, 2), + (4, 3), +]; + +/// Scalefactor band counts per partition for the MPEG-2 LSF scalefactor +/// scheme, indexed `[block number][0 = long, 1 = short, 2 = mixed]`. +pub(crate) const LSF_PARTITIONS: [[[u8; 4]; 3]; 6] = [ + [[6, 5, 5, 5], [9, 9, 9, 9], [6, 9, 9, 9]], + [[6, 5, 7, 3], [9, 9, 12, 6], [6, 9, 12, 6]], + [[11, 10, 0, 0], [18, 18, 0, 0], [15, 18, 0, 0]], + [[7, 7, 7, 0], [12, 12, 12, 0], [6, 15, 12, 0]], + [[6, 6, 6, 3], [12, 9, 9, 6], [6, 12, 9, 6]], + [[8, 8, 5, 0], [15, 12, 9, 0], [6, 18, 9, 0]], +]; + +/// The largest quantised magnitude Layer III can code (15 plus 13 linbits). +pub(crate) const MAX_QUANT: usize = 8206; + +/// `|is|^(4/3)`, the requantisation curve, tabulated once. +pub(crate) fn power43() -> &'static [f32; MAX_QUANT + 1] { + static TABLE: OnceLock> = OnceLock::new(); + TABLE.get_or_init(|| { + let mut table = Box::new([0.0f32; MAX_QUANT + 1]); + for (i, slot) in table.iter_mut().enumerate() { + *slot = (i as f64).powf(4.0 / 3.0) as f32; + } + table + }) +} + +/// The four Layer III block windows: normal, start, short, stop. +pub(crate) fn windows() -> &'static [[f32; 36]; 4] { + static WINDOWS: OnceLock<[[f32; 36]; 4]> = OnceLock::new(); + WINDOWS.get_or_init(|| { + let mut w = [[0.0f32; 36]; 4]; + let sin36 = |i: usize| (std::f64::consts::PI / 36.0 * (i as f64 + 0.5)).sin() as f32; + let sin12 = |i: usize| (std::f64::consts::PI / 12.0 * (i as f64 + 0.5)).sin() as f32; + for (i, slot) in w[0].iter_mut().enumerate() { + *slot = sin36(i); + } + for (i, slot) in w[1].iter_mut().enumerate() { + *slot = match i { + 0..=17 => sin36(i), + 18..=23 => 1.0, + 24..=29 => sin12(i - 18), + _ => 0.0, + }; + } + for (i, slot) in w[2].iter_mut().enumerate().take(12) { + *slot = sin12(i); + } + for (i, slot) in w[3].iter_mut().enumerate() { + *slot = match i { + 0..=5 => 0.0, + 6..=11 => sin12(i - 6), + 12..=17 => 1.0, + _ => sin36(i), + }; + } + w + }) +} + +/// Alias-reduction butterfly coefficients, `(cs, ca)` for the eight lines each +/// side of a subband boundary. +pub(crate) fn alias_coefficients() -> &'static [(f32, f32); 8] { + static COEFFS: OnceLock<[(f32, f32); 8]> = OnceLock::new(); + COEFFS.get_or_init(|| { + let ci = [ + -0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037, + ]; + let mut out = [(0.0f32, 0.0f32); 8]; + for (slot, c) in out.iter_mut().zip(ci) { + let norm = (1.0f64 + c * c).sqrt(); + *slot = ((1.0 / norm) as f32, (c / norm) as f32); + } + out + }) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn every_band_layout_spans_its_granule() { + for rate in [44100, 48000, 32000, 24000, 22050, 16000, 12000, 11025, 8000] { + let long: u16 = long_widths(rate).iter().sum(); + let short: u16 = short_widths(rate).iter().sum(); + assert_eq!(long, 576, "long bands at {rate} Hz"); + assert_eq!(short * 3, 576, "short bands at {rate} Hz"); + assert_eq!(long_starts(rate)[22], 576); + assert_eq!(short_starts(rate)[13], 192); + } + } + + #[test] + fn lsf_partitions_cover_their_band_counts() { + for (block, entry) in LSF_PARTITIONS.iter().enumerate() { + let sums: Vec = entry + .iter() + .map(|p| p.iter().map(|v| u32::from(*v)).sum()) + .collect(); + assert_eq!(sums, vec![21, 36, 33], "block number {block}"); + } + } +} diff --git a/crates/ec-mp3/src/window.rs b/crates/ec-mp3/src/window.rs new file mode 100644 index 00000000..e27a7e3a --- /dev/null +++ b/crates/ec-mp3/src/window.rs @@ -0,0 +1,527 @@ +//! The Layer III polyphase window, measured from a reference decoder. +//! +//! `scripts/mp3-tables/` feeds frames whose spectrum it chooses through +//! ffmpeg and least-squares fits the 512 window taps to the PCM that comes +//! back; the fit residual is 1.6e-6 relative, i.e. the f32 noise floor of the +//! decoder that was measured. The same taps serve the encoder's analysis +//! filterbank (scaled by 1/32), which reconstructs to -85 dB -- the +//! pseudo-QMF's own design limit, not an approximation of ours. +//! +//! The eight taps at index `p % 64 == 16` multiply a matrixing row that is +//! identically zero, so they are unobservable and unused; they are zero here. + +/// The 512-tap prototype filter shared by the analysis and synthesis banks. +pub(crate) static WINDOW: [f32; 512] = [ + 0.000000011415852, + -0.000015267362, + -0.000015203146, + -0.0000151986715, + -0.00001516934, + -0.000015331996, + -0.000015299296, + -0.000030369547, + -0.00003051874, + -0.000030387224, + -0.00003047262, + -0.00004553826, + -0.000045790093, + -0.00006033324, + -0.00006074798, + -0.00007623177, + 0.0000000000000007771561, + -0.00009158812, + -0.00010707284, + -0.00010752892, + -0.00012210483, + -0.0001375902, + -0.00015264975, + -0.00016808163, + -0.000198351, + -0.00021326676, + -0.00024415043, + -0.00025923923, + -0.00028996877, + -0.00032021772, + -0.00036640486, + -0.00039679479, + -0.00044255037, + -0.00047290753, + -0.00053397013, + -0.00057965296, + -0.00062562595, + -0.00068629114, + -0.00074790895, + -0.00080878945, + -0.00088501174, + -0.00096131716, + -0.0010379666, + -0.0011140599, + -0.0012055617, + -0.0012974035, + -0.001388574, + -0.0014802893, + -0.0015868805, + -0.0016939237, + -0.0017852938, + -0.0019078987, + -0.0020141946, + -0.0021213335, + -0.0022432955, + -0.0023501269, + -0.0024565875, + -0.0025787377, + -0.0026854768, + -0.00279207, + -0.0028991497, + -0.0029907583, + -0.0030822374, + -0.0031738034, + 0.003250133, + 0.0033262433, + 0.00338757, + 0.0034334313, + 0.0034637738, + 0.0034788004, + 0.0034790176, + 0.0034639053, + 0.0034180349, + 0.0033721782, + 0.0032808688, + 0.0031739867, + 0.003051756, + 0.0028841344, + 0.0027005575, + 0.0024872634, + 0.0000000000000012733496, + 0.0019376706, + 0.0016176497, + 0.0012662442, + 0.00086979714, + 0.00044235107, + -0.000030705753, + -0.0005494556, + -0.001098628, + -0.0016938953, + -0.0023345852, + -0.0030061814, + -0.0037231992, + -0.004486055, + -0.0052950876, + -0.0061187474, + -0.0070038103, + -0.0079192305, + -0.008865455, + -0.009841983, + -0.010849041, + -0.011887125, + -0.012939475, + -0.014022803, + -0.015121499, + -0.01623552, + -0.01734931, + -0.018463053, + -0.019577023, + -0.02069092, + -0.021789964, + -0.022857735, + -0.023910528, + -0.024933018, + -0.0259098, + -0.02684026, + -0.027725205, + -0.028533855, + -0.029281769, + -0.029937815, + -0.030532835, + -0.031005554, + -0.03138714, + -0.03166223, + -0.031814594, + -0.031844933, + -0.03173854, + -0.031478826, + 0.031082166, + 0.0305177, + 0.029785281, + 0.02888459, + 0.027801497, + 0.0265352, + 0.025085581, + 0.023422332, + 0.021575933, + 0.019531135, + 0.017257782, + 0.014800756, + 0.0121154785, + 0.009231564, + 0.006134068, + 0.0028228818, + -0.000000000000000644611, + -0.0043945615, + -0.008316075, + -0.012420815, + -0.01670837, + -0.021178978, + -0.025818132, + -0.030609008, + -0.035552945, + -0.040634155, + -0.045837644, + -0.05113255, + -0.056533795, + -0.061996475, + -0.06752017, + -0.07305916, + -0.0786286, + -0.0841829, + -0.089706406, + -0.095169336, + -0.10054016, + -0.10581998, + -0.11094653, + -0.115921035, + -0.12069705, + -0.12525961, + -0.12956229, + -0.13359062, + -0.13729873, + -0.1406705, + -0.14367695, + -0.1462553, + -0.14842229, + -0.1501159, + -0.15130647, + -0.15196219, + -0.1520692, + -0.15159595, + -0.15049735, + -0.14877312, + -0.14636232, + -0.14326483, + -0.13944978, + -0.13488811, + -0.12957762, + -0.12347438, + -0.11657697, + -0.108856454, + 0.10031129, + 0.090927154, + 0.080688596, + 0.06959536, + 0.057617296, + 0.04478508, + 0.031082308, + 0.01651004, + 0.0010681328, + -0.015228168, + -0.03237904, + -0.050354324, + -0.069168, + -0.08877562, + -0.109161384, + -0.13031028, + -0.00000000000000026023126, + -0.17478941, + -0.19805925, + -0.22198515, + -0.24650589, + -0.27159062, + -0.29721087, + -0.32331842, + -0.34986892, + -0.3768008, + -0.40408376, + -0.43165684, + -0.45947304, + -0.48747197, + -0.5156101, + -0.5438234, + -0.5720369, + -0.60021967, + -0.62829626, + -0.6562196, + -0.68391407, + -0.7113179, + -0.7383724, + -0.76502967, + -0.7912138, + -0.8168645, + -0.84194964, + -0.86636347, + -0.89009124, + -0.91305554, + -0.93519616, + -0.9564821, + -0.9768524, + -0.99624646, + -1.0146182, + -1.0319365, + -1.0481571, + -1.0632175, + -1.0771183, + -1.0897832, + -1.1012113, + -1.1113733, + -1.1202233, + -1.1277452, + -1.1339263, + -1.1387645, + -1.1422124, + -1.1442869, + 1.1449894, + 1.1442884, + 1.1422125, + 1.1387625, + 1.133927, + 1.1277479, + 1.1202255, + 1.1113749, + 1.1012119, + 1.0897831, + 1.077118, + 1.0632172, + 1.048157, + 1.0319374, + 1.0146184, + 0.9962471, + 0.0000000000000007964717, + 0.95648247, + 0.93519664, + 0.9130558, + 0.8900912, + 0.8663634, + 0.84194976, + 0.81686413, + 0.7912142, + 0.76503056, + 0.7383738, + 0.7113198, + 0.68391466, + 0.6562191, + 0.6282958, + 0.6002202, + 0.5720369, + 0.54382306, + 0.51561016, + 0.48747298, + 0.45947272, + 0.43165582, + 0.40408316, + 0.37680054, + 0.34986863, + 0.32331842, + 0.29721078, + 0.27159154, + 0.24650584, + 0.2219845, + 0.19805893, + 0.17478915, + 0.1522064, + 0.13030985, + 0.10916119, + 0.088775314, + 0.06916808, + 0.050354168, + 0.03237904, + 0.015228211, + -0.0010681684, + -0.016510095, + -0.031082127, + -0.04478449, + -0.05761706, + -0.06959555, + -0.08068876, + -0.09092727, + 0.10031129, + 0.10885651, + 0.11657729, + 0.123474106, + 0.12957765, + 0.13488798, + 0.1394502, + 0.14326526, + 0.14636232, + 0.14877336, + 0.15049754, + 0.15159558, + 0.15206915, + 0.15196228, + 0.15130645, + 0.15011622, + 0.0000000000000002206003, + 0.14625533, + 0.14367671, + 0.14067101, + 0.13729863, + 0.1335911, + 0.12956247, + 0.12525932, + 0.120697, + 0.115920916, + 0.11094674, + 0.10581983, + 0.100540325, + 0.095169336, + 0.089706264, + 0.08418277, + 0.07862859, + 0.073058985, + 0.067519896, + 0.061996456, + 0.05653381, + 0.051132552, + 0.0458371, + 0.040634338, + 0.035553053, + 0.030609237, + 0.02581771, + 0.021179507, + 0.01670833, + 0.012420671, + 0.008315938, + 0.004394627, + 0.0006866427, + -0.0028229149, + -0.006134143, + -0.009231619, + -0.012115582, + -0.014800927, + -0.017258044, + -0.019531146, + -0.021575898, + -0.023422075, + -0.025085574, + -0.026534922, + -0.027801469, + -0.028885014, + -0.029785192, + -0.03051723, + 0.031082176, + 0.03147878, + 0.031738393, + 0.03184512, + 0.031814706, + 0.03166176, + 0.031387117, + 0.031005694, + 0.030532828, + 0.029937604, + 0.029281935, + 0.02853383, + 0.027725317, + 0.026840411, + 0.02590936, + 0.024932835, + -0.0000000000000014298339, + 0.022857612, + 0.021789733, + 0.020690892, + 0.019577093, + 0.018462965, + 0.017348979, + 0.016235009, + 0.015121544, + 0.014023043, + 0.0129397465, + 0.011886712, + 0.010849021, + 0.009841979, + 0.008865594, + 0.007919409, + 0.007003773, + 0.0061188545, + 0.0052949484, + 0.0044858786, + 0.003723058, + 0.0030056525, + 0.0023346553, + 0.0016937256, + 0.0010986148, + 0.0005493129, + 0.00003062855, + -0.00044273847, + -0.00086982694, + -0.0012664495, + -0.0016174339, + -0.001937911, + -0.0022277806, + -0.0024872052, + -0.0027008213, + -0.0028840094, + -0.003051711, + -0.0031738107, + -0.0032806862, + -0.0033721055, + -0.0034179622, + -0.0034639246, + -0.00347904, + -0.00347909, + -0.003463723, + -0.0034331984, + -0.0033875592, + -0.0033261578, + 0.0032501116, + 0.0031737192, + 0.0030822048, + 0.0029911308, + 0.0028991015, + 0.0027921288, + 0.0026856647, + 0.0025788378, + 0.002456706, + 0.0023499262, + 0.0022431447, + 0.002120262, + 0.0020142195, + 0.0019073315, + 0.001785405, + 0.001693759, + 0.0000000000000009972893, + 0.0014800375, + 0.0013885009, + 0.001296985, + 0.0012054051, + 0.0011147871, + 0.0010375459, + 0.0009614164, + 0.0008849344, + 0.00080879295, + 0.00074773876, + 0.0006866758, + 0.0006256105, + 0.0005799012, + 0.00053403573, + 0.00047302843, + 0.00044260576, + 0.00039682162, + 0.0003660489, + 0.00032072325, + 0.00028996973, + 0.00025934313, + 0.00024398624, + 0.00021362594, + 0.00019845674, + 0.00016780205, + 0.00015235315, + 0.0001368079, + 0.00012211184, + 0.00010672097, + 0.000106991814, + 0.00009128963, + 0.000076291864, + 0.00007616151, + 0.00006127107, + 0.000060929906, + 0.00004582208, + 0.000045436722, + 0.000030140414, + 0.000030621795, + 0.000030583265, + 0.000030157482, + 0.000015142228, + 0.0000153379, + 0.00001535084, + 0.000015364727, + 0.000015056947, + 0.000015421143, +]; diff --git a/crates/ec-mp3/tests/decode_matrix.rs b/crates/ec-mp3/tests/decode_matrix.rs new file mode 100644 index 00000000..1b0fbc7e --- /dev/null +++ b/crates/ec-mp3/tests/decode_matrix.rs @@ -0,0 +1,180 @@ +//! Our decoder against ffmpeg's, over every MP3 fixture: same sample count, +//! same samples. +//! +//! Correlation rather than a bit-exact compare, because Layer III's output is +//! defined by an inverse transform rather than by an integer recipe; ISO/IEC +//! 11172-4 states decoder accuracy the same way. The bar here is 0.999, and +//! what the fixtures actually reach is printed. +//! +//! Run the table: +//! cargo test -p ec-mp3 --release --test decode_matrix -- --nocapture + +use std::path::{Path, PathBuf}; +use std::process::Command; +use std::time::Instant; + +use ec_mp3::Mp3Reader; + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") +} + +fn mp3_fixtures() -> Vec { + let dir = fixtures().join("audio"); + let Ok(entries) = std::fs::read_dir(&dir) else { + return Vec::new(); + }; + let mut out: Vec = entries + .flatten() + .map(|e| e.path()) + .filter(|p| p.extension().is_some_and(|e| e == "mp3")) + .collect(); + out.sort(); + out +} + +fn ffmpeg_decode(path: &Path) -> Option<(Vec, u32, usize)> { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "f32le", "-"]) + .output() + .ok()?; + if !out.status.success() { + return None; + } + let samples = out + .stdout + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(); + let probe = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "a:0", + "-show_entries", + "stream=channels,sample_rate", + "-of", + "default=noprint_wrappers=1", + ]) + .arg(path) + .output() + .ok()?; + let text = String::from_utf8_lossy(&probe.stdout); + let field = |key: &str| { + text.lines() + .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) + .and_then(|v| v.trim().parse::().ok()) + }; + Some((samples, field("sample_rate")?, field("channels")? as usize)) +} + +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let n = a.len().min(b.len()); + let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); + for i in 0..n { + let (x, y) = (a[i] as f64, b[i] as f64); + ab += x * y; + aa += x * x; + bb += y * y; + } + if aa == 0.0 || bb == 0.0 { + return f64::from(u8::from(aa == bb)); + } + ab / (aa * bb).sqrt() +} + +/// Best correlation over the priming shift ffmpeg applied, and that shift. +/// +/// The score is the whole overlap rather than a window: fixture tones are +/// periodic, so a short window correlates almost as well one period out and +/// the search would settle on the wrong shift. +fn best_alignment(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) { + let mut best = (f64::MIN, 0usize); + let mut offset = 0; + while offset < got.len() && offset <= 2304 * channels { + let n = (got.len() - offset).min(want.len()).min(200_000); + let corr = correlation(&got[offset..offset + n], &want[..n]); + if corr > best.0 { + best = (corr, offset); + } + offset += channels; + } + let (_, offset) = best; + // The first and last frames are the encoder-delay and padding regions that + // gapless trimming exists for: the reservoir the first frame points back + // into predates the stream, and the last frame's tail is padding ffmpeg + // drops. Every frame between them is compared. + let skip = 1152 * channels; + let n = (got.len() - offset) + .min(want.len()) + .saturating_sub(2 * skip); + ( + correlation( + &got[offset + skip..offset + skip + n], + &want[skip..skip + n], + ), + offset, + ) +} + +#[test] +fn decodes_every_fixture_like_ffmpeg() { + let files = mp3_fixtures(); + if files.is_empty() { + eprintln!("no MP3 fixtures: run scripts/gen-fixtures.sh and scripts/gen-mp3-fixtures.sh"); + return; + } + println!( + "{:<34} {:>6} {:>3} {:>9} {:>9} {:>8}", + "fixture", "rate", "ch", "samples", "corr", "x rt" + ); + let mut worst = 1.0f64; + let mut failures = Vec::new(); + for path in &files { + let bytes = std::fs::read(path).expect("read fixture"); + let Some((want, rate, channels)) = ffmpeg_decode(path) else { + panic!("ffmpeg could not decode {}", path.display()); + }; + let start = Instant::now(); + let mut reader = Mp3Reader::new(); + reader.push(&bytes); + let frames = reader.decode_all(); + let elapsed = start.elapsed().as_secs_f64(); + let mut got = Vec::with_capacity(want.len()); + for frame in &frames { + got.extend_from_slice(&frame.samples); + } + let name = path.file_name().unwrap().to_string_lossy(); + // ffmpeg honours the LAME delay/padding tags and drops the encoder's + // priming samples; we hand back every frame we were given, so the + // comparison finds the shift first. Gapless trimming is a container + // concern, not a decoder one. + let (corr, offset) = best_alignment(&got, &want, channels); + let seconds = got.len() as f64 / (rate as f64 * channels as f64); + let realtime = seconds / elapsed.max(1e-9); + println!( + "{name:<34} {rate:>6} {channels:>3} {:>9} {corr:>9.6} {realtime:>8.0} (+{offset})", + got.len() + ); + // A sample count that disagrees by more than the encoder delay plus + // padding means we lost or invented audio, which correlation alone + // would hide. Two frames covers both ends of the gapless trim. + let slack = 2 * 1152 * channels; + if got.len() + slack < want.len() || want.len() + slack < got.len() { + failures.push(format!( + "{name}: {} samples, ffmpeg {} ", + got.len(), + want.len() + )); + } + if corr < 0.999 { + failures.push(format!("{name}: correlation {corr:.6}")); + } + worst = worst.min(corr); + } + println!("worst correlation {worst:.6} over {} fixtures", files.len()); + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/crates/ec-mp3/tests/encode_matrix.rs b/crates/ec-mp3/tests/encode_matrix.rs new file mode 100644 index 00000000..1de2a716 --- /dev/null +++ b/crates/ec-mp3/tests/encode_matrix.rs @@ -0,0 +1,223 @@ +//! Our encoder measured the only way a lossy one can be: encode, decode the +//! result with ffmpeg, correlate against the samples that went in. +//! +//! The bar is the incumbent this crate replaces, `rusty_mp3` 0.6.1, measured on +//! the same fixtures and the same metric (see `BAR`, and +//! `scripts/mp3-incumbent-bar.md` for how those numbers were produced). +//! +//! Run the table: +//! cargo test -p ec-mp3 --release --test encode_matrix -- --nocapture + +use std::path::{Path, PathBuf}; +use std::process::Command; + +use ec_mp3::{Mp3Encoder, Mp3EncoderConfig}; + +/// Correlation `rusty_mp3` 0.6.1 reaches on this corpus, measured with this +/// same alignment and metric (its own encoder, ffmpeg's decoder). The tone +/// fixtures reach 1.0 on both encoders and so cannot separate them; the +/// `mp3src-*` material — glide, broadband noise and a click every half second — +/// is what does. +const BAR: [(&str, [f64; 3]); 4] = [ + ("mp3src-mono-44100", [0.99920, 0.99983, 0.99999]), + ("mp3src-stereo-44100", [0.99612, 0.99847, 0.99972]), + ("mp3src-mono-48000", [0.99867, 0.99972, 0.99998]), + ("mp3src-stereo-48000", [0.99461, 0.99787, 0.99956]), +]; +const BITRATES: [u32; 3] = [128, 192, 320]; + +/// The incumbent's number for this fixture and bitrate. Fixtures it was not +/// measured on (the tones, which both encoders code perfectly) fall back to its +/// worst result at that rate. +fn bar_for(name: &str, kbps: u32) -> f64 { + let index = BITRATES.iter().position(|k| *k == kbps).unwrap_or(0); + for (fixture, values) in BAR { + if name.starts_with(fixture) { + return values[index]; + } + } + BAR.iter() + .map(|(_, v)| v[index]) + .fold(f64::INFINITY, f64::min) +} + +fn fixtures() -> PathBuf { + Path::new(env!("CARGO_MANIFEST_DIR")).join("../../fixtures") +} + +fn workdir(test: &str) -> PathBuf { + let dir = std::env::temp_dir().join(format!("ec-mp3-{}-{test}", std::process::id())); + std::fs::create_dir_all(&dir).expect("create work dir"); + dir +} + +/// Reads a WAV fixture as interleaved f32 plus its rate and channel count. +fn read_wav(path: &Path) -> Option<(Vec, u32, usize)> { + let out = Command::new("ffmpeg") + .args(["-v", "error", "-i"]) + .arg(path) + .args(["-f", "f32le", "-"]) + .output() + .ok()?; + if !out.status.success() { + return None; + } + let samples = out + .stdout + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(); + let probe = Command::new("ffprobe") + .args([ + "-v", + "error", + "-select_streams", + "a:0", + "-show_entries", + "stream=channels,sample_rate", + "-of", + "default=noprint_wrappers=1", + ]) + .arg(path) + .output() + .ok()?; + let text = String::from_utf8_lossy(&probe.stdout); + let field = |key: &str| { + text.lines() + .find_map(|l| l.strip_prefix(key)?.strip_prefix('=')) + .and_then(|v| v.trim().parse::().ok()) + }; + Some((samples, field("sample_rate")?, field("channels")? as usize)) +} + +fn correlation(a: &[f32], b: &[f32]) -> f64 { + let n = a.len().min(b.len()); + let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); + for i in 0..n { + let (x, y) = (a[i] as f64, b[i] as f64); + ab += x * y; + aa += x * x; + bb += y * y; + } + if aa == 0.0 || bb == 0.0 { + return 0.0; + } + ab / (aa * bb).sqrt() +} + +/// Best correlation over the encoder delay, which no MP3 encoder avoids. +fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) { + let mut best = (f64::MIN, 0usize); + let mut offset = 0; + while offset + channels < got.len() && offset <= 3000 * channels { + let n = (got.len() - offset).min(want.len()); + let skip = 1152 * channels; + if n <= 2 * skip { + break; + } + let corr = correlation( + &got[offset + skip..offset + n - skip], + &want[skip..n - skip], + ); + if corr > best.0 { + best = (corr, offset); + } + offset += channels; + } + best +} + +fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec { + let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { + bitrate_kbps: kbps, + vbr_quality: None, + }); + encoder + .push_pcm_f32(pcm, channels as u16, rate) + .expect("encoder accepts the fixture"); + encoder.finish(); + let mut out = Vec::new(); + while let Ok(frame) = encoder.next_packet() { + out.extend_from_slice(&frame); + } + out +} + +#[test] +fn encodes_above_the_incumbent_bar() { + let dir = fixtures().join("audio"); + let mut sources: Vec = std::fs::read_dir(&dir) + .into_iter() + .flatten() + .flatten() + .map(|e| e.path()) + .filter(|p| { + let name = p.file_name().map(|n| n.to_string_lossy().to_string()); + name.is_some_and(|n| n.starts_with("wav16-") || n.starts_with("mp3src-")) + && p.extension().is_some_and(|e| e == "wav") + }) + .collect(); + sources.sort(); + sources.retain(|p| { + let name = p.file_name().unwrap().to_string_lossy().to_string(); + name.contains("mono") || name.contains("stereo") + }); + if sources.is_empty() { + eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); + return; + } + let work = workdir("encode"); + println!( + "{:<30} {:>5} {:>6} {:>3} {:>9} {:>8} {:>9}", + "fixture", "kbps", "rate", "ch", "corr", "bar", "kbit/s" + ); + let mut failures = Vec::new(); + for source in &sources { + let Some((pcm, rate, channels)) = read_wav(source) else { + continue; + }; + for kbps in BITRATES { + let bar = bar_for(&source.file_name().unwrap().to_string_lossy(), kbps); + let bytes = encode(&pcm, rate, channels, kbps); + let path = work.join(format!( + "{}-{kbps}.mp3", + source.file_stem().unwrap().to_string_lossy() + )); + std::fs::write(&path, &bytes).expect("write encoded file"); + let out = Command::new("ffmpeg") + .args(["-v", "warning", "-i"]) + .arg(&path) + .args(["-f", "f32le", "-"]) + .output() + .expect("run ffmpeg"); + let stderr = String::from_utf8_lossy(&out.stderr).trim().to_string(); + if !stderr.is_empty() { + failures.push(format!("{}: ffmpeg said {stderr}", path.display())); + } + let decoded: Vec = out + .stdout + .chunks_exact(4) + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) + .collect(); + let (corr, _offset) = aligned(&decoded, &pcm, channels); + let seconds = pcm.len() as f64 / (rate as f64 * channels as f64); + let measured = bytes.len() as f64 * 8.0 / seconds / 1000.0; + let name = source.file_name().unwrap().to_string_lossy(); + println!( + "{name:<30} {kbps:>5} {rate:>6} {channels:>3} {corr:>9.5} {bar:>8.5} {measured:>9.1}" + ); + // Matching counts as passing: at 320 kbit/s both encoders are + // within a part in 10^5 of the source and the difference between + // them is smaller than the metric resolves. + if corr < bar - 1e-5 { + failures.push(format!("{name} at {kbps} kbit/s: {corr:.5} < bar {bar:.5}")); + } + if (measured - kbps as f64).abs() > kbps as f64 * 0.05 { + failures.push(format!( + "{name} at {kbps} kbit/s: wrote {measured:.1} kbit/s" + )); + } + } + } + assert!(failures.is_empty(), "{failures:#?}"); +} diff --git a/scripts/gen-mp3-fixtures.sh b/scripts/gen-mp3-fixtures.sh new file mode 100755 index 00000000..88052171 --- /dev/null +++ b/scripts/gen-mp3-fixtures.sh @@ -0,0 +1,69 @@ +#!/usr/bin/env bash +# MP3 fixtures beyond the family matrix in gen-fixtures.sh: every Layer III +# sampling frequency (MPEG-1, MPEG-2 LSF and MPEG-2.5), both channel modes, +# CBR and VBR, on material that forces block switching and a wide spread of +# Huffman tables. +# +# The family matrix only covers 44.1/48 kHz stereo and mono at one bitrate, +# which leaves the LSF side info, the 8 kHz band layout and the short-block +# path unexercised — every one of those is a separate table in the decoder. +# +# Output: fixtures/audio/mp3ext---.mp3 (gitignored). +set -euo pipefail + +here=$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd) +FIXTURES="$here/../fixtures" +mkdir -p "$FIXTURES/audio" + +src="$FIXTURES/audio/.mp3src.wav" +if [ ! -f "$src" ]; then + # A tone with a glide, broadband noise and a click every half second: the + # click is what makes an encoder switch to short blocks, and the noise is + # what makes it reach for the escape-coded Huffman tables. + 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)" + right="0.30*sin(2*PI*443*t)+0.12*(random(1)-0.5)+0.7*lt(mod(t\,0.5)\,0.002)" + ffmpeg -v error -y -f lavfi -i "aevalsrc='${left}'|'${right}':d=3:s=48000" \ + -c:a pcm_s16le "$src" +fi + +# The same material as PCM, mono and stereo, for the encoder's quality table: +# a tone fixture cannot tell two encoders apart, and this one can. +for rate in 44100 48000; do + for mode in mono stereo; do + channels=1 + [ "$mode" = stereo ] && channels=2 + ffmpeg -v error -y -i "$src" -ar "$rate" -ac "$channels" -c:a pcm_s16le \ + "$FIXTURES/audio/mp3src-${mode}-${rate}.wav" + done +done + +RATES=(48000 44100 32000 24000 22050 16000 12000 11025 8000) +made=0 +for rate in "${RATES[@]}"; do + for mode in mono stereo; do + channels=1 + [ "$mode" = stereo ] && channels=2 + for setting in cbr128 cbr320 vbr2; do + case "$setting" in + cbr128) opts=(-b:a 128k) ;; + cbr320) opts=(-b:a 320k) ;; + vbr2) opts=(-q:a 2) ;; + esac + # MPEG-2/2.5 rates cap out well below 320 kbit/s. + if [ "$setting" = cbr320 ] && [ "$rate" -lt 32000 ]; then + continue + fi + out="$FIXTURES/audio/mp3ext-${mode}-${rate}-${setting}.mp3" + ffmpeg -v error -y -i "$src" -ar "$rate" -ac "$channels" \ + -c:a libmp3lame "${opts[@]}" "$out" + made=$((made + 1)) + done + done +done +# One simple-stereo file: LAME picks joint stereo by default, so the plain +# left/right path would otherwise never be decoded. +ffmpeg -v error -y -i "$src" -ar 44100 -ac 2 -c:a libmp3lame -b:a 192k \ + -joint_stereo 0 "$FIXTURES/audio/mp3ext-simplestereo-44100-cbr192.mp3" +made=$((made + 1)) + +echo "wrote $made MP3 fixtures to $FIXTURES/audio" diff --git a/scripts/mp3-tables/emit_tables.py b/scripts/mp3-tables/emit_tables.py new file mode 100644 index 00000000..1b87d526 --- /dev/null +++ b/scripts/mp3-tables/emit_tables.py @@ -0,0 +1,53 @@ +"""Turn the measured Huffman tables into ec-mp3 source.""" + +import json + +HDR = '''//! Layer III Huffman code tables. +//! +//! Every entry here was *measured*, not transcribed: `scripts/mp3-tables.py` +//! writes legal Layer III frames whose main-data bits it chooses, decodes them +//! with ffmpeg, and walks each code tree by asking whether all continuations of +//! a bit prefix decode to the same pair. The result is checked for a Kraft sum +//! of exactly 1, for full coverage of the value grid, and for uniqueness before +//! it is written out, so a wrong entry cannot reach this file silently. +//! +//! `(length, code)` indexed by `x * dim + y`, where `x` and `y` are the two +//! (or four, for the count1 tables) values the codeword yields, in the order +//! they are written to the spectrum. + +''' + + +def emit_table(name, entries, dim, nvals): + idx = {} + for code, vals in entries.items(): + i = 0 + for v in vals: + i = i * dim + v + idx[i] = (len(code), int(code, 2) if code else 0) + assert len(idx) == dim ** nvals, (name, len(idx)) + body = ", ".join(f"({idx[i][0]}, {idx[i][1]})" for i in range(dim ** nvals)) + return f"static {name}: [(u8, u16); {dim ** nvals}] = [{body}];\n" + + +def main(): + tabs = json.load(open("huffman.json")) + out = [HDR] + names = {} + for key in ("1", "2", "3", "5", "6", "7", "8", "9", "10", "11", "12", + "13", "15", "16", "24"): + entries = tabs[key] + dim = max(max(v) for v in entries.values()) + 1 + name = f"T{key}" + names[key] = name + out.append(emit_table(name, entries, dim, 2)) + for sel in (0, 1): + entries = tabs[f"count1_{sel}"] + out.append(emit_table(f"C{sel}", entries, 2, 4)) + with open("huffman_tables.rs", "w") as f: + f.write("\n".join(out)) + print("wrote huffman_tables.rs") + + +if __name__ == "__main__": + main() diff --git a/scripts/mp3-tables/learn_huffman.py b/scripts/mp3-tables/learn_huffman.py new file mode 100644 index 00000000..63670b35 --- /dev/null +++ b/scripts/mp3-tables/learn_huffman.py @@ -0,0 +1,95 @@ +"""Measure every Layer III Huffman table by walking the code tree against the +ffmpeg decoder: a prefix is a codeword exactly when every continuation decodes +to the same pair (values clamped at 15, so linbits escapes compare equal).""" + +import json +import sys +import numpy as np +from probe_engine import Engine, values + +# (table index used on the wire, entries per axis, linbits, coefficients read) +BIG_TABLES = [ + (1, 2, 0), (2, 3, 0), (3, 3, 0), (5, 4, 0), (6, 4, 0), + (7, 6, 0), (8, 6, 0), (9, 6, 0), (10, 8, 0), (11, 8, 0), (12, 8, 0), + (13, 16, 0), (15, 16, 0), (16, 16, 1), (24, 16, 4), +] +MAXDEPTH = 24 + + +def learn_table(engine, tsel, dim, quad=False): + """Returns {codeword bits (tuple) : tuple of values}.""" + leaves = {} + level = [()] + depth = 0 + while level: + depth += 1 + if depth > MAXDEPTH: + raise RuntimeError(f"table {tsel}: tree deeper than {MAXDEPTH}") + probes = [] + for prefix in level: + for fill in (0, 1): + bits = list(prefix) + [fill] * 48 + if quad: + probes.append((bits, 0, 0, tsel)) + else: + probes.append((bits, tsel, 1, 0)) + got = engine.run(probes) + n = 4 if quad else 2 + nxt = [] + for i, prefix in enumerate(level): + v0 = np.minimum(values(got[2 * i], n), 15) + v1 = np.minimum(values(got[2 * i + 1], n), 15) + if tuple(v0) == tuple(v1): + leaves[prefix] = tuple(int(x) for x in v0) + else: + nxt.append(prefix + (0,)) + nxt.append(prefix + (1,)) + level = nxt + return leaves + + +def check(leaves, dim, quad, name): + kraft = sum(2.0 ** -len(c) for c in leaves) + vals = sorted(leaves.values()) + expect = dim ** (4 if quad else 2) + ok = True + if abs(kraft - 1.0) > 1e-12: + print(f" !! {name}: kraft = {kraft}") + ok = False + if len(leaves) != expect: + print(f" !! {name}: {len(leaves)} leaves, expected {expect}") + ok = False + if len(set(vals)) != len(vals): + print(f" !! {name}: duplicate values") + ok = False + return ok + + +def main(): + Minv = np.load("Minv.npy") + engine = Engine(Minv) + out = {} + allok = True + for tsel, dim, linbits in BIG_TABLES: + leaves = learn_table(engine, tsel, dim) + ok = check(leaves, dim, False, f"table {tsel}") + allok &= ok + maxlen = max(len(c) for c in leaves) + print(f"table {tsel:2d}: {len(leaves):3d} codes, max len {maxlen:2d}, " + f"linbits {linbits}, ok={ok}") + out[str(tsel)] = {"".join(map(str, c)): v for c, v in leaves.items()} + for tsel in (0, 1): + leaves = learn_table(engine, tsel, 2, quad=True) + ok = check(leaves, 2, True, f"count1 {tsel}") + allok &= ok + print(f"count1 {tsel}: {len(leaves)} codes, max len " + f"{max(len(c) for c in leaves)}, ok={ok}") + out[f"count1_{tsel}"] = {"".join(map(str, c)): v for c, v in leaves.items()} + with open("huffman.json", "w") as f: + json.dump(out, f, indent=0) + print("all tables consistent:", allok) + return 0 if allok else 1 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/mp3-tables/learn_sfb.py b/scripts/mp3-tables/learn_sfb.py new file mode 100644 index 00000000..534921de --- /dev/null +++ b/scripts/mp3-tables/learn_sfb.py @@ -0,0 +1,56 @@ +"""Measure the MPEG-1 long-block scalefactor band edges: flat spectrum, one +band attenuated at a time, read the edges off the recovered coefficients.""" + +import sys +import numpy as np +from mp3probe import BitWriter, Granule, frame_bytes, ffmpeg_decode +from probe_engine import GLOBAL_GAIN, SCALE + +TABLE1 = [(1, 0b1), (3, 0b001), (2, 0b01), (3, 0b000)] +SC = 13 # slen1 = slen2 = 3 +SLEN = 3 +NBANDS = 21 # scalefactors transmitted for sfb 0..20 + + +def probe_bits(band): + bw = BitWriter() + for b in range(NBANDS): + bw.w(7 if b == band else 0, SLEN) + ln, code = TABLE1[3] # (1,1) + for _ in range(288): + bw.w(code, ln) + bw.w(0, 1) + bw.w(0, 1) + return bw.bits + + +def main(): + Minv = np.load("Minv.npy") + for srate_idx, srate in enumerate([44100, 48000, 32000]): + stream = b"" + for band in range(NBANDS): + bits = probe_bits(band) + g = Granule(part2_3_length=len(bits), big_values=288, + global_gain=GLOBAL_GAIN, scalefac_compress=SC, + table_select=(1, 1, 1)) + stream += frame_bytes([g, Granule()], [bits, []], srate_idx=srate_idx) + stream += frame_bytes([Granule(), Granule()], [[], []], srate_idx=srate_idx) + pcm, err = ffmpeg_decode(stream) + assert not err.strip(), err + edges = [0] + for band in range(NBANDS): + xr = (pcm[band * 2304:(band + 1) * 2304] @ Minv)[:576] + att = np.abs(xr) / SCALE + low = np.where(att < 0.5)[0] # attenuated by 2^-3.5 + if len(low) == 0: + print(f" {srate}: band {band} showed no attenuation") + continue + edges.append(int(low[-1]) + 1) + widths = [edges[i + 1] - edges[i] for i in range(len(edges) - 1)] + widths.append(576 - edges[-1]) + print(f"{srate} long widths ({sum(widths)}): {widths}") + return 0 + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/mp3-tables/learn_window.py b/scripts/mp3-tables/learn_window.py new file mode 100644 index 00000000..37f57cf0 --- /dev/null +++ b/scripts/mp3-tables/learn_window.py @@ -0,0 +1,83 @@ +"""Measure the Layer III synthesis window D[512] from the ffmpeg decoder. + +Probes carry only +-1 spectral values, written with Huffman table 1 (four +codewords), so nothing but the header/side-info syntax is assumed. The decode +chain up to the synthesis window is modelled exactly, leaving a linear system +pcm = A @ D that a least-squares solve inverts. +""" + +import numpy as np +import sys +from mp3probe import (BitWriter, Granule, frame_bytes, ffmpeg_decode, + granules_to_subband, synthesis_basis) + +# table 1: (x,y) -> (length, code), index = x*2 + y +TABLE1 = [(1, 0b1), (3, 0b001), (2, 0b01), (3, 0b000)] + +GLOBAL_GAIN = 170 # 2^((gg-210)/4) = 2^-10 spectral scale, far from clipping + + +def write_pairs(pairs): + bw = BitWriter() + for (x, sx), (y, sy) in pairs: + ln, code = TABLE1[x * 2 + y] + bw.w(code, ln) + if x: + bw.w(sx, 1) + if y: + bw.w(sy, 1) + return bw.bits + + +def probe_frames(rng, nframes=6, npairs=288): + """Random +-1 spectra; returns (mp3 bytes, list of granule spectra).""" + stream = b"" + spectra = [] + for _ in range(nframes): + grans, mains = [], [] + for _g in range(2): + vals = rng.integers(0, 2, size=(npairs, 2)) + signs = rng.integers(0, 2, size=(npairs, 2)) + pairs = [((int(vals[i, 0]), int(signs[i, 0])), + (int(vals[i, 1]), int(signs[i, 1]))) for i in range(npairs)] + bits = write_pairs(pairs) + grans.append(Granule(part2_3_length=len(bits), big_values=npairs, + global_gain=GLOBAL_GAIN, table_select=(1, 1, 1))) + mains.append(bits) + xr = np.zeros(576) + scale = 2.0 ** ((GLOBAL_GAIN - 210) / 4.0) + for i in range(npairs): + for j in range(2): + v = float(vals[i, j]) + if signs[i, j]: + v = -v + xr[2 * i + j] = v * scale + spectra.append(xr) + stream += frame_bytes(grans, mains) + return stream, spectra + + +def main(): + rng = np.random.default_rng(0xC0DE) + mp3, spectra = probe_frames(rng) + pcm, err = ffmpeg_decode(mp3) + print(f"ffmpeg: {len(pcm)} samples, stderr={err.strip()!r}, peak={np.abs(pcm).max():.6g}") + slots = granules_to_subband(spectra) + A = synthesis_basis(slots) + print(f"model: {A.shape[0]} samples from {len(slots)} slots") + n = min(len(pcm), A.shape[0]) + # frame-granularity alignment search + best = None + for off in range(0, len(pcm) - n + 1, 1152 // 2): + D, res, rank, _ = np.linalg.lstsq(A[:n], pcm[off:off + n], rcond=None) + resid = np.linalg.norm(A[:n] @ D - pcm[off:off + n]) / max(np.linalg.norm(pcm[off:off + n]), 1e-30) + if best is None or resid < best[0]: + best = (resid, off, D, rank) + resid, off, D, rank = best + print(f"offset={off} rank={rank} relative residual={resid:.3e}") + print(f"D peak={np.abs(D).max():.6g} D[0..4]={D[:5]}") + np.save("D.npy", D) + + +if __name__ == "__main__": + sys.exit(main()) diff --git a/scripts/mp3-tables/lsf_probe.py b/scripts/mp3-tables/lsf_probe.py new file mode 100644 index 00000000..52006c3c --- /dev/null +++ b/scripts/mp3-tables/lsf_probe.py @@ -0,0 +1,71 @@ +"""Short-block reorder probes for the low sampling frequencies: one non-zero +coefficient per granule, so the spectral position it lands in reveals the +scalefactor band widths.""" +import numpy as np +from mp3probe import BitWriter, Granule +from learn_window import TABLE1, GLOBAL_GAIN + +RATES = {8000: (0, 2), 11025: (0, 0), 12000: (0, 1), 16000: (2, 2), 22050: (2, 0), 24000: (2, 1)} +BITRATES_V2 = [0, 8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160] + + +def lsf_frame(granule, main_bits, rate, bitrate_idx=14): + version_id, rate_idx = RATES[rate] + frame_len = 72 * BITRATES_V2[bitrate_idx] * 1000 // rate + bw = BitWriter() + bw.w(0x7FF, 11); bw.w(version_id, 2); bw.w(0b01, 2); bw.w(1, 1) + bw.w(bitrate_idx, 4); bw.w(rate_idx, 2); bw.w(0, 1); bw.w(0, 1) + bw.w(0b11, 2); bw.w(0, 2); bw.w(0, 1); bw.w(1, 1); bw.w(0, 2) + bw.w(0, 8) # main_data_begin + bw.w(0, 1) # private + g = granule + bw.w(g.part2_3_length, 12); bw.w(g.big_values, 9); bw.w(g.global_gain, 8) + bw.w(g.scalefac_compress, 9) + bw.w(1 if g.block_type else 0, 1) + if g.block_type: + bw.w(g.block_type, 2); bw.w(g.mixed_block, 1) + for t in g.table_select[:2]: + bw.w(t, 5) + for s in g.subblock_gain: + bw.w(s, 3) + else: + for t in g.table_select: + bw.w(t, 5) + bw.w(g.region0_count, 4); bw.w(g.region1_count, 3) + bw.w(g.scalefac_scale, 1); bw.w(g.count1table_select, 1) + assert len(bw) == 32 + 9 * 8, len(bw) + bw.bits.extend(main_bits) + assert len(bw) <= frame_len * 8, (len(bw), frame_len * 8) + return bw.bytes(pad_to=frame_len) + + +def pair_bits(x, y): + bw = BitWriter() + ln, code = TABLE1[x * 2 + y] + bw.w(code, ln) + if x: + bw.w(0, 1) + if y: + bw.w(0, 1) + return bw.bits + + +def build(rate, positions): + stream = b"" + for pos in positions: + bits = [] + for i in range(288): + bits += pair_bits(1 if 2 * i == pos else 0, 1 if 2 * i + 1 == pos else 0) + g = Granule(part2_3_length=len(bits), big_values=288, global_gain=GLOBAL_GAIN, + table_select=(1, 1, 1), block_type=2, mixed_block=0) + stream += lsf_frame(g, bits, rate) + stream += lsf_frame(Granule(), [], rate) + return stream + + +if __name__ == "__main__": + import sys + rate = int(sys.argv[1]) + positions = list(range(576)) + open(f"/tmp/lsf{rate}.mp3", "wb").write(build(rate, positions)) + print("wrote", rate, len(positions)) diff --git a/scripts/mp3-tables/mp3op.py b/scripts/mp3-tables/mp3op.py new file mode 100644 index 00000000..a85f4d9f --- /dev/null +++ b/scripts/mp3-tables/mp3op.py @@ -0,0 +1,85 @@ +"""The linear map (requantised spectrum -> PCM) for one probe frame, and its +pseudo-inverse: what turns an ffmpeg decode back into the integers a probe's +Huffman bits decoded to.""" + +import math +import numpy as np +from mp3probe import ALIAS_CS, ALIAS_CA, WIN_NORMAL + +NSLOTS = 72 # probe frame (36 slots) + trailing silent frame +NSAMPLES = NSLOTS * 32 + + +def imdct_matrix(): + n = 36 + return np.array([[math.cos(math.pi / (2 * n) * (2 * i + 1 + n // 2) * (2 * k + 1)) + for k in range(18)] for i in range(n)]) * WIN_NORMAL[:, None] + + +def alias_matrix(): + ar = np.eye(576) + for sb in range(1, 32): + for i in range(8): + lo, hi = sb * 18 - 1 - i, sb * 18 + i + a, b = ar[lo].copy(), ar[hi].copy() + ar[lo] = a * ALIAS_CS[i] - b * ALIAS_CA[i] + ar[hi] = b * ALIAS_CS[i] + a * ALIAS_CA[i] + return ar + + +def spectrum_to_slots(): + """(2 granules x 576) -> (72 slots x 32 subbands), flattened columns.""" + imw = imdct_matrix() + ar = alias_matrix() + L = np.zeros((1152, NSLOTS * 32)) + for g in range(2): + for sb in range(32): + for k in range(18): + col = np.zeros(NSLOTS * 32) + for i in range(18): + t0 = 18 * g + i + sign = -1.0 if (sb % 2 == 1 and i % 2 == 1) else 1.0 + col[t0 * 32 + sb] += imw[i, k] * sign + t1 = 18 * (g + 1) + i + sign = -1.0 if (sb % 2 == 1 and i % 2 == 1) else 1.0 + col[t1 * 32 + sb] += imw[18 + i, k] * sign + # the alias butterflies mix coefficients before the imdct + L[g * 576:(g + 1) * 576] += np.outer(ar[sb * 18 + k, :], col) + return L + + +def slots_to_pcm(D): + N = np.array([[math.cos((16 + i) * (2 * k + 1) * math.pi / 64) for k in range(32)] + for i in range(64)]) + S = np.zeros((NSLOTS * 32, NSAMPLES)) + for i in range(16): + Ci = np.zeros((32, 32)) + for j in range(32): + b = j if i % 2 == 0 else j + 32 + Ci[j] = D[j + 32 * i] * N[b] + for t in range(NSLOTS): + s = t - i + if s < 0: + continue + S[s * 32:(s + 1) * 32, t * 32:(t + 1) * 32] += Ci.T + return S + + +def build(D): + M = spectrum_to_slots() @ slots_to_pcm(D) + return M, np.linalg.pinv(M) + + +if __name__ == "__main__": + D = np.load("D.npy") + M, Minv = build(D) + np.save("M.npy", M) + np.save("Minv.npy", Minv) + print("M", M.shape, "cond ok") + + # self-check: round-trip a random spectrum through the model + rng = np.random.default_rng(7) + c = rng.normal(size=1152) * 1e-3 + pcm = c @ M + back = pcm @ Minv + print("model round-trip max err", np.abs(back - c).max()) diff --git a/scripts/mp3-tables/mp3probe.py b/scripts/mp3-tables/mp3probe.py new file mode 100644 index 00000000..46a44f43 --- /dev/null +++ b/scripts/mp3-tables/mp3probe.py @@ -0,0 +1,211 @@ +"""Black-box probe rig for MPEG-1 Layer III. + +Builds legal Layer III frames whose main data we control bit for bit, decodes +them with ffmpeg, and models the decode chain analytically so the spec's +constant tables (synthesis window, Huffman codes, scalefactor bands) can be +*measured* rather than copied from an implementation. +""" + +import math +import subprocess +import tempfile +import os +import numpy as np + +SRATES = [44100, 48000, 32000] +BITRATES = [0, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320] + + +class BitWriter: + def __init__(self): + self.bits = [] + + def w(self, value, n): + for i in range(n - 1, -1, -1): + self.bits.append((value >> i) & 1) + + def __len__(self): + return len(self.bits) + + def bytes(self, pad_to=None): + bits = list(self.bits) + if pad_to is not None: + bits += [0] * (pad_to * 8 - len(bits)) + while len(bits) % 8: + bits.append(0) + out = bytearray() + for i in range(0, len(bits), 8): + b = 0 + for j in range(8): + b = (b << 1) | bits[i + j] + out.append(b) + return bytes(out) + + +class Granule: + """One granule of side info; long blocks only (all the probes need).""" + + def __init__(self, part2_3_length=0, big_values=0, global_gain=210, + scalefac_compress=0, table_select=(0, 0, 0), region0_count=15, + region1_count=1, preflag=0, scalefac_scale=0, count1table_select=0, + block_type=0, mixed_block=0, subblock_gain=(0, 0, 0)): + self.block_type = block_type + self.mixed_block = mixed_block + self.subblock_gain = subblock_gain + self.part2_3_length = part2_3_length + self.big_values = big_values + self.global_gain = global_gain + self.scalefac_compress = scalefac_compress + self.table_select = table_select + self.region0_count = region0_count + self.region1_count = region1_count + self.preflag = preflag + self.scalefac_scale = scalefac_scale + self.count1table_select = count1table_select + + def write(self, bw): + bw.w(self.part2_3_length, 12) + bw.w(self.big_values, 9) + bw.w(self.global_gain, 8) + bw.w(self.scalefac_compress, 4) + bw.w(1 if self.block_type else 0, 1) # window_switching_flag + if self.block_type: + bw.w(self.block_type, 2) + bw.w(self.mixed_block, 1) + for t in self.table_select[:2]: + bw.w(t, 5) + for g in self.subblock_gain: + bw.w(g, 3) + else: + for t in self.table_select: + bw.w(t, 5) + bw.w(self.region0_count, 4) + bw.w(self.region1_count, 3) + bw.w(self.preflag, 1) + bw.w(self.scalefac_scale, 1) + bw.w(self.count1table_select, 1) + + +def frame_bytes(granules, main_data, srate_idx=0, bitrate_idx=14, padding=0): + """One mono MPEG-1 Layer III frame. `main_data` is a list of bit lists.""" + srate = SRATES[srate_idx] + frame_len = 144 * BITRATES[bitrate_idx] * 1000 // srate + padding + bw = BitWriter() + bw.w(0x7FF, 11) + bw.w(0b11, 2) # MPEG-1 + bw.w(0b01, 2) # Layer III + bw.w(1, 1) # no CRC + bw.w(bitrate_idx, 4) + bw.w(srate_idx, 2) + bw.w(padding, 1) + bw.w(0, 1) + bw.w(0b11, 2) # mono + bw.w(0, 2) + bw.w(0, 1) + bw.w(1, 1) + bw.w(0, 2) + # side info, mono: 17 bytes + bw.w(0, 9) # main_data_begin + bw.w(0, 5) # private_bits + bw.w(0, 4) # scfsi + for g in granules: + g.write(bw) + assert len(bw) == 32 + 17 * 8, len(bw) + for bits in main_data: + bw.bits.extend(bits) + assert len(bw) <= frame_len * 8, (len(bw), frame_len * 8) + return bw.bytes(pad_to=frame_len) + + +def ffmpeg_decode(mp3: bytes, channels=1): + """Decode with ffmpeg, returning float32 samples (no resampling).""" + with tempfile.NamedTemporaryFile(suffix=".mp3", delete=False) as f: + f.write(mp3) + path = f.name + try: + p = subprocess.run( + ["ffmpeg", "-v", "error", "-i", path, "-f", "f32le", "-ac", str(channels), "-"], + capture_output=True, check=True) + return np.frombuffer(p.stdout, dtype=np.float32).astype(np.float64), p.stderr.decode() + finally: + os.unlink(path) + + +# ---------------------------------------------------------------- model side + +def imdct36(X): + """ISO Layer III IMDCT, n = 36.""" + n = 36 + out = np.zeros(n) + for i in range(n): + s = 0.0 + for k in range(n // 2): + s += X[k] * math.cos(math.pi / (2 * n) * (2 * i + 1 + n // 2) * (2 * k + 1)) + out[i] = s + return out + + +WIN_NORMAL = np.array([math.sin(math.pi / 36 * (i + 0.5)) for i in range(36)]) + +ALIAS_CI = [-0.6, -0.535, -0.33, -0.185, -0.095, -0.041, -0.0142, -0.0037] +ALIAS_CS = np.array([1.0 / math.sqrt(1.0 + c * c) for c in ALIAS_CI]) +ALIAS_CA = np.array([c / math.sqrt(1.0 + c * c) for c in ALIAS_CI]) + + +def alias_reduce(xr): + """In-place butterflies across the 31 long-block subband boundaries.""" + xr = xr.copy() + for sb in range(1, 32): + for i in range(8): + lo = sb * 18 - 1 - i + hi = sb * 18 + i + a, b = xr[lo], xr[hi] + xr[lo] = a * ALIAS_CS[i] - b * ALIAS_CA[i] + xr[hi] = b * ALIAS_CS[i] + a * ALIAS_CA[i] + return xr + + +def granules_to_subband(granule_spectra): + """Requantised spectra (long blocks) -> subband samples [slot][32].""" + overlap = np.zeros((32, 18)) + slots = [] + for xr in granule_spectra: + xr = alias_reduce(xr) + block = np.zeros((18, 32)) + for sb in range(32): + y = imdct36(xr[sb * 18: sb * 18 + 18]) * WIN_NORMAL + block[:, sb] = y[:18] + overlap[sb] + overlap[sb] = y[18:] + for t in range(18): + for sb in range(1, 32, 2): + if t % 2 == 1: + block[t, sb] = -block[t, sb] + slots.extend(block) + return np.array(slots) + + +def synthesis_basis(slots): + """Per output sample, the 512 coefficients multiplying D (the window). + + Returns an (nsamples, 512) matrix A with pcm = A @ D. + """ + nslots = len(slots) + N = np.array([[math.cos((16 + i) * (2 * k + 1) * math.pi / 64) for k in range(32)] + for i in range(64)]) + blocks = slots @ N.T # [slot][64] V blocks + A = np.zeros((nslots * 32, 512)) + for t in range(nslots): + for j in range(32): + row = A[t * 32 + j] + for i in range(16): + p = j + 32 * i + a, b = divmod(p, 64) + m = 2 * a + (1 if b >= 32 else 0) + s = t - m + if s >= 0: + row[p] = blocks[s][b] + return A + + +def synthesise(slots, D): + return synthesis_basis(slots) @ D diff --git a/scripts/mp3-tables/probe_engine.py b/scripts/mp3-tables/probe_engine.py new file mode 100644 index 00000000..f9c723b1 --- /dev/null +++ b/scripts/mp3-tables/probe_engine.py @@ -0,0 +1,54 @@ +"""Batch probe runner: many one-pair probes per ffmpeg invocation.""" + +import numpy as np +from mp3probe import Granule, frame_bytes, ffmpeg_decode + +GLOBAL_GAIN = 150 +SCALE = 2.0 ** ((GLOBAL_GAIN - 210) / 4.0) +PART2_3 = 48 + + +class Engine: + def __init__(self, Minv): + self.Minv = Minv + + def run(self, probes): + """probes: list of (bits, table_select, big_values, count1table_select). + + Returns one array of 576 requantised coefficients per probe. + """ + stream = b"" + for i in range(0, len(probes), 2): + pair = probes[i:i + 2] + grans, mains = [], [] + for bits, tsel, bigv, c1 in pair: + bits = list(bits) + [0] * (PART2_3 - len(bits)) + grans.append(Granule(part2_3_length=PART2_3, big_values=bigv, + global_gain=GLOBAL_GAIN, + table_select=(tsel, tsel, tsel), + count1table_select=c1)) + mains.append(bits[:PART2_3]) + while len(grans) < 2: + grans.append(Granule()) + mains.append([]) + stream += frame_bytes(grans, mains) + stream += frame_bytes([Granule(), Granule()], [[], []]) + pcm, err = ffmpeg_decode(stream) + nframes = (len(probes) + 1) // 2 + assert len(pcm) >= nframes * 2304, (len(pcm), nframes * 2304, err) + windows = np.stack([pcm[i * 2304:(i + 1) * 2304] for i in range(nframes)]) + coeffs = windows @ self.Minv # (nframes, 1152) + out = [] + for i in range(len(probes)): + out.append(coeffs[i // 2][(i % 2) * 576:((i % 2) + 1) * 576]) + return out + + +def values(xr, n): + """First n integer magnitudes of a recovered granule.""" + mag = np.abs(xr[:n]) / SCALE + return np.round(np.power(np.maximum(mag, 0.0), 0.75)).astype(np.int64) + + +def signs(xr, n): + return np.sign(xr[:n]).astype(np.int64) diff --git a/scripts/mp3-tables/run.sh b/scripts/mp3-tables/run.sh new file mode 100755 index 00000000..d2d5596a --- /dev/null +++ b/scripts/mp3-tables/run.sh @@ -0,0 +1,30 @@ +#!/usr/bin/env bash +# Regenerates ec-mp3's measured constant tables. +# +# Layer III's Huffman codes and its 512-tap polyphase window are normative data +# that no formula produces. Rather than copy them out of an existing +# implementation, these scripts measure them: they write legal Layer III frames +# whose main-data bits they choose, decode them with ffmpeg, and read the answer +# back through a model of the decode chain. +# +# learn_window.py least-squares fits the 512 window taps to the PCM ffmpeg +# returns for spectra we chose (residual 1.6e-6, the f32 +# noise floor of the decoder being measured) +# mp3op.py builds the spectrum -> PCM operator and its pseudo-inverse +# learn_huffman.py walks every code tree: a bit prefix is a codeword exactly +# when all continuations decode to the same pair. Checks a +# Kraft sum of 1, full coverage and uniqueness per table +# learn_sfb.py MPEG-1 long scalefactor band widths, one band attenuated +# at a time (these agreed with the published layouts) +# lsf_probe.py short-block reorder at the low sampling frequencies +# emit_tables.py writes huffman_tables.rs +# +# Needs ffmpeg, python3 and numpy. Output lands beside the scripts; copy +# huffman_tables.rs and window.rs into crates/ec-mp3/src/. +set -euo pipefail +cd "$(dirname "${BASH_SOURCE[0]}")" +python3 learn_window.py +python3 mp3op.py +python3 learn_huffman.py +python3 learn_sfb.py +python3 emit_tables.py diff --git a/shims/rusty_mp3/Cargo.toml b/shims/rusty_mp3/Cargo.toml new file mode 100644 index 00000000..a400de79 --- /dev/null +++ b/shims/rusty_mp3/Cargo.toml @@ -0,0 +1,11 @@ +[package] +name = "rusty_mp3" +description = "Compatibility shim: the rusty_mp3 0.6.1 surface, implemented over ec-mp3." +version = "0.6.1" +edition.workspace = true +license.workspace = true +authors.workspace = true + +[dependencies] +ec-mp3.workspace = true +ec-core.workspace = true diff --git a/shims/rusty_mp3/src/lib.rs b/shims/rusty_mp3/src/lib.rs new file mode 100644 index 00000000..9632ca1e --- /dev/null +++ b/shims/rusty_mp3/src/lib.rs @@ -0,0 +1,217 @@ +//! `rusty_mp3` 0.6.1's surface, over [`ec_mp3`]. +//! +//! This crate exists to be swapped in by `[patch.crates-io]`: it carries the +//! incumbent's name and version so a consumer's `use rusty_mp3::…` compiles +//! unchanged. Only what edith consumes plus the streaming decoder beside it is +//! here — [`Mp3Encoder`] with [`Mp3EncoderConfig`], [`Mp3Decoder`] with +//! [`DecodedAudio`], and an [`Error`] carrying the incumbent's `Eof`/`Again` +//! contract — because a shim that grows a surface nobody calls is a second +//! implementation to keep honest. +//! +//! Behaviour differences from the incumbent, all stated: `vbr_quality` picks a +//! constant bitrate rather than varying the rate per frame (see +//! [`ec_mp3::encode::Mp3EncoderConfig`]), and the encoder writes the `Info` +//! header frame first, as the incumbent does. + +#![forbid(unsafe_code)] +#![warn(missing_docs)] + +use std::collections::VecDeque; +use std::fmt; + +/// The incumbent's error type. +#[derive(Debug)] +pub enum Error { + /// No more frames will arrive. + Eof, + /// Not enough data buffered yet; push more and retry. + Again, + /// The bitstream is malformed, or the configuration is not codable. + Format(String), +} + +impl fmt::Display for Error { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Error::Eof => write!(f, "end of stream"), + Error::Again => write!(f, "need more data"), + Error::Format(why) => write!(f, "mp3: {why}"), + } + } +} + +impl std::error::Error for Error {} + +impl From for Error { + fn from(error: ec_core::error::Error) -> Error { + match error { + ec_core::error::Error::Eof => Error::Eof, + ec_core::error::Error::NeedMore => Error::Again, + other => Error::Format(other.to_string()), + } + } +} + +/// The incumbent's result alias. +pub type Result = std::result::Result; + +/// One decoded frame of audio. +#[derive(Debug, Clone)] +pub struct DecodedAudio { + /// Sample rate in Hz. + pub sample_rate: u32, + /// Channel count. + pub channels: u16, + /// Interleaved samples in `[-1, 1]`. + pub samples: Vec, +} + +/// A streaming MP3 decoder. +#[derive(Debug, Default)] +pub struct Mp3Decoder { + reader: ec_mp3::Mp3Reader, + queue: VecDeque, + eof: bool, +} + +impl Mp3Decoder { + /// A decoder with nothing buffered. + pub fn new() -> Mp3Decoder { + Mp3Decoder::default() + } + + /// Buffers bytes and decodes whatever whole frames they complete. + pub fn push(&mut self, bytes: &[u8]) { + self.reader.push(bytes); + while let Ok(frame) = self.reader.next_frame() { + self.queue.push_back(DecodedAudio { + sample_rate: frame.sample_rate, + channels: frame.channels as u16, + samples: frame.samples, + }); + } + } + + /// The next decoded frame, [`Error::Again`] until one is complete and + /// [`Error::Eof`] once [`Mp3Decoder::flush`] has been called and drained. + pub fn next_frame(&mut self) -> Result { + match self.queue.pop_front() { + Some(frame) => Ok(frame), + None if self.eof => Err(Error::Eof), + None => Err(Error::Again), + } + } + + /// Marks the end of input. + pub fn flush(&mut self) { + self.eof = true; + } +} + +/// Encoder settings, field for field as the incumbent declares them. +#[derive(Debug, Clone, Default)] +pub struct Mp3EncoderConfig { + /// Constant bitrate in kbit/s. + pub bitrate_kbps: u32, + /// Quality on a normalised `[0, 1]` scale instead of a bitrate. + pub vbr_quality: Option, +} + +/// The incumbent's quality-to-bitrate curve, in kbit/s. +pub fn vbr_quality_index(q: f32) -> f32 { + ec_mp3::encode::bitrate_for_quality(q) as f32 +} + +/// A streaming MP3 encoder. +#[derive(Debug)] +pub struct Mp3Encoder { + inner: ec_mp3::Mp3Encoder, +} + +impl Mp3Encoder { + /// An encoder that configures itself from the first PCM it is given. + pub fn new(config: Mp3EncoderConfig) -> Mp3Encoder { + Mp3Encoder { + inner: ec_mp3::Mp3Encoder::new(ec_mp3::Mp3EncoderConfig { + bitrate_kbps: config.bitrate_kbps, + vbr_quality: config.vbr_quality, + }), + } + } + + /// Feeds interleaved `f32` samples. + pub fn push_pcm_f32( + &mut self, + interleaved: &[f32], + channels: u16, + sample_rate: u32, + ) -> Result<()> { + Ok(self + .inner + .push_pcm_f32(interleaved, channels, sample_rate)?) + } + + /// Feeds interleaved 16-bit samples. + pub fn push_pcm_s16( + &mut self, + interleaved: &[i16], + channels: u16, + sample_rate: u32, + ) -> Result<()> { + Ok(self + .inner + .push_pcm_s16(interleaved, channels, sample_rate)?) + } + + /// Ends the stream and flushes the tail. + pub fn finish(&mut self) { + self.inner.finish(); + } + + /// The next complete frame; [`Error::Eof`] once drained after + /// [`Mp3Encoder::finish`]. + pub fn next_packet(&mut self) -> Result> { + Ok(self.inner.next_packet()?) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + /// The call shape edith uses, end to end: config in, frames out, and our + /// own decoder reads them back. + #[test] + fn encodes_and_decodes_through_the_incumbent_surface() { + let rate = 44100; + let pcm: Vec = (0..rate * 2 / 4) + .map(|i| ((i as f32 * 0.05).sin() * 8000.0) as i16) + .collect(); + let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { + bitrate_kbps: 192, + vbr_quality: None, + }); + encoder.push_pcm_s16(&pcm, 2, rate as u32).unwrap(); + encoder.finish(); + let mut bytes = Vec::new(); + while let Ok(frame) = encoder.next_packet() { + bytes.extend_from_slice(&frame); + } + assert!(bytes.len() > 1000, "wrote {} bytes", bytes.len()); + + let mut decoder = Mp3Decoder::new(); + decoder.push(&bytes); + decoder.flush(); + let mut frames = 0; + let mut samples = 0; + while let Ok(frame) = decoder.next_frame() { + assert_eq!(frame.sample_rate, rate as u32); + assert_eq!(frame.channels, 2); + frames += 1; + samples += frame.samples.len(); + } + assert!(frames > 5, "decoded {frames} frames"); + assert!(samples >= pcm.len() / 2, "decoded {samples} samples"); + assert!(matches!(decoder.next_frame(), Err(Error::Eof))); + } +}