forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust381.2 MiBe18142dTahinli5 hours ago4543 commits

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