From 1648ef05f5a3062ec5ce42235e6d79b55f452546 Mon Sep 17 00:00:00 2001 From: el-j Date: Sun, 15 Nov 2026 22:15:58 +0100 Subject: [PATCH] craft-audio: MPEG-1/2 Layer II (MP2) encoder (mpa-encode) Constant bit rate mono and stereo at 16-48 kHz, written from ISO/IEC 11172-3 and 13818-3. Decoded by our decoder and by ffmpeg as an oracle. Closes #1545. --- crates/audio/Cargo.toml | 7 + crates/audio/README.md | 2 + crates/audio/src/lib.rs | 2 +- crates/audio/src/mp3/mod.rs | 4 +- crates/audio/src/mpa/encoder.rs | 493 +++++++++++++++++++++++ crates/audio/src/mpa/mod.rs | 18 + crates/audio/tests/mp2_encoder_oracle.rs | 228 +++++++++++ 7 files changed, 751 insertions(+), 3 deletions(-) create mode 100644 crates/audio/src/mpa/encoder.rs create mode 100644 crates/audio/tests/mp2_encoder_oracle.rs diff --git a/crates/audio/Cargo.toml b/crates/audio/Cargo.toml index 645246130..3584b4f7d 100644 --- a/crates/audio/Cargo.toml +++ b/crates/audio/Cargo.toml @@ -55,6 +55,9 @@ ac3-encode = ["craft-media/bitstream"] eac3-encode = ["craft-media/bitstream"] # MPEG-1/2 Layer III (MP3) encoder (`mp3`). mp3-encode = ["craft-media/bitstream"] +# MPEG-1/2 Layer II (MP2) encoder (`mpa::encoder`). It shares the polyphase analysis filter of the +# MP3 encoder and the tables of the MP1/MP2 decoder. +mpa-encode = ["mpa-decode", "mp3-encode"] # Multi-resolution waveform overviews (`peaks`). peaks = [] # Encode AAC channels in parallel (with `aac-encode`). @@ -88,6 +91,10 @@ required-features = ["decode", "lossless-encode", "peaks"] name = "codecs" required-features = ["decode", "encode"] +[[test]] +name = "mp2_encoder_oracle" +required-features = ["mpa-encode"] + [[test]] name = "qoa_oracle" required-features = ["qoa"] diff --git a/crates/audio/README.md b/crates/audio/README.md index 63251db8d..f9ab17529 100644 --- a/crates/audio/README.md +++ b/crates/audio/README.md @@ -42,6 +42,7 @@ No default features. The shared types (`AudioBuffer`, `AudioInfo`, `ChannelLayou | `mpa-decode` | `mpa::Decoder` | craft-media `bitstream` | | `mp3-decode` | `mp3::Decoder`, `mp3::InfoTag` | `mpa-decode` | | `mp3-encode` | `mp3::Encoder`; `encode`, `FileEncoder` for MP3 | craft-media `bitstream` | +| `mpa-encode` | `mpa::encoder::Encoder` (Layer II / MP2 frames) | `mpa-decode`, `mp3-encode` | | `peaks` | `peaks::Peaks` | none | | `rayon` | parallel AAC encoding (with `aac-encode`) | `rayon` | | `serde` | `Serialize`/`Deserialize` on the shared types | `serde` | @@ -538,6 +539,7 @@ Each codec module's rustdoc lists the coding tools it implements. | Opus (`opus`) | RFC 6716, 8251, 7845 | decoder: SILK, hybrid, CELT, all frame sizes, PLC and FEC, multistream (`Decoder`) and single stream (`StreamDecoder`), 8–48 kHz output; encoder (`Encoder`): SILK, hybrid, CELT, 48 kHz, 20 ms frames, mono or stereo | all 36 RFC 8251 conformance cases; encoder output through ffmpeg's two Opus decoders | | AC-3/E-AC-3 (`ac3`) | decoder: ATSC A/52:2012; encoder/programme API: ETSI TS 102 366 V1.4.1 | single-syncframe and complete-programme decoding; packet encoding through discrete 7.1 (see below) | decoder comparisons and encoder output through ffmpeg, CRC/channel/timing/bit-budget regressions; synthetic quality limitations below | | MP1/MP2 (`mpa`) | ISO/IEC 11172-3, 13818-3 | Layer I and II, MPEG-1/2/2.5, 8–48 kHz; also the Layer II rate/mode pairs the spec disallows (ffmpeg's default mono 384 kbit/s); no free format | ffmpeg-encoded streams, 73–84 dB SNR | +| MP2 encoder (`mpa::encoder`) | ISO/IEC 11172-3 (§2.4, Annex B and C), 13818-3 | Layer II, constant bit rate, mono or stereo (no joint stereo), 32/44.1/48 kHz at the spec's rate/mode pairs and 16/22.05/24 kHz at 8–160 kbit/s; no CRC | our decoder and ffmpeg decode the frames; SNR of 20–37 dB on tone mixes, and the 481-sample filter delay matches | | MP3 decoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, MPEG-1/2/2.5, 8–48 kHz, every bit rate, CBR and VBR; mono, stereo, dual channel, joint stereo (mid/side and intensity); long, short and mixed blocks; bit reservoir; CRC read, not checked; Xing / Info / VBRI and LAME tags; no free format (read through symphonia) | ffmpeg's float decoder: 127–131 dB SNR on LAME streams of every sampling frequency (CBR, VBR, CRC, no reservoir, transients with short blocks) and on this crate's encoder's; intensity stereo and mixed blocks through LAME frames edited to use them (112–131 dB) | | MP3 encoder (`mp3`) | ISO/IEC 11172-3, 13818-3 | Layer III, constant bit rate: 32–320 kbit/s at 32/44.1/48 kHz, 8–160 kbit/s at 16/22.05/24 kHz; mono, stereo, joint stereo (mid/side); bit reservoir; long blocks only; no Xing/Info tag, VBR, CRC or free format | ffmpeg decodes every Huffman code as intended; full encodes at every sampling frequency checked with ffprobe and by SNR of ffmpeg's decode | | ALAC (`alac`) | Apple's reference implementation | decode and encode, 1–8 channels, 16/20/24/32 bits (decode: any depth 1–32), fast mode, magic cookie in MP4/Matroska and CAF form | Apple's reference: same packets from the encoder, same samples from both decoders on 766 configurations; ffmpeg: bit-exact both ways | diff --git a/crates/audio/src/lib.rs b/crates/audio/src/lib.rs index be0678303..669328592 100644 --- a/crates/audio/src/lib.rs +++ b/crates/audio/src/lib.rs @@ -26,7 +26,7 @@ //! - [`peaks`] (feature `peaks`): min/max/RMS pyramid for waveform drawing. //! - Codec modules for packet-level use, each with its own features: [`aac`] (`aac-decode`, //! `aac-encode`), [`alac`] (`alac-decode`, `alac-encode`), [`opus`] (`opus-decode`, and -//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`), [`mp3`] +//! [`opus::encoder`] with `opus-encode`), [`ac3`] (`ac3-decode`), [`mpa`] (`mpa-decode`; `mpa-encode`: the Layer II encoder), [`mp3`] //! (`mp3-decode`, `mp3-encode`), [`flac`] (`flac-encode`: the packet encoder), [`qoa`] //! (`qoa-decode`, `qoa-encode`: whole QOA files). //! diff --git a/crates/audio/src/mp3/mod.rs b/crates/audio/src/mp3/mod.rs index d28607110..e273e903c 100644 --- a/crates/audio/src/mp3/mod.rs +++ b/crates/audio/src/mp3/mod.rs @@ -39,13 +39,13 @@ mod decoder; #[cfg(feature = "mp3-encode")] mod encoder; #[cfg(feature = "mp3-encode")] -mod filterbank; +pub(crate) mod filterbank; #[cfg(feature = "mp3-encode")] mod huffman; mod huffman_tables; #[cfg(feature = "mp3-encode")] mod quantize; -mod tables; +pub(crate) mod tables; #[cfg(feature = "mp3-decode")] pub use decoder::{Decoder, InfoTag}; diff --git a/crates/audio/src/mpa/encoder.rs b/crates/audio/src/mpa/encoder.rs new file mode 100644 index 000000000..000f86fe7 --- /dev/null +++ b/crates/audio/src/mpa/encoder.rs @@ -0,0 +1,493 @@ +//! The Layer II encoder; the module docs are in `mpa/mod.rs`. + +// Index loops follow the specification's pseudo-code (FilmCraft allows this lint workspace-wide). +#![allow(clippy::needless_range_loop)] + +use craft_media::bitstream::BitWriter; + +use super::tables::{self, AllocTable, SUBBANDS}; +use crate::mp3::filterbank::Polyphase; +use crate::mp3::tables::ath_db; + +/// Settings an [`Encoder`] refuses. +#[non_exhaustive] +#[derive(Debug, thiserror::Error, PartialEq, Eq)] +pub enum EncodeError { + /// A sample rate outside [`SAMPLE_RATES`]. + #[error("MP2: unsupported sample rate {0} Hz (32, 44.1, 48 kHz, or 16, 22.05, 24 kHz)")] + SampleRate(u32), + /// A bit rate that is not one of [`bitrates`] for the sample rate and channel count. + #[error("MP2: unsupported bit rate {kbps} kbit/s at {rate} Hz with {channels} channel(s)")] + Bitrate { + /// The bit rate asked for, kbit/s. + kbps: u32, + /// The sample rate, Hz. + rate: u32, + /// The channel count. + channels: usize, + }, + /// More than two channels, or none. + #[error("MP2: unsupported channel count {0} (1 or 2)")] + Channels(usize), +} + +/// Result with this module's [`EncodeError`]. +pub type EncodeResult = std::result::Result; + +/// Encoder settings. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct Config { + /// One of [`SAMPLE_RATES`]. + pub sample_rate: u32, + /// 1 or 2. Two channels are coded as stereo (`mode` 00), each with its own allocation. + pub channels: usize, + /// One of [`bitrates`] for the sample rate and channel count, kbit/s. + pub bitrate_kbps: u32, +} + +impl Config { + /// `channels` at `sample_rate`, constant `bitrate_kbps`. + pub fn cbr(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Config { + Config { sample_rate, channels, bitrate_kbps } + } +} + +/// The sample rates the encoder accepts. +pub const SAMPLE_RATES: [u32; 6] = [32_000, 44_100, 48_000, 16_000, 22_050, 24_000]; + +/// Samples by which a standard decoder's output lags the input: the polyphase analysis and +/// synthesis filters. +pub const DELAY: u32 = 481; + +/// Samples per channel in a frame. +pub const FRAME_SAMPLES: usize = 1152; + +/// Bit rates ISO/IEC 11172-3 Table 3-B.2 allows for a single channel at 32 / 44.1 / 48 kHz. +const MPEG1_MONO: [u32; 10] = [32, 48, 56, 64, 80, 96, 112, 128, 160, 192]; +/// Bit rates it allows for two channels. +const MPEG1_STEREO: [u32; 10] = [64, 96, 112, 128, 160, 192, 224, 256, 320, 384]; + +/// Whether `rate` is one of the MPEG-2 lower sampling frequencies; `None` if it is unsupported. +fn is_lsf(rate: u32) -> Option { + match rate { + 32_000 | 44_100 | 48_000 => Some(false), + 16_000 | 22_050 | 24_000 => Some(true), + _ => None, + } +} + +/// The bit rates (kbit/s) a Layer II stream can use at `sample_rate` with `channels` channels: +/// at 32 / 44.1 / 48 kHz the combinations ISO/IEC 11172-3 allows (32-192 for one channel, 64-384 +/// for two), at the lower sampling frequencies 8-160 for either. Empty for an unsupported rate. +pub fn bitrates(sample_rate: u32, channels: usize) -> &'static [u32] { + match is_lsf(sample_rate) { + Some(false) if channels == 1 => &MPEG1_MONO, + Some(false) => &MPEG1_STEREO, + Some(true) => &tables::BITRATES_LSF_L23[1..], + None => &[], + } +} + +/// The highest bit rate at `sample_rate` and `channels` not above `kbps` (the lowest one when +/// `kbps` is below all of them); `None` for an unsupported rate. +pub fn nearest_bitrate(sample_rate: u32, channels: usize, kbps: u32) -> Option { + let rates = bitrates(sample_rate, channels); + rates.iter().rev().find(|&&r| r <= kbps).or(rates.first()).copied() +} + +/// SNR-free noise model: the power of the error of rounding a value in ±1 to one of `steps` +/// levels spaced `2 / steps` apart, is `(2 / steps)² / 12`. +fn quantization_noise(steps: u16) -> f32 { + let d = 2.0 / f32::from(steps); + d * d / 12.0 +} + +/// Index of the scalefactor for a peak of `peak` (Table 3-B.1): the smallest scalefactor that is +/// at least `peak`, i.e. the largest index. +fn scalefactor_index(peak: f32) -> u32 { + if peak.is_nan() || peak <= 0.0 { + return 62; + } + let mut i = (3.0 * (1.0 - f64::from(peak).log2())).floor().clamp(0.0, 62.0) as u32; + while i > 0 && tables::scalefactor(i) < peak { + i -= 1; + } + while i < 62 && tables::scalefactor(i + 1) >= peak { + i += 1; + } + i +} + +/// Which scalefactors of a subband's three parts are sent (`scfsi`, §2.4.1.6) and what they are. +fn share(sf: [u32; 3]) -> (u32, [u32; 3]) { + let near = |a: u32, b: u32| a.abs_diff(b) <= 1; + let [a, b, c] = sf; + if near(a, b) && near(b, c) && near(a, c) { + let m = a.min(b).min(c); + (2, [m, m, m]) + } else if near(a, b) { + let m = a.min(b); + (1, [m, m, c]) + } else if near(b, c) { + let m = b.min(c); + (3, [a, m, m]) + } else { + (0, sf) + } +} + +/// Scalefactors sent for an `scfsi` class. +fn scalefactors_sent(scfsi: u32) -> u64 { + match scfsi { + 0 => 3, + 2 => 1, + _ => 2, + } +} + +/// Bits of the 12 granules of samples in a subband with `steps` quantization steps. +fn sample_bits(steps: u16) -> u64 { + 12 * match tables::grouping(steps) { + Some(bits) => u64::from(bits), + None => 3 * u64::from((u32::from(steps) + 1).trailing_zeros()), + } +} + +/// What the encoder decided for one channel of a frame. +#[derive(Clone)] +struct ChannelPlan { + /// The allocation value (index into the table's row) per subband. + alloc: [usize; SUBBANDS], + /// `scfsi` per subband. + scfsi: [u32; SUBBANDS], + /// The scalefactor index of each part of each subband, after sharing. + sf: [[u32; 3]; SUBBANDS], + /// Mean square of each subband's samples. + energy: [f32; SUBBANDS], +} + +/// A Layer II encoder. Feed planar `f32` samples (full scale ±1) to [`Encoder::encode`]; it +/// returns whole frames as they are completed. [`Encoder::flush`] pads the end with silence and +/// returns the rest. +/// +/// ``` +/// use craft_audio::mpa::encoder::{Config, DELAY, Encoder}; +/// +/// let left: Vec = (0..48_000).map(|i| (i as f32 * 0.05).sin() * 0.5).collect(); +/// let right = left.clone(); +/// let mut enc = Encoder::new(Config::cbr(48_000, 2, 192))?; +/// let mut mp2 = enc.encode(&[&left, &right]); // whole frames as they complete +/// mp2.extend(enc.flush()); // pads with silence to the last input sample +/// assert_eq!(mp2.len() % 576, 0); // 192 kbit/s at 48 kHz: 576 bytes per frame +/// assert_eq!(DELAY, 481); // a decoder's output lags the input by this many samples +/// # Ok::<(), craft_audio::mpa::encoder::EncodeError>(()) +/// ``` +pub struct Encoder { + cfg: Config, + lsf: bool, + sr_index: u32, + br_index: u32, + table: AllocTable, + sblimit: usize, + /// The masking offset floor per subband (power), from the threshold in quiet. + ath: [f32; SUBBANDS], + poly: Vec, + /// Buffered input per channel, and how much of it is consumed. + input: Vec>, + consumed: usize, + /// Remainder accumulator for the padding slot (44.1 / 22.05 kHz). + pad_acc: u64, + samples_in: u64, + frames: u64, +} + +impl Encoder { + /// An encoder for `cfg`, or the setting it cannot carry. + pub fn new(cfg: Config) -> EncodeResult { + let lsf = is_lsf(cfg.sample_rate).ok_or(EncodeError::SampleRate(cfg.sample_rate))?; + if !(1..=2).contains(&cfg.channels) { + return Err(EncodeError::Channels(cfg.channels)); + } + let bad = EncodeError::Bitrate { kbps: cfg.bitrate_kbps, rate: cfg.sample_rate, channels: cfg.channels }; + if !bitrates(cfg.sample_rate, cfg.channels).contains(&cfg.bitrate_kbps) { + return Err(bad); + } + let (rates, bitrate_table): (&[u32; 3], &[u32; 15]) = + if lsf { (&[22_050, 24_000, 16_000], &tables::BITRATES_LSF_L23) } else { (&tables::SAMPLE_RATES, &tables::BITRATES_MPEG1_L2) }; + let sr_index = rates.iter().position(|&r| r == cfg.sample_rate).ok_or(EncodeError::SampleRate(cfg.sample_rate))?; + let br_index = bitrate_table.iter().position(|&b| b == cfg.bitrate_kbps).ok_or(bad)?; + let per_channel = cfg.bitrate_kbps / cfg.channels as u32; + let table = AllocTable::select(lsf, cfg.sample_rate, per_channel); + let sblimit = table.sblimit().min(SUBBANDS); + let mut ath = [0f32; SUBBANDS]; + for (sb, a) in ath.iter_mut().enumerate() { + let centre = (sb as f64 + 0.5) * f64::from(cfg.sample_rate) / 64.0; + // a full-scale sine has a mean square of 1/2 and plays back at about 96 dB SPL + *a = (0.5 * 10f64.powf((ath_db(centre) - 96.0) / 10.0)) as f32; + } + Ok(Encoder { + cfg, + lsf, + sr_index: sr_index as u32, + br_index: br_index as u32, + table, + sblimit, + ath, + poly: vec![Polyphase::new(); cfg.channels], + input: vec![Vec::new(); cfg.channels], + consumed: 0, + pad_acc: 0, + samples_in: 0, + frames: 0, + }) + } + + /// The settings. + pub fn config(&self) -> &Config { + &self.cfg + } + + /// Samples per channel in a frame: 1152. + pub fn frame_samples(&self) -> usize { + FRAME_SAMPLES + } + + /// Samples by which a standard decoder's output lags the input. + pub fn delay(&self) -> u32 { + DELAY + } + + /// Frames written so far. + pub fn frames(&self) -> u64 { + self.frames + } + + /// Encode planar samples (one slice per channel; a missing channel is silence, extra ones + /// are ignored, every channel takes the first channel's length). Returns the completed frames. + pub fn encode(&mut self, planar: &[&[f32]]) -> Vec { + let n = planar.first().map_or(0, |p| p.len()); + for (c, buf) in self.input.iter_mut().enumerate() { + let src = planar.get(c).copied().unwrap_or(&[]); + buf.extend((0..n).map(|i| src.get(i).copied().filter(|v| v.is_finite()).unwrap_or(0.0).clamp(-4.0, 4.0))); + } + self.samples_in = self.samples_in.saturating_add(n as u64); + let mut out = Vec::new(); + self.drain(&mut out); + out + } + + /// Encode the buffered rest padded with silence, plus enough silence that a decoder outputs + /// every input sample, and return the remaining frames. + pub fn flush(&mut self) -> Vec { + let fs = FRAME_SAMPLES as u64; + let needed = if self.samples_in == 0 { self.frames } else { self.samples_in.saturating_add(u64::from(DELAY)).div_ceil(fs) }; + let have = self.input.first().map_or(0, |b| b.len().saturating_sub(self.consumed)); + let want = (needed.saturating_sub(self.frames) as usize).saturating_mul(FRAME_SAMPLES); + if want > have { + for buf in &mut self.input { + buf.resize(self.consumed + want, 0.0); + } + } + let mut out = Vec::new(); + self.drain(&mut out); + self.input.iter_mut().for_each(Vec::clear); + self.consumed = 0; + out + } + + /// Encode every whole frame of buffered input. + fn drain(&mut self, out: &mut Vec) { + while self.input.first().is_some_and(|b| b.len() - self.consumed >= FRAME_SAMPLES) { + let mut sub = vec![[[0f32; SUBBANDS]; 36]; self.cfg.channels]; + for (ch, slots) in sub.iter_mut().enumerate() { + let (Some(buf), Some(poly)) = (self.input.get(ch), self.poly.get_mut(ch)) else { continue }; + let frame = buf.get(self.consumed..self.consumed + FRAME_SAMPLES).unwrap_or(&[]); + for (slot, chunk) in slots.iter_mut().zip(frame.as_chunks::<32>().0) { + poly.filter(chunk, slot); + } + } + self.consumed += FRAME_SAMPLES; + self.write_frame(&sub, out); + self.frames += 1; + } + // keep the buffer small + if self.consumed >= 1 << 16 { + for buf in &mut self.input { + buf.drain(..self.consumed); + } + self.consumed = 0; + } + } + + /// The scalefactors and energies of a channel's 36 time slots. + fn analyse(&self, slots: &[[f32; SUBBANDS]; 36]) -> ChannelPlan { + let mut plan = ChannelPlan { alloc: [0; SUBBANDS], scfsi: [0; SUBBANDS], sf: [[62; 3]; SUBBANDS], energy: [0.0; SUBBANDS] }; + for sb in 0..self.sblimit { + let mut sf = [62u32; 3]; + for (part, s) in sf.iter_mut().enumerate() { + let peak = slots[12 * part..12 * part + 12].iter().map(|slot| slot[sb].abs()).fold(0f32, f32::max); + *s = scalefactor_index(peak); + } + (plan.scfsi[sb], plan.sf[sb]) = share(sf); + plan.energy[sb] = slots.iter().map(|slot| slot[sb] * slot[sb]).sum::() / 36.0; + } + plan + } + + /// Choose the allocation of every subband of every channel with the bits the frame has. + fn allocate(&self, plans: &mut [ChannelPlan], mut bits_left: i64) { + let nch = plans.len(); + // power the quantization noise of each subband may have before it is audible: a spread + // of the band energies, never below the threshold in quiet + let mut mask = vec![[0f32; SUBBANDS]; nch]; + for (m, plan) in mask.iter_mut().zip(plans.iter()) { + for sb in 0..self.sblimit { + let mut level = self.ath[sb]; + for j in 0..self.sblimit { + let atten_db = 14.0 + 20.0 * sb.abs_diff(j) as f32; + level = level.max(plan.energy[j] * 10f32.powf(-atten_db / 10.0)); + } + m[sb] = level; + } + } + // the fixed cost: every subband's allocation field + for sb in 0..self.sblimit { + bits_left -= (nch * self.table.row(sb).len().trailing_zeros() as usize) as i64; + } + // the noise a subband has with allocation `a`: dropped, or the mean over its parts + let noise = |plan: &ChannelPlan, sb: usize, a: usize| -> f32 { + let row = self.table.row(sb); + let steps = row.get(a).copied().unwrap_or(0); + if steps == 0 { + return plan.energy[sb]; + } + let mean_sf2 = plan.sf[sb].iter().map(|&i| tables::scalefactor(i).powi(2)).sum::() / 3.0; + (quantization_noise(steps) * mean_sf2).min(plan.energy[sb]) + }; + let cost = |plan: &ChannelPlan, sb: usize, a: usize| -> i64 { + let row = self.table.row(sb); + let step = |a: usize| row.get(a).copied().unwrap_or(0); + let (from, to) = (step(a), step(a + 1)); + let mut bits = sample_bits(to) as i64 - if from == 0 { 0 } else { sample_bits(from) as i64 }; + if from == 0 { + bits += 2 + 6 * scalefactors_sent(plan.scfsi[sb]) as i64; + } + bits + }; + let mut blocked = vec![[false; SUBBANDS]; nch]; + loop { + // the subband whose noise is furthest above its mask + let mut best: Option<(usize, usize, f32)> = None; + for (ch, plan) in plans.iter().enumerate() { + for sb in 0..self.sblimit { + let a = plan.alloc[sb]; + if a + 1 >= self.table.row(sb).len() || blocked[ch][sb] || plan.energy[sb] <= 0.0 { + continue; + } + let ratio = noise(plan, sb, a) / mask[ch][sb].max(1e-20); + if ratio > 1e-3 && best.is_none_or(|(_, _, r)| ratio > r) { + best = Some((ch, sb, ratio)); + } + } + } + let Some((ch, sb, _)) = best else { break }; + let plan = &mut plans[ch]; + let c = cost(plan, sb, plan.alloc[sb]); + if c <= bits_left { + bits_left -= c; + plan.alloc[sb] += 1; + } else { + blocked[ch][sb] = true; + } + } + } + + fn write_frame(&mut self, sub: &[[[f32; SUBBANDS]; 36]], out: &mut Vec) { + let nch = self.cfg.channels; + // frame length: 144 bytes per kbit/s over the sampling rate, plus a slot when the + // remainder has added up to one + let rate = u64::from(self.cfg.sample_rate); + let exact = 144 * u64::from(self.cfg.bitrate_kbps) * 1000; + self.pad_acc += exact % rate; + let pad = self.pad_acc >= rate; + if pad { + self.pad_acc -= rate; + } + let frame_bytes = (exact / rate) as usize + usize::from(pad); + + let mut plans: Vec = sub.iter().map(|s| self.analyse(s)).collect(); + self.allocate(&mut plans, frame_bytes as i64 * 8 - 32); + + let mut w = BitWriter::new(); + w.write_bits(0xFFF, 12); + w.write_bits(u32::from(!self.lsf), 1); + w.write_bits(0b10, 2); // Layer II + w.write_bits(1, 1); // no CRC + w.write_bits(self.br_index, 4); + w.write_bits(self.sr_index, 2); + w.write_bits(u32::from(pad), 1); + w.write_bits(0, 1); // private + w.write_bits(if nch == 1 { 3 } else { 0 }, 2); // mono or stereo + w.write_bits(0, 2); // mode extension + w.write_bits(0, 1); // copyright + w.write_bits(1, 1); // original + w.write_bits(0, 2); // emphasis + for sb in 0..self.sblimit { + let nbal = self.table.row(sb).len().trailing_zeros(); + for plan in &plans { + w.write_bits(plan.alloc[sb] as u32, nbal); + } + } + for sb in 0..self.sblimit { + for plan in &plans { + if plan.alloc[sb] != 0 { + w.write_bits(plan.scfsi[sb], 2); + } + } + } + for sb in 0..self.sblimit { + for plan in &plans { + if plan.alloc[sb] == 0 { + continue; + } + let [a, b, c] = plan.sf[sb]; + match plan.scfsi[sb] { + 0 => [a, b, c].iter().for_each(|&s| w.write_bits(s, 6)), + 1 => [a, c].iter().for_each(|&s| w.write_bits(s, 6)), + 2 => w.write_bits(a, 6), + _ => [a, b].iter().for_each(|&s| w.write_bits(s, 6)), + } + } + } + for gr in 0..12 { + let part = gr / 4; + for sb in 0..self.sblimit { + for (ch, plan) in plans.iter().enumerate() { + let a = plan.alloc[sb]; + let steps = self.table.row(sb).get(a).copied().unwrap_or(0); + if steps == 0 { + continue; + } + let scale = tables::scalefactor(plan.sf[sb][part]); + let n = u32::from(steps); + let code = |k: usize| -> u32 { + let x = (sub[ch][3 * gr + k][sb] / scale).clamp(-1.0, 1.0); + // the reconstruction points are (2v + 1 - n) / n + ((x * n as f32 + n as f32 - 1.0) / 2.0).round().clamp(0.0, (n - 1) as f32) as u32 + }; + let v = [code(0), code(1), code(2)]; + match tables::grouping(steps) { + Some(bits) => w.write_bits(v[0] + n * v[1] + n * n * v[2], bits), + None => { + let nb = (n + 1).trailing_zeros(); + v.iter().for_each(|&x| w.write_bits(x, nb)); + } + } + } + } + } + let mut bytes = w.finish(); + bytes.resize(frame_bytes, 0); + out.extend_from_slice(&bytes); + } +} diff --git a/crates/audio/src/mpa/mod.rs b/crates/audio/src/mpa/mod.rs index f1d5b6378..3db204176 100644 --- a/crates/audio/src/mpa/mod.rs +++ b/crates/audio/src/mpa/mod.rs @@ -13,12 +13,30 @@ //! format (bit rate index 0, whose frame length is only known from the next sync word) and the //! CRC (read, not checked, like most decoders). //! +//! # Encoder (feature `mpa-encode`) +//! +//! [`encoder::Encoder`] writes Layer II streams, written from ISO/IEC 11172-3 (§2.4.1.6 bit stream +//! syntax, Annex B tables, Annex C encoding process) and ISO/IEC 13818-3. +//! +//! - Constant bit rate: 32-192 kbit/s mono and 64-384 kbit/s stereo at 32 / 44.1 / 48 kHz (the +//! rate and mode pairs of Table 3-B.2), 8-160 kbit/s at 16 / 22.05 / 24 kHz. Mono, or stereo with +//! each channel allocated on its own (no joint stereo, no dual channel). +//! - The polyphase analysis filterbank of Annex C.1.3 (shared with the Layer III encoder), a +//! scalefactor per 12 samples with the `scfsi` sharing of §2.4.1.6, and a bit allocation chosen by +//! spending the frame's bits where the quantization noise is furthest above a simple masking +//! estimate (the band energies spread over the neighbouring subbands, never below the threshold +//! in quiet). It is not one of the psychoacoustic models of Annex D. +//! - Output: frames only, no CRC, no ID3 tag. Frames written one after another are a playable +//! `.mp2` file. A decoder's output lags the input by [`encoder::DELAY`] samples. +//! //! From FilmCraft's `filmcraft-mpa` (storytold/filmcraft@8fda2f2). Public items keep their names, so //! FilmCraft can re-export this module. // Index loops follow the specification's pseudo-code (FilmCraft allows this lint workspace-wide). #![allow(clippy::needless_range_loop)] +#[cfg(feature = "mpa-encode")] +pub mod encoder; pub(crate) mod tables; use craft_media::bitstream::BitReader; diff --git a/crates/audio/tests/mp2_encoder_oracle.rs b/crates/audio/tests/mp2_encoder_oracle.rs new file mode 100644 index 000000000..ca4d15bd3 --- /dev/null +++ b/crates/audio/tests/mp2_encoder_oracle.rs @@ -0,0 +1,228 @@ +//! The Layer II encoder (feature `mpa-encode`): every frame has the header and size its settings +//! give and decodes with our decoder; ffmpeg as an external decoder (skipped without ffmpeg, a +//! failure with `CRAFT_MEDIA_REQUIRE_ORACLES=1`) decodes the stream without a complaint, to the +//! right length, and its output, aligned by [`DELAY`], matches the input within a signal-to-noise +//! ratio per bit rate. The bounds sit well under what the encoder reaches today; white noise loses +//! the subbands above the table's last one (a sixth of it at 48 kHz), so its bound is low. + +use std::path::Path; +use std::process::{Command, Stdio}; + +use craft_audio::mpa::encoder::{Config, DELAY, EncodeError, Encoder, bitrates, nearest_bitrate}; +use craft_audio::mpa::{Decoder, Mode, Version, parse_header}; + +fn chords(rate: u32, n: usize, detune: f32) -> Vec { + let f = [220.0, 277.18, 329.63, 440.0, 1318.5, 3520.0]; + let a = [0.2, 0.15, 0.12, 0.1, 0.05, 0.02]; + (0..n) + .map(|i| { + let t = i as f32 / rate as f32; + f.iter().zip(a).map(|(f, a)| a * (2.0 * std::f32::consts::PI * f * (1.0 + detune) * t).sin()).sum::() + }) + .collect() +} + +fn noise(n: usize, amp: f32, seed: u64) -> Vec { + let mut s = seed.wrapping_mul(0x9E37_79B9_7F4A_7C15) | 1; + (0..n) + .map(|_| { + s ^= s << 13; + s ^= s >> 7; + s ^= s << 17; + ((s >> 40) as f32 / (1u64 << 24) as f32 * 2.0 - 1.0) * amp + }) + .collect() +} + +fn encode(cfg: Config, input: &[Vec], chunk: usize) -> Vec { + let mut enc = Encoder::new(cfg).expect("encoder"); + let mut out = Vec::new(); + let n = input[0].len(); + let mut pos = 0; + while pos < n { + let end = (pos + chunk).min(n); + let planes: Vec<&[f32]> = input.iter().map(|c| &c[pos..end]).collect(); + out.extend(enc.encode(&planes)); + pos = end; + } + out.extend(enc.flush()); + out +} + +/// Split a stream into frames by its headers; every header must be one the settings give. +fn frames<'a>(bytes: &'a [u8], cfg: &Config) -> Vec<&'a [u8]> { + let mut out = Vec::new(); + let mut pos = 0; + while pos < bytes.len() { + let h = parse_header(&bytes[pos..]).unwrap_or_else(|e| panic!("frame {} at byte {pos}: {e}", out.len())); + assert_eq!(h.layer, 2); + assert_eq!(h.version, if cfg.sample_rate >= 32_000 { Version::Mpeg1 } else { Version::Mpeg2 }); + assert_eq!((h.sample_rate, h.bitrate_kbps), (cfg.sample_rate, cfg.bitrate_kbps)); + assert_eq!(h.mode, if cfg.channels == 1 { Mode::Mono } else { Mode::Stereo }); + assert!(!h.crc); + out.push(&bytes[pos..pos + h.frame_bytes]); + pos += h.frame_bytes; + } + assert_eq!(pos, bytes.len(), "the stream ends on a frame boundary"); + out +} + +fn snr(input: &[f32], dec: &[f32]) -> f64 { + let (mut s, mut n) = (0f64, 0f64); + for (a, b) in input.iter().zip(dec) { + s += f64::from(*a) * f64::from(*a); + n += f64::from(a - b) * f64::from(a - b); + } + 10.0 * (s / n.max(1e-30)).log10() +} + +struct Case { + name: &'static str, + rate: u32, + channels: usize, + kbps: u32, + signal: fn(u32, usize, usize) -> Vec, + min_snr: f64, +} + +fn sig_chords(rate: u32, n: usize, c: usize) -> Vec { + chords(rate, n, 0.003 * c as f32) +} +fn sig_noise(_rate: u32, n: usize, c: usize) -> Vec { + noise(n, 0.25, 11 + c as u64) +} + +const CASES: &[Case] = &[ + Case { name: "chords", rate: 48_000, channels: 2, kbps: 192, signal: sig_chords, min_snr: 30.0 }, + Case { name: "chords", rate: 44_100, channels: 2, kbps: 128, signal: sig_chords, min_snr: 25.0 }, + Case { name: "chords", rate: 44_100, channels: 1, kbps: 64, signal: sig_chords, min_snr: 25.0 }, + Case { name: "chords", rate: 32_000, channels: 2, kbps: 96, signal: sig_chords, min_snr: 20.0 }, + Case { name: "chords", rate: 22_050, channels: 2, kbps: 64, signal: sig_chords, min_snr: 20.0 }, + Case { name: "chords", rate: 24_000, channels: 1, kbps: 32, signal: sig_chords, min_snr: 18.0 }, + Case { name: "noise", rate: 48_000, channels: 2, kbps: 384, signal: sig_noise, min_snr: 4.0 }, + Case { name: "noise", rate: 44_100, channels: 2, kbps: 256, signal: sig_noise, min_snr: 4.0 }, +]; + +fn inputs(c: &Case, n: usize) -> Vec> { + (0..c.channels).map(|ch| (c.signal)(c.rate, n, ch)).collect() +} + +#[test] +fn frames_have_the_size_and_header_their_settings_give_and_decode_with_our_decoder() { + for c in CASES { + let n = c.rate as usize * 2 + 777; + let cfg = Config::cbr(c.rate, c.channels, c.kbps); + let bytes = encode(cfg, &inputs(c, n), 1000); + let frames = frames(&bytes, &cfg); + // every input sample and the filter delay fit in the frames, and no more than one frame more + let covered = frames.len() * 1152; + assert!(covered >= n + DELAY as usize && covered < n + DELAY as usize + 1152, "{}: {} frames for {n} samples", c.name, frames.len()); + // 144 kbit/s-slots per frame, the padding slots adding up to the exact rate + let nominal = f64::from(c.kbps) * 125.0 * covered as f64 / f64::from(c.rate); + assert!((bytes.len() as f64 - nominal).abs() < 1.0 + f64::from(c.rate) / 1000.0, "{}: {} bytes against {nominal}", c.name, bytes.len()); + let mut dec = Decoder::new(); + let mut out = vec![Vec::new(); c.channels]; + for f in frames { + let frame = dec.decode(f).unwrap_or_else(|e| panic!("{}: {e}", c.name)); + for (o, ch) in out.iter_mut().zip(frame.channels) { + o.extend(ch); + } + } + let d = DELAY as usize; + for (ch, input) in inputs(c, n).iter().enumerate() { + let s = snr(input, &out[ch][d..d + n]); + println!("{:<7} {:>5} Hz {}ch {:>3} kbps: SNR {s:.2} dB (our decoder)", c.name, c.rate, c.channels, c.kbps); + assert!(s >= c.min_snr, "{} {} Hz {}ch {} kbps: SNR {s:.2} dB under {}", c.name, c.rate, c.channels, c.kbps, c.min_snr); + } + } +} + +#[test] +fn the_stream_does_not_depend_on_how_the_input_is_chunked() { + let c = &CASES[1]; + let n = 44_100 + 333; + let cfg = Config::cbr(c.rate, c.channels, c.kbps); + let input = inputs(c, n); + let whole = encode(cfg, &input, n); + for chunk in [1, 7, 1152, 5000] { + assert_eq!(encode(cfg, &input, chunk), whole, "chunk {chunk}"); + } +} + +#[test] +fn silence_and_nothing_encode_to_valid_frames() { + let cfg = Config::cbr(48_000, 2, 128); + let silent = vec![vec![0f32; 5000]; 2]; + let bytes = encode(cfg, &silent, 5000); + let fs = frames(&bytes, &cfg); + let mut dec = Decoder::new(); + for f in fs { + let frame = dec.decode(f).expect("decode"); + assert!(frame.channels.iter().flatten().all(|v| v.abs() < 1e-6)); + } + assert!(Encoder::new(cfg).expect("encoder").flush().is_empty(), "no input, no frames"); +} + +#[test] +fn hostile_samples_are_tamed() { + let cfg = Config::cbr(44_100, 2, 192); + let mut x = vec![0f32; 4000]; + for (i, v) in x.iter_mut().enumerate() { + *v = [f32::NAN, f32::INFINITY, -f32::INFINITY, 1e30, -1e30, 3.0, 0.5][i % 7]; + } + let bytes = encode(cfg, &[x.clone(), x], 4000); + let mut dec = Decoder::new(); + for f in frames(&bytes, &cfg) { + dec.decode(f).expect("decode"); + } +} + +#[test] +fn settings_that_cannot_be_carried_are_refused() { + assert_eq!(Encoder::new(Config::cbr(44_000, 2, 128)).err(), Some(EncodeError::SampleRate(44_000))); + assert_eq!(Encoder::new(Config::cbr(44_100, 3, 128)).err(), Some(EncodeError::Channels(3))); + assert_eq!(Encoder::new(Config::cbr(44_100, 0, 128)).err(), Some(EncodeError::Channels(0))); + // ISO/IEC 11172-3 allows neither 32 kbit/s for two channels nor 224 for one + assert!(matches!(Encoder::new(Config::cbr(44_100, 2, 32)), Err(EncodeError::Bitrate { .. }))); + assert!(matches!(Encoder::new(Config::cbr(44_100, 1, 224)), Err(EncodeError::Bitrate { .. }))); + assert!(matches!(Encoder::new(Config::cbr(44_100, 2, 130)), Err(EncodeError::Bitrate { .. }))); + assert_eq!(bitrates(44_100, 1).len(), 10); + assert_eq!(bitrates(22_050, 2).first(), Some(&8)); + assert!(bitrates(8_000, 2).is_empty()); + assert_eq!(nearest_bitrate(44_100, 2, 100), Some(96)); + assert_eq!(nearest_bitrate(44_100, 2, 1), Some(64)); + assert_eq!(nearest_bitrate(8_000, 2, 100), None); +} + +fn ffmpeg_decode(ff: &Path, path: &Path, channels: usize) -> (Vec>, String) { + let out = Command::new(ff) + .args(["-v", "error", "-nostdin", "-i"]) + .arg(path) + .args(["-f", "f32le", "-acodec", "pcm_f32le", "-"]) + .stdin(Stdio::null()) + .output() + .expect("run ffmpeg"); + let samples: Vec = out.stdout.as_chunks::<4>().0.iter().map(|b| f32::from_le_bytes(*b)).collect(); + let planar = (0..channels).map(|c| samples.iter().skip(c).step_by(channels).copied().collect()).collect(); + (planar, String::from_utf8_lossy(&out.stderr).into_owned()) +} + +#[test] +fn ffmpeg_decodes_our_streams_to_the_input() { + let Some(ff) = craft_media_testkit::ffmpeg() else { return }; + let dir = craft_media_testkit::fixture_subdir("mp2enc"); + for c in CASES { + let n = c.rate as usize * 2 + 777; + let input = inputs(c, n); + let bytes = encode(Config::cbr(c.rate, c.channels, c.kbps), &input, 1000); + let path = dir.join(format!("{}_{}_{}ch_{}k.mp2", c.name, c.rate, c.channels, c.kbps)); + std::fs::write(&path, &bytes).expect("write"); + let (dec, err) = ffmpeg_decode(&ff, &path, c.channels); + assert!(err.trim().is_empty(), "{}: ffmpeg reported: {err}", path.display()); + let d = DELAY as usize; + assert!(dec[0].len() >= n + d, "{}: decoded {} samples, need {}", c.name, dec[0].len(), n + d); + let s = (0..c.channels).map(|ch| snr(&input[ch], &dec[ch][d..d + n])).sum::() / c.channels as f64; + println!("{:<7} {:>5} Hz {}ch {:>3} kbps: SNR {s:.2} dB (ffmpeg)", c.name, c.rate, c.channels, c.kbps); + assert!(s >= c.min_snr, "{} {} Hz {}ch {} kbps: SNR {s:.2} dB under {}", c.name, c.rate, c.channels, c.kbps, c.min_snr); + } +}