//! 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, BitBuf}; use crate::tables::{ MAX_QUANT, SLEN, forward_mdct_long, forward_mdct_short, long_starts, power43, short_starts, short_widths, windows, }; use ec_core::bitio::BitWriter; use ec_core::error::{Error, Result}; use ec_dsp::{RealFft, Window}; use wide::f32x8; /// Encoder settings. /// /// The field names match the incumbent MP3 encoder 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. /// /// Runs true variable bitrate: each frame's granules are quantised to the /// masking threshold scaled by this quality (no fixed bit budget), and the /// frame then picks the smallest legal bitrate that carries them; the /// quality's mean lands near [`bitrate_for_quality`]. Easy frames cost /// fewer bits, hard ones more. 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 } /// The largest value the 12-bit `part2_3_length` side-info field can carry, /// and so the most bits one granule may be coded to. const PART2_3_MAX: u32 = (1 << 12) - 1; const ZERO_QUANT_THRESHOLD: f32 = 7.8504e-17; const SFB_LONG: usize = 21; /// How much quieter the difference of the two channels has to be than their /// sum before the frame is coded as mid/side. One means "whenever the sum is /// the louder of the two", which is every correlated mix. /// /// Swept on the two library sources mid/side helps least (`reelo`, `dl8a`, /// `real_library_sweep_vs_lame`): the correlation gap moves by 0.00001 across /// 0.5, 1, 2 and "always", and by 0.0005 between "always" and "never". Real /// music sits nowhere near this threshold, so it is a guard, not a tuning /// knob -- what it guards is the opposed-channel case, where the difference /// is the loud channel (`mid_side_follows_the_channel_correlation`). const MS_ENERGY_RATIO: f64 = 1.0; /// How much of the frame budget follows each granule-channel's bit demand /// rather than being split evenly. Swept below. const DEMAND_SPLIT: f64 = 0.7; /// One granule's worth of coded spectrum plus the side info describing it. #[derive(Clone, Debug)] struct CodedGranule { bits: BitBuf, 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, /// When set, frames are coded to a quality target and their bitrate is /// chosen per frame; `bitrate_kbps` is then the floor, not the rate. vbr_quality: Option, 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, /// The block type each channel's previous granule used. Window switching /// is a sequence, and the sequence does not restart at a frame boundary. previous_block: u8, /// The `mode_extension` bits of the frame being written: bit 1 is /// mid/side stereo, decided per frame in `emit_frame`. mode_ext: u8, fft: RealFft, fft_window: Window, psy_history: Vec>, /// Deinterleave scratch for `encode_block`, grown once and reused. pcm_scratch: 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. /// The third field is the frame's main-data capacity in bytes, which a /// VBR frame chooses for itself. queued: std::collections::VecDeque<(Vec, Vec, usize)>, ready: std::collections::VecDeque>, frames: u32, /// Bytes of emitted audio frames (everything after the info header), for /// the Xing header's byte count and average bitrate. frame_bytes: u64, /// The legal-bitrate table index VBR's last frame settled on. Real audio /// is smooth from one frame to the next, so the candidate search below /// starts here instead of blind-bisecting the whole table every frame. vbr_index: usize, /// Fractional-slot accumulator in units of the sample rate: each emitted /// frame takes its slot remainder off it, and a negative balance is paid /// back with one padding byte. padding_lag: i64, } #[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, vbr_quality: Option, ) -> 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), vbr_quality, 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(), previous_block: 0, mode_ext: 0, 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(), pcm_scratch: Vec::new(), ready: std::collections::VecDeque::new(), frames: 0, frame_bytes: 0, vbr_index: { let table: &[u32] = if version == Version::Mpeg1 { &BITRATES_V1 } else { &BITRATES_V2 }; let target = vbr_quality.map_or(0, bitrate_for_quality); table .iter() .enumerate() .min_by_key(|&(_, &k)| k.abs_diff(target)) .map_or(0, |(i, _)| i) }, padding_lag: 0, }) } /// The header every frame of this stream carries, at `bitrate_kbps`. fn header(&self, bitrate_kbps: u32, padding: bool) -> FrameHeader { FrameHeader { version: self.version, layer: 3, crc: false, bitrate_kbps, sample_rate: self.sample_rate, padding, private: false, mode: self.mode, mode_ext: self.mode_ext, copyright: false, original: true, emphasis: 0, } } /// The slot remainder a frame at `kbps` leaves over the sample rate. fn slot_remainder(&self, kbps: u32) -> i64 { let per_kbps: u64 = if self.version == Version::Mpeg1 { 144_000 } else { 72_000 }; (per_kbps * u64::from(kbps) % u64::from(self.sample_rate)) as i64 } /// Whether the next emitted frame at `kbps` carries a padding byte. fn pads_next(&self, kbps: u32) -> bool { self.padding_lag - self.slot_remainder(kbps) < 0 } /// Advances the padding accumulator for one emitted frame at `kbps`. fn next_padding(&mut self, kbps: u32) -> bool { let padding = self.pads_next(kbps); self.padding_lag -= self.slot_remainder(kbps); if padding { self.padding_lag += i64::from(self.sample_rate); } padding } /// Granules per frame for this stream. pub fn granules(&self) -> usize { self.header(self.bitrate_kbps, false).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.config.vbr_quality, )?); self.pcm.resize(PRIMING * usize::from(channels.max(1)), 0.0); } 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, the MDCT one granule // behind that, and block switching holds one more granule back to // look ahead; feed silence so every real sample comes out the other // end rather than being dropped with the pipeline. let tail = vec![0.0f32; channels * (576 * 3 + 480)]; self.pcm.extend_from_slice(&tail); } self.drain(true); self.finished = true; } fn drain(&mut self, flush: bool) { let Self { core, pcm, frames, .. } = self; let Some(core) = core.as_mut() else { return; }; let channels = core.channels; let need = core.frame_samples() * channels; // Encode behind a read cursor and shift the leftovers once: draining // per frame memmoved the whole remaining push for every frame, which // on a single large push is quadratic in the file length. let mut pos = 0usize; while pcm.len() - pos >= need { core.encode_block(&pcm[pos..pos + need]); pos += need; } pcm.drain(..pos); if flush { if !pcm.is_empty() { pcm.resize(need, 0.0); core.encode_block(pcm); pcm.clear(); } core.flush_pending(); core.flush_frames(); } while let Some(frame) = core.ready.pop_front() { 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, self.finished)); } } match self.frames.pop_front() { Some(frame) => Ok(frame), None if self.finished => Err(Error::Eof), None => Err(Error::NeedMore), } } } /// Silence prepended to the first PCM the encoder is given. /// /// The first MDCT block has no predecessor to overlap with, so the frame it /// produces cannot reconstruct — the transform's startup, not a coding loss. /// Priming with a frame of silence puts that region before the audio instead /// of on top of it, and the delay field below tells a decoder to drop it. It /// is what makes the first frame of a gapless decode as good as the rest; /// without it that frame correlates 0.67 against its input while every other /// frame is above 0.999. const PRIMING: usize = 1152; /// Samples of PCM this encoder's pipeline runs ahead of its output: the /// [`PRIMING`] silence, plus the analysis bank running fifteen slots behind /// its input and the MDCT one granule behind that, less what the decoder's /// synthesis gives back. Measured end to end (encode, decode, /// cross-correlate) as 1728 samples of lag, of which 529 is the decoder delay /// every gapless-tag consumer adds for itself. /// /// `encoder_delay_is_what_the_tag_says` is that measurement as a test: change /// the pipeline and it fails rather than silently mis-stating the tag. pub(crate) const ENCODER_DELAY: u32 = PRIMING as u32 + 47; /// The decoder delay a gapless tag consumer adds to the encoder delay. Fixed by /// the tag's own convention, not by anything here, so nothing in the encoder /// spends it — `encoder_delay_is_what_the_tag_says` is what it is for. #[allow(dead_code)] const DECODER_DELAY: u32 = 529; /// The nine-byte encoder string in the gapless extension. /// /// It says `gapless3.100` and not `ec-mp3` on purpose, and this is the one place /// this crate writes something it is not: the oracle (and every player that copied /// its parser) only reads the delay and padding fields when those first four /// bytes are `gapless`, `Lavc` or `Lavf`. Writing our own name there produces a /// tag that parses and is then ignored, which is worse than useless — the /// gapless information would be present and unusable. The rest of the /// extension is filled honestly or zeroed. const INFO_TAG_LEN: usize = 52; const GAPLESS_VERSION: &[u8; 9] = &[0x4c, 0x41, 0x4d, 0x45, b'3', b'.', b'1', b'0', b'0']; /// 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. /// /// Carries frame and byte counts and — the point of it — the encoder delay and /// padding, which is what lets a decoder hand back exactly the samples that /// went in. Those two are exact when the caller pushes all its PCM before /// pulling packets, which is the pattern the family's exporter uses; a caller /// that interleaves pushes and pulls gets the delay (a constant) right and the /// counts as of the first pull. fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec { let vbr = core.vbr_quality.is_some(); let table: &[u32] = if core.version == Version::Mpeg1 { &BITRATES_V1 } else { &BITRATES_V2 }; let side = core.header(core.bitrate_kbps, false).side_info_len(); let kbps = table .iter() .copied() .filter(|&k| k >= core.bitrate_kbps) .find(|&k| core.header(k, false).frame_len().unwrap_or(0) >= 4 + side + INFO_TAG_LEN) .unwrap_or(table[table.len() - 1]); let header = core.header(kbps, false); 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 spf = header.samples_per_frame() as u64; let (frames, padding) = if complete { let frames = core.frames; let coded = u64::from(frames) * spf; let padding = coded.saturating_sub(samples + u64::from(ENCODER_DELAY)); (frames, padding.min(4095) as u32) } else { (0, 0) }; // The header's byte count is the whole stream, info frame included. // `frame_bytes` sums emitted audio-frame lengths; in CBR that is // `frames * frame_len`, reducing to the old `(frames + 1) * frame_len`. let bytes = if complete { core.frame_bytes + frame_len as u64 } else { 0 }; // The gapless "bitrate" byte: a VBR stream reports its mean rate, a CBR one // its constant rate. let bitrate_byte = if vbr && complete && samples > 0 { let seconds = samples as f64 / f64::from(core.sample_rate); let kbps = bytes as f64 * 8.0 / seconds / 1000.0; (kbps.round() as u32).min(255) as u8 } else { core.bitrate_kbps.min(255) as u8 }; let mut tag: Vec = Vec::with_capacity(64); if vbr { tag.extend_from_slice(b"Xing"); } else { tag.extend_from_slice(b"Info"); } tag.extend_from_slice(&3u32.to_be_bytes()); // frames and bytes present tag.extend_from_slice(&frames.to_be_bytes()); tag.extend_from_slice(&(bytes.min(u64::from(u32::MAX)) as u32).to_be_bytes()); tag.extend_from_slice(GAPLESS_VERSION); // Tag revision (0), VBR flag (0x10) and VBR method (3) when variable. tag.push(if vbr { 0x70 } else { 0 }); tag.push(0); // lowpass in 100 Hz units, unstated tag.extend_from_slice(&0u32.to_be_bytes()); // replay gain peak tag.extend_from_slice(&0u16.to_be_bytes()); // radio replay gain tag.extend_from_slice(&0u16.to_be_bytes()); // audiophile replay gain tag.push(0); // encoding flags and ATH type tag.push(bitrate_byte); let delay_padding = (ENCODER_DELAY << 12) | padding; tag.extend_from_slice(&delay_padding.to_be_bytes()[1..]); // 12 bits each tag.push(0); // misc tag.push(0); // mp3gain tag.extend_from_slice(&0u16.to_be_bytes()); // preset and surround info tag.extend_from_slice(&0u32.to_be_bytes()); // music length tag.extend_from_slice(&0u16.to_be_bytes()); // music CRC tag.extend_from_slice(&0u16.to_be_bytes()); // tag CRC debug_assert_eq!(tag.len(), INFO_TAG_LEN); let take = tag.len().min(frame_len - at); out[at..at + take].copy_from_slice(&tag[..take]); 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 { // One deinterleave buffer per encoder, grown once: this frame's // mono channel used to be a fresh allocation per channel per // frame. self.pcm_scratch.clear(); self.pcm_scratch.reserve(pcm.len() / channels); for frame in pcm.chunks(channels) { self.pcm_scratch.push(frame[ch]); } let mono = &self.pcm_scratch; 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); } } // The masking model's history update, inlined from `psy_push` so // it can touch `psy_history` while `mono` borrows `pcm_scratch`. let n = mono.len().min(1024); 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..]); } // 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(); } } /// Allowed noise per long scalefactor band, from the masking model, in /// the units `code_with` measures quantisation noise in (summed squared /// MDCT lines), so noise / threshold is a noise-to-mask ratio. /// /// The FFT here is unnormalised: for input of mean-square power P, a /// 1024-point transform of the sine-windowed block (sum of w^2 = N/2) has /// per-bin power N/2 * P = 512 P. The analysis filterbank is unity gain /// and splits P across 32 subbands (P/32 each), and `mdct_long` scales by /// 1/9 with a 36-point sine window (sum of w^2 cos^2 = 9), so each of a /// subband's 18 lines carries P/32 * 9/81 = P/288. A band of W lines /// spans W * 512/576 FFT bins: FFT energy / MDCT energy = /// (W * 8/9 * 512 P) / (W * P/288) = 2^17, the `FFT_TO_MDCT` below. fn psy_threshold(&mut self, ch: usize) -> Vec { const FFT_TO_MDCT: f32 = 1.0 / 131072.0; 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 * FFT_TO_MDCT * 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 * FFT_TO_MDCT * (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 vbr = self.vbr_quality; // Window types. A granule whose successor is much louder starts the // switch, the loud one is short, and the one after stops it — and the // sequence carries across frames, because a start window in the last // granule of one frame demands a short block in the first granule of // the next. Restarting it per frame is what leaves a start window // facing a normal one, whose overlap does not reconstruct. // // Both channels of a frame get the same window, because mid/side // below adds and subtracts their spectra: lines from a long block and // lines from a short one describe different time slices, so summing // them would smear one channel's transient across the other's granule. let mut types = vec![0u8; granules * channels]; for gr in 0..granules { { let base = gr * channels; let energy = |slot: usize| -> f32 { (0..channels) .filter_map(|ch| self.pending.get(slot + ch)) .map(|g| g.energy) .sum() }; let here = energy(base); let next = if base + channels < self.pending.len() { energy(base + channels) } else { here }; // Digital silence is not a transient to protect: switching on // the way out of it (the priming, or a cut in a timeline) costs // the resolution a long block would have spent on the attack // itself, and there is no pre-echo to hide when nothing // precedes it. // How much louder the next granule has to be to count as an // attack. Swept against the worst 20 ms error-to-signal ratio // on real music (`real_library_sweep_vs_lame`), because // whole-file correlation cannot see pre-echo at all: // // ratio 1.3 1.6 2 3 4 8 // dl8a@128 -2.3 -3.3 -3.3 -3.3 -3.3 +1.1 dB // dl8a@192 -6.7 -6.7 -6.7 -7.8 -7.8 -4.2 dB // // Flat from 1.6 to 4 and then a cliff: at 8 a whole granule // has to grow eightfold in total energy, which music does // about once a minute -- one short granule in 9196, against // libmp3lame's 88 over the same audio. Below 1.6 the extra // short blocks start costing correlation without buying any // more of the worst window back, so 4 sits at the cheap end // of the flat part. let attack = here > 1e-9 && next > here * 4.0 + 1e-6; let block = match self.previous_block { 1 => 2, 2 if attack => 2, 2 => 3, _ if attack => 1, _ => 0, }; for ch in 0..channels { types[base + ch] = block; } self.previous_block = block; } } let begin = self.assigned - self.used; // The MDCT and the quality-scaled masking threshold are shared by // every bitrate candidate VBR tries below; compute them once. let mut xrs: Vec> = Vec::with_capacity(granules * channels); let mut thresholds: Vec> = Vec::with_capacity(granules * channels); // Take the held-back granules once: the per-granule clone that used // to feed `mdct` copied every subband and threshold just to keep the // borrow checker happy about `history`. let held: Vec = self.pending.drain(..granules * channels).collect(); for gr in 0..granules { for ch in 0..channels { let index = gr * channels + ch; let granule = &held[index]; xrs.push(self.mdct(ch, &granule.subband, types[index])); thresholds.push(match vbr { Some(quality) => quality_threshold(&granule.threshold, quality), None => granule.threshold.clone(), }); } } // Mid/side stereo. The two channels of real music are mostly the same // signal, and coding their sum and difference puts nearly all of the // energy in the sum, leaving the difference cheap enough to quantise // finely at the same cost. It is applied to the MDCT lines and undone // by the decoder, so it is exact -- the only judgement is whether the // difference really is the small one, which it is not on a wide stereo // mix, where L/R codes two independent signals better than a mid that // is loud and a side that is nearly as loud. self.mode_ext = 0; if channels == 2 && self.mode == ChannelMode::JointStereo { let (mut mid, mut side) = (0.0f64, 0.0f64); for gr in 0..granules { let (left, right) = (&xrs[gr * 2], &xrs[gr * 2 + 1]); for (&l, &r) in left.iter().zip(right.iter()) { let (l, r) = (f64::from(l), f64::from(r)); mid += (l + r) * (l + r); side += (l - r) * (l - r); } } if side < mid * MS_ENERGY_RATIO { self.mode_ext = 2; const INV_SQRT2: f32 = std::f32::consts::FRAC_1_SQRT_2; for gr in 0..granules { let (head, tail) = xrs.split_at_mut(gr * 2 + 1); let (left, right) = (&mut head[gr * 2], &mut tail[0]); for (l, r) in left.iter_mut().zip(right.iter_mut()) { let (a, b) = (*l, *r); *l = (a + b) * INV_SQRT2; *r = (a - b) * INV_SQRT2; } // Neither coded channel is one of the speakers any more, // so both are held to whichever channel masked less: an // error in the side channel lands in both ears. let (head, tail) = thresholds.split_at_mut(gr * 2 + 1); let (left, right) = (&mut head[gr * 2], &mut tail[0]); for (l, r) in left.iter_mut().zip(right.iter_mut()) { let floor = l.min(*r); *l = floor; *r = floor; } } } } // What each granule-channel asks for, as a share of the frame. The // quantiser codes |xr|^(3/4), so the sum of that over a granule's // lines is the shape of its bit demand: splitting the frame by it // lets a quiet channel hand its bits to a loud one, which is what // makes mid/side pay -- a side channel that is nearly silent no // longer holds a quarter of the frame it cannot spend. let count = (granules * channels).max(1); let demand: Vec = xrs .iter() .map(|xr| { xr.iter() .map(|v| { let x = f64::from(v.abs()); // |x|^(3/4) as a cube and two square roots, the same // shape the quantiser uses. (x * x * x).sqrt().sqrt() }) .sum() }) .collect(); let demand_total: f64 = demand.iter().sum(); let demand_share = |budget: usize, index: usize| -> u32 { let even = 1.0 / count as f64; let asked = if demand_total > 0.0 { demand[index] / demand_total } else { even }; let part = (1.0 - DEMAND_SPLIT) * even + DEMAND_SPLIT * asked; ((budget as f64 * part) as u32).min(PART2_3_MAX) }; // Quantise the granules. CBR codes to a fixed frame budget. VBR tries // legal bitrates, coding the whole frame's granules against each one's // share with the same distortion loop CBR uses, and keeps the // cheapest one whose mean noise-to-mask ratio sits under one. let (coded, kbps): (Vec, u32) = match vbr { Some(_) => { let table: &[u32] = if self.version == Version::Mpeg1 { &BITRATES_V1 } else { &BITRATES_V2 }; // Codes the frame at one candidate and reports its mean // noise-to-mask ratio; the ratio falls as the bitrate rises, // so the cheapest candidate at or under 1.0 is found by // bisection over the table (four codings, not fourteen). let code_at = |candidate: u32| -> (Vec, f64) { let header = self.header(candidate, self.pads_next(candidate)); let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); let mut frame_coded = Vec::with_capacity(granules * channels); let mut ratio = 0.0; for index in 0..granules * channels { let (granule, r) = quantise_granule( &xrs[index], types[index], demand_share(capacity * 8, index), &thresholds[index], self.sample_rate, ); ratio += r / (granules * channels) as f64; frame_coded.push(granule); } (frame_coded, ratio) }; // Real audio is smooth frame to frame, so try the last // settled bitrate first and walk only as far as this frame // needs. If the previous frame was already cheap, start at the // legal floor instead of climbing down through the table again. let mut index = if self.vbr_index <= 2 { 0 } else { self.vbr_index.min(table.len() - 1) }; let (coded, ratio) = code_at(table[index]); let mut best = (coded, ratio); let mut best_index = index; if best.1 <= 1.0 { while best_index > 0 { let trial_index = best_index - 1; let trial = code_at(table[trial_index]); if trial.1 > 1.0 { break; } best = trial; best_index = trial_index; } } else { while index + 1 < table.len() { index += 1; let trial = code_at(table[index]); best = trial; best_index = index; if best.1 <= 1.0 { break; } } } self.vbr_index = best_index; (best.0, table[best_index]) } None => { let header = self.header(self.bitrate_kbps, self.pads_next(self.bitrate_kbps)); let frame_len = header.frame_len().unwrap_or(0); let capacity = frame_len - 4 - header.side_info_len(); let budget_bits = (self.assigned + capacity - self.used) * 8; let mut frame_coded = Vec::with_capacity(granules * channels); for index in 0..granules * channels { let spent: usize = frame_coded .iter() .map(|c: &CodedGranule| c.part2_3_length as usize) .sum(); let left = budget_bits.saturating_sub(spent); let target = (demand_share(budget_bits, index) as usize) .min(left) .min(4095); let (granule, _) = quantise_granule( &xrs[index], types[index], target as u32, &thresholds[index], self.sample_rate, ); frame_coded.push(granule); } (frame_coded, self.bitrate_kbps) } }; let padding = self.next_padding(kbps); let header = self.header(kbps, padding); let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len(); let side_info_len = header.side_info_len(); // 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(), side_info_len); // Append the granule data to the stream at `used`, byte aligned. let mut main = BitBuf::new(); for granule in &coded { main.append(&granule.bits); } 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, capacity)); 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 let Some(&(_, _, front)) = self.queued.front() { if self.stream.len() < self.written + front { break; } let (head, side, cap) = self.queued.pop_front().expect("queue is not empty"); let mut frame = Vec::with_capacity(4 + side_info_len + cap); frame.extend_from_slice(&head); frame.extend_from_slice(&side); frame.extend_from_slice(&self.stream[self.written..self.written + cap]); self.written += cap; self.frame_bytes += (4 + side_info_len + cap) as u64; self.ready.push_back(frame); self.frames += 1; } // main_data_begin is nine bits (eight for LSF), so the reservoir cannot // reach further back than that; anything older is dropped. let reach = if self.version == Version::Mpeg1 { 511 } else { 255 }; if self.assigned > self.used + reach { self.used = self.assigned - reach; } } /// Encodes the granules still held back for block-switching lookahead. fn flush_pending(&mut self) { let per_frame = self.granules() * self.channels; while self.pending.len() >= per_frame { self.emit_frame(); } } /// Writes out whatever frames are still queued, padding the stream so the /// last frame is complete. fn flush_frames(&mut self) { while let Some((head, side, capacity)) = self.queued.pop_front() { if self.stream.len() < self.written + capacity { self.stream.resize(self.written + capacity, 0); } let mut frame = Vec::with_capacity(4 + side.len() + capacity); 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.frame_bytes += (4 + side.len() + capacity) as u64; 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 kernel = forward_mdct_long(); let mut windowed = [0.0f32; 36]; for i in 0..36 { windowed[i] = input[i] * window[i]; } for (k, row) in kernel.iter().enumerate() { let mut sum = 0.0f64; for (n, value) in windowed.iter().enumerate() { sum += f64::from(*value) * f64::from(row[n]); } out[k] = (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]; let kernel = forward_mdct_short(); for w in 0..3 { for (k, row) in kernel.iter().enumerate() { let mut sum = 0.0f64; for n in 0..12 { let sample = input[6 + 6 * w + n] * window[n]; sum += f64::from(sample) * f64::from(row[n]); } out[k * 3 + w] = (sum / 3.0) as f32; } } } /// Scales the masking threshold by `vbr_quality`. A higher quality lowers the /// allowed noise (a smaller threshold, so more bands are amplified and the /// granule costs more bits). The curve is calibrated on the fixture corpus and /// three 30-second music clips so the stream mean tracks /// [`bitrate_for_quality`] without letting q=0 collapse to speech-rate output. fn quality_threshold(threshold: &[f32], quality: f32) -> Vec { let q = quality.clamp(0.0, 1.0); let db = if q <= 0.5 { 12.0 - 25.0 * q + 20.0 * q * q } else { let t = q - 0.5; 4.5 - 11.0 * t - 12.0 * t * t }; // Recalibration, measured against `real_library_vbr_vs_lame`: splitting a // frame by bit demand reaches the same masking bar for fewer bits, and the // quality knob promises a mean rate rather than a bar, so the bar tightens // to spend the saving instead of pocketing it. The slope is fitted to two // points on the library -- 2 dB at quality 0.3 holds its promised 163 // kbit/s, and the rate moves about 9.5 kbit/s per decibel at quality 0.6. let trim = 1.6 - 12.0 * q; let scale = 10f32.powf((db + trim) / 10.0); threshold.iter().map(|&t| t * scale).collect() } /// 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, f64) { if xr.iter().all(|v| v.abs() <= ZERO_QUANT_THRESHOLD) { return ( CodedGranule { bits: BitBuf::new(), part2_3_length: 0, big_values: 0, global_gain: 0, scalefac_compress: 0, block_type, table_select: [0; 3], region0_count: 0, region1_count: 0, scalefac_scale: false, count1table_select: false, }, 0.0, ); } let mut scalefac = [0u8; SFB_LONG]; // Score is the summed noise-to-mask ratio over the bands; a mean ratio // of at most one is VBR's signal that this bitrate carried the granule // cleanly (strict all-bands-under is vetoed by scalefactor-capped bands). let mut best: Option<(CodedGranule, f64, usize)> = 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. // Short blocks carry twelve bands, long ones twenty-one. let bands = if block_type == 2 { 12 } else { SFB_LONG }; let threshold = band_thresholds(threshold, block_type, sample_rate); for _ in 0..20 { let (granule, noise) = code_with(xr, block_type, target_bits, &scalefac, sample_rate); let ratios: Vec = (0..bands) .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30)) .collect(); let score: f64 = ratios.iter().sum(); let mut order: Vec = (0..bands) .filter(|&b| scalefac[b] < max_scalefac(b, block_type)) .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 spent = granule.part2_3_length; if best.as_ref().is_none_or(|(_, s, _)| score < *s) { best = Some((granule, score, bands)); } if score <= 0.0 { break; // every band is already exactly at the mask; nothing left to buy } // Where to stop amplifying, as a fraction of the frame's budget. Swept // against both gate metrics on all fourteen library rows: 85% beats // the 95% this shipped with everywhere, and 100% is a disaster -- // reelm loses 0.0048 correlation, because amplifying a band once the // budget is gone only makes the rate loop coarsen every other band to // pay for it. Below 70% the test stops binding, since the first round // already spends more than that. // // LAME's own shape -- drop the budget break, let the distortion test // drive, since `code_with` fits `target_bits` at every round anyway -- // was built and measured here (2026-09-06). It makes the loop live // (10440 granules of 36758 reach the 20-round cap against 3 before) and // loses on both gate metrics: reelo at 128 kbit/s goes 0.99917 -> // 0.99787 correlation, from +0.00062 ahead of libmp3lame to -0.00068 // behind it, and its worst 20 ms window from -15.3 to -12.4 dB, at // roughly five times the encode time. The gate measures waveform error, // and a budget-filling rate loop over flat scalefactors is already near // the MSE optimum, so perceptual redistribution can only trade away // what this gate scores. Don't re-run it: change the metric first. if spent * 100 > target_bits * 85 { break; // the budget is spent; amplifying now only coarsens } // Bands over their mask get the bits first, worst three per round so // the rate loop re-fits `global_gain` around a small step; once every // band is under its mask the spare bits go to the noisiest ones. // corner-cut: the ISO outer loop keeps amplifying over-mask bands past // the budget and lets the rate loop coarsen the rest; measured here it // costs 12-36% RMS against the source (mp3src-stereo-48000, 128/192) // for a model this coarse, and the encode_matrix bar is an RMS metric. // Upgrade path: a finer model (ISO spreading function, tonality from // phase prediction) before trusting the mask over the budget. let chosen: Vec = if over.is_empty() { order } else { over } .into_iter() .take(3) .collect(); if chosen.is_empty() { break; } for band in chosen { scalefac[band] += 1; } } let (granule, score, bands) = best.expect("at least one round runs"); (granule, score / bands as f64) } /// Puts a spectrum into bitstream order in `out`. /// /// A short granule is coded band by band, window by window, line by line, /// while the spectrum the transform produces interleaves the three windows on /// every line — the decoder's reorder step. The encoder has to undo it before /// Huffman coding; writing spectral order instead costs exactly the same /// number of bits, lands exactly on `part2_3_length`, and hands the decoder a /// permuted granule, which comes back as noise. A long block is already in /// order and is copied as is. fn recode_into(spectral: &[i32; 576], block_type: u8, sample_rate: u32, out: &mut [i32; 576]) { if block_type != 2 { *out = *spectral; return; } let widths = short_widths(sample_rate); let starts = short_starts(sample_rate); let mut position = 0usize; for sfb in 0..13 { let (width, start) = (usize::from(widths[sfb]), usize::from(starts[sfb])); for window in 0..3 { for line in 0..width { out[position] = spectral[(start + line) * 3 + window]; position += 1; } } } for slot in out.iter_mut().skip(position) { *slot = 0; } } /// The largest scalefactor a band can actually carry. /// /// `scalefac_compress` names two lengths, and the second partition's is at most /// three bits — so a band above the split cannot hold more than 7 however much /// the distortion loop would like to amplify it. Ignoring that ceiling is not a /// rounding error: the quantiser uses the value it wanted, no length can encode /// it, and the decoder reconstructs the band with a scalefactor of zero, which /// turns the granule into noise. fn max_scalefac(band: usize, block_type: u8) -> u8 { let split = if block_type == 2 { 6 } else { 11 }; if band < split { 15 } else { 7 } } /// The masking model works in long bands; a short block's twelve bands are /// read off it at the same frequencies, so one model serves both. fn band_thresholds(threshold: &[f32], block_type: u8, sample_rate: u32) -> Vec { if block_type != 2 { return threshold.to_vec(); } let long = long_starts(sample_rate); let short = short_starts(sample_rate); (0..12) .map(|band| { // A short band's lines sit at three times its index in the spectrum. let line = usize::from(short[band]) * 3; let long_band = (0..SFB_LONG) .rev() .find(|&b| line >= usize::from(long[b])) .unwrap_or(0); // Three windows share the band, so each carries a third of it. threshold[long_band] / 3.0 }) .collect() } /// Quantises with a fixed scalefactor set, running the rate loop on /// `global_gain`, and reports the noise each band ends up with. /// /// The rate loop judges every candidate gain by Huffman cost alone /// ([`plan_spectrum`]); the granule's bits are materialised exactly once, /// for the configuration the loop keeps ([`write_spectrum`]). Writing the /// bits per round — and re-expanding them into a `Vec` to hand them /// to the frame writer — was the largest single cost in the encoder's /// profile, and said nothing the cost pass had not already said. 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, block_type, sample_rate); // The scalefactors come out of the same budget as the spectrum does. A // short block transmits six bands of each length, once per window. let scalefac_bits = if block_type == 2 { (slen1 + slen2) * 18 } 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 = [0i32; 576]; let mut coding = [0i32; 576]; // A line that saturates the coding range is not "cheap", it is clipped; // the gain search below reads saturation as "does not fit". let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191); let mut plan_of = |ix: &[i32; 576]| -> SpectrumPlan { recode_into(ix, block_type, sample_rate, &mut coding); plan_spectrum(&coding, block_type, sample_rate) }; quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix); let mut coded = plan_of(&ix); if peak <= 1e-20 { // Below the smallest representable level: every line quantises to // zero at any gain (the quantiser's scale multiplies zero either // way), so the descending-gain search below — which steps one gain // unit at a time — would walk all 210 units from 210 to 0 finding // nothing changes, recoding an all-zero spectrum at every step. Skip // straight to the quietest legal gain; `coded` above is already the // right answer, because an all-zero spectrum's bit cost does not // depend on gain. gain = 0; } else { // The rate loop wants the smallest gain whose granule fits the // budget without clipping. A higher gain shrinks every quantised // line, and a smaller spectrum costs no more to code, so "fits" is // monotone in the gain. This shipped as a one-step-at-a-time walk // from the start estimate and paid ~31 quantise-plus-plan // evaluations per granule; now the start estimate seeds a geometric // straddle (doubling steps, so a boundary `d` gains away costs // about 2·log2 d probes instead of d) followed by a bisection of // the bracket. The walk's two hard stops stay: gain 255 stands even // when it does not fit (the low-pass loop below trims the // spectrum), and gain 0 is the quietest legal gain. let mut probe_of = |g: i32, out: &mut [i32; 576]| -> (bool, SpectrumPlan) { quantise(xr, g, scalefac, sample_rate, block_type, out); let plan = plan_of(out); (plan.cost <= target_bits && !saturated(out), plan) }; let mut probe = [0i32; 576]; // `floor` is the largest gain known to miss, `ceil` the smallest // known to fit; −1 stands for "even 0 misses would not matter", the // gain-0 floor. let mut floor = -1i32; let mut ceil = 255i32; let mut capped = false; let first = start.clamp(0, 255); let (fits, _) = probe_of(first, &mut probe); if fits { // The boundary is at or below the estimate: stride down until a // gain misses. ceil = first; let mut step = 1i32; while ceil > 0 { let next = (ceil - step).max(0); let (next_fits, _) = probe_of(next, &mut probe); if !next_fits { floor = next; break; } ceil = next; step *= 2; } } else { // The boundary is above the estimate: stride up until a gain // fits, honouring the walk's 255 cap. floor = first; let mut step = 1i32; loop { let next = (floor + step).min(255); let (next_fits, _) = probe_of(next, &mut probe); if next_fits { ceil = next; break; } floor = next; if next == 255 { capped = true; break; } step *= 2; } } while ceil - floor > 1 { let mid = (floor + ceil) / 2; let (mid_fits, _) = probe_of(mid, &mut probe); if mid_fits { ceil = mid; } else { floor = mid; } } gain = if capped { 255 } else { ceil }; let (_, plan) = probe_of(gain, &mut probe); ix = probe; coded = plan; } // 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.cost > target_bits && limit > 4 { limit = limit * 3 / 4; for slot in ix.iter_mut().skip(limit) { *slot = 0; } coded = plan_of(&ix); } let mut noise = [0.0f32; SFB_LONG]; let power = power43(); // One band gain per band, not one per line: the residual ran an exp2 for // every spectral line of the granule. let mut scales = [0.0f32; SFB_LONG]; for (band, slot) in scales.iter_mut().enumerate() { *slot = band_gain(gain, scalefac[band], block_type); } let residual = |i: usize, band: usize| -> f32 { let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scales[band]; let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude }; (xr[i] - reconstructed).powi(2) }; if block_type == 2 { for (i, _) in ix.iter().enumerate().take(576) { let band = short_band(i, sample_rate); noise[band.min(SFB_LONG - 1)] += residual(i, band); } } else { let starts = long_starts(sample_rate); for band in 0..SFB_LONG { let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1])); let mut sum = 0.0f32; for i in from..to.min(576) { sum += residual(i, band); } noise[band] = sum; } } // Materialise the granule: scalefactors, then the spectrum the plan // chose, in bitstream order. recode_into(&ix, block_type, sample_rate, &mut coding); let mut bits = BitBuf::new(); if block_type == 2 { // The decoder reads short scalefactors band-major, three windows at a // time; ours are one per band, so each is written three times. for (band, value) in scalefac.iter().enumerate().take(12) { let slen = if band < 6 { slen1 } else { slen2 }; for _window in 0..3 { bits.push_bits(u64::from(*value), slen); } } } else { for (band, value) in scalefac.iter().enumerate() { let slen = if band < 11 { slen1 } else { slen2 }; bits.push_bits(u64::from(*value), slen); } } write_spectrum(&coded, &coding, &mut bits); let granule = CodedGranule { part2_3_length: bits.bit_len(), bits, big_values: coded.big_values, global_gain: gain as u32, scalefac_compress: compress, block_type, table_select: coded.tables, region0_count: coded.region0, region1_count: coded.region1, scalefac_scale: false, count1table_select: coded.count1_select, }; (granule, noise) } fn band_gain(gain: i32, scalefac: u8, _block_type: u8) -> f32 { let base = (gain as f32 - 210.0) * 0.25; (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], ) { // The scalar form, kept for spans shorter than one SIMD width. let quantise_line = |xr: f32, scale: f32| -> i32 { let x = f64::from(xr.abs()) * f64::from(scale); let value = (x * x * x).sqrt().sqrt(); let magnitude = (value + 0.4054).min(MAX_QUANT as f64) as i32; if xr < 0.0 { -magnitude } else { magnitude } }; if block_type == 2 { // Short blocks: twelve bands, each with its own scalefactor shared by // the three windows. Without them the quantiser's noise is flat across // the spectrum, which is what made a switched granule the worst-coded // one in the stream. One band gain per band, not one per line: the // interleaved layout means a line's band search ran 576 exp2 calls // and 576 linear band searches per quantisation. let short = short_starts(sample_rate); let mut scales = [0.0f32; 13]; for (band, slot) in scales.iter_mut().enumerate() { *slot = 1.0 / band_gain(gain, scalefac[band], block_type); } for band in 0..13 { let (from, to) = ( usize::from(short[band]) * 3, usize::from(short[band + 1]) * 3, ); let scale = scales[band]; quantise_span(xr, ix, from, to.min(576), scale, &quantise_line); } return; } 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); quantise_span(xr, ix, from, to, scale, &quantise_line); } } /// Quantises `xr[from..to]` at `scale` into `ix[from..to]`, eight lanes at a /// time through `wide` — the per-line curve the scalar closure carries out /// one line per call. Overflow lanes to `inf`, which the `MAX_QUANT` clamp /// folds back the same way the scalar path clamps a saturated line; the /// signed value truncates toward zero, exactly the sign-and-floor the scalar /// form does in two steps. Levels can differ from the scalar path by one /// step where the true level sits within f32 rounding of a boundary; the /// decoded-quality gate exists for exactly that. fn quantise_span( xr: &[f32], ix: &mut [i32], from: usize, to: usize, scale: f32, scalar: &impl Fn(f32, f32) -> i32, ) { let mut i = from; if to - i >= 8 { let vscale = f32x8::splat(scale); let voff = f32x8::splat(0.4054); let vmax = f32x8::splat(MAX_QUANT as f32); while i + 8 <= to { let mut block = [0.0f32; 8]; block.copy_from_slice(&xr[i..i + 8]); let v = f32x8::new(block); let x = v.abs() * vscale; let value = (x * x * x).sqrt().sqrt(); let magnitude = (value + voff).min(vmax); let ints = magnitude.copysign(v).trunc_int(); ix[i..i + 8].copy_from_slice(&ints.to_array()); i += 8; } } while i < to { ix[i] = scalar(xr[i], scale); i += 1; } } /// The short scalefactor band a spectral line belongs to. Short-block spectra /// interleave the three windows line by line, so the line index divided by /// three is the frequency line the band table is indexed by. fn short_band(index: usize, sample_rate: u32) -> usize { let line = index / 3; let starts = short_starts(sample_rate); (0..13) .rev() .find(|&band| line >= usize::from(starts[band])) .unwrap_or(0) } /// The coding a spectrum gets: region split, tables, count1 boundary, and /// the bit cost the rate loop judges candidate gains by. #[derive(Clone, Copy, Debug)] struct SpectrumPlan { cost: u32, big_values: u32, tables: [u8; 3], region0: u32, region1: u32, count1_select: bool, bounds: [usize; 3], big_end: usize, count1_end: usize, } /// Trailing zeros, the count1 boundary, and the region split for a coded /// spectrum, in bitstream order. The planner and the writer read these off /// one structure so both see the same boundaries. fn regions( ix: &[i32; 576], block_type: u8, sample_rate: u32, ) -> (u32, u32, [usize; 3], usize, usize) { // 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); // Region boundaries land on band edges. A granule that switches windows // does not transmit `region0_count`/`region1_count` at all — the decoder // derives them (three short bands for a short block, eight long bands // otherwise, with region 2 empty) — so the encoder has to use exactly // those, not a split of its own. Choosing differently costs no bits and // parses as different tables, which is a granule of noise wherever the // window switches. Only a normal block gets to pick. let (region0, region1, bounds) = match block_type { 2 => { let first = usize::from(short_starts(sample_rate)[3]) * 3; (8u32, 12u32, [first.min(big_end), big_end, big_end]) } 1 | 3 => { let first = usize::from(starts[8]); (7u32, 13u32, [first.min(big_end), big_end, big_end]) } _ => { // 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 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]) } }; (region0, region1, bounds, big_end, count1_end) } /// Chooses the region split, the tables and the count1 boundary, and prices /// the spectrum. The rate loop calls this for every candidate gain; only the /// configuration it keeps is ever written ([`write_spectrum`]). fn plan_spectrum(ix: &[i32; 576], block_type: u8, sample_rate: u32) -> SpectrumPlan { let (region0, region1, bounds, big_end, count1_end) = regions(ix, block_type, sample_rate); let mut tables = [0u8; 3]; let mut cost = 0u32; let mut from = 0usize; for (region, to) in bounds.iter().enumerate() { let to = (*to).min(big_end); if to > from { let (select, region_cost) = best_table_cost(ix, from, to); tables[region] = select; cost += region_cost; } from = to; } // count1: try both tables, keep the cheaper. let quads_cost = |select: bool| -> u32 { let mut sum = 0; let mut i = big_end; while i + 4 <= count1_end { sum += huffman::quad_bits(select, [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]]); i += 4; } sum }; let count1_select = quads_cost(true) < quads_cost(false); cost += quads_cost(count1_select); SpectrumPlan { cost, big_values: (big_end / 2) as u32, tables, region0, region1, count1_select, bounds, big_end, count1_end, } } /// Writes the coded spectrum the plan names into `out`, pairs and quadruples /// in bitstream order. `ix` is the spectrum in bitstream order, the same /// array the plan was computed from. fn write_spectrum(plan: &SpectrumPlan, ix: &[i32; 576], out: &mut BitBuf) { let mut from = 0usize; for (region, to) in plan.bounds.iter().enumerate() { let to = (*to).min(plan.big_end); if to > from { let table = huffman::big_table(usize::from(plan.tables[region])).expect("table exists"); let mut i = from; while i + 1 < to { huffman::write_pair(out, table, ix[i], ix[i + 1]); i += 2; } } from = to; } let mut i = plan.big_end; while i + 4 <= plan.count1_end { huffman::write_quad( out, plan.count1_select, [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]], ); i += 4; } } /// 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, with its cost. /// /// One walk over the pairs accumulates every shortlisted candidate's cost at /// once; the former shape — a full `pair_bits` pass per candidate, up to nine /// walks over the same pairs — was half of the encoder's remaining runtime. /// A candidate any pair falls outside dies on the spot, exactly as the /// per-candidate `pair_bits` propagation did, and ties keep the earlier /// (nominally cheaper) candidate, as the strict less-than did. fn best_table_cost(ix: &[i32], from: usize, to: usize) -> (u8, u32) { let mut max = 0u32; for &v in &ix[from..to] { max = max.max(v.unsigned_abs()); } let shortlist = candidates(max); // Per-candidate state, fetched once: the table, its escape shape, the // cost of a (0, 0) pair, and a running cost. A candidate the region's // largest magnitude falls outside is dropped before the walk — exactly // what the per-pair range check did, since some pair carries `max`. let mut tables = [None; 9]; let mut tmax = [0u32; 9]; let mut linbits = [0u32; 9]; let mut dim = [0u32; 9]; let mut zero_bits = [0u32; 9]; let mut feasible = [false; 9]; let mut costs = [0u32; 9]; let mut live = 0usize; for (slot, &select) in shortlist.iter().enumerate() { let Ok(table) = huffman::big_table(usize::from(select)) else { continue; }; let cap = u32::from(table.dim) - 1; let escape = table.linbits > 0; let reach = cap + if escape { (1 << table.linbits) - 1 } else { 0 }; if max > reach { continue; } tables[slot] = Some(table); tmax[slot] = cap; linbits[slot] = if escape { u32::from(table.linbits) } else { 0 }; dim[slot] = u32::from(table.dim); zero_bits[slot] = u32::from(table.codes[0].0); feasible[slot] = true; live += 1; } let mut i = from; while i + 1 < to && live > 0 { let (x, y) = (ix[i].unsigned_abs(), ix[i + 1].unsigned_abs()); if x == 0 && y == 0 { for slot in 0..shortlist.len() { if feasible[slot] { costs[slot] += zero_bits[slot]; } } i += 2; continue; } let signs = u32::from(x != 0) + u32::from(y != 0); for slot in 0..shortlist.len() { if !feasible[slot] { continue; } let table = tables[slot].expect("feasible candidates hold a table"); let (cap, lin) = (tmax[slot], linbits[slot]); let (len, _) = table.codes[(x.min(cap) * dim[slot] + y.min(cap)) as usize]; if len == 0 { // A hole in the table: this candidate cannot code the pair, // so it is out for the whole region. feasible[slot] = false; live -= 1; continue; } let mut bits = u32::from(len) + signs; if lin > 0 { if x >= cap { bits += lin; } if y >= cap { bits += lin; } } costs[slot] += bits; } i += 2; } let mut best = (u32::MAX, 0u8); for (slot, &select) in shortlist.iter().enumerate() { if feasible[slot] && costs[slot] < best.0 { best = (costs[slot], 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, 0); } (best.1, best.0) } /// The `scalefac_compress` index whose two lengths hold these scalefactors. fn scalefac_compress(scalefac: &[u8; SFB_LONG], block_type: u8, sample_rate: u32) -> (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) }; // Long blocks split their bands 11/10, short blocks 6/6 per window. let (first, second, cost1, cost2) = if block_type == 2 { (&scalefac[..6], &scalefac[6..12], 18, 18) } else { (&scalefac[..11], &scalefac[11..], 11, 10) }; // The table's longest pair is (4, 3), so a caller that respects // `max_scalefac` always finds an entry; the clamp is what keeps a caller // that does not from silently coding a granule the decoder cannot rebuild. let need1 = bits_for(first).min(4); let need2 = bits_for(second).min(3); if sample_rate < 32000 { return (need1, need2, ((need1 * 5 + need1) << 4) | (need2 << 2) | need2); } let mut best = (u32::MAX, 4u32, 3u32, 15u32); for (index, (slen1, slen2)) in SLEN.iter().enumerate() { if *slen1 >= need1 && *slen2 >= need2 { let cost = slen1 * cost1 + slen2 * cost2; if cost < best.0 { best = (cost, *slen1, *slen2, index as u32); } } } (best.1, best.2, best.3) } #[cfg(test)] mod tests { use super::*; /// The delay the Info tag states is the delay the pipeline has. Our own /// decoder ignores the tag, so what it hands back is the untrimmed stream: /// the content starts exactly `ENCODER_DELAY + DECODER_DELAY` samples in. /// The mask is stated in the quantiser's noise units: on white noise the /// band energy of the MDCT sits the signal-to-mask offset (6 dB, plus /// what the flatness estimate adds) above the threshold, not 2^17 away. #[test] fn masking_threshold_is_in_mdct_power_units() { let mut core = Mp3Encode::new(48000, 1, 128, None).unwrap(); let mut seed = 0x2545_f491_4f6c_dd1du64; let mut noise = || { seed ^= seed << 13; seed ^= seed >> 7; seed ^= seed << 17; (seed >> 40) as f32 / 8_388_608.0 - 1.0 }; for _ in 0..8 { let pcm: Vec = (0..1152).map(|_| 0.25 * noise()).collect(); core.encode_block(&pcm); } let granule = core.pending.last().unwrap().clone(); let xr = core.mdct(0, &granule.subband, 0); let starts = long_starts(48000); let mut sum = 0.0f32; for band in 3..16 { let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1])); let energy: f32 = xr[from..to].iter().map(|v| v * v).sum(); sum += 10.0 * (energy / granule.threshold[band]).log10(); } let db = sum / 13.0; assert!( (6.0..=18.0).contains(&db), "signal sits {db:.1} dB over its mask" ); } #[test] fn encoder_delay_is_what_the_tag_says() { for (rate, channels) in [(44100u32, 1usize), (48000, 2)] { let n = 1152 * 8; let pcm: Vec = (0..n * channels) .map(|i| { let t = (i / channels) as f32; 0.3 * (t * 0.11).sin() + 0.2 * (t * 0.7).cos() }) .collect(); let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { bitrate_kbps: 320, vbr_quality: None, }); encoder .push_pcm_f32(&pcm, channels as u16, rate) .expect("encoder accepts this shape"); encoder.finish(); let mut bytes = Vec::new(); while let Ok(frame) = encoder.next_packet() { bytes.extend_from_slice(&frame); } let mut reader = crate::Mp3Reader::new(); reader.push(&bytes); let mut out: Vec = Vec::new(); for frame in reader.decode_all() { out.extend_from_slice(&frame.samples); } let mut best = (f64::MIN, 0usize); let window = 4096 * channels; let mut lag = 0; while lag + window * 2 < out.len() { let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); for i in 0..window { let (x, y) = (out[lag + window + i] as f64, pcm[window + 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, lag / channels); } lag += channels; } assert!(best.0 > 0.999, "round trip correlation {:.6}", best.0); assert_eq!( best.1 as u32, ENCODER_DELAY + DECODER_DELAY, "measured lag at {rate} Hz, {channels} channels" ); } } /// The whole window sequence — normal, start, short, stop, normal — has to /// reconstruct, not just the long blocks. This runs the transform pair /// directly, so a failure points at the windows rather than at the /// quantiser. #[test] fn window_sequence_reconstructs() { use crate::filterbank::Imdct; let imdct = Imdct::default(); let types = [0u8, 0, 1, 2, 3, 0, 0]; let signal: Vec = (0..18 * (types.len() + 2)) .map(|i| ((i as f32) * 0.37).sin() + 0.3 * ((i as f32) * 1.7).cos()) .collect(); let mut output = vec![0.0f32; signal.len()]; let mut overlap = [0.0f32; 18]; for (granule, block_type) in types.iter().enumerate() { let mut window = [0.0f32; 36]; for (i, slot) in window.iter_mut().enumerate() { let index = granule * 18 + i; if index < signal.len() { *slot = signal[index]; } } let mut spectrum = [0.0f32; 18]; if *block_type == 2 { mdct_short(&window, &mut spectrum); } else { mdct_long(&window, *block_type, &mut spectrum); } let mut block = [0.0f32; 36]; if *block_type == 2 { imdct.short(&spectrum, &mut block); } else { imdct.long(&spectrum, *block_type, &mut block); } for t in 0..18 { let index = granule * 18 + t; if index < output.len() { output[index] = block[t] + overlap[t]; } } overlap.copy_from_slice(&block[18..]); } // The first granule has no predecessor and the last no successor. for (granule, block_type) in types.iter().enumerate().take(types.len() - 1).skip(1) { let mut error = 0.0f64; let mut energy = 0.0f64; for i in granule * 18..(granule + 1) * 18 { error += (output[i] - signal[i]).powi(2) as f64; energy += (signal[i] * signal[i]) as f64; } let snr = 10.0 * (energy / error.max(1e-30)).log10(); assert!( snr > 60.0, "granule {granule} (block type {block_type}) reconstructs at {snr:.1} dB" ); } } /// A granule that switches to short blocks must come back as itself. /// /// Short blocks are coded band-major with the three windows interleaved on /// every line, which is not the order the transform produces them in. Miss /// that permutation and the bit count still lands exactly on /// `part2_3_length`, every fixture still decodes, and only the switched /// granules come back as noise — so this test drives an attack that forces /// the switch and checks the granules around it. #[test] fn switched_granules_reconstruct() { let rate = 44100u32; let n = 1152 * 12; let attack = 1152 * 6; let pcm: Vec = (0..n) .map(|i| { let t = i as f32; let tone = 0.5 * (t * 0.21).sin() + 0.3 * (t * 0.93).cos(); // Six frames of near-silence, then full level: an attack no // block-switching encoder can ignore. if i < attack { tone * 0.002 } else { tone } }) .collect(); let mut encoder = Mp3Encoder::new(Mp3EncoderConfig { bitrate_kbps: 320, vbr_quality: None, }); encoder .push_pcm_f32(&pcm, 1, rate) .expect("encoder accepts this"); encoder.finish(); let mut bytes = Vec::new(); while let Ok(frame) = encoder.next_packet() { bytes.extend_from_slice(&frame); } let mut reader = crate::Mp3Reader::new(); reader.push(&bytes); let mut out: Vec = Vec::new(); for frame in reader.decode_all() { out.extend_from_slice(&frame.samples); } let lag = (ENCODER_DELAY + DECODER_DELAY) as usize; // Every granule from the attack onward, where the switch happens. let mut worst = (1.0f64, 0usize); let mut granule = attack / 576; while (granule + 1) * 576 + lag <= out.len() && (granule + 1) * 576 <= pcm.len() { let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64); for i in granule * 576..(granule + 1) * 576 { let (x, y) = (out[i + lag] as f64, pcm[i] as f64); ab += x * y; aa += x * x; bb += y * y; } let corr = ab / (aa * bb).sqrt().max(1e-30); if corr < worst.0 { worst = (corr, granule); } granule += 1; } assert!( worst.0 > 0.99, "granule {} reconstructs at {:.4}", worst.1, worst.0 ); } #[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, None).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] ); } } }