forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

encode.rs2331 lines, 94.9 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 /// 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: 3,
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 let mut exit = ("cap", 19usize);
1205 for round in 0..20 {
1206 let (granule, noise) = code_with(xr, block_type, target_bits, &scalefac, sample_rate);
1207 let ratios: Vec<f64> = (0..bands)
1208 .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30))
1209 .collect();
1210 let score: f64 = ratios.iter().sum();
1211 let mut order: Vec<usize> = (0..bands)
1212 .filter(|&b| scalefac[b] < max_scalefac(b, block_type))
1213 .collect();
1214 order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a]));
1215 let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect();
1216 let spent = granule.part2_3_length;
1217 if best.as_ref().is_none_or(|(_, s, _)| score < *s) {
1218 best = Some((granule, score, bands));
1219 }
1220 if score <= 0.0 {
1221 exit = ("mask", round);
1222 break; // every band is already exactly at the mask; nothing left to buy
1223 }
1224 // Where to stop amplifying, as a fraction of the frame's budget. Swept
1225 // against both gate metrics on all fourteen library rows: 85% beats
1226 // the 95% this shipped with everywhere, and 100% is a disaster --
1227 // reelm loses 0.0048 correlation, because amplifying a band once the
1228 // budget is gone only makes the rate loop coarsen every other band to
1229 // pay for it. Below 70% the test stops binding, since the first round
1230 // already spends more than that.
1231 //
1232 // LAME's own shape -- drop the budget break, let the distortion test
1233 // drive, since `code_with` fits `target_bits` at every round anyway --
1234 // was built and measured here (2026-09-06). It makes the loop live
1235 // (10440 granules of 36758 reach the 20-round cap against 3 before) and
1236 // loses on both gate metrics: reelo at 128 kbit/s goes 0.99917 ->
1237 // 0.99787 correlation, from +0.00062 ahead of libmp3lame to -0.00068
1238 // behind it, and its worst 20 ms window from -15.3 to -12.4 dB, at
1239 // roughly five times the encode time. The gate measures waveform error,
1240 // and a budget-filling rate loop over flat scalefactors is already near
1241 // the MSE optimum, so perceptual redistribution can only trade away
1242 // what this gate scores. Don't re-run it: change the metric first.
1243 if spent * 100 > target_bits * 85 {
1244 exit = ("budget", round);
1245 break; // the budget is spent; amplifying now only coarsens
1246 }
1247 // Bands over their mask get the bits first, worst three per round so
1248 // the rate loop re-fits `global_gain` around a small step; once every
1249 // band is under its mask the spare bits go to the noisiest ones.
1250 // corner-cut: the ISO outer loop keeps amplifying over-mask bands past
1251 // the budget and lets the rate loop coarsen the rest; measured here it
1252 // costs 12-36% RMS against the source (mp3src-stereo-48000, 128/192)
1253 // for a model this coarse, and the encode_matrix bar is an RMS metric.
1254 // Upgrade path: a finer model (ISO spreading function, tonality from
1255 // phase prediction) before trusting the mask over the budget.
1256 let chosen: Vec<usize> = if over.is_empty() { order } else { over }
1257 .into_iter()
1258 .take(3)
1259 .collect();
1260 if chosen.is_empty() {
1261 exit = ("saturated", round);
1262 break;
1263 }
1264 for band in chosen {
1265 scalefac[band] += 1;
1266 }
1267 }
1268 census(exit);
1269 let (granule, score, bands) = best.expect("at least one round runs");
1270 (granule, score / bands as f64)
1271}
1272
1273/// Exit-reason census for the distortion loop: with `EC_MP3_LOOP_TRACE` set,
1274/// one `mp3loop <reason> <round>` line per granule on stderr, so a sweep can be
1275/// counted with `sort | uniq -c`. The loop's shape is the encoder's open
1276/// question; without this the only evidence it ever iterates is indirect.
1277fn census(exit: (&str, usize)) {
1278 static ON: std::sync::OnceLock<bool> = std::sync::OnceLock::new();
1279 if *ON.get_or_init(|| std::env::var_os("EC_MP3_LOOP_TRACE").is_some()) {
1280 eprintln!("mp3loop {} {}", exit.0, exit.1);
1281 }
1282}
1283
1284/// Puts a spectrum into bitstream order in `out`.
1285///
1286/// A short granule is coded band by band, window by window, line by line,
1287/// while the spectrum the transform produces interleaves the three windows on
1288/// every line — the decoder's reorder step. The encoder has to undo it before
1289/// Huffman coding; writing spectral order instead costs exactly the same
1290/// number of bits, lands exactly on `part2_3_length`, and hands the decoder a
1291/// permuted granule, which comes back as noise. A long block is already in
1292/// order and is copied as is.
1293fn recode_into(spectral: &[i32; 576], block_type: u8, sample_rate: u32, out: &mut [i32; 576]) {
1294 if block_type != 2 {
1295 *out = *spectral;
1296 return;
1297 }
1298 let widths = short_widths(sample_rate);
1299 let starts = short_starts(sample_rate);
1300 let mut position = 0usize;
1301 for sfb in 0..13 {
1302 let (width, start) = (usize::from(widths[sfb]), usize::from(starts[sfb]));
1303 for window in 0..3 {
1304 for line in 0..width {
1305 out[position] = spectral[(start + line) * 3 + window];
1306 position += 1;
1307 }
1308 }
1309 }
1310 for slot in out.iter_mut().skip(position) {
1311 *slot = 0;
1312 }
1313}
1314
1315/// The largest scalefactor a band can actually carry.
1316///
1317/// `scalefac_compress` names two lengths, and the second partition's is at most
1318/// three bits — so a band above the split cannot hold more than 7 however much
1319/// the distortion loop would like to amplify it. Ignoring that ceiling is not a
1320/// rounding error: the quantiser uses the value it wanted, no length can encode
1321/// it, and the decoder reconstructs the band with a scalefactor of zero, which
1322/// turns the granule into noise.
1323fn max_scalefac(band: usize, block_type: u8) -> u8 {
1324 let split = if block_type == 2 { 6 } else { 11 };
1325 if band < split { 15 } else { 7 }
1326}
1327
1328/// The masking model works in long bands; a short block's twelve bands are
1329/// read off it at the same frequencies, so one model serves both.
1330fn band_thresholds(threshold: &[f32], block_type: u8, sample_rate: u32) -> Vec<f32> {
1331 if block_type != 2 {
1332 return threshold.to_vec();
1333 }
1334 let long = long_starts(sample_rate);
1335 let short = short_starts(sample_rate);
1336 (0..12)
1337 .map(|band| {
1338 // A short band's lines sit at three times its index in the spectrum.
1339 let line = usize::from(short[band]) * 3;
1340 let long_band = (0..SFB_LONG)
1341 .rev()
1342 .find(|&b| line >= usize::from(long[b]))
1343 .unwrap_or(0);
1344 // Three windows share the band, so each carries a third of it.
1345 threshold[long_band] / 3.0
1346 })
1347 .collect()
1348}
1349
1350/// Quantises with a fixed scalefactor set, running the rate loop on
1351/// `global_gain`, and reports the noise each band ends up with.
1352///
1353/// The rate loop judges every candidate gain by Huffman cost alone
1354/// ([`plan_spectrum`]); the granule's bits are materialised exactly once,
1355/// for the configuration the loop keeps ([`write_spectrum`]). Writing the
1356/// bits per round — and re-expanding them into a `Vec<bool>` to hand them
1357/// to the frame writer — was the largest single cost in the encoder's
1358/// profile, and said nothing the cost pass had not already said.
1359fn code_with(
1360 xr: &[f32],
1361 block_type: u8,
1362 budget_bits: u32,
1363 scalefac: &[u8; SFB_LONG],
1364 sample_rate: u32,
1365) -> (CodedGranule, [f32; SFB_LONG]) {
1366 let (slen1, slen2, compress) = scalefac_compress(scalefac, block_type, sample_rate);
1367 // The scalefactors come out of the same budget as the spectrum does. A
1368 // short block transmits six bands of each length, once per window.
1369 let scalefac_bits = if block_type == 2 {
1370 (slen1 + slen2) * 18
1371 } else {
1372 slen1 * 11 + slen2 * 10
1373 };
1374 let target_bits = budget_bits.saturating_sub(scalefac_bits);
1375 let peak = xr.iter().fold(0.0f32, |acc, v| acc.max(v.abs()));
1376 // A starting gain that puts the loudest line near the top of the coded
1377 // range: |xr| / 2^((g-210)/4) raised to 3/4 should land around 8000.
1378 let start = if peak > 1e-20 {
1379 (210.0 + 4.0 * (peak.log2() - 13.0 / 0.75)).round() as i32
1380 } else {
1381 210
1382 };
1383 let mut gain = start.clamp(0, 255);
1384 let mut ix = [0i32; 576];
1385 let mut coding = [0i32; 576];
1386 // A line that saturates the coding range is not "cheap", it is clipped;
1387 // the gain search below reads saturation as "does not fit".
1388 let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191);
1389 let mut plan_of = |ix: &[i32; 576]| -> SpectrumPlan {
1390 recode_into(ix, block_type, sample_rate, &mut coding);
1391 plan_spectrum(&coding, block_type, sample_rate)
1392 };
1393 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
1394 let mut coded = plan_of(&ix);
1395 if peak <= 1e-20 {
1396 // Below the smallest representable level: every line quantises to
1397 // zero at any gain (the quantiser's scale multiplies zero either
1398 // way), so the descending-gain search below — which steps one gain
1399 // unit at a time — would walk all 210 units from 210 to 0 finding
1400 // nothing changes, recoding an all-zero spectrum at every step. Skip
1401 // straight to the quietest legal gain; `coded` above is already the
1402 // right answer, because an all-zero spectrum's bit cost does not
1403 // depend on gain.
1404 gain = 0;
1405 } else {
1406 // The rate loop wants the smallest gain whose granule fits the
1407 // budget without clipping. A higher gain shrinks every quantised
1408 // line, and a smaller spectrum costs no more to code, so "fits" is
1409 // monotone in the gain. This shipped as a one-step-at-a-time walk
1410 // from the start estimate and paid ~31 quantise-plus-plan
1411 // evaluations per granule; now the start estimate seeds a geometric
1412 // straddle (doubling steps, so a boundary `d` gains away costs
1413 // about 2·log2 d probes instead of d) followed by a bisection of
1414 // the bracket. The walk's two hard stops stay: gain 255 stands even
1415 // when it does not fit (the low-pass loop below trims the
1416 // spectrum), and gain 0 is the quietest legal gain.
1417 let mut probe_of = |g: i32, out: &mut [i32; 576]| -> (bool, SpectrumPlan) {
1418 quantise(xr, g, scalefac, sample_rate, block_type, out);
1419 let plan = plan_of(out);
1420 (plan.cost <= target_bits && !saturated(out), plan)
1421 };
1422 let mut probe = [0i32; 576];
1423 // `floor` is the largest gain known to miss, `ceil` the smallest
1424 // known to fit; −1 stands for "even 0 misses would not matter", the
1425 // gain-0 floor.
1426 let mut floor = -1i32;
1427 let mut ceil = 255i32;
1428 let mut capped = false;
1429 let first = start.clamp(0, 255);
1430 let (fits, _) = probe_of(first, &mut probe);
1431 if fits {
1432 // The boundary is at or below the estimate: stride down until a
1433 // gain misses.
1434 ceil = first;
1435 let mut step = 1i32;
1436 while ceil > 0 {
1437 let next = (ceil - step).max(0);
1438 let (next_fits, _) = probe_of(next, &mut probe);
1439 if !next_fits {
1440 floor = next;
1441 break;
1442 }
1443 ceil = next;
1444 step *= 2;
1445 }
1446 } else {
1447 // The boundary is above the estimate: stride up until a gain
1448 // fits, honouring the walk's 255 cap.
1449 floor = first;
1450 let mut step = 1i32;
1451 loop {
1452 let next = (floor + step).min(255);
1453 let (next_fits, _) = probe_of(next, &mut probe);
1454 if next_fits {
1455 ceil = next;
1456 break;
1457 }
1458 floor = next;
1459 if next == 255 {
1460 capped = true;
1461 break;
1462 }
1463 step *= 2;
1464 }
1465 }
1466 while ceil - floor > 1 {
1467 let mid = (floor + ceil) / 2;
1468 let (mid_fits, _) = probe_of(mid, &mut probe);
1469 if mid_fits {
1470 ceil = mid;
1471 } else {
1472 floor = mid;
1473 }
1474 }
1475 gain = if capped { 255 } else { ceil };
1476 let (_, plan) = probe_of(gain, &mut probe);
1477 ix = probe;
1478 coded = plan;
1479 }
1480 // Last resort: if even the quietest legal gain will not fit the bits we
1481 // were given, drop the top of the spectrum until it does. A granule that
1482 // overruns its budget would corrupt the reservoir for every frame after
1483 // it, which is far worse than a low-passed one.
1484 let mut limit = 576usize;
1485 while coded.cost > target_bits && limit > 4 {
1486 limit = limit * 3 / 4;
1487 for slot in ix.iter_mut().skip(limit) {
1488 *slot = 0;
1489 }
1490 coded = plan_of(&ix);
1491 }
1492 let mut noise = [0.0f32; SFB_LONG];
1493 let power = power43();
1494 // One band gain per band, not one per line: the residual ran an exp2 for
1495 // every spectral line of the granule.
1496 let mut scales = [0.0f32; SFB_LONG];
1497 for (band, slot) in scales.iter_mut().enumerate() {
1498 *slot = band_gain(gain, scalefac[band], block_type);
1499 }
1500 let residual = |i: usize, band: usize| -> f32 {
1501 let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scales[band];
1502 let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude };
1503 (xr[i] - reconstructed).powi(2)
1504 };
1505 if block_type == 2 {
1506 for (i, _) in ix.iter().enumerate().take(576) {
1507 let band = short_band(i, sample_rate);
1508 noise[band.min(SFB_LONG - 1)] += residual(i, band);
1509 }
1510 } else {
1511 let starts = long_starts(sample_rate);
1512 for band in 0..SFB_LONG {
1513 let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1]));
1514 let mut sum = 0.0f32;
1515 for i in from..to.min(576) {
1516 sum += residual(i, band);
1517 }
1518 noise[band] = sum;
1519 }
1520 }
1521 // Materialise the granule: scalefactors, then the spectrum the plan
1522 // chose, in bitstream order.
1523 recode_into(&ix, block_type, sample_rate, &mut coding);
1524 let mut bits = BitBuf::new();
1525 if block_type == 2 {
1526 // The decoder reads short scalefactors band-major, three windows at a
1527 // time; ours are one per band, so each is written three times.
1528 for (band, value) in scalefac.iter().enumerate().take(12) {
1529 let slen = if band < 6 { slen1 } else { slen2 };
1530 for _window in 0..3 {
1531 bits.push_bits(u64::from(*value), slen);
1532 }
1533 }
1534 } else {
1535 for (band, value) in scalefac.iter().enumerate() {
1536 let slen = if band < 11 { slen1 } else { slen2 };
1537 bits.push_bits(u64::from(*value), slen);
1538 }
1539 }
1540 write_spectrum(&coded, &coding, &mut bits);
1541 let granule = CodedGranule {
1542 part2_3_length: bits.bit_len(),
1543 bits,
1544 big_values: coded.big_values,
1545 global_gain: gain as u32,
1546 scalefac_compress: compress,
1547 block_type,
1548 table_select: coded.tables,
1549 region0_count: coded.region0,
1550 region1_count: coded.region1,
1551 scalefac_scale: false,
1552 count1table_select: coded.count1_select,
1553 };
1554 (granule, noise)
1555}
1556
1557fn band_gain(gain: i32, scalefac: u8, _block_type: u8) -> f32 {
1558 let base = (gain as f32 - 210.0) * 0.25;
1559 (base - 0.5 * f32::from(scalefac)).exp2()
1560}
1561
1562/// The spectrum as integers, per the decoder's requantisation read backwards.
1563fn quantise(
1564 xr: &[f32],
1565 gain: i32,
1566 scalefac: &[u8; SFB_LONG],
1567 sample_rate: u32,
1568 block_type: u8,
1569 ix: &mut [i32],
1570) {
1571 // The scalar form, kept for spans shorter than one SIMD width.
1572 let quantise_line = |xr: f32, scale: f32| -> i32 {
1573 let x = f64::from(xr.abs()) * f64::from(scale);
1574 let value = (x * x * x).sqrt().sqrt();
1575 let magnitude = (value + 0.4054).min(MAX_QUANT as f64) as i32;
1576 if xr < 0.0 { -magnitude } else { magnitude }
1577 };
1578 if block_type == 2 {
1579 // Short blocks: twelve bands, each with its own scalefactor shared by
1580 // the three windows. Without them the quantiser's noise is flat across
1581 // the spectrum, which is what made a switched granule the worst-coded
1582 // one in the stream. One band gain per band, not one per line: the
1583 // interleaved layout means a line's band search ran 576 exp2 calls
1584 // and 576 linear band searches per quantisation.
1585 let short = short_starts(sample_rate);
1586 let mut scales = [0.0f32; 13];
1587 for (band, slot) in scales.iter_mut().enumerate() {
1588 *slot = 1.0 / band_gain(gain, scalefac[band], block_type);
1589 }
1590 for band in 0..13 {
1591 let (from, to) = (
1592 usize::from(short[band]) * 3,
1593 usize::from(short[band + 1]) * 3,
1594 );
1595 let scale = scales[band];
1596 quantise_span(xr, ix, from, to.min(576), scale, &quantise_line);
1597 }
1598 return;
1599 }
1600 let starts = long_starts(sample_rate);
1601 // 22 bands, not 21: the topmost band carries no transmitted scalefactor,
1602 // but it does carry audio — zeroing it low-passes the encoder at 16 kHz.
1603 for band in 0..22 {
1604 let (from, to) = (
1605 usize::from(starts[band]),
1606 usize::from(starts[band + 1]).min(576),
1607 );
1608 let scalefac = if band < SFB_LONG { scalefac[band] } else { 0 };
1609 let scale = 1.0 / band_gain(gain, scalefac, block_type);
1610 quantise_span(xr, ix, from, to, scale, &quantise_line);
1611 }
1612}
1613
1614/// Quantises `xr[from..to]` at `scale` into `ix[from..to]`, eight lanes at a
1615/// time through `wide` — the per-line curve the scalar closure carries out
1616/// one line per call. Overflow lanes to `inf`, which the `MAX_QUANT` clamp
1617/// folds back the same way the scalar path clamps a saturated line; the
1618/// signed value truncates toward zero, exactly the sign-and-floor the scalar
1619/// form does in two steps. Levels can differ from the scalar path by one
1620/// step where the true level sits within f32 rounding of a boundary; the
1621/// decoded-quality gate exists for exactly that.
1622fn quantise_span(
1623 xr: &[f32],
1624 ix: &mut [i32],
1625 from: usize,
1626 to: usize,
1627 scale: f32,
1628 scalar: &impl Fn(f32, f32) -> i32,
1629) {
1630 let mut i = from;
1631 if to - i >= 8 {
1632 let vscale = f32x8::splat(scale);
1633 let voff = f32x8::splat(0.4054);
1634 let vmax = f32x8::splat(MAX_QUANT as f32);
1635 while i + 8 <= to {
1636 let mut block = [0.0f32; 8];
1637 block.copy_from_slice(&xr[i..i + 8]);
1638 let v = f32x8::new(block);
1639 let x = v.abs() * vscale;
1640 let value = (x * x * x).sqrt().sqrt();
1641 let magnitude = (value + voff).min(vmax);
1642 let ints = magnitude.copysign(v).trunc_int();
1643 ix[i..i + 8].copy_from_slice(&ints.to_array());
1644 i += 8;
1645 }
1646 }
1647 while i < to {
1648 ix[i] = scalar(xr[i], scale);
1649 i += 1;
1650 }
1651}
1652
1653/// The short scalefactor band a spectral line belongs to. Short-block spectra
1654/// interleave the three windows line by line, so the line index divided by
1655/// three is the frequency line the band table is indexed by.
1656fn short_band(index: usize, sample_rate: u32) -> usize {
1657 let line = index / 3;
1658 let starts = short_starts(sample_rate);
1659 (0..13)
1660 .rev()
1661 .find(|&band| line >= usize::from(starts[band]))
1662 .unwrap_or(0)
1663}
1664
1665/// The coding a spectrum gets: region split, tables, count1 boundary, and
1666/// the bit cost the rate loop judges candidate gains by.
1667#[derive(Clone, Copy, Debug)]
1668struct SpectrumPlan {
1669 cost: u32,
1670 big_values: u32,
1671 tables: [u8; 3],
1672 region0: u32,
1673 region1: u32,
1674 count1_select: bool,
1675 bounds: [usize; 3],
1676 big_end: usize,
1677 count1_end: usize,
1678}
1679
1680/// Trailing zeros, the count1 boundary, and the region split for a coded
1681/// spectrum, in bitstream order. The planner and the writer read these off
1682/// one structure so both see the same boundaries.
1683fn regions(
1684 ix: &[i32; 576],
1685 block_type: u8,
1686 sample_rate: u32,
1687) -> (u32, u32, [usize; 3], usize, usize) {
1688 // Trailing zeros are not coded at all; before them, a run of values in
1689 // -1..=1 is coded four at a time.
1690 let mut rzero = 576;
1691 while rzero > 0 && ix[rzero - 1] == 0 {
1692 rzero -= 1;
1693 }
1694 let count1_end = (rzero.div_ceil(4) * 4).min(576);
1695 let mut count1_start = count1_end;
1696 while count1_start >= 4
1697 && ix[count1_start - 4..count1_start]
1698 .iter()
1699 .all(|v| v.abs() <= 1)
1700 {
1701 count1_start -= 4;
1702 }
1703 let big_end = count1_start;
1704
1705 let starts = long_starts(sample_rate);
1706 // Region boundaries land on band edges. A granule that switches windows
1707 // does not transmit `region0_count`/`region1_count` at all — the decoder
1708 // derives them (three short bands for a short block, eight long bands
1709 // otherwise, with region 2 empty) — so the encoder has to use exactly
1710 // those, not a split of its own. Choosing differently costs no bits and
1711 // parses as different tables, which is a granule of noise wherever the
1712 // window switches. Only a normal block gets to pick.
1713 let (region0, region1, bounds) = match block_type {
1714 2 => {
1715 let first = usize::from(short_starts(sample_rate)[3]) * 3;
1716 (8u32, 12u32, [first.min(big_end), big_end, big_end])
1717 }
1718 1 | 3 => {
1719 let first = usize::from(starts[8]);
1720 (7u32, 13u32, [first.min(big_end), big_end, big_end])
1721 }
1722 _ => {
1723 // Splitting the big-value region in three roughly equal parts is
1724 // what makes the three tables specialise; searching every legal
1725 // split costs far more than it saves.
1726 let band_at = |target: usize| -> usize {
1727 (0..21)
1728 .min_by_key(|&b| usize::from(starts[b + 1]).abs_diff(target))
1729 .unwrap_or(7)
1730 };
1731 let r0 = band_at(big_end / 3).min(15);
1732 let r1 = band_at(big_end * 2 / 3).saturating_sub(r0 + 1).min(7);
1733 let a = usize::from(starts[(r0 + 1).min(21)]).min(big_end);
1734 let b = usize::from(starts[(r0 + r1 + 2).min(21)]).min(big_end);
1735 (r0 as u32, r1 as u32, [a, b.max(a), big_end])
1736 }
1737 };
1738 (region0, region1, bounds, big_end, count1_end)
1739}
1740
1741/// Chooses the region split, the tables and the count1 boundary, and prices
1742/// the spectrum. The rate loop calls this for every candidate gain; only the
1743/// configuration it keeps is ever written ([`write_spectrum`]).
1744fn plan_spectrum(ix: &[i32; 576], block_type: u8, sample_rate: u32) -> SpectrumPlan {
1745 let (region0, region1, bounds, big_end, count1_end) = regions(ix, block_type, sample_rate);
1746 let mut tables = [0u8; 3];
1747 let mut cost = 0u32;
1748 let mut from = 0usize;
1749 for (region, to) in bounds.iter().enumerate() {
1750 let to = (*to).min(big_end);
1751 if to > from {
1752 let (select, region_cost) = best_table_cost(ix, from, to);
1753 tables[region] = select;
1754 cost += region_cost;
1755 }
1756 from = to;
1757 }
1758 // count1: try both tables, keep the cheaper.
1759 let quads_cost = |select: bool| -> u32 {
1760 let mut sum = 0;
1761 let mut i = big_end;
1762 while i + 4 <= count1_end {
1763 sum += huffman::quad_bits(select, [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]]);
1764 i += 4;
1765 }
1766 sum
1767 };
1768 let count1_select = quads_cost(true) < quads_cost(false);
1769 cost += quads_cost(count1_select);
1770 SpectrumPlan {
1771 cost,
1772 big_values: (big_end / 2) as u32,
1773 tables,
1774 region0,
1775 region1,
1776 count1_select,
1777 bounds,
1778 big_end,
1779 count1_end,
1780 }
1781}
1782
1783/// Writes the coded spectrum the plan names into `out`, pairs and quadruples
1784/// in bitstream order. `ix` is the spectrum in bitstream order, the same
1785/// array the plan was computed from.
1786fn write_spectrum(plan: &SpectrumPlan, ix: &[i32; 576], out: &mut BitBuf) {
1787 let mut from = 0usize;
1788 for (region, to) in plan.bounds.iter().enumerate() {
1789 let to = (*to).min(plan.big_end);
1790 if to > from {
1791 let table = huffman::big_table(usize::from(plan.tables[region])).expect("table exists");
1792 let mut i = from;
1793 while i + 1 < to {
1794 huffman::write_pair(out, table, ix[i], ix[i + 1]);
1795 i += 2;
1796 }
1797 }
1798 from = to;
1799 }
1800 let mut i = plan.big_end;
1801 while i + 4 <= plan.count1_end {
1802 huffman::write_quad(
1803 out,
1804 plan.count1_select,
1805 [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]],
1806 );
1807 i += 4;
1808 }
1809}
1810
1811/// Tables that can code a region whose largest magnitude is `max`, cheapest
1812/// candidates first. Anything above 15 needs an escape-coded table, and the
1813/// escape tables differ only in how many linbits they spend.
1814fn candidates(max: u32) -> &'static [u8] {
1815 match max {
1816 0..=1 => &[1, 2, 3, 5, 6, 7, 8, 9],
1817 2 => &[2, 3, 5, 6, 7, 8, 9, 10],
1818 3 => &[5, 6, 7, 8, 9, 10, 11, 12],
1819 4..=5 => &[7, 8, 9, 10, 11, 12, 13, 15],
1820 6..=7 => &[10, 11, 12, 13, 15],
1821 8..=15 => &[13, 15, 16, 24],
1822 16..=16 => &[16, 17, 18, 19, 20, 21, 22, 23, 24],
1823 17..=18 => &[17, 18, 19, 20, 21, 22, 23, 24, 25],
1824 19..=30 => &[18, 19, 20, 21, 22, 23, 25, 26, 27],
1825 31..=78 => &[20, 21, 22, 23, 26, 27, 28, 29],
1826 79..=270 => &[21, 22, 23, 28, 29, 30, 31],
1827 271..=1038 => &[22, 23, 30, 31],
1828 _ => &[23, 31],
1829 }
1830}
1831
1832/// The cheapest table for one region, with its cost.
1833///
1834/// One walk over the pairs accumulates every shortlisted candidate's cost at
1835/// once; the former shape — a full `pair_bits` pass per candidate, up to nine
1836/// walks over the same pairs — was half of the encoder's remaining runtime.
1837/// A candidate any pair falls outside dies on the spot, exactly as the
1838/// per-candidate `pair_bits` propagation did, and ties keep the earlier
1839/// (nominally cheaper) candidate, as the strict less-than did.
1840fn best_table_cost(ix: &[i32], from: usize, to: usize) -> (u8, u32) {
1841 let mut max = 0u32;
1842 for &v in &ix[from..to] {
1843 max = max.max(v.unsigned_abs());
1844 }
1845 let shortlist = candidates(max);
1846 // Per-candidate state, fetched once: the table, its escape shape, the
1847 // cost of a (0, 0) pair, and a running cost. A candidate the region's
1848 // largest magnitude falls outside is dropped before the walk — exactly
1849 // what the per-pair range check did, since some pair carries `max`.
1850 let mut tables = [None; 9];
1851 let mut tmax = [0u32; 9];
1852 let mut linbits = [0u32; 9];
1853 let mut dim = [0u32; 9];
1854 let mut zero_bits = [0u32; 9];
1855 let mut feasible = [false; 9];
1856 let mut costs = [0u32; 9];
1857 let mut live = 0usize;
1858 for (slot, &select) in shortlist.iter().enumerate() {
1859 let Ok(table) = huffman::big_table(usize::from(select)) else {
1860 continue;
1861 };
1862 let cap = u32::from(table.dim) - 1;
1863 let escape = table.linbits > 0;
1864 let reach = cap + if escape { (1 << table.linbits) - 1 } else { 0 };
1865 if max > reach {
1866 continue;
1867 }
1868 tables[slot] = Some(table);
1869 tmax[slot] = cap;
1870 linbits[slot] = if escape { u32::from(table.linbits) } else { 0 };
1871 dim[slot] = u32::from(table.dim);
1872 zero_bits[slot] = u32::from(table.codes[0].0);
1873 feasible[slot] = true;
1874 live += 1;
1875 }
1876 let mut i = from;
1877 while i + 1 < to && live > 0 {
1878 let (x, y) = (ix[i].unsigned_abs(), ix[i + 1].unsigned_abs());
1879 if x == 0 && y == 0 {
1880 for slot in 0..shortlist.len() {
1881 if feasible[slot] {
1882 costs[slot] += zero_bits[slot];
1883 }
1884 }
1885 i += 2;
1886 continue;
1887 }
1888 let signs = u32::from(x != 0) + u32::from(y != 0);
1889 for slot in 0..shortlist.len() {
1890 if !feasible[slot] {
1891 continue;
1892 }
1893 let table = tables[slot].expect("feasible candidates hold a table");
1894 let (cap, lin) = (tmax[slot], linbits[slot]);
1895 let (len, _) = table.codes[(x.min(cap) * dim[slot] + y.min(cap)) as usize];
1896 if len == 0 {
1897 // A hole in the table: this candidate cannot code the pair,
1898 // so it is out for the whole region.
1899 feasible[slot] = false;
1900 live -= 1;
1901 continue;
1902 }
1903 let mut bits = u32::from(len) + signs;
1904 if lin > 0 {
1905 if x >= cap {
1906 bits += lin;
1907 }
1908 if y >= cap {
1909 bits += lin;
1910 }
1911 }
1912 costs[slot] += bits;
1913 }
1914 i += 2;
1915 }
1916 let mut best = (u32::MAX, 0u8);
1917 for (slot, &select) in shortlist.iter().enumerate() {
1918 if feasible[slot] && costs[slot] < best.0 {
1919 best = (costs[slot], select);
1920 }
1921 }
1922 if best.1 == 0 {
1923 // Nothing in the shortlist fits, which only a value above the coding
1924 // range can cause; fall back to the widest escape table.
1925 return (23, 0);
1926 }
1927 (best.1, best.0)
1928}
1929
1930/// The `scalefac_compress` index whose two lengths hold these scalefactors.
1931fn scalefac_compress(scalefac: &[u8; SFB_LONG], block_type: u8, sample_rate: u32) -> (u32, u32, u32) {
1932 let bits_for = |slice: &[u8]| -> u32 {
1933 let max = slice.iter().copied().max().unwrap_or(0);
1934 (0..=4u32).find(|n| max < (1 << n)).unwrap_or(4)
1935 };
1936 // Long blocks split their bands 11/10, short blocks 6/6 per window.
1937 let (first, second, cost1, cost2) = if block_type == 2 {
1938 (&scalefac[..6], &scalefac[6..12], 18, 18)
1939 } else {
1940 (&scalefac[..11], &scalefac[11..], 11, 10)
1941 };
1942 // The table's longest pair is (4, 3), so a caller that respects
1943 // `max_scalefac` always finds an entry; the clamp is what keeps a caller
1944 // that does not from silently coding a granule the decoder cannot rebuild.
1945 let need1 = bits_for(first).min(4);
1946 let need2 = bits_for(second).min(3);
1947 if sample_rate < 32000 {
1948 return (need1, need2, ((need1 * 5 + need1) << 4) | (need2 << 2) | need2);
1949 }
1950 let mut best = (u32::MAX, 4u32, 3u32, 15u32);
1951 for (index, (slen1, slen2)) in SLEN.iter().enumerate() {
1952 if *slen1 >= need1 && *slen2 >= need2 {
1953 let cost = slen1 * cost1 + slen2 * cost2;
1954 if cost < best.0 {
1955 best = (cost, *slen1, *slen2, index as u32);
1956 }
1957 }
1958 }
1959 (best.1, best.2, best.3)
1960}
1961
1962#[cfg(test)]
1963mod tests {
1964 use super::*;
1965
1966 /// The delay the Info tag states is the delay the pipeline has. Our own
1967 /// decoder ignores the tag, so what it hands back is the untrimmed stream:
1968 /// the content starts exactly `ENCODER_DELAY + DECODER_DELAY` samples in.
1969 /// The mask is stated in the quantiser's noise units: on white noise the
1970 /// band energy of the MDCT sits the signal-to-mask offset (6 dB, plus
1971 /// what the flatness estimate adds) above the threshold, not 2^17 away.
1972 #[test]
1973 fn masking_threshold_is_in_mdct_power_units() {
1974 let mut core = Mp3Encode::new(48000, 1, 128, None).unwrap();
1975 let mut seed = 0x2545_f491_4f6c_dd1du64;
1976 let mut noise = || {
1977 seed ^= seed << 13;
1978 seed ^= seed >> 7;
1979 seed ^= seed << 17;
1980 (seed >> 40) as f32 / 8_388_608.0 - 1.0
1981 };
1982 for _ in 0..8 {
1983 let pcm: Vec<f32> = (0..1152).map(|_| 0.25 * noise()).collect();
1984 core.encode_block(&pcm);
1985 }
1986 let granule = core.pending.last().unwrap().clone();
1987 let xr = core.mdct(0, &granule.subband, 0);
1988 let starts = long_starts(48000);
1989 let mut sum = 0.0f32;
1990 for band in 3..16 {
1991 let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1]));
1992 let energy: f32 = xr[from..to].iter().map(|v| v * v).sum();
1993 sum += 10.0 * (energy / granule.threshold[band]).log10();
1994 }
1995 let db = sum / 13.0;
1996 assert!(
1997 (6.0..=18.0).contains(&db),
1998 "signal sits {db:.1} dB over its mask"
1999 );
2000 }
2001
2002 #[test]
2003 fn encoder_delay_is_what_the_tag_says() {
2004 for (rate, channels) in [(44100u32, 1usize), (48000, 2)] {
2005 let n = 1152 * 8;
2006 let pcm: Vec<f32> = (0..n * channels)
2007 .map(|i| {
2008 let t = (i / channels) as f32;
2009 0.3 * (t * 0.11).sin() + 0.2 * (t * 0.7).cos()
2010 })
2011 .collect();
2012 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
2013 bitrate_kbps: 320,
2014 vbr_quality: None,
2015 });
2016 encoder
2017 .push_pcm_f32(&pcm, channels as u16, rate)
2018 .expect("encoder accepts this shape");
2019 encoder.finish();
2020 let mut bytes = Vec::new();
2021 while let Ok(frame) = encoder.next_packet() {
2022 bytes.extend_from_slice(&frame);
2023 }
2024 let mut reader = crate::Mp3Reader::new();
2025 reader.push(&bytes);
2026 let mut out: Vec<f32> = Vec::new();
2027 for frame in reader.decode_all() {
2028 out.extend_from_slice(&frame.samples);
2029 }
2030 let mut best = (f64::MIN, 0usize);
2031 let window = 4096 * channels;
2032 let mut lag = 0;
2033 while lag + window * 2 < out.len() {
2034 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
2035 for i in 0..window {
2036 let (x, y) = (out[lag + window + i] as f64, pcm[window + i] as f64);
2037 ab += x * y;
2038 aa += x * x;
2039 bb += y * y;
2040 }
2041 let corr = ab / (aa * bb).sqrt().max(1e-30);
2042 if corr > best.0 {
2043 best = (corr, lag / channels);
2044 }
2045 lag += channels;
2046 }
2047 assert!(best.0 > 0.999, "round trip correlation {:.6}", best.0);
2048 assert_eq!(
2049 best.1 as u32,
2050 ENCODER_DELAY + DECODER_DELAY,
2051 "measured lag at {rate} Hz, {channels} channels"
2052 );
2053 }
2054 }
2055
2056 /// The whole window sequence — normal, start, short, stop, normal — has to
2057 /// reconstruct, not just the long blocks. This runs the transform pair
2058 /// directly, so a failure points at the windows rather than at the
2059 /// quantiser.
2060 #[test]
2061 fn window_sequence_reconstructs() {
2062 use crate::filterbank::Imdct;
2063 let imdct = Imdct::default();
2064 let types = [0u8, 0, 1, 2, 3, 0, 0];
2065 let signal: Vec<f32> = (0..18 * (types.len() + 2))
2066 .map(|i| ((i as f32) * 0.37).sin() + 0.3 * ((i as f32) * 1.7).cos())
2067 .collect();
2068 let mut output = vec![0.0f32; signal.len()];
2069 let mut overlap = [0.0f32; 18];
2070 for (granule, block_type) in types.iter().enumerate() {
2071 let mut window = [0.0f32; 36];
2072 for (i, slot) in window.iter_mut().enumerate() {
2073 let index = granule * 18 + i;
2074 if index < signal.len() {
2075 *slot = signal[index];
2076 }
2077 }
2078 let mut spectrum = [0.0f32; 18];
2079 if *block_type == 2 {
2080 mdct_short(&window, &mut spectrum);
2081 } else {
2082 mdct_long(&window, *block_type, &mut spectrum);
2083 }
2084 let mut block = [0.0f32; 36];
2085 if *block_type == 2 {
2086 imdct.short(&spectrum, &mut block);
2087 } else {
2088 imdct.long(&spectrum, *block_type, &mut block);
2089 }
2090 for t in 0..18 {
2091 let index = granule * 18 + t;
2092 if index < output.len() {
2093 output[index] = block[t] + overlap[t];
2094 }
2095 }
2096 overlap.copy_from_slice(&block[18..]);
2097 }
2098 // The first granule has no predecessor and the last no successor.
2099 for (granule, block_type) in types.iter().enumerate().take(types.len() - 1).skip(1) {
2100 let mut error = 0.0f64;
2101 let mut energy = 0.0f64;
2102 for i in granule * 18..(granule + 1) * 18 {
2103 error += (output[i] - signal[i]).powi(2) as f64;
2104 energy += (signal[i] * signal[i]) as f64;
2105 }
2106 let snr = 10.0 * (energy / error.max(1e-30)).log10();
2107 assert!(
2108 snr > 60.0,
2109 "granule {granule} (block type {block_type}) reconstructs at {snr:.1} dB"
2110 );
2111 }
2112 }
2113
2114 /// A granule that switches to short blocks must come back as itself.
2115 ///
2116 /// Short blocks are coded band-major with the three windows interleaved on
2117 /// every line, which is not the order the transform produces them in. Miss
2118 /// that permutation and the bit count still lands exactly on
2119 /// `part2_3_length`, every fixture still decodes, and only the switched
2120 /// granules come back as noise — so this test drives an attack that forces
2121 /// the switch and checks the granules around it.
2122 #[test]
2123 fn switched_granules_reconstruct() {
2124 let rate = 44100u32;
2125 let n = 1152 * 12;
2126 let attack = 1152 * 6;
2127 let pcm: Vec<f32> = (0..n)
2128 .map(|i| {
2129 let t = i as f32;
2130 let tone = 0.5 * (t * 0.21).sin() + 0.3 * (t * 0.93).cos();
2131 // Six frames of near-silence, then full level: an attack no
2132 // block-switching encoder can ignore.
2133 if i < attack { tone * 0.002 } else { tone }
2134 })
2135 .collect();
2136 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
2137 bitrate_kbps: 320,
2138 vbr_quality: None,
2139 });
2140 encoder
2141 .push_pcm_f32(&pcm, 1, rate)
2142 .expect("encoder accepts this");
2143 encoder.finish();
2144 let mut bytes = Vec::new();
2145 while let Ok(frame) = encoder.next_packet() {
2146 bytes.extend_from_slice(&frame);
2147 }
2148 let mut reader = crate::Mp3Reader::new();
2149 reader.push(&bytes);
2150 let mut out: Vec<f32> = Vec::new();
2151 for frame in reader.decode_all() {
2152 out.extend_from_slice(&frame.samples);
2153 }
2154 let lag = (ENCODER_DELAY + DECODER_DELAY) as usize;
2155 // Every granule from the attack onward, where the switch happens.
2156 let mut worst = (1.0f64, 0usize);
2157 let mut granule = attack / 576;
2158 while (granule + 1) * 576 + lag <= out.len() && (granule + 1) * 576 <= pcm.len() {
2159 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
2160 for i in granule * 576..(granule + 1) * 576 {
2161 let (x, y) = (out[i + lag] as f64, pcm[i] as f64);
2162 ab += x * y;
2163 aa += x * x;
2164 bb += y * y;
2165 }
2166 let corr = ab / (aa * bb).sqrt().max(1e-30);
2167 if corr < worst.0 {
2168 worst = (corr, granule);
2169 }
2170 granule += 1;
2171 }
2172 assert!(
2173 worst.0 > 0.99,
2174 "granule {} reconstructs at {:.4}",
2175 worst.1,
2176 worst.0
2177 );
2178 }
2179
2180 #[test]
2181 fn bitrates_snap_to_legal_values() {
2182 assert_eq!(snap_bitrate(Version::Mpeg1, 128), 128);
2183 assert_eq!(snap_bitrate(Version::Mpeg1, 130), 128);
2184 assert_eq!(snap_bitrate(Version::Mpeg1, 1000), 320);
2185 assert_eq!(snap_bitrate(Version::Mpeg2, 128), 128);
2186 assert_eq!(snap_bitrate(Version::Mpeg2, 320), 160);
2187 }
2188
2189 #[test]
2190 fn unsupported_rates_are_refused_by_name() {
2191 let err = Mp3Encode::new(96000, 2, 128, None).unwrap_err();
2192 assert!(format!("{err}").contains("96000 Hz"), "{err}");
2193 }
2194
2195 /// The encoder's whole analysis chain against the decoder's whole
2196 /// synthesis chain, quantisation left out: what comes back is what went
2197 /// in, delayed by the filterbank.
2198 #[test]
2199 fn analysis_chain_round_trips_through_the_decoder() {
2200 use crate::filterbank::{Imdct, Synthesis, alias_reduce};
2201 let imdct = Imdct::default();
2202 let mut analysis = Analysis::default();
2203 let mut synthesis = Synthesis::default();
2204 let n = 32 * 32 * 24;
2205 let input: Vec<f32> = (0..n)
2206 .map(|i| {
2207 let t = i as f32;
2208 0.4 * (t * 0.05).sin() + 0.2 * (t * 0.31).cos()
2209 })
2210 .collect();
2211 let mut slots: Vec<[f32; 32]> = Vec::new();
2212 for chunk in input.chunks(32) {
2213 if let Some(slot) = analysis.push(chunk) {
2214 slots.push(slot);
2215 }
2216 }
2217 let granules = slots.len() / 18;
2218 let mut history = [[0.0f32; 32]; 18];
2219 let mut overlap = [[0.0f32; 18]; 32];
2220 let mut output: Vec<f32> = Vec::new();
2221 for g in 0..granules {
2222 let granule = &slots[g * 18..g * 18 + 18];
2223 let mut xr = vec![0.0f32; 576];
2224 for sb in 0..32 {
2225 let mut window = [0.0f32; 36];
2226 for t in 0..18 {
2227 let sign = if sb % 2 == 1 && t % 2 == 1 { -1.0 } else { 1.0 };
2228 window[t] = history[t][sb] * sign;
2229 window[18 + t] = granule[t][sb] * sign;
2230 }
2231 mdct_long(&window, 0, &mut xr[sb * 18..sb * 18 + 18]);
2232 }
2233 alias_expand(&mut xr, 32);
2234 history.copy_from_slice(granule);
2235 // decoder side
2236 alias_reduce(&mut xr, 32);
2237 let mut out_slots = [[0.0f32; 32]; 18];
2238 let mut block = [0.0f32; 36];
2239 for sb in 0..32 {
2240 imdct.long(&xr[sb * 18..sb * 18 + 18], 0, &mut block);
2241 for t in 0..18 {
2242 let mut sample = block[t] + overlap[sb][t];
2243 overlap[sb][t] = block[18 + t];
2244 if sb % 2 == 1 && t % 2 == 1 {
2245 sample = -sample;
2246 }
2247 out_slots[t][sb] = sample;
2248 }
2249 }
2250 let mut pcm = [0.0f32; 32];
2251 for slot in &out_slots {
2252 synthesis.slot(slot, &mut pcm);
2253 output.extend_from_slice(&pcm);
2254 }
2255 }
2256 // Find the delay, then check the reconstruction is faithful. The
2257 // comparison starts past the filterbank's ramp-up, which is silence
2258 // sliding into the window rather than anything the transform got wrong.
2259 let (from, len) = (4096usize, 8192usize);
2260 let mut best = (f64::MIN, 0usize);
2261 for delay in 0..output.len().min(2048) {
2262 if delay + from + len > output.len() || from + len > input.len() {
2263 break;
2264 }
2265 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
2266 for i in from..from + len {
2267 let (x, y) = (output[delay + i] as f64, input[i] as f64);
2268 ab += x * y;
2269 aa += x * x;
2270 bb += y * y;
2271 }
2272 let corr = ab / (aa * bb).sqrt().max(1e-30);
2273 if corr > best.0 {
2274 best = (corr, delay);
2275 }
2276 }
2277 assert!(
2278 best.0 > 0.99999,
2279 "analysis/synthesis correlation {:.6} at delay {}",
2280 best.0,
2281 best.1
2282 );
2283 }
2284
2285 /// The forward MDCT and the decoder's inverse are a reconstructing pair:
2286 /// two overlapped granules of a signal come back as themselves.
2287 #[test]
2288 fn mdct_round_trips_under_overlap_add() {
2289 use crate::filterbank::Imdct;
2290 let imdct = Imdct::default();
2291 let signal: Vec<f32> = (0..72)
2292 .map(|i| ((i as f32) * 0.37).sin() + 0.3 * ((i as f32) * 1.1).cos())
2293 .collect();
2294 let mut output = vec![0.0f32; 72];
2295 let mut previous = [0.0f32; 18];
2296 for granule in 0..3 {
2297 let mut input = [0.0f32; 36];
2298 for (i, slot) in input.iter_mut().enumerate() {
2299 let index = granule * 18 + i;
2300 if index < signal.len() {
2301 *slot = signal[index];
2302 }
2303 }
2304 let mut spectrum = [0.0f32; 18];
2305 mdct_long(&input, 0, &mut spectrum);
2306 let mut block = [0.0f32; 36];
2307 imdct.long(&spectrum, 0, &mut block);
2308 for t in 0..18 {
2309 let index = granule * 18 + t;
2310 if index < output.len() {
2311 output[index] = block[t] + previous[t];
2312 }
2313 }
2314 previous.copy_from_slice(&block[18..]);
2315 }
2316 // The first granule has no predecessor, so compare from the second.
2317 let mut worst = 0.0f32;
2318 for i in 18..54 {
2319 worst = worst.max((output[i] - signal[i]).abs());
2320 }
2321 println!("mdct round trip worst absolute error {worst:e}");
2322 for i in 18..54 {
2323 assert!(
2324 (output[i] - signal[i]).abs() < 1e-5,
2325 "sample {i}: {} vs {}",
2326 output[i],
2327 signal[i]
2328 );
2329 }
2330 }
2331}