forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBd9bea4aTahinli3 months ago1566 commits

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