forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBeee0a69Tahinli3 months ago415 commits

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