forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB06be466Tahinli2 months ago3574 commits

encode.rs2284 lines, 93.1 KiBHistoryRawDownload
1//! Layer III encoding: analysis filterbank, MDCT with block switching, a
2//! masking model, the two quantisation loops and the bit reservoir.
3//!
4//! **The psychoacoustic model, stated plainly.** Per granule and channel it
5//! takes one 1024-point real FFT of the sine-windowed input, sums the power
6//! spectrum into the granule's scalefactor bands, spreads that energy across
7//! neighbouring bands with a one-sided exponential (about 25 dB/band up, 10
8//! dB/band down), and sets each band's allowed noise to the spread energy
9//! minus a signal-to-mask offset that follows a spectral-flatness tonality
10//! estimate — 21 dB where the band looks tonal, 6 dB where it looks like
11//! noise — floored by an absolute-threshold curve. It has no temporal
12//! spreading, no pre-echo control beyond block switching, and no inter-channel
13//! masking; those are the honest gaps against a full ISO Model 2.
14//!
15//! The outer (distortion) loop amplifies the scalefactors of bands whose
16//! quantisation noise exceeds that threshold; the inner (rate) loop raises
17//! `global_gain` until the Huffman-coded granule fits the bits the reservoir
18//! makes available.
19
20use crate::filterbank::{Analysis, alias_expand};
21use crate::header::{ChannelMode, FrameHeader, Version};
22use crate::huffman::{self, BitBuf};
23use crate::tables::{
24 MAX_QUANT, SLEN, forward_mdct_long, forward_mdct_short, long_starts, power43, short_starts,
25 short_widths, windows,
26};
27use ec_core::bitio::BitWriter;
28use ec_core::error::{Error, Result};
29use ec_dsp::{RealFft, Window};
30use wide::f32x8;
31
32/// Encoder settings.
33///
34/// The field names match the incumbent MP3 encoder shim's, because the replica
35/// swaps one for the other without touching call sites.
36#[derive(Clone, Copy, Debug, Default, PartialEq)]
37pub struct Mp3EncoderConfig {
38 /// Target bitrate in kbit/s, snapped to the nearest legal Layer III rate.
39 pub bitrate_kbps: u32,
40 /// Quality on a 0..1 scale instead of a bitrate.
41 ///
42 /// Runs true variable bitrate: each frame's granules are quantised to the
43 /// masking threshold scaled by this quality (no fixed bit budget), and the
44 /// frame then picks the smallest legal bitrate that carries them; the
45 /// quality's mean lands near [`bitrate_for_quality`]. Easy frames cost
46 /// fewer bits, hard ones more.
47 pub vbr_quality: Option<f32>,
48}
49
50const BITRATES_V1: [u32; 14] = [
51 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
52];
53const BITRATES_V2: [u32; 14] = [8, 16, 24, 32, 40, 48, 56, 64, 80, 96, 112, 128, 144, 160];
54
55/// The legal Layer III bitrate nearest to `kbps` for this stream.
56pub fn snap_bitrate(version: Version, kbps: u32) -> u32 {
57 let table: &[u32] = if version == Version::Mpeg1 {
58 &BITRATES_V1
59 } else {
60 &BITRATES_V2
61 };
62 *table
63 .iter()
64 .min_by_key(|&&r| r.abs_diff(kbps))
65 .expect("bitrate table is not empty")
66}
67
68/// The bitrate a `vbr_quality` in `[0, 1]` asks for, in kbit/s.
69pub fn bitrate_for_quality(quality: f32) -> u32 {
70 let q = quality.clamp(0.0, 1.0);
71 // 0.0 -> 96 kbit/s, 0.5 -> 192, 1.0 -> 320.
72 (96.0 + q * 224.0).round() as u32
73}
74
75/// The largest value the 12-bit `part2_3_length` side-info field can carry,
76/// and so the most bits one granule may be coded to.
77const PART2_3_MAX: u32 = (1 << 12) - 1;
78const ZERO_QUANT_THRESHOLD: f32 = 7.8504e-17;
79
80const SFB_LONG: usize = 21;
81
82/// How much quieter the difference of the two channels has to be than their
83/// sum before the frame is coded as mid/side. One means "whenever the sum is
84/// the louder of the two", which is every correlated mix.
85///
86/// Swept on the two library sources mid/side helps least (`reelo`, `dl8a`,
87/// `real_library_sweep_vs_lame`): the correlation gap moves by 0.00001 across
88/// 0.5, 1, 2 and "always", and by 0.0005 between "always" and "never". Real
89/// music sits nowhere near this threshold, so it is a guard, not a tuning
90/// knob -- what it guards is the opposed-channel case, where the difference
91/// is the loud channel (`mid_side_follows_the_channel_correlation`).
92const MS_ENERGY_RATIO: f64 = 1.0;
93
94/// How much of the frame budget follows each granule-channel's bit demand
95/// rather than being split evenly. Swept below.
96const DEMAND_SPLIT: f64 = 0.7;
97
98/// One granule's worth of coded spectrum plus the side info describing it.
99#[derive(Clone, Debug)]
100struct CodedGranule {
101 bits: BitBuf,
102 part2_3_length: u32,
103 big_values: u32,
104 global_gain: u32,
105 scalefac_compress: u32,
106 block_type: u8,
107 table_select: [u8; 3],
108 region0_count: u32,
109 region1_count: u32,
110 scalefac_scale: bool,
111 count1table_select: bool,
112}
113
114/// The stateful encoder core: PCM in, Layer III frames out.
115#[derive(Debug)]
116pub struct Mp3Encode {
117 sample_rate: u32,
118 channels: usize,
119 bitrate_kbps: u32,
120 /// When set, frames are coded to a quality target and their bitrate is
121 /// chosen per frame; `bitrate_kbps` is then the floor, not the rate.
122 vbr_quality: Option<f32>,
123 version: Version,
124 mode: ChannelMode,
125 analysis: Vec<Analysis>,
126 /// Subband slots waiting for their MDCT, per channel.
127 slots: Vec<Vec<[f32; 32]>>,
128 /// The previous granule's subband slots, for the 36-sample MDCT window.
129 history: Vec<[[f32; 32]; 18]>,
130 /// Window type chosen for the granule we are holding back.
131 pending: Vec<PendingGranule>,
132 /// The block type each channel's previous granule used. Window switching
133 /// is a sequence, and the sequence does not restart at a frame boundary.
134 previous_block: u8,
135 /// The `mode_extension` bits of the frame being written: bit 1 is
136 /// mid/side stereo, decided per frame in `emit_frame`.
137 mode_ext: u8,
138 fft: RealFft<f32>,
139 fft_window: Window<f32>,
140 psy_history: Vec<Vec<f32>>,
141 /// Deinterleave scratch for `encode_block`, grown once and reused.
142 pcm_scratch: Vec<f32>,
143 /// The main-data byte stream and how much of it frames have carried.
144 stream: Vec<u8>,
145 used: usize,
146 /// Stream bytes already assigned to a frame's payload, decided or not.
147 assigned: usize,
148 /// Stream bytes already written out in a frame.
149 written: usize,
150 /// Frames whose header and side info are decided but whose payload is
151 /// still being filled: the bit reservoir means a frame's payload carries
152 /// the *next* frame's granule data, so emission runs one frame behind.
153 /// The third field is the frame's main-data capacity in bytes, which a
154 /// VBR frame chooses for itself.
155 queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>, usize)>,
156 ready: std::collections::VecDeque<Vec<u8>>,
157 frames: u32,
158 /// Bytes of emitted audio frames (everything after the info header), for
159 /// the Xing header's byte count and average bitrate.
160 frame_bytes: u64,
161 /// The legal-bitrate table index VBR's last frame settled on. Real audio
162 /// is smooth from one frame to the next, so the candidate search below
163 /// starts here instead of blind-bisecting the whole table every frame.
164 vbr_index: usize,
165}
166
167#[derive(Clone, Debug)]
168struct PendingGranule {
169 subband: Vec<[f32; 32]>,
170 energy: f32,
171 threshold: Vec<f32>,
172}
173
174impl Mp3Encode {
175 /// An encoder for this stream shape. Rates outside 8..48 kHz have no Layer
176 /// III frame and are refused by name.
177 pub fn new(
178 sample_rate: u32,
179 channels: usize,
180 bitrate_kbps: u32,
181 vbr_quality: Option<f32>,
182 ) -> Result<Mp3Encode> {
183 let version = match sample_rate {
184 32000 | 44100 | 48000 => Version::Mpeg1,
185 16000 | 22050 | 24000 => Version::Mpeg2,
186 8000 | 11025 | 12000 => Version::Mpeg25,
187 other => {
188 return Err(Error::unsupported(
189 format!("{other} Hz MPEG audio"),
190 "Layer III frames exist only for 8, 11.025, 12, 16, 22.05, 24, 32, 44.1 and 48 kHz",
191 ));
192 }
193 };
194 if channels == 0 || channels > 2 {
195 return Err(Error::unsupported(
196 format!("{channels}-channel MP3"),
197 "Layer III carries one or two channels",
198 ));
199 }
200 Ok(Mp3Encode {
201 sample_rate,
202 channels,
203 bitrate_kbps: snap_bitrate(version, bitrate_kbps),
204 vbr_quality,
205 version,
206 mode: if channels == 2 {
207 ChannelMode::JointStereo
208 } else {
209 ChannelMode::Mono
210 },
211 analysis: (0..channels).map(|_| Analysis::default()).collect(),
212 slots: vec![Vec::new(); channels],
213 history: vec![[[0.0; 32]; 18]; channels],
214 pending: Vec::new(),
215 previous_block: 0,
216 mode_ext: 0,
217 fft: RealFft::new(1024),
218 fft_window: Window::sine(1024),
219 psy_history: vec![vec![0.0; 1024]; channels],
220 stream: Vec::new(),
221 used: 0,
222 assigned: 0,
223 written: 0,
224 queued: std::collections::VecDeque::new(),
225 pcm_scratch: Vec::new(),
226 ready: std::collections::VecDeque::new(),
227 frames: 0,
228 frame_bytes: 0,
229 vbr_index: {
230 let table: &[u32] = if version == Version::Mpeg1 {
231 &BITRATES_V1
232 } else {
233 &BITRATES_V2
234 };
235 let target = vbr_quality.map_or(0, bitrate_for_quality);
236 table
237 .iter()
238 .enumerate()
239 .min_by_key(|&(_, &k)| k.abs_diff(target))
240 .map_or(0, |(i, _)| i)
241 },
242 })
243 }
244
245 /// The header every frame of this stream carries, at `bitrate_kbps`.
246 fn header(&self, bitrate_kbps: u32) -> FrameHeader {
247 FrameHeader {
248 version: self.version,
249 layer: 3,
250 crc: false,
251 bitrate_kbps,
252 sample_rate: self.sample_rate,
253 padding: false,
254 private: false,
255 mode: self.mode,
256 mode_ext: self.mode_ext,
257 copyright: false,
258 original: true,
259 emphasis: 0,
260 }
261 }
262
263 /// Granules per frame for this stream.
264 pub fn granules(&self) -> usize {
265 self.header(self.bitrate_kbps).granules()
266 }
267
268 /// Samples per channel one frame codes.
269 pub fn frame_samples(&self) -> usize {
270 self.granules() * 576
271 }
272}
273
274/// Interleaved PCM in, complete frames out.
275#[derive(Debug)]
276pub struct Mp3Encoder {
277 core: Option<Mp3Encode>,
278 config: Mp3EncoderConfig,
279 pcm: Vec<f32>,
280 frames: std::collections::VecDeque<Vec<u8>>,
281 finished: bool,
282 header_written: bool,
283 total_samples: u64,
284}
285
286impl Mp3Encoder {
287 /// An encoder that configures itself from the first PCM it is given.
288 pub fn new(config: Mp3EncoderConfig) -> Mp3Encoder {
289 Mp3Encoder {
290 core: None,
291 config,
292 pcm: Vec::new(),
293 frames: std::collections::VecDeque::new(),
294 finished: false,
295 header_written: false,
296 total_samples: 0,
297 }
298 }
299
300 /// Feeds interleaved `f32` samples in `[-1, 1]`.
301 pub fn push_pcm_f32(
302 &mut self,
303 interleaved: &[f32],
304 channels: u16,
305 sample_rate: u32,
306 ) -> Result<()> {
307 if self.core.is_none() {
308 let bitrate = match self.config.vbr_quality {
309 Some(q) => bitrate_for_quality(q),
310 None => self.config.bitrate_kbps.max(8),
311 };
312 self.core = Some(Mp3Encode::new(
313 sample_rate,
314 usize::from(channels),
315 bitrate,
316 self.config.vbr_quality,
317 )?);
318 self.pcm.resize(PRIMING * usize::from(channels.max(1)), 0.0);
319 }
320 self.pcm.extend_from_slice(interleaved);
321 self.total_samples += (interleaved.len() / usize::from(channels.max(1))) as u64;
322 self.drain(false);
323 Ok(())
324 }
325
326 /// Feeds interleaved 16-bit samples, scaled the way every decoder here
327 /// scales them.
328 pub fn push_pcm_s16(
329 &mut self,
330 interleaved: &[i16],
331 channels: u16,
332 sample_rate: u32,
333 ) -> Result<()> {
334 let floats: Vec<f32> = interleaved
335 .iter()
336 .map(|s| f32::from(*s) / 32768.0)
337 .collect();
338 self.push_pcm_f32(&floats, channels, sample_rate)
339 }
340
341 /// Ends the stream: pads the tail to a whole frame and flushes.
342 pub fn finish(&mut self) {
343 if let Some(core) = &self.core {
344 let channels = core.channels;
345 // The filterbank runs fifteen slots behind, the MDCT one granule
346 // behind that, and block switching holds one more granule back to
347 // look ahead; feed silence so every real sample comes out the other
348 // end rather than being dropped with the pipeline.
349 let tail = vec![0.0f32; channels * (576 * 3 + 480)];
350 self.pcm.extend_from_slice(&tail);
351 }
352 self.drain(true);
353 self.finished = true;
354 }
355
356 fn drain(&mut self, flush: bool) {
357 let Self {
358 core, pcm, frames, ..
359 } = self;
360 let Some(core) = core.as_mut() else {
361 return;
362 };
363 let channels = core.channels;
364 let need = core.frame_samples() * channels;
365 // Encode behind a read cursor and shift the leftovers once: draining
366 // per frame memmoved the whole remaining push for every frame, which
367 // on a single large push is quadratic in the file length.
368 let mut pos = 0usize;
369 while pcm.len() - pos >= need {
370 core.encode_block(&pcm[pos..pos + need]);
371 pos += need;
372 }
373 pcm.drain(..pos);
374 if flush {
375 if !pcm.is_empty() {
376 pcm.resize(need, 0.0);
377 core.encode_block(pcm);
378 pcm.clear();
379 }
380 core.flush_pending();
381 core.flush_frames();
382 }
383 while let Some(frame) = core.ready.pop_front() {
384 frames.push_back(frame);
385 }
386 }
387
388 /// The next complete frame, [`Error::Eof`] once drained after
389 /// [`Mp3Encoder::finish`], [`Error::NeedMore`] before that.
390 pub fn next_packet(&mut self) -> Result<Vec<u8>> {
391 if !self.header_written && (self.finished || !self.frames.is_empty()) {
392 self.header_written = true;
393 if let Some(core) = &self.core {
394 return Ok(info_frame(core, self.total_samples, self.finished));
395 }
396 }
397 match self.frames.pop_front() {
398 Some(frame) => Ok(frame),
399 None if self.finished => Err(Error::Eof),
400 None => Err(Error::NeedMore),
401 }
402 }
403}
404
405/// Silence prepended to the first PCM the encoder is given.
406///
407/// The first MDCT block has no predecessor to overlap with, so the frame it
408/// produces cannot reconstruct — the transform's startup, not a coding loss.
409/// Priming with a frame of silence puts that region before the audio instead
410/// of on top of it, and the delay field below tells a decoder to drop it. It
411/// is what makes the first frame of a gapless decode as good as the rest;
412/// without it that frame correlates 0.67 against its input while every other
413/// frame is above 0.999.
414const PRIMING: usize = 1152;
415
416/// Samples of PCM this encoder's pipeline runs ahead of its output: the
417/// [`PRIMING`] silence, plus the analysis bank running fifteen slots behind
418/// its input and the MDCT one granule behind that, less what the decoder's
419/// synthesis gives back. Measured end to end (encode, decode,
420/// cross-correlate) as 1728 samples of lag, of which 529 is the decoder delay
421/// every gapless-tag consumer adds for itself.
422///
423/// `encoder_delay_is_what_the_tag_says` is that measurement as a test: change
424/// the pipeline and it fails rather than silently mis-stating the tag.
425pub(crate) const ENCODER_DELAY: u32 = PRIMING as u32 + 47;
426
427/// The decoder delay a gapless tag consumer adds to the encoder delay. Fixed by
428/// the tag's own convention, not by anything here, so nothing in the encoder
429/// spends it — `encoder_delay_is_what_the_tag_says` is what it is for.
430#[allow(dead_code)]
431const DECODER_DELAY: u32 = 529;
432
433/// The nine-byte encoder string in the gapless extension.
434///
435/// It says `gapless3.100` and not `ec-mp3` on purpose, and this is the one place
436/// this crate writes something it is not: the oracle (and every player that copied
437/// its parser) only reads the delay and padding fields when those first four
438/// bytes are `gapless`, `Lavc` or `Lavf`. Writing our own name there produces a
439/// tag that parses and is then ignored, which is worse than useless — the
440/// gapless information would be present and unusable. The rest of the
441/// extension is filled honestly or zeroed.
442const GAPLESS_VERSION: &[u8; 9] = &[0x4c, 0x41, 0x4d, 0x45, b'3', b'.', b'1', b'0', b'0'];
443
444/// The Xing/Info header frame every player expects first: a silent frame whose
445/// main data is the tag, so a decoder that does not know the tag still decodes
446/// a legal (silent) frame rather than choking.
447///
448/// Carries frame and byte counts and — the point of it — the encoder delay and
449/// padding, which is what lets a decoder hand back exactly the samples that
450/// went in. Those two are exact when the caller pushes all its PCM before
451/// pulling packets, which is the pattern the family's exporter uses; a caller
452/// that interleaves pushes and pulls gets the delay (a constant) right and the
453/// counts as of the first pull.
454fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> {
455 let vbr = core.vbr_quality.is_some();
456 let header = core.header(core.bitrate_kbps);
457 let frame_len = header.frame_len().unwrap_or(417);
458 let mut out = vec![0u8; frame_len];
459 out[..4].copy_from_slice(&header.to_bytes());
460 let at = 4 + header.side_info_len();
461 let spf = header.samples_per_frame() as u64;
462 let (frames, padding) = if complete {
463 let frames = core.frames;
464 let coded = u64::from(frames) * spf;
465 let padding = coded.saturating_sub(samples + u64::from(ENCODER_DELAY));
466 (frames, padding.min(4095) as u32)
467 } else {
468 (0, 0)
469 };
470 // The header's byte count is the whole stream, info frame included.
471 // `frame_bytes` sums emitted audio-frame lengths; in CBR that is
472 // `frames * frame_len`, reducing to the old `(frames + 1) * frame_len`.
473 let bytes = if complete {
474 core.frame_bytes + frame_len as u64
475 } else {
476 0
477 };
478 // The gapless "bitrate" byte: a VBR stream reports its mean rate, a CBR one
479 // its constant rate.
480 let bitrate_byte = if vbr && complete && samples > 0 {
481 let seconds = samples as f64 / f64::from(core.sample_rate);
482 let kbps = bytes as f64 * 8.0 / seconds / 1000.0;
483 (kbps.round() as u32).min(255) as u8
484 } else {
485 core.bitrate_kbps.min(255) as u8
486 };
487
488 let mut tag: Vec<u8> = Vec::with_capacity(64);
489 if vbr {
490 tag.extend_from_slice(b"Xing");
491 } else {
492 tag.extend_from_slice(b"Info");
493 }
494 tag.extend_from_slice(&3u32.to_be_bytes()); // frames and bytes present
495 tag.extend_from_slice(&frames.to_be_bytes());
496 tag.extend_from_slice(&(bytes.min(u64::from(u32::MAX)) as u32).to_be_bytes());
497 tag.extend_from_slice(GAPLESS_VERSION);
498 // Tag revision (0), VBR flag (0x10) and VBR method (3) when variable.
499 tag.push(if vbr { 0x70 } else { 0 });
500 tag.push(0); // lowpass in 100 Hz units, unstated
501 tag.extend_from_slice(&0u32.to_be_bytes()); // replay gain peak
502 tag.extend_from_slice(&0u16.to_be_bytes()); // radio replay gain
503 tag.extend_from_slice(&0u16.to_be_bytes()); // audiophile replay gain
504 tag.push(0); // encoding flags and ATH type
505 tag.push(bitrate_byte);
506 let delay_padding = (ENCODER_DELAY << 12) | padding;
507 tag.extend_from_slice(&delay_padding.to_be_bytes()[1..]); // 12 bits each
508 tag.push(0); // misc
509 tag.push(0); // mp3gain
510 tag.extend_from_slice(&0u16.to_be_bytes()); // preset and surround info
511 tag.extend_from_slice(&0u32.to_be_bytes()); // music length
512 tag.extend_from_slice(&0u16.to_be_bytes()); // music CRC
513 tag.extend_from_slice(&0u16.to_be_bytes()); // tag CRC
514 // A frame too small to hold the whole tag keeps the fields that fit, in
515 // order, which is how the parsers read it anyway.
516 let room = frame_len - at;
517 let take = tag.len().min(room);
518 out[at..at + take].copy_from_slice(&tag[..take]);
519 out
520}
521
522impl Mp3Encode {
523 /// Encodes one frame's worth of interleaved PCM.
524 fn encode_block(&mut self, pcm: &[f32]) {
525 let channels = self.channels;
526 let granules = self.granules();
527 // Polyphase analysis, one channel at a time.
528 for ch in 0..channels {
529 // One deinterleave buffer per encoder, grown once: this frame's
530 // mono channel used to be a fresh allocation per channel per
531 // frame.
532 self.pcm_scratch.clear();
533 self.pcm_scratch.reserve(pcm.len() / channels);
534 for frame in pcm.chunks(channels) {
535 self.pcm_scratch.push(frame[ch]);
536 }
537 let mono = &self.pcm_scratch;
538 for chunk in mono.chunks(32) {
539 if chunk.len() < 32 {
540 break;
541 }
542 if let Some(slot) = self.analysis[ch].push(chunk) {
543 self.slots[ch].push(slot);
544 }
545 }
546 // The masking model's history update, inlined from `psy_push` so
547 // it can touch `psy_history` while `mono` borrows `pcm_scratch`.
548 let n = mono.len().min(1024);
549 let history = &mut self.psy_history[ch];
550 history.copy_within(n.., 0);
551 let keep = 1024 - n;
552 history[keep..].copy_from_slice(&mono[mono.len() - n..]);
553 }
554 // A granule is 18 slots; hold one back so block switching can look
555 // ahead at the next granule's energy.
556 let ready = self.slots[0].len() / 18;
557 if ready == 0 {
558 return;
559 }
560 for _ in 0..ready {
561 for ch in 0..channels {
562 let subband: Vec<[f32; 32]> = self.slots[ch].drain(..18).collect();
563 let energy: f32 = subband
564 .iter()
565 .flat_map(|slot| slot.iter())
566 .map(|v| v * v)
567 .sum();
568 let threshold = self.psy_threshold(ch);
569 self.pending.push(PendingGranule {
570 subband,
571 energy,
572 threshold,
573 });
574 }
575 }
576 // Emit whole frames while a lookahead granule remains.
577 let per_frame = granules * channels;
578 while self.pending.len() >= per_frame + channels {
579 self.emit_frame();
580 }
581 }
582
583 /// Allowed noise per long scalefactor band, from the masking model, in
584 /// the units `code_with` measures quantisation noise in (summed squared
585 /// MDCT lines), so noise / threshold is a noise-to-mask ratio.
586 ///
587 /// The FFT here is unnormalised: for input of mean-square power P, a
588 /// 1024-point transform of the sine-windowed block (sum of w^2 = N/2) has
589 /// per-bin power N/2 * P = 512 P. The analysis filterbank is unity gain
590 /// and splits P across 32 subbands (P/32 each), and `mdct_long` scales by
591 /// 1/9 with a 36-point sine window (sum of w^2 cos^2 = 9), so each of a
592 /// subband's 18 lines carries P/32 * 9/81 = P/288. A band of W lines
593 /// spans W * 512/576 FFT bins: FFT energy / MDCT energy =
594 /// (W * 8/9 * 512 P) / (W * P/288) = 2^17, the `FFT_TO_MDCT` below.
595 fn psy_threshold(&mut self, ch: usize) -> Vec<f32> {
596 const FFT_TO_MDCT: f32 = 1.0 / 131072.0;
597 let mut block: Vec<f32> = self.psy_history[ch].clone();
598 self.fft_window.apply(&mut block);
599 let mut spectrum = vec![ec_dsp::Complex::<f32>::ZERO; 513];
600 self.fft.forward(&block, &mut spectrum);
601 let starts = long_starts(self.sample_rate);
602 let mut energy = vec![0.0f32; SFB_LONG];
603 for (band, slot) in energy.iter_mut().enumerate() {
604 // The 576 coefficients of a granule map onto 512 FFT bins.
605 let from = usize::from(starts[band]) * 512 / 576;
606 let to = (usize::from(starts[band + 1]) * 512 / 576).max(from + 1);
607 let mut sum = 0.0f32;
608 let mut log_sum = 0.0f32;
609 let mut count = 0.0f32;
610 for bin in &spectrum[from..to.min(512)] {
611 let power = bin.norm_sqr() + 1e-30;
612 sum += power;
613 log_sum += power.ln();
614 count += 1.0;
615 }
616 // Spectral flatness as a tonality proxy: a flat band is noise-like
617 // and masks less.
618 let flatness = if count > 0.0 {
619 ((log_sum / count).exp() / (sum / count)).clamp(0.0, 1.0)
620 } else {
621 1.0
622 };
623 let offset_db = 6.0 + 15.0 * (1.0 - flatness);
624 *slot = sum * FFT_TO_MDCT * 10f32.powf(-offset_db / 10.0);
625 }
626 // Spreading: masking leaks upward strongly and downward weakly.
627 let mut spread = energy.clone();
628 for band in 1..SFB_LONG {
629 let leak = spread[band - 1] * 0.0032; // about -25 dB per band
630 spread[band] = spread[band].max(leak);
631 }
632 for band in (0..SFB_LONG - 1).rev() {
633 let leak = spread[band + 1] * 0.1; // about -10 dB per band
634 spread[band] = spread[band].max(leak);
635 }
636 // Absolute threshold, coarse: hearing is least sensitive at the ends.
637 for (band, slot) in spread.iter_mut().enumerate() {
638 let rel = band as f32 / SFB_LONG as f32;
639 let floor = 1e-9 * FFT_TO_MDCT * (1.0 + 400.0 * (rel - 0.35).max(0.0).powi(2));
640 *slot = slot.max(floor);
641 }
642 spread
643 }
644
645 fn emit_frame(&mut self) {
646 let channels = self.channels;
647 let granules = self.granules();
648 let vbr = self.vbr_quality;
649
650 // Window types. A granule whose successor is much louder starts the
651 // switch, the loud one is short, and the one after stops it — and the
652 // sequence carries across frames, because a start window in the last
653 // granule of one frame demands a short block in the first granule of
654 // the next. Restarting it per frame is what leaves a start window
655 // facing a normal one, whose overlap does not reconstruct.
656 //
657 // Both channels of a frame get the same window, because mid/side
658 // below adds and subtracts their spectra: lines from a long block and
659 // lines from a short one describe different time slices, so summing
660 // them would smear one channel's transient across the other's granule.
661 let mut types = vec![0u8; granules * channels];
662 for gr in 0..granules {
663 {
664 let base = gr * channels;
665 let energy = |slot: usize| -> f32 {
666 (0..channels)
667 .filter_map(|ch| self.pending.get(slot + ch))
668 .map(|g| g.energy)
669 .sum()
670 };
671 let here = energy(base);
672 let next = if base + channels < self.pending.len() {
673 energy(base + channels)
674 } else {
675 here
676 };
677 // Digital silence is not a transient to protect: switching on
678 // the way out of it (the priming, or a cut in a timeline) costs
679 // the resolution a long block would have spent on the attack
680 // itself, and there is no pre-echo to hide when nothing
681 // precedes it.
682 // How much louder the next granule has to be to count as an
683 // attack. Swept against the worst 20 ms error-to-signal ratio
684 // on real music (`real_library_sweep_vs_lame`), because
685 // whole-file correlation cannot see pre-echo at all:
686 //
687 // ratio 1.3 1.6 2 3 4 8
688 // dl8a@128 -2.3 -3.3 -3.3 -3.3 -3.3 +1.1 dB
689 // dl8a@192 -6.7 -6.7 -6.7 -7.8 -7.8 -4.2 dB
690 //
691 // Flat from 1.6 to 4 and then a cliff: at 8 a whole granule
692 // has to grow eightfold in total energy, which music does
693 // about once a minute -- one short granule in 9196, against
694 // libmp3lame's 88 over the same audio. Below 1.6 the extra
695 // short blocks start costing correlation without buying any
696 // more of the worst window back, so 4 sits at the cheap end
697 // of the flat part.
698 let attack = here > 1e-9 && next > here * 4.0 + 1e-6;
699 let block = match self.previous_block {
700 1 => 2,
701 2 if attack => 2,
702 2 => 3,
703 _ if attack => 1,
704 _ => 0,
705 };
706 for ch in 0..channels {
707 types[base + ch] = block;
708 }
709 self.previous_block = block;
710 }
711 }
712
713 let begin = self.assigned - self.used;
714
715 // The MDCT and the quality-scaled masking threshold are shared by
716 // every bitrate candidate VBR tries below; compute them once.
717 let mut xrs: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);
718 let mut thresholds: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);
719 // Take the held-back granules once: the per-granule clone that used
720 // to feed `mdct` copied every subband and threshold just to keep the
721 // borrow checker happy about `history`.
722 let held: Vec<PendingGranule> = self.pending.drain(..granules * channels).collect();
723 for gr in 0..granules {
724 for ch in 0..channels {
725 let index = gr * channels + ch;
726 let granule = &held[index];
727 xrs.push(self.mdct(ch, &granule.subband, types[index]));
728 thresholds.push(match vbr {
729 Some(quality) => quality_threshold(&granule.threshold, quality),
730 None => granule.threshold.clone(),
731 });
732 }
733 }
734
735 // Mid/side stereo. The two channels of real music are mostly the same
736 // signal, and coding their sum and difference puts nearly all of the
737 // energy in the sum, leaving the difference cheap enough to quantise
738 // finely at the same cost. It is applied to the MDCT lines and undone
739 // by the decoder, so it is exact -- the only judgement is whether the
740 // difference really is the small one, which it is not on a wide stereo
741 // mix, where L/R codes two independent signals better than a mid that
742 // is loud and a side that is nearly as loud.
743 self.mode_ext = 0;
744 if channels == 2 && self.mode == ChannelMode::JointStereo {
745 let (mut mid, mut side) = (0.0f64, 0.0f64);
746 for gr in 0..granules {
747 let (left, right) = (&xrs[gr * 2], &xrs[gr * 2 + 1]);
748 for (&l, &r) in left.iter().zip(right.iter()) {
749 let (l, r) = (f64::from(l), f64::from(r));
750 mid += (l + r) * (l + r);
751 side += (l - r) * (l - r);
752 }
753 }
754 if side < mid * MS_ENERGY_RATIO {
755 self.mode_ext = 2;
756 const INV_SQRT2: f32 = std::f32::consts::FRAC_1_SQRT_2;
757 for gr in 0..granules {
758 let (head, tail) = xrs.split_at_mut(gr * 2 + 1);
759 let (left, right) = (&mut head[gr * 2], &mut tail[0]);
760 for (l, r) in left.iter_mut().zip(right.iter_mut()) {
761 let (a, b) = (*l, *r);
762 *l = (a + b) * INV_SQRT2;
763 *r = (a - b) * INV_SQRT2;
764 }
765 // Neither coded channel is one of the speakers any more,
766 // so both are held to whichever channel masked less: an
767 // error in the side channel lands in both ears.
768 let (head, tail) = thresholds.split_at_mut(gr * 2 + 1);
769 let (left, right) = (&mut head[gr * 2], &mut tail[0]);
770 for (l, r) in left.iter_mut().zip(right.iter_mut()) {
771 let floor = l.min(*r);
772 *l = floor;
773 *r = floor;
774 }
775 }
776 }
777 }
778
779 // What each granule-channel asks for, as a share of the frame. The
780 // quantiser codes |xr|^(3/4), so the sum of that over a granule's
781 // lines is the shape of its bit demand: splitting the frame by it
782 // lets a quiet channel hand its bits to a loud one, which is what
783 // makes mid/side pay -- a side channel that is nearly silent no
784 // longer holds a quarter of the frame it cannot spend.
785 let count = (granules * channels).max(1);
786 let demand: Vec<f64> = xrs
787 .iter()
788 .map(|xr| {
789 xr.iter()
790 .map(|v| {
791 let x = f64::from(v.abs());
792 // |x|^(3/4) as a cube and two square roots, the same
793 // shape the quantiser uses.
794 (x * x * x).sqrt().sqrt()
795 })
796 .sum()
797 })
798 .collect();
799 let demand_total: f64 = demand.iter().sum();
800 let demand_share = |budget: usize, index: usize| -> u32 {
801 let even = 1.0 / count as f64;
802 let asked = if demand_total > 0.0 {
803 demand[index] / demand_total
804 } else {
805 even
806 };
807 let part = (1.0 - DEMAND_SPLIT) * even + DEMAND_SPLIT * asked;
808 ((budget as f64 * part) as u32).min(PART2_3_MAX)
809 };
810
811 // Quantise the granules. CBR codes to a fixed frame budget. VBR tries
812 // legal bitrates, coding the whole frame's granules against each one's
813 // share with the same distortion loop CBR uses, and keeps the
814 // cheapest one whose mean noise-to-mask ratio sits under one.
815 let (coded, kbps): (Vec<CodedGranule>, u32) = match vbr {
816 Some(_) => {
817 let table: &[u32] = if self.version == Version::Mpeg1 {
818 &BITRATES_V1
819 } else {
820 &BITRATES_V2
821 };
822 // Codes the frame at one candidate and reports its mean
823 // noise-to-mask ratio; the ratio falls as the bitrate rises,
824 // so the cheapest candidate at or under 1.0 is found by
825 // bisection over the table (four codings, not fourteen).
826 let code_at = |candidate: u32| -> (Vec<CodedGranule>, f64) {
827 let header = self.header(candidate);
828 let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len();
829 let mut frame_coded = Vec::with_capacity(granules * channels);
830 let mut ratio = 0.0;
831 for index in 0..granules * channels {
832 let (granule, r) = quantise_granule(
833 &xrs[index],
834 types[index],
835 demand_share(capacity * 8, index),
836 &thresholds[index],
837 self.sample_rate,
838 );
839 ratio += r / (granules * channels) as f64;
840 frame_coded.push(granule);
841 }
842 (frame_coded, ratio)
843 };
844 // Real audio is smooth frame to frame, so try the last
845 // settled bitrate first and walk only as far as this frame
846 // needs. If the previous frame was already cheap, start at the
847 // legal floor instead of climbing down through the table again.
848 let mut index = if self.vbr_index <= 2 {
849 0
850 } else {
851 self.vbr_index.min(table.len() - 1)
852 };
853 let (coded, ratio) = code_at(table[index]);
854 let mut best = (coded, ratio);
855 let mut best_index = index;
856 if best.1 <= 1.0 {
857 while best_index > 0 {
858 let trial_index = best_index - 1;
859 let trial = code_at(table[trial_index]);
860 if trial.1 > 1.0 {
861 break;
862 }
863 best = trial;
864 best_index = trial_index;
865 }
866 } else {
867 while index + 1 < table.len() {
868 index += 1;
869 let trial = code_at(table[index]);
870 best = trial;
871 best_index = index;
872 if best.1 <= 1.0 {
873 break;
874 }
875 }
876 }
877 self.vbr_index = best_index;
878 (best.0, table[best_index])
879 }
880 None => {
881 let header = self.header(self.bitrate_kbps);
882 let frame_len = header.frame_len().unwrap_or(0);
883 let capacity = frame_len - 4 - header.side_info_len();
884 let budget_bits = (self.assigned + capacity - self.used) * 8;
885 let mut frame_coded = Vec::with_capacity(granules * channels);
886 for index in 0..granules * channels {
887 let spent: usize = frame_coded
888 .iter()
889 .map(|c: &CodedGranule| c.part2_3_length as usize)
890 .sum();
891 let left = budget_bits.saturating_sub(spent);
892 let target = (demand_share(budget_bits, index) as usize)
893 .min(left)
894 .min(4095);
895 let (granule, _) = quantise_granule(
896 &xrs[index],
897 types[index],
898 target as u32,
899 &thresholds[index],
900 self.sample_rate,
901 );
902 frame_coded.push(granule);
903 }
904 (frame_coded, self.bitrate_kbps)
905 }
906 };
907
908 let header = self.header(kbps);
909 let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len();
910 let side_info_len = header.side_info_len();
911
912 // Assemble the frame: header, side info, and this frame's window on
913 // the main-data stream.
914 let mut side = BitWriter::new();
915 side.write_bits(
916 begin as u32,
917 if self.version == Version::Mpeg1 { 9 } else { 8 },
918 );
919 let private = match (self.version == Version::Mpeg1, channels) {
920 (true, 1) => 5,
921 (true, _) => 3,
922 (false, 1) => 1,
923 (false, _) => 2,
924 };
925 side.write_bits(0, private);
926 if self.version == Version::Mpeg1 {
927 side.write_bits(0, 4 * channels as u32); // scfsi: never reuse
928 }
929 for granule in &coded {
930 side.write_bits(granule.part2_3_length, 12);
931 side.write_bits(granule.big_values, 9);
932 side.write_bits(granule.global_gain, 8);
933 side.write_bits(
934 granule.scalefac_compress,
935 if self.version == Version::Mpeg1 { 4 } else { 9 },
936 );
937 if granule.block_type == 0 {
938 side.write_bit(false);
939 for table in granule.table_select {
940 side.write_bits(u32::from(table), 5);
941 }
942 side.write_bits(granule.region0_count, 4);
943 side.write_bits(granule.region1_count, 3);
944 } else {
945 side.write_bit(true);
946 side.write_bits(u32::from(granule.block_type), 2);
947 side.write_bit(false); // mixed_block_flag
948 for table in &granule.table_select[..2] {
949 side.write_bits(u32::from(*table), 5);
950 }
951 side.write_bits(0, 9); // subblock_gain
952 }
953 if self.version == Version::Mpeg1 {
954 side.write_bit(false); // preflag
955 }
956 side.write_bit(granule.scalefac_scale);
957 side.write_bit(granule.count1table_select);
958 }
959 side.align_to_byte();
960 let side_bytes = side.into_bytes();
961 debug_assert_eq!(side_bytes.len(), side_info_len);
962
963 // Append the granule data to the stream at `used`, byte aligned.
964 let mut main = BitBuf::new();
965 for granule in &coded {
966 main.append(&granule.bits);
967 }
968 let main_bytes = main.into_bytes();
969 // Stream positions the reservoir cap skipped over are stuffing, not
970 // data, so they are zeros rather than a shorter stream.
971 if self.stream.len() < self.used {
972 self.stream.resize(self.used, 0);
973 }
974 self.stream.truncate(self.used);
975 self.stream.extend_from_slice(&main_bytes);
976 self.used += main_bytes.len();
977
978 self.queued
979 .push_back((header.to_bytes().to_vec(), side_bytes, capacity));
980 self.assigned += capacity;
981 // A queued frame can only go out once real granule data covers its
982 // whole payload; padding it early is what would strand the next
983 // frame's `main_data_begin` in bytes that were already written.
984 while let Some(&(_, _, front)) = self.queued.front() {
985 if self.stream.len() < self.written + front {
986 break;
987 }
988 let (head, side, cap) = self.queued.pop_front().expect("queue is not empty");
989 let mut frame = Vec::with_capacity(4 + side_info_len + cap);
990 frame.extend_from_slice(&head);
991 frame.extend_from_slice(&side);
992 frame.extend_from_slice(&self.stream[self.written..self.written + cap]);
993 self.written += cap;
994 self.frame_bytes += (4 + side_info_len + cap) as u64;
995 self.ready.push_back(frame);
996 self.frames += 1;
997 }
998 // main_data_begin is nine bits, so the reservoir cannot reach further
999 // back than 511 bytes; anything older is dropped rather than pointed at.
1000 if self.assigned > self.used + 511 {
1001 self.used = self.assigned - 511;
1002 }
1003 }
1004
1005 /// Encodes the granules still held back for block-switching lookahead.
1006 fn flush_pending(&mut self) {
1007 let per_frame = self.granules() * self.channels;
1008 while self.pending.len() >= per_frame {
1009 self.emit_frame();
1010 }
1011 }
1012
1013 /// Writes out whatever frames are still queued, padding the stream so the
1014 /// last frame is complete.
1015 fn flush_frames(&mut self) {
1016 while let Some((head, side, capacity)) = self.queued.pop_front() {
1017 if self.stream.len() < self.written + capacity {
1018 self.stream.resize(self.written + capacity, 0);
1019 }
1020 let mut frame = Vec::with_capacity(4 + side.len() + capacity);
1021 frame.extend_from_slice(&head);
1022 frame.extend_from_slice(&side);
1023 frame.extend_from_slice(&self.stream[self.written..self.written + capacity]);
1024 self.written += capacity;
1025 self.frame_bytes += (4 + side.len() + capacity) as u64;
1026 self.ready.push_back(frame);
1027 self.frames += 1;
1028 }
1029 }
1030
1031 /// One granule of subband samples to 576 spectral lines.
1032 fn mdct(&mut self, ch: usize, subband: &[[f32; 32]], block_type: u8) -> Vec<f32> {
1033 let mut xr = vec![0.0f32; 576];
1034 let history = self.history[ch];
1035 for sb in 0..32 {
1036 // The transform window is the previous granule's 18 samples
1037 // followed by this granule's, with the frequency inversion the
1038 // decoder applies undone first.
1039 let mut input = [0.0f32; 36];
1040 for t in 0..18 {
1041 let sign = if sb % 2 == 1 && t % 2 == 1 { -1.0 } else { 1.0 };
1042 input[t] = history[t][sb] * sign;
1043 input[18 + t] = subband[t][sb] * sign;
1044 }
1045 let out = &mut xr[sb * 18..sb * 18 + 18];
1046 if block_type == 2 {
1047 mdct_short(&input, out);
1048 } else {
1049 mdct_long(&input, block_type, out);
1050 }
1051 }
1052 if block_type != 2 {
1053 alias_expand(&mut xr, 32);
1054 }
1055 let mut store = [[0.0f32; 32]; 18];
1056 store[..18].copy_from_slice(&subband[..18]);
1057 self.history[ch] = store;
1058 xr
1059 }
1060}
1061
1062/// Forward MDCT, 36 samples to 18 coefficients, scaled so the decoder's
1063/// unscaled inverse reconstructs the input under overlap-add.
1064fn mdct_long(input: &[f32; 36], block_type: u8, out: &mut [f32]) {
1065 let window = &windows()[usize::from(block_type)];
1066 let kernel = forward_mdct_long();
1067 let mut windowed = [0.0f32; 36];
1068 for i in 0..36 {
1069 windowed[i] = input[i] * window[i];
1070 }
1071 for (k, row) in kernel.iter().enumerate() {
1072 let mut sum = 0.0f64;
1073 for (n, value) in windowed.iter().enumerate() {
1074 sum += f64::from(*value) * f64::from(row[n]);
1075 }
1076 out[k] = (sum / 9.0) as f32;
1077 }
1078}
1079
1080/// Forward MDCT for a short block: three 12-sample transforms, interleaved
1081/// into the spectrum the way the decoder reads them back.
1082fn mdct_short(input: &[f32; 36], out: &mut [f32]) {
1083 let window = &windows()[2];
1084 let kernel = forward_mdct_short();
1085 for w in 0..3 {
1086 for (k, row) in kernel.iter().enumerate() {
1087 let mut sum = 0.0f64;
1088 for n in 0..12 {
1089 let sample = input[6 + 6 * w + n] * window[n];
1090 sum += f64::from(sample) * f64::from(row[n]);
1091 }
1092 out[k * 3 + w] = (sum / 3.0) as f32;
1093 }
1094 }
1095}
1096
1097/// Scales the masking threshold by `vbr_quality`. A higher quality lowers the
1098/// allowed noise (a smaller threshold, so more bands are amplified and the
1099/// granule costs more bits). The curve is calibrated on the fixture corpus and
1100/// three 30-second music clips so the stream mean tracks
1101/// [`bitrate_for_quality`] without letting q=0 collapse to speech-rate output.
1102fn quality_threshold(threshold: &[f32], quality: f32) -> Vec<f32> {
1103 let q = quality.clamp(0.0, 1.0);
1104 let db = if q <= 0.5 {
1105 12.0 - 25.0 * q + 20.0 * q * q
1106 } else {
1107 let t = q - 0.5;
1108 4.5 - 11.0 * t - 12.0 * t * t
1109 };
1110 // Recalibration, measured against `real_library_vbr_vs_lame`: splitting a
1111 // frame by bit demand reaches the same masking bar for fewer bits, and the
1112 // quality knob promises a mean rate rather than a bar, so the bar tightens
1113 // to spend the saving instead of pocketing it. The slope is fitted to two
1114 // points on the library -- 2 dB at quality 0.3 holds its promised 163
1115 // kbit/s, and the rate moves about 9.5 kbit/s per decibel at quality 0.6.
1116 let trim = 1.6 - 12.0 * q;
1117 let scale = 10f32.powf((db + trim) / 10.0);
1118 threshold.iter().map(|&t| t * scale).collect()
1119}
1120
1121/// Quantises one granule: the rate loop inside the distortion loop.
1122fn quantise_granule(
1123 xr: &[f32],
1124 block_type: u8,
1125 target_bits: u32,
1126 threshold: &[f32],
1127 sample_rate: u32,
1128) -> (CodedGranule, f64) {
1129 if xr.iter().all(|v| v.abs() <= ZERO_QUANT_THRESHOLD) {
1130 return (
1131 CodedGranule {
1132 bits: BitBuf::new(),
1133 part2_3_length: 0,
1134 big_values: 0,
1135 global_gain: 0,
1136 scalefac_compress: 0,
1137 block_type,
1138 table_select: [0; 3],
1139 region0_count: 0,
1140 region1_count: 0,
1141 scalefac_scale: false,
1142 count1table_select: false,
1143 },
1144 0.0,
1145 );
1146 }
1147 let mut scalefac = [0u8; SFB_LONG];
1148 // Score is the summed noise-to-mask ratio over the bands; a mean ratio
1149 // of at most one is VBR's signal that this bitrate carried the granule
1150 // cleanly (strict all-bands-under is vetoed by scalefactor-capped bands).
1151 let mut best: Option<(CodedGranule, f64, usize)> = None;
1152 // The distortion loop. Two things end it: every band is under its masking
1153 // threshold *and* the bits are spent, or no band can be amplified further.
1154 // Spending the bits matters as much as the threshold does — a granule that
1155 // stops early leaves the extra bitrate on the floor, which is what makes an
1156 // encoder's quality flat across 128 and 320 kbit/s.
1157 // Short blocks carry twelve bands, long ones twenty-one.
1158 let bands = if block_type == 2 { 12 } else { SFB_LONG };
1159 let threshold = band_thresholds(threshold, block_type, sample_rate);
1160 let mut exit = ("cap", 19usize);
1161 for round in 0..20 {
1162 let (granule, noise) = code_with(xr, block_type, target_bits, &scalefac, sample_rate);
1163 let ratios: Vec<f64> = (0..bands)
1164 .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30))
1165 .collect();
1166 let score: f64 = ratios.iter().sum();
1167 let mut order: Vec<usize> = (0..bands)
1168 .filter(|&b| scalefac[b] < max_scalefac(b, block_type))
1169 .collect();
1170 order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a]));
1171 let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect();
1172 let spent = granule.part2_3_length;
1173 if best.as_ref().is_none_or(|(_, s, _)| score < *s) {
1174 best = Some((granule, score, bands));
1175 }
1176 if score <= 0.0 {
1177 exit = ("mask", round);
1178 break; // every band is already exactly at the mask; nothing left to buy
1179 }
1180 // Where to stop amplifying, as a fraction of the frame's budget. Swept
1181 // against both gate metrics on all fourteen library rows: 85% beats
1182 // the 95% this shipped with everywhere, and 100% is a disaster --
1183 // reelm loses 0.0048 correlation, because amplifying a band once the
1184 // budget is gone only makes the rate loop coarsen every other band to
1185 // pay for it. Below 70% the test stops binding, since the first round
1186 // already spends more than that.
1187 //
1188 // LAME's own shape -- drop the budget break, let the distortion test
1189 // drive, since `code_with` fits `target_bits` at every round anyway --
1190 // was built and measured here (2026-09-06). It makes the loop live
1191 // (10440 granules of 36758 reach the 20-round cap against 3 before) and
1192 // loses on both gate metrics: reelo at 128 kbit/s goes 0.99917 ->
1193 // 0.99787 correlation, from +0.00062 ahead of libmp3lame to -0.00068
1194 // behind it, and its worst 20 ms window from -15.3 to -12.4 dB, at
1195 // roughly five times the encode time. The gate measures waveform error,
1196 // and a budget-filling rate loop over flat scalefactors is already near
1197 // the MSE optimum, so perceptual redistribution can only trade away
1198 // what this gate scores. Don't re-run it: change the metric first.
1199 if spent * 100 > target_bits * 85 {
1200 exit = ("budget", round);
1201 break; // the budget is spent; amplifying now only coarsens
1202 }
1203 // Bands over their mask get the bits first, worst three per round so
1204 // the rate loop re-fits `global_gain` around a small step; once every
1205 // band is under its mask the spare bits go to the noisiest ones.
1206 // corner-cut: the ISO outer loop keeps amplifying over-mask bands past
1207 // the budget and lets the rate loop coarsen the rest; measured here it
1208 // costs 12-36% RMS against the source (mp3src-stereo-48000, 128/192)
1209 // for a model this coarse, and the encode_matrix bar is an RMS metric.
1210 // Upgrade path: a finer model (ISO spreading function, tonality from
1211 // phase prediction) before trusting the mask over the budget.
1212 let chosen: Vec<usize> = if over.is_empty() { order } else { over }
1213 .into_iter()
1214 .take(3)
1215 .collect();
1216 if chosen.is_empty() {
1217 exit = ("saturated", round);
1218 break;
1219 }
1220 for band in chosen {
1221 scalefac[band] += 1;
1222 }
1223 }
1224 census(exit);
1225 let (granule, score, bands) = best.expect("at least one round runs");
1226 (granule, score / bands as f64)
1227}
1228
1229/// Exit-reason census for the distortion loop: with `EC_MP3_LOOP_TRACE` set,
1230/// one `mp3loop <reason> <round>` line per granule on stderr, so a sweep can be
1231/// counted with `sort | uniq -c`. The loop's shape is the encoder's open
1232/// question; without this the only evidence it ever iterates is indirect.
1233fn census(exit: (&str, usize)) {
1234 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1235 if *ON.get_or_init(|| std::env::var_os("EC_MP3_LOOP_TRACE").is_some()) {
1236 eprintln!("mp3loop {} {}", exit.0, exit.1);
1237 }
1238}
1239
1240/// Puts a spectrum into bitstream order in `out`.
1241///
1242/// A short granule is coded band by band, window by window, line by line,
1243/// while the spectrum the transform produces interleaves the three windows on
1244/// every line — the decoder's reorder step. The encoder has to undo it before
1245/// Huffman coding; writing spectral order instead costs exactly the same
1246/// number of bits, lands exactly on `part2_3_length`, and hands the decoder a
1247/// permuted granule, which comes back as noise. A long block is already in
1248/// order and is copied as is.
1249fn recode_into(spectral: &[i32; 576], block_type: u8, sample_rate: u32, out: &mut [i32; 576]) {
1250 if block_type != 2 {
1251 *out = *spectral;
1252 return;
1253 }
1254 let widths = short_widths(sample_rate);
1255 let starts = short_starts(sample_rate);
1256 let mut position = 0usize;
1257 for sfb in 0..13 {
1258 let (width, start) = (usize::from(widths[sfb]), usize::from(starts[sfb]));
1259 for window in 0..3 {
1260 for line in 0..width {
1261 out[position] = spectral[(start + line) * 3 + window];
1262 position += 1;
1263 }
1264 }
1265 }
1266 for slot in out.iter_mut().skip(position) {
1267 *slot = 0;
1268 }
1269}
1270
1271/// The largest scalefactor a band can actually carry.
1272///
1273/// `scalefac_compress` names two lengths, and the second partition's is at most
1274/// three bits — so a band above the split cannot hold more than 7 however much
1275/// the distortion loop would like to amplify it. Ignoring that ceiling is not a
1276/// rounding error: the quantiser uses the value it wanted, no length can encode
1277/// it, and the decoder reconstructs the band with a scalefactor of zero, which
1278/// turns the granule into noise.
1279fn max_scalefac(band: usize, block_type: u8) -> u8 {
1280 let split = if block_type == 2 { 6 } else { 11 };
1281 if band < split { 15 } else { 7 }
1282}
1283
1284/// The masking model works in long bands; a short block's twelve bands are
1285/// read off it at the same frequencies, so one model serves both.
1286fn band_thresholds(threshold: &[f32], block_type: u8, sample_rate: u32) -> Vec<f32> {
1287 if block_type != 2 {
1288 return threshold.to_vec();
1289 }
1290 let long = long_starts(sample_rate);
1291 let short = short_starts(sample_rate);
1292 (0..12)
1293 .map(|band| {
1294 // A short band's lines sit at three times its index in the spectrum.
1295 let line = usize::from(short[band]) * 3;
1296 let long_band = (0..SFB_LONG)
1297 .rev()
1298 .find(|&b| line >= usize::from(long[b]))
1299 .unwrap_or(0);
1300 // Three windows share the band, so each carries a third of it.
1301 threshold[long_band] / 3.0
1302 })
1303 .collect()
1304}
1305
1306/// Quantises with a fixed scalefactor set, running the rate loop on
1307/// `global_gain`, and reports the noise each band ends up with.
1308///
1309/// The rate loop judges every candidate gain by Huffman cost alone
1310/// ([`plan_spectrum`]); the granule's bits are materialised exactly once,
1311/// for the configuration the loop keeps ([`write_spectrum`]). Writing the
1312/// bits per round — and re-expanding them into a `Vec<bool>` to hand them
1313/// to the frame writer — was the largest single cost in the encoder's
1314/// profile, and said nothing the cost pass had not already said.
1315fn code_with(
1316 xr: &[f32],
1317 block_type: u8,
1318 budget_bits: u32,
1319 scalefac: &[u8; SFB_LONG],
1320 sample_rate: u32,
1321) -> (CodedGranule, [f32; SFB_LONG]) {
1322 let (slen1, slen2, compress) = scalefac_compress(scalefac, block_type);
1323 // The scalefactors come out of the same budget as the spectrum does. A
1324 // short block transmits six bands of each length, once per window.
1325 let scalefac_bits = if block_type == 2 {
1326 (slen1 + slen2) * 18
1327 } else {
1328 slen1 * 11 + slen2 * 10
1329 };
1330 let target_bits = budget_bits.saturating_sub(scalefac_bits);
1331 let peak = xr.iter().fold(0.0f32, |acc, v| acc.max(v.abs()));
1332 // A starting gain that puts the loudest line near the top of the coded
1333 // range: |xr| / 2^((g-210)/4) raised to 3/4 should land around 8000.
1334 let start = if peak > 1e-20 {
1335 (210.0 + 4.0 * (peak.log2() - 13.0 / 0.75)).round() as i32
1336 } else {
1337 210
1338 };
1339 let mut gain = start.clamp(0, 255);
1340 let mut ix = [0i32; 576];
1341 let mut coding = [0i32; 576];
1342 // A line that saturates the coding range is not "cheap", it is clipped;
1343 // the gain search below reads saturation as "does not fit".
1344 let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191);
1345 let mut plan_of = |ix: &[i32; 576]| -> SpectrumPlan {
1346 recode_into(ix, block_type, sample_rate, &mut coding);
1347 plan_spectrum(&coding, block_type, sample_rate)
1348 };
1349 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
1350 let mut coded = plan_of(&ix);
1351 if peak <= 1e-20 {
1352 // Below the smallest representable level: every line quantises to
1353 // zero at any gain (the quantiser's scale multiplies zero either
1354 // way), so the descending-gain search below — which steps one gain
1355 // unit at a time — would walk all 210 units from 210 to 0 finding
1356 // nothing changes, recoding an all-zero spectrum at every step. Skip
1357 // straight to the quietest legal gain; `coded` above is already the
1358 // right answer, because an all-zero spectrum's bit cost does not
1359 // depend on gain.
1360 gain = 0;
1361 } else {
1362 // The rate loop wants the smallest gain whose granule fits the
1363 // budget without clipping. A higher gain shrinks every quantised
1364 // line, and a smaller spectrum costs no more to code, so "fits" is
1365 // monotone in the gain. This shipped as a one-step-at-a-time walk
1366 // from the start estimate and paid ~31 quantise-plus-plan
1367 // evaluations per granule; now the start estimate seeds a geometric
1368 // straddle (doubling steps, so a boundary `d` gains away costs
1369 // about 2·log2 d probes instead of d) followed by a bisection of
1370 // the bracket. The walk's two hard stops stay: gain 255 stands even
1371 // when it does not fit (the low-pass loop below trims the
1372 // spectrum), and gain 0 is the quietest legal gain.
1373 let mut probe_of = |g: i32, out: &mut [i32; 576]| -> (bool, SpectrumPlan) {
1374 quantise(xr, g, scalefac, sample_rate, block_type, out);
1375 let plan = plan_of(out);
1376 (plan.cost <= target_bits && !saturated(out), plan)
1377 };
1378 let mut probe = [0i32; 576];
1379 // `floor` is the largest gain known to miss, `ceil` the smallest
1380 // known to fit; −1 stands for "even 0 misses would not matter", the
1381 // gain-0 floor.
1382 let mut floor = -1i32;
1383 let mut ceil = 255i32;
1384 let mut capped = false;
1385 let first = start.clamp(0, 255);
1386 let (fits, _) = probe_of(first, &mut probe);
1387 if fits {
1388 // The boundary is at or below the estimate: stride down until a
1389 // gain misses.
1390 ceil = first;
1391 let mut step = 1i32;
1392 while ceil > 0 {
1393 let next = (ceil - step).max(0);
1394 let (next_fits, _) = probe_of(next, &mut probe);
1395 if !next_fits {
1396 floor = next;
1397 break;
1398 }
1399 ceil = next;
1400 step *= 2;
1401 }
1402 } else {
1403 // The boundary is above the estimate: stride up until a gain
1404 // fits, honouring the walk's 255 cap.
1405 floor = first;
1406 let mut step = 1i32;
1407 loop {
1408 let next = (floor + step).min(255);
1409 let (next_fits, _) = probe_of(next, &mut probe);
1410 if next_fits {
1411 ceil = next;
1412 break;
1413 }
1414 floor = next;
1415 if next == 255 {
1416 capped = true;
1417 break;
1418 }
1419 step *= 2;
1420 }
1421 }
1422 while ceil - floor > 1 {
1423 let mid = (floor + ceil) / 2;
1424 let (mid_fits, _) = probe_of(mid, &mut probe);
1425 if mid_fits {
1426 ceil = mid;
1427 } else {
1428 floor = mid;
1429 }
1430 }
1431 gain = if capped { 255 } else { ceil };
1432 let (_, plan) = probe_of(gain, &mut probe);
1433 ix = probe;
1434 coded = plan;
1435 }
1436 // Last resort: if even the quietest legal gain will not fit the bits we
1437 // were given, drop the top of the spectrum until it does. A granule that
1438 // overruns its budget would corrupt the reservoir for every frame after
1439 // it, which is far worse than a low-passed one.
1440 let mut limit = 576usize;
1441 while coded.cost > target_bits && limit > 4 {
1442 limit = limit * 3 / 4;
1443 for slot in ix.iter_mut().skip(limit) {
1444 *slot = 0;
1445 }
1446 coded = plan_of(&ix);
1447 }
1448 let mut noise = [0.0f32; SFB_LONG];
1449 let power = power43();
1450 // One band gain per band, not one per line: the residual ran an exp2 for
1451 // every spectral line of the granule.
1452 let mut scales = [0.0f32; SFB_LONG];
1453 for (band, slot) in scales.iter_mut().enumerate() {
1454 *slot = band_gain(gain, scalefac[band], block_type);
1455 }
1456 let residual = |i: usize, band: usize| -> f32 {
1457 let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scales[band];
1458 let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude };
1459 (xr[i] - reconstructed).powi(2)
1460 };
1461 if block_type == 2 {
1462 for (i, _) in ix.iter().enumerate().take(576) {
1463 let band = short_band(i, sample_rate);
1464 noise[band.min(SFB_LONG - 1)] += residual(i, band);
1465 }
1466 } else {
1467 let starts = long_starts(sample_rate);
1468 for band in 0..SFB_LONG {
1469 let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1]));
1470 let mut sum = 0.0f32;
1471 for i in from..to.min(576) {
1472 sum += residual(i, band);
1473 }
1474 noise[band] = sum;
1475 }
1476 }
1477 // Materialise the granule: scalefactors, then the spectrum the plan
1478 // chose, in bitstream order.
1479 recode_into(&ix, block_type, sample_rate, &mut coding);
1480 let mut bits = BitBuf::new();
1481 if block_type == 2 {
1482 // The decoder reads short scalefactors band-major, three windows at a
1483 // time; ours are one per band, so each is written three times.
1484 for (band, value) in scalefac.iter().enumerate().take(12) {
1485 let slen = if band < 6 { slen1 } else { slen2 };
1486 for _window in 0..3 {
1487 bits.push_bits(u64::from(*value), slen);
1488 }
1489 }
1490 } else {
1491 for (band, value) in scalefac.iter().enumerate() {
1492 let slen = if band < 11 { slen1 } else { slen2 };
1493 bits.push_bits(u64::from(*value), slen);
1494 }
1495 }
1496 write_spectrum(&coded, &coding, &mut bits);
1497 let granule = CodedGranule {
1498 part2_3_length: bits.bit_len(),
1499 bits,
1500 big_values: coded.big_values,
1501 global_gain: gain as u32,
1502 scalefac_compress: compress,
1503 block_type,
1504 table_select: coded.tables,
1505 region0_count: coded.region0,
1506 region1_count: coded.region1,
1507 scalefac_scale: false,
1508 count1table_select: coded.count1_select,
1509 };
1510 (granule, noise)
1511}
1512
1513fn band_gain(gain: i32, scalefac: u8, _block_type: u8) -> f32 {
1514 let base = (gain as f32 - 210.0) * 0.25;
1515 (base - 0.5 * f32::from(scalefac)).exp2()
1516}
1517
1518/// The spectrum as integers, per the decoder's requantisation read backwards.
1519fn quantise(
1520 xr: &[f32],
1521 gain: i32,
1522 scalefac: &[u8; SFB_LONG],
1523 sample_rate: u32,
1524 block_type: u8,
1525 ix: &mut [i32],
1526) {
1527 // The scalar form, kept for spans shorter than one SIMD width.
1528 let quantise_line = |xr: f32, scale: f32| -> i32 {
1529 let x = f64::from(xr.abs()) * f64::from(scale);
1530 let value = (x * x * x).sqrt().sqrt();
1531 let magnitude = (value + 0.4054).min(MAX_QUANT as f64) as i32;
1532 if xr < 0.0 { -magnitude } else { magnitude }
1533 };
1534 if block_type == 2 {
1535 // Short blocks: twelve bands, each with its own scalefactor shared by
1536 // the three windows. Without them the quantiser's noise is flat across
1537 // the spectrum, which is what made a switched granule the worst-coded
1538 // one in the stream. One band gain per band, not one per line: the
1539 // interleaved layout means a line's band search ran 576 exp2 calls
1540 // and 576 linear band searches per quantisation.
1541 let short = short_starts(sample_rate);
1542 let mut scales = [0.0f32; 13];
1543 for (band, slot) in scales.iter_mut().enumerate() {
1544 *slot = 1.0 / band_gain(gain, scalefac[band], block_type);
1545 }
1546 for band in 0..13 {
1547 let (from, to) = (
1548 usize::from(short[band]) * 3,
1549 usize::from(short[band + 1]) * 3,
1550 );
1551 let scale = scales[band];
1552 quantise_span(xr, ix, from, to.min(576), scale, &quantise_line);
1553 }
1554 return;
1555 }
1556 let starts = long_starts(sample_rate);
1557 // 22 bands, not 21: the topmost band carries no transmitted scalefactor,
1558 // but it does carry audio — zeroing it low-passes the encoder at 16 kHz.
1559 for band in 0..22 {
1560 let (from, to) = (
1561 usize::from(starts[band]),
1562 usize::from(starts[band + 1]).min(576),
1563 );
1564 let scalefac = if band < SFB_LONG { scalefac[band] } else { 0 };
1565 let scale = 1.0 / band_gain(gain, scalefac, block_type);
1566 quantise_span(xr, ix, from, to, scale, &quantise_line);
1567 }
1568}
1569
1570/// Quantises `xr[from..to]` at `scale` into `ix[from..to]`, eight lanes at a
1571/// time through `wide` — the per-line curve the scalar closure carries out
1572/// one line per call. Overflow lanes to `inf`, which the `MAX_QUANT` clamp
1573/// folds back the same way the scalar path clamps a saturated line; the
1574/// signed value truncates toward zero, exactly the sign-and-floor the scalar
1575/// form does in two steps. Levels can differ from the scalar path by one
1576/// step where the true level sits within f32 rounding of a boundary; the
1577/// decoded-quality gate exists for exactly that.
1578fn quantise_span(
1579 xr: &[f32],
1580 ix: &mut [i32],
1581 from: usize,
1582 to: usize,
1583 scale: f32,
1584 scalar: &impl Fn(f32, f32) -> i32,
1585) {
1586 let mut i = from;
1587 if to - i >= 8 {
1588 let vscale = f32x8::splat(scale);
1589 let voff = f32x8::splat(0.4054);
1590 let vmax = f32x8::splat(MAX_QUANT as f32);
1591 while i + 8 <= to {
1592 let mut block = [0.0f32; 8];
1593 block.copy_from_slice(&xr[i..i + 8]);
1594 let v = f32x8::new(block);
1595 let x = v.abs() * vscale;
1596 let value = (x * x * x).sqrt().sqrt();
1597 let magnitude = (value + voff).min(vmax);
1598 let ints = magnitude.copysign(v).trunc_int();
1599 ix[i..i + 8].copy_from_slice(&ints.to_array());
1600 i += 8;
1601 }
1602 }
1603 while i < to {
1604 ix[i] = scalar(xr[i], scale);
1605 i += 1;
1606 }
1607}
1608
1609/// The short scalefactor band a spectral line belongs to. Short-block spectra
1610/// interleave the three windows line by line, so the line index divided by
1611/// three is the frequency line the band table is indexed by.
1612fn short_band(index: usize, sample_rate: u32) -> usize {
1613 let line = index / 3;
1614 let starts = short_starts(sample_rate);
1615 (0..13)
1616 .rev()
1617 .find(|&band| line >= usize::from(starts[band]))
1618 .unwrap_or(0)
1619}
1620
1621/// The coding a spectrum gets: region split, tables, count1 boundary, and
1622/// the bit cost the rate loop judges candidate gains by.
1623#[derive(Clone, Copy, Debug)]
1624struct SpectrumPlan {
1625 cost: u32,
1626 big_values: u32,
1627 tables: [u8; 3],
1628 region0: u32,
1629 region1: u32,
1630 count1_select: bool,
1631 bounds: [usize; 3],
1632 big_end: usize,
1633 count1_end: usize,
1634}
1635
1636/// Trailing zeros, the count1 boundary, and the region split for a coded
1637/// spectrum, in bitstream order. The planner and the writer read these off
1638/// one structure so both see the same boundaries.
1639fn regions(
1640 ix: &[i32; 576],
1641 block_type: u8,
1642 sample_rate: u32,
1643) -> (u32, u32, [usize; 3], usize, usize) {
1644 // Trailing zeros are not coded at all; before them, a run of values in
1645 // -1..=1 is coded four at a time.
1646 let mut rzero = 576;
1647 while rzero > 0 && ix[rzero - 1] == 0 {
1648 rzero -= 1;
1649 }
1650 let count1_end = (rzero.div_ceil(4) * 4).min(576);
1651 let mut count1_start = count1_end;
1652 while count1_start >= 4
1653 && ix[count1_start - 4..count1_start]
1654 .iter()
1655 .all(|v| v.abs() <= 1)
1656 {
1657 count1_start -= 4;
1658 }
1659 let big_end = count1_start;
1660
1661 let starts = long_starts(sample_rate);
1662 // Region boundaries land on band edges. A granule that switches windows
1663 // does not transmit `region0_count`/`region1_count` at all — the decoder
1664 // derives them (three short bands for a short block, eight long bands
1665 // otherwise, with region 2 empty) — so the encoder has to use exactly
1666 // those, not a split of its own. Choosing differently costs no bits and
1667 // parses as different tables, which is a granule of noise wherever the
1668 // window switches. Only a normal block gets to pick.
1669 let (region0, region1, bounds) = match block_type {
1670 2 => {
1671 let first = usize::from(short_starts(sample_rate)[3]) * 3;
1672 (8u32, 12u32, [first.min(big_end), big_end, big_end])
1673 }
1674 1 | 3 => {
1675 let first = usize::from(starts[8]);
1676 (7u32, 13u32, [first.min(big_end), big_end, big_end])
1677 }
1678 _ => {
1679 // Splitting the big-value region in three roughly equal parts is
1680 // what makes the three tables specialise; searching every legal
1681 // split costs far more than it saves.
1682 let band_at = |target: usize| -> usize {
1683 (0..21)
1684 .min_by_key(|&b| usize::from(starts[b + 1]).abs_diff(target))
1685 .unwrap_or(7)
1686 };
1687 let r0 = band_at(big_end / 3).min(15);
1688 let r1 = band_at(big_end * 2 / 3).saturating_sub(r0 + 1).min(7);
1689 let a = usize::from(starts[(r0 + 1).min(21)]).min(big_end);
1690 let b = usize::from(starts[(r0 + r1 + 2).min(21)]).min(big_end);
1691 (r0 as u32, r1 as u32, [a, b.max(a), big_end])
1692 }
1693 };
1694 (region0, region1, bounds, big_end, count1_end)
1695}
1696
1697/// Chooses the region split, the tables and the count1 boundary, and prices
1698/// the spectrum. The rate loop calls this for every candidate gain; only the
1699/// configuration it keeps is ever written ([`write_spectrum`]).
1700fn plan_spectrum(ix: &[i32; 576], block_type: u8, sample_rate: u32) -> SpectrumPlan {
1701 let (region0, region1, bounds, big_end, count1_end) = regions(ix, block_type, sample_rate);
1702 let mut tables = [0u8; 3];
1703 let mut cost = 0u32;
1704 let mut from = 0usize;
1705 for (region, to) in bounds.iter().enumerate() {
1706 let to = (*to).min(big_end);
1707 if to > from {
1708 let (select, region_cost) = best_table_cost(ix, from, to);
1709 tables[region] = select;
1710 cost += region_cost;
1711 }
1712 from = to;
1713 }
1714 // count1: try both tables, keep the cheaper.
1715 let quads_cost = |select: bool| -> u32 {
1716 let mut sum = 0;
1717 let mut i = big_end;
1718 while i + 4 <= count1_end {
1719 sum += huffman::quad_bits(select, [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]]);
1720 i += 4;
1721 }
1722 sum
1723 };
1724 let count1_select = quads_cost(true) < quads_cost(false);
1725 cost += quads_cost(count1_select);
1726 SpectrumPlan {
1727 cost,
1728 big_values: (big_end / 2) as u32,
1729 tables,
1730 region0,
1731 region1,
1732 count1_select,
1733 bounds,
1734 big_end,
1735 count1_end,
1736 }
1737}
1738
1739/// Writes the coded spectrum the plan names into `out`, pairs and quadruples
1740/// in bitstream order. `ix` is the spectrum in bitstream order, the same
1741/// array the plan was computed from.
1742fn write_spectrum(plan: &SpectrumPlan, ix: &[i32; 576], out: &mut BitBuf) {
1743 let mut from = 0usize;
1744 for (region, to) in plan.bounds.iter().enumerate() {
1745 let to = (*to).min(plan.big_end);
1746 if to > from {
1747 let table = huffman::big_table(usize::from(plan.tables[region])).expect("table exists");
1748 let mut i = from;
1749 while i + 1 < to {
1750 huffman::write_pair(out, table, ix[i], ix[i + 1]);
1751 i += 2;
1752 }
1753 }
1754 from = to;
1755 }
1756 let mut i = plan.big_end;
1757 while i + 4 <= plan.count1_end {
1758 huffman::write_quad(
1759 out,
1760 plan.count1_select,
1761 [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]],
1762 );
1763 i += 4;
1764 }
1765}
1766
1767/// Tables that can code a region whose largest magnitude is `max`, cheapest
1768/// candidates first. Anything above 15 needs an escape-coded table, and the
1769/// escape tables differ only in how many linbits they spend.
1770fn candidates(max: u32) -> &'static [u8] {
1771 match max {
1772 0..=1 => &[1, 2, 3, 5, 6, 7, 8, 9],
1773 2 => &[2, 3, 5, 6, 7, 8, 9, 10],
1774 3 => &[5, 6, 7, 8, 9, 10, 11, 12],
1775 4..=5 => &[7, 8, 9, 10, 11, 12, 13, 15],
1776 6..=7 => &[10, 11, 12, 13, 15],
1777 8..=15 => &[13, 15, 16, 24],
1778 16..=16 => &[16, 17, 18, 19, 20, 21, 22, 23, 24],
1779 17..=18 => &[17, 18, 19, 20, 21, 22, 23, 24, 25],
1780 19..=30 => &[18, 19, 20, 21, 22, 23, 25, 26, 27],
1781 31..=78 => &[20, 21, 22, 23, 26, 27, 28, 29],
1782 79..=270 => &[21, 22, 23, 28, 29, 30, 31],
1783 271..=1038 => &[22, 23, 30, 31],
1784 _ => &[23, 31],
1785 }
1786}
1787
1788/// The cheapest table for one region, with its cost.
1789///
1790/// One walk over the pairs accumulates every shortlisted candidate's cost at
1791/// once; the former shape — a full `pair_bits` pass per candidate, up to nine
1792/// walks over the same pairs — was half of the encoder's remaining runtime.
1793/// A candidate any pair falls outside dies on the spot, exactly as the
1794/// per-candidate `pair_bits` propagation did, and ties keep the earlier
1795/// (nominally cheaper) candidate, as the strict less-than did.
1796fn best_table_cost(ix: &[i32], from: usize, to: usize) -> (u8, u32) {
1797 let mut max = 0u32;
1798 for &v in &ix[from..to] {
1799 max = max.max(v.unsigned_abs());
1800 }
1801 let shortlist = candidates(max);
1802 // Per-candidate state, fetched once: the table, its escape shape, the
1803 // cost of a (0, 0) pair, and a running cost. A candidate the region's
1804 // largest magnitude falls outside is dropped before the walk — exactly
1805 // what the per-pair range check did, since some pair carries `max`.
1806 let mut tables = [None; 9];
1807 let mut tmax = [0u32; 9];
1808 let mut linbits = [0u32; 9];
1809 let mut dim = [0u32; 9];
1810 let mut zero_bits = [0u32; 9];
1811 let mut feasible = [false; 9];
1812 let mut costs = [0u32; 9];
1813 let mut live = 0usize;
1814 for (slot, &select) in shortlist.iter().enumerate() {
1815 let Ok(table) = huffman::big_table(usize::from(select)) else {
1816 continue;
1817 };
1818 let cap = u32::from(table.dim) - 1;
1819 let escape = table.linbits > 0;
1820 let reach = cap + if escape { (1 << table.linbits) - 1 } else { 0 };
1821 if max > reach {
1822 continue;
1823 }
1824 tables[slot] = Some(table);
1825 tmax[slot] = cap;
1826 linbits[slot] = if escape { u32::from(table.linbits) } else { 0 };
1827 dim[slot] = u32::from(table.dim);
1828 zero_bits[slot] = u32::from(table.codes[0].0);
1829 feasible[slot] = true;
1830 live += 1;
1831 }
1832 let mut i = from;
1833 while i + 1 < to && live > 0 {
1834 let (x, y) = (ix[i].unsigned_abs(), ix[i + 1].unsigned_abs());
1835 if x == 0 && y == 0 {
1836 for slot in 0..shortlist.len() {
1837 if feasible[slot] {
1838 costs[slot] += zero_bits[slot];
1839 }
1840 }
1841 i += 2;
1842 continue;
1843 }
1844 let signs = u32::from(x != 0) + u32::from(y != 0);
1845 for slot in 0..shortlist.len() {
1846 if !feasible[slot] {
1847 continue;
1848 }
1849 let table = tables[slot].expect("feasible candidates hold a table");
1850 let (cap, lin) = (tmax[slot], linbits[slot]);
1851 let (len, _) = table.codes[(x.min(cap) * dim[slot] + y.min(cap)) as usize];
1852 if len == 0 {
1853 // A hole in the table: this candidate cannot code the pair,
1854 // so it is out for the whole region.
1855 feasible[slot] = false;
1856 live -= 1;
1857 continue;
1858 }
1859 let mut bits = u32::from(len) + signs;
1860 if lin > 0 {
1861 if x >= cap {
1862 bits += lin;
1863 }
1864 if y >= cap {
1865 bits += lin;
1866 }
1867 }
1868 costs[slot] += bits;
1869 }
1870 i += 2;
1871 }
1872 let mut best = (u32::MAX, 0u8);
1873 for (slot, &select) in shortlist.iter().enumerate() {
1874 if feasible[slot] && costs[slot] < best.0 {
1875 best = (costs[slot], select);
1876 }
1877 }
1878 if best.1 == 0 {
1879 // Nothing in the shortlist fits, which only a value above the coding
1880 // range can cause; fall back to the widest escape table.
1881 return (23, 0);
1882 }
1883 (best.1, best.0)
1884}
1885
1886/// The `scalefac_compress` index whose two lengths hold these scalefactors.
1887fn scalefac_compress(scalefac: &[u8; SFB_LONG], block_type: u8) -> (u32, u32, u32) {
1888 let bits_for = |slice: &[u8]| -> u32 {
1889 let max = slice.iter().copied().max().unwrap_or(0);
1890 (0..=4u32).find(|n| max < (1 << n)).unwrap_or(4)
1891 };
1892 // Long blocks split their bands 11/10, short blocks 6/6 per window.
1893 let (first, second, cost1, cost2) = if block_type == 2 {
1894 (&scalefac[..6], &scalefac[6..12], 18, 18)
1895 } else {
1896 (&scalefac[..11], &scalefac[11..], 11, 10)
1897 };
1898 // The table's longest pair is (4, 3), so a caller that respects
1899 // `max_scalefac` always finds an entry; the clamp is what keeps a caller
1900 // that does not from silently coding a granule the decoder cannot rebuild.
1901 let need1 = bits_for(first).min(4);
1902 let need2 = bits_for(second).min(3);
1903 let mut best = (u32::MAX, 4u32, 3u32, 15u32);
1904 for (index, (slen1, slen2)) in SLEN.iter().enumerate() {
1905 if *slen1 >= need1 && *slen2 >= need2 {
1906 let cost = slen1 * cost1 + slen2 * cost2;
1907 if cost < best.0 {
1908 best = (cost, *slen1, *slen2, index as u32);
1909 }
1910 }
1911 }
1912 (best.1, best.2, best.3)
1913}
1914
1915#[cfg(test)]
1916mod tests {
1917 use super::*;
1918
1919 /// The delay the Info tag states is the delay the pipeline has. Our own
1920 /// decoder ignores the tag, so what it hands back is the untrimmed stream:
1921 /// the content starts exactly `ENCODER_DELAY + DECODER_DELAY` samples in.
1922 /// The mask is stated in the quantiser's noise units: on white noise the
1923 /// band energy of the MDCT sits the signal-to-mask offset (6 dB, plus
1924 /// what the flatness estimate adds) above the threshold, not 2^17 away.
1925 #[test]
1926 fn masking_threshold_is_in_mdct_power_units() {
1927 let mut core = Mp3Encode::new(48000, 1, 128, None).unwrap();
1928 let mut seed = 0x2545_f491_4f6c_dd1du64;
1929 let mut noise = || {
1930 seed ^= seed << 13;
1931 seed ^= seed >> 7;
1932 seed ^= seed << 17;
1933 (seed >> 40) as f32 / 8_388_608.0 - 1.0
1934 };
1935 for _ in 0..8 {
1936 let pcm: Vec<f32> = (0..1152).map(|_| 0.25 * noise()).collect();
1937 core.encode_block(&pcm);
1938 }
1939 let granule = core.pending.last().unwrap().clone();
1940 let xr = core.mdct(0, &granule.subband, 0);
1941 let starts = long_starts(48000);
1942 let mut sum = 0.0f32;
1943 for band in 3..16 {
1944 let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1]));
1945 let energy: f32 = xr[from..to].iter().map(|v| v * v).sum();
1946 sum += 10.0 * (energy / granule.threshold[band]).log10();
1947 }
1948 let db = sum / 13.0;
1949 assert!(
1950 (6.0..=18.0).contains(&db),
1951 "signal sits {db:.1} dB over its mask"
1952 );
1953 }
1954
1955 #[test]
1956 fn encoder_delay_is_what_the_tag_says() {
1957 for (rate, channels) in [(44100u32, 1usize), (48000, 2)] {
1958 let n = 1152 * 8;
1959 let pcm: Vec<f32> = (0..n * channels)
1960 .map(|i| {
1961 let t = (i / channels) as f32;
1962 0.3 * (t * 0.11).sin() + 0.2 * (t * 0.7).cos()
1963 })
1964 .collect();
1965 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
1966 bitrate_kbps: 320,
1967 vbr_quality: None,
1968 });
1969 encoder
1970 .push_pcm_f32(&pcm, channels as u16, rate)
1971 .expect("encoder accepts this shape");
1972 encoder.finish();
1973 let mut bytes = Vec::new();
1974 while let Ok(frame) = encoder.next_packet() {
1975 bytes.extend_from_slice(&frame);
1976 }
1977 let mut reader = crate::Mp3Reader::new();
1978 reader.push(&bytes);
1979 let mut out: Vec<f32> = Vec::new();
1980 for frame in reader.decode_all() {
1981 out.extend_from_slice(&frame.samples);
1982 }
1983 let mut best = (f64::MIN, 0usize);
1984 let window = 4096 * channels;
1985 let mut lag = 0;
1986 while lag + window * 2 < out.len() {
1987 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
1988 for i in 0..window {
1989 let (x, y) = (out[lag + window + i] as f64, pcm[window + i] as f64);
1990 ab += x * y;
1991 aa += x * x;
1992 bb += y * y;
1993 }
1994 let corr = ab / (aa * bb).sqrt().max(1e-30);
1995 if corr > best.0 {
1996 best = (corr, lag / channels);
1997 }
1998 lag += channels;
1999 }
2000 assert!(best.0 > 0.999, "round trip correlation {:.6}", best.0);
2001 assert_eq!(
2002 best.1 as u32,
2003 ENCODER_DELAY + DECODER_DELAY,
2004 "measured lag at {rate} Hz, {channels} channels"
2005 );
2006 }
2007 }
2008
2009 /// The whole window sequence — normal, start, short, stop, normal — has to
2010 /// reconstruct, not just the long blocks. This runs the transform pair
2011 /// directly, so a failure points at the windows rather than at the
2012 /// quantiser.
2013 #[test]
2014 fn window_sequence_reconstructs() {
2015 use crate::filterbank::Imdct;
2016 let imdct = Imdct::default();
2017 let types = [0u8, 0, 1, 2, 3, 0, 0];
2018 let signal: Vec<f32> = (0..18 * (types.len() + 2))
2019 .map(|i| ((i as f32) * 0.37).sin() + 0.3 * ((i as f32) * 1.7).cos())
2020 .collect();
2021 let mut output = vec![0.0f32; signal.len()];
2022 let mut overlap = [0.0f32; 18];
2023 for (granule, block_type) in types.iter().enumerate() {
2024 let mut window = [0.0f32; 36];
2025 for (i, slot) in window.iter_mut().enumerate() {
2026 let index = granule * 18 + i;
2027 if index < signal.len() {
2028 *slot = signal[index];
2029 }
2030 }
2031 let mut spectrum = [0.0f32; 18];
2032 if *block_type == 2 {
2033 mdct_short(&window, &mut spectrum);
2034 } else {
2035 mdct_long(&window, *block_type, &mut spectrum);
2036 }
2037 let mut block = [0.0f32; 36];
2038 if *block_type == 2 {
2039 imdct.short(&spectrum, &mut block);
2040 } else {
2041 imdct.long(&spectrum, *block_type, &mut block);
2042 }
2043 for t in 0..18 {
2044 let index = granule * 18 + t;
2045 if index < output.len() {
2046 output[index] = block[t] + overlap[t];
2047 }
2048 }
2049 overlap.copy_from_slice(&block[18..]);
2050 }
2051 // The first granule has no predecessor and the last no successor.
2052 for (granule, block_type) in types.iter().enumerate().take(types.len() - 1).skip(1) {
2053 let mut error = 0.0f64;
2054 let mut energy = 0.0f64;
2055 for i in granule * 18..(granule + 1) * 18 {
2056 error += (output[i] - signal[i]).powi(2) as f64;
2057 energy += (signal[i] * signal[i]) as f64;
2058 }
2059 let snr = 10.0 * (energy / error.max(1e-30)).log10();
2060 assert!(
2061 snr > 60.0,
2062 "granule {granule} (block type {block_type}) reconstructs at {snr:.1} dB"
2063 );
2064 }
2065 }
2066
2067 /// A granule that switches to short blocks must come back as itself.
2068 ///
2069 /// Short blocks are coded band-major with the three windows interleaved on
2070 /// every line, which is not the order the transform produces them in. Miss
2071 /// that permutation and the bit count still lands exactly on
2072 /// `part2_3_length`, every fixture still decodes, and only the switched
2073 /// granules come back as noise — so this test drives an attack that forces
2074 /// the switch and checks the granules around it.
2075 #[test]
2076 fn switched_granules_reconstruct() {
2077 let rate = 44100u32;
2078 let n = 1152 * 12;
2079 let attack = 1152 * 6;
2080 let pcm: Vec<f32> = (0..n)
2081 .map(|i| {
2082 let t = i as f32;
2083 let tone = 0.5 * (t * 0.21).sin() + 0.3 * (t * 0.93).cos();
2084 // Six frames of near-silence, then full level: an attack no
2085 // block-switching encoder can ignore.
2086 if i < attack { tone * 0.002 } else { tone }
2087 })
2088 .collect();
2089 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
2090 bitrate_kbps: 320,
2091 vbr_quality: None,
2092 });
2093 encoder
2094 .push_pcm_f32(&pcm, 1, rate)
2095 .expect("encoder accepts this");
2096 encoder.finish();
2097 let mut bytes = Vec::new();
2098 while let Ok(frame) = encoder.next_packet() {
2099 bytes.extend_from_slice(&frame);
2100 }
2101 let mut reader = crate::Mp3Reader::new();
2102 reader.push(&bytes);
2103 let mut out: Vec<f32> = Vec::new();
2104 for frame in reader.decode_all() {
2105 out.extend_from_slice(&frame.samples);
2106 }
2107 let lag = (ENCODER_DELAY + DECODER_DELAY) as usize;
2108 // Every granule from the attack onward, where the switch happens.
2109 let mut worst = (1.0f64, 0usize);
2110 let mut granule = attack / 576;
2111 while (granule + 1) * 576 + lag <= out.len() && (granule + 1) * 576 <= pcm.len() {
2112 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
2113 for i in granule * 576..(granule + 1) * 576 {
2114 let (x, y) = (out[i + lag] as f64, pcm[i] as f64);
2115 ab += x * y;
2116 aa += x * x;
2117 bb += y * y;
2118 }
2119 let corr = ab / (aa * bb).sqrt().max(1e-30);
2120 if corr < worst.0 {
2121 worst = (corr, granule);
2122 }
2123 granule += 1;
2124 }
2125 assert!(
2126 worst.0 > 0.99,
2127 "granule {} reconstructs at {:.4}",
2128 worst.1,
2129 worst.0
2130 );
2131 }
2132
2133 #[test]
2134 fn bitrates_snap_to_legal_values() {
2135 assert_eq!(snap_bitrate(Version::Mpeg1, 128), 128);
2136 assert_eq!(snap_bitrate(Version::Mpeg1, 130), 128);
2137 assert_eq!(snap_bitrate(Version::Mpeg1, 1000), 320);
2138 assert_eq!(snap_bitrate(Version::Mpeg2, 128), 128);
2139 assert_eq!(snap_bitrate(Version::Mpeg2, 320), 160);
2140 }
2141
2142 #[test]
2143 fn unsupported_rates_are_refused_by_name() {
2144 let err = Mp3Encode::new(96000, 2, 128, None).unwrap_err();
2145 assert!(format!("{err}").contains("96000 Hz"), "{err}");
2146 }
2147
2148 /// The encoder's whole analysis chain against the decoder's whole
2149 /// synthesis chain, quantisation left out: what comes back is what went
2150 /// in, delayed by the filterbank.
2151 #[test]
2152 fn analysis_chain_round_trips_through_the_decoder() {
2153 use crate::filterbank::{Imdct, Synthesis, alias_reduce};
2154 let imdct = Imdct::default();
2155 let mut analysis = Analysis::default();
2156 let mut synthesis = Synthesis::default();
2157 let n = 32 * 32 * 24;
2158 let input: Vec<f32> = (0..n)
2159 .map(|i| {
2160 let t = i as f32;
2161 0.4 * (t * 0.05).sin() + 0.2 * (t * 0.31).cos()
2162 })
2163 .collect();
2164 let mut slots: Vec<[f32; 32]> = Vec::new();
2165 for chunk in input.chunks(32) {
2166 if let Some(slot) = analysis.push(chunk) {
2167 slots.push(slot);
2168 }
2169 }
2170 let granules = slots.len() / 18;
2171 let mut history = [[0.0f32; 32]; 18];
2172 let mut overlap = [[0.0f32; 18]; 32];
2173 let mut output: Vec<f32> = Vec::new();
2174 for g in 0..granules {
2175 let granule = &slots[g * 18..g * 18 + 18];
2176 let mut xr = vec![0.0f32; 576];
2177 for sb in 0..32 {
2178 let mut window = [0.0f32; 36];
2179 for t in 0..18 {
2180 let sign = if sb % 2 == 1 && t % 2 == 1 { -1.0 } else { 1.0 };
2181 window[t] = history[t][sb] * sign;
2182 window[18 + t] = granule[t][sb] * sign;
2183 }
2184 mdct_long(&window, 0, &mut xr[sb * 18..sb * 18 + 18]);
2185 }
2186 alias_expand(&mut xr, 32);
2187 history.copy_from_slice(granule);
2188 // decoder side
2189 alias_reduce(&mut xr, 32);
2190 let mut out_slots = [[0.0f32; 32]; 18];
2191 let mut block = [0.0f32; 36];
2192 for sb in 0..32 {
2193 imdct.long(&xr[sb * 18..sb * 18 + 18], 0, &mut block);
2194 for t in 0..18 {
2195 let mut sample = block[t] + overlap[sb][t];
2196 overlap[sb][t] = block[18 + t];
2197 if sb % 2 == 1 && t % 2 == 1 {
2198 sample = -sample;
2199 }
2200 out_slots[t][sb] = sample;
2201 }
2202 }
2203 let mut pcm = [0.0f32; 32];
2204 for slot in &out_slots {
2205 synthesis.slot(slot, &mut pcm);
2206 output.extend_from_slice(&pcm);
2207 }
2208 }
2209 // Find the delay, then check the reconstruction is faithful. The
2210 // comparison starts past the filterbank's ramp-up, which is silence
2211 // sliding into the window rather than anything the transform got wrong.
2212 let (from, len) = (4096usize, 8192usize);
2213 let mut best = (f64::MIN, 0usize);
2214 for delay in 0..output.len().min(2048) {
2215 if delay + from + len > output.len() || from + len > input.len() {
2216 break;
2217 }
2218 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
2219 for i in from..from + len {
2220 let (x, y) = (output[delay + i] as f64, input[i] as f64);
2221 ab += x * y;
2222 aa += x * x;
2223 bb += y * y;
2224 }
2225 let corr = ab / (aa * bb).sqrt().max(1e-30);
2226 if corr > best.0 {
2227 best = (corr, delay);
2228 }
2229 }
2230 assert!(
2231 best.0 > 0.99999,
2232 "analysis/synthesis correlation {:.6} at delay {}",
2233 best.0,
2234 best.1
2235 );
2236 }
2237
2238 /// The forward MDCT and the decoder's inverse are a reconstructing pair:
2239 /// two overlapped granules of a signal come back as themselves.
2240 #[test]
2241 fn mdct_round_trips_under_overlap_add() {
2242 use crate::filterbank::Imdct;
2243 let imdct = Imdct::default();
2244 let signal: Vec<f32> = (0..72)
2245 .map(|i| ((i as f32) * 0.37).sin() + 0.3 * ((i as f32) * 1.1).cos())
2246 .collect();
2247 let mut output = vec![0.0f32; 72];
2248 let mut previous = [0.0f32; 18];
2249 for granule in 0..3 {
2250 let mut input = [0.0f32; 36];
2251 for (i, slot) in input.iter_mut().enumerate() {
2252 let index = granule * 18 + i;
2253 if index < signal.len() {
2254 *slot = signal[index];
2255 }
2256 }
2257 let mut spectrum = [0.0f32; 18];
2258 mdct_long(&input, 0, &mut spectrum);
2259 let mut block = [0.0f32; 36];
2260 imdct.long(&spectrum, 0, &mut block);
2261 for t in 0..18 {
2262 let index = granule * 18 + t;
2263 if index < output.len() {
2264 output[index] = block[t] + previous[t];
2265 }
2266 }
2267 previous.copy_from_slice(&block[18..]);
2268 }
2269 // The first granule has no predecessor, so compare from the second.
2270 let mut worst = 0.0f32;
2271 for i in 18..54 {
2272 worst = worst.max((output[i] - signal[i]).abs());
2273 }
2274 println!("mdct round trip worst absolute error {worst:e}");
2275 for i in 18..54 {
2276 assert!(
2277 (output[i] - signal[i]).abs() < 1e-5,
2278 "sample {i}: {} vs {}",
2279 output[i],
2280 signal[i]
2281 );
2282 }
2283 }
2284}