forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiBdb36daaTahinli3 months ago92 commits

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