forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB30d372eTahinli3 months ago42 commits

encode.rs1207 lines, 44.7 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, 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 fft: RealFft<f32>,
105 fft_window: Window<f32>,
106 psy_history: Vec<Vec<f32>>,
107 /// The main-data byte stream and how much of it frames have carried.
108 stream: Vec<u8>,
109 used: usize,
110 /// Stream bytes already assigned to a frame's payload, decided or not.
111 assigned: usize,
112 /// Stream bytes already written out in a frame.
113 written: usize,
114 /// Frames whose header and side info are decided but whose payload is
115 /// still being filled: the bit reservoir means a frame's payload carries
116 /// the *next* frame's granule data, so emission runs one frame behind.
117 queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>)>,
118 ready: std::collections::VecDeque<Vec<u8>>,
119 frames: u32,
120}
121
122#[derive(Clone, Debug)]
123struct PendingGranule {
124 subband: Vec<[f32; 32]>,
125 energy: f32,
126 threshold: Vec<f32>,
127}
128
129impl Mp3Encode {
130 /// An encoder for this stream shape. Rates outside 8..48 kHz have no Layer
131 /// III frame and are refused by name.
132 pub fn new(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Result<Mp3Encode> {
133 let version = match sample_rate {
134 32000 | 44100 | 48000 => Version::Mpeg1,
135 16000 | 22050 | 24000 => Version::Mpeg2,
136 8000 | 11025 | 12000 => Version::Mpeg25,
137 other => {
138 return Err(Error::unsupported(
139 format!("{other} Hz MPEG audio"),
140 "Layer III frames exist only for 8, 11.025, 12, 16, 22.05, 24, 32, 44.1 and 48 kHz",
141 ));
142 }
143 };
144 if channels == 0 || channels > 2 {
145 return Err(Error::unsupported(
146 format!("{channels}-channel MP3"),
147 "Layer III carries one or two channels",
148 ));
149 }
150 Ok(Mp3Encode {
151 sample_rate,
152 channels,
153 bitrate_kbps: snap_bitrate(version, bitrate_kbps),
154 version,
155 mode: if channels == 2 {
156 ChannelMode::JointStereo
157 } else {
158 ChannelMode::Mono
159 },
160 analysis: (0..channels).map(|_| Analysis::default()).collect(),
161 slots: vec![Vec::new(); channels],
162 history: vec![[[0.0; 32]; 18]; channels],
163 pending: Vec::new(),
164 fft: RealFft::new(1024),
165 fft_window: Window::sine(1024),
166 psy_history: vec![vec![0.0; 1024]; channels],
167 stream: Vec::new(),
168 used: 0,
169 assigned: 0,
170 written: 0,
171 queued: std::collections::VecDeque::new(),
172 ready: std::collections::VecDeque::new(),
173 frames: 0,
174 })
175 }
176
177 /// The header every frame of this stream carries.
178 fn header(&self) -> FrameHeader {
179 FrameHeader {
180 version: self.version,
181 layer: 3,
182 crc: false,
183 bitrate_kbps: self.bitrate_kbps,
184 sample_rate: self.sample_rate,
185 padding: false,
186 private: false,
187 mode: self.mode,
188 mode_ext: 0,
189 copyright: false,
190 original: true,
191 emphasis: 0,
192 }
193 }
194
195 /// Granules per frame for this stream.
196 pub fn granules(&self) -> usize {
197 self.header().granules()
198 }
199
200 /// Samples per channel one frame codes.
201 pub fn frame_samples(&self) -> usize {
202 self.granules() * 576
203 }
204}
205
206/// Interleaved PCM in, complete frames out.
207#[derive(Debug)]
208pub struct Mp3Encoder {
209 core: Option<Mp3Encode>,
210 config: Mp3EncoderConfig,
211 pcm: Vec<f32>,
212 frames: std::collections::VecDeque<Vec<u8>>,
213 finished: bool,
214 header_written: bool,
215 total_samples: u64,
216}
217
218impl Mp3Encoder {
219 /// An encoder that configures itself from the first PCM it is given.
220 pub fn new(config: Mp3EncoderConfig) -> Mp3Encoder {
221 Mp3Encoder {
222 core: None,
223 config,
224 pcm: Vec::new(),
225 frames: std::collections::VecDeque::new(),
226 finished: false,
227 header_written: false,
228 total_samples: 0,
229 }
230 }
231
232 /// Feeds interleaved `f32` samples in `[-1, 1]`.
233 pub fn push_pcm_f32(
234 &mut self,
235 interleaved: &[f32],
236 channels: u16,
237 sample_rate: u32,
238 ) -> Result<()> {
239 if self.core.is_none() {
240 let bitrate = match self.config.vbr_quality {
241 Some(q) => bitrate_for_quality(q),
242 None => self.config.bitrate_kbps.max(8),
243 };
244 self.core = Some(Mp3Encode::new(sample_rate, usize::from(channels), bitrate)?);
245 }
246 self.pcm.extend_from_slice(interleaved);
247 self.total_samples += (interleaved.len() / usize::from(channels.max(1))) as u64;
248 self.drain(false);
249 Ok(())
250 }
251
252 /// Feeds interleaved 16-bit samples, scaled the way every decoder here
253 /// scales them.
254 pub fn push_pcm_s16(
255 &mut self,
256 interleaved: &[i16],
257 channels: u16,
258 sample_rate: u32,
259 ) -> Result<()> {
260 let floats: Vec<f32> = interleaved
261 .iter()
262 .map(|s| f32::from(*s) / 32768.0)
263 .collect();
264 self.push_pcm_f32(&floats, channels, sample_rate)
265 }
266
267 /// Ends the stream: pads the tail to a whole frame and flushes.
268 pub fn finish(&mut self) {
269 if let Some(core) = &self.core {
270 let channels = core.channels;
271 // The filterbank runs fifteen slots behind, and the MDCT one
272 // granule behind that; feed silence so the last real samples come
273 // out the other end.
274 let tail = vec![0.0f32; channels * (576 * 2 + 480)];
275 self.pcm.extend_from_slice(&tail);
276 }
277 self.drain(true);
278 self.finished = true;
279 }
280
281 fn drain(&mut self, flush: bool) {
282 let Some(core) = self.core.as_mut() else {
283 return;
284 };
285 let channels = core.channels;
286 let need = core.frame_samples() * channels;
287 while self.pcm.len() >= need {
288 let block: Vec<f32> = self.pcm.drain(..need).collect();
289 core.encode_block(&block);
290 }
291 if flush {
292 if !self.pcm.is_empty() {
293 let mut block = std::mem::take(&mut self.pcm);
294 block.resize(need, 0.0);
295 core.encode_block(&block);
296 }
297 core.flush_frames();
298 }
299 while let Some(frame) = core.ready.pop_front() {
300 self.frames.push_back(frame);
301 }
302 }
303
304 /// The next complete frame, [`Error::Eof`] once drained after
305 /// [`Mp3Encoder::finish`], [`Error::NeedMore`] before that.
306 pub fn next_packet(&mut self) -> Result<Vec<u8>> {
307 if !self.header_written && (self.finished || !self.frames.is_empty()) {
308 self.header_written = true;
309 if let Some(core) = &self.core {
310 return Ok(info_frame(core, self.total_samples));
311 }
312 }
313 match self.frames.pop_front() {
314 Some(frame) => Ok(frame),
315 None if self.finished => Err(Error::Eof),
316 None => Err(Error::NeedMore),
317 }
318 }
319}
320
321/// The Xing/Info header frame every player expects first: a silent frame whose
322/// main data is the tag, so a decoder that does not know the tag still decodes
323/// a legal (silent) frame rather than choking.
324fn info_frame(core: &Mp3Encode, samples: u64) -> Vec<u8> {
325 let header = core.header();
326 let frame_len = header.frame_len().unwrap_or(417);
327 let mut out = vec![0u8; frame_len];
328 out[..4].copy_from_slice(&header.to_bytes());
329 let at = 4 + header.side_info_len();
330 let tag: &[u8] = b"Info";
331 out[at..at + 4].copy_from_slice(tag);
332 out[at + 4..at + 8].copy_from_slice(&1u32.to_be_bytes()); // frames field present
333 let frames = samples.div_ceil(header.samples_per_frame() as u64) as u32;
334 out[at + 8..at + 12].copy_from_slice(&frames.to_be_bytes());
335 out
336}
337
338impl Mp3Encode {
339 /// Encodes one frame's worth of interleaved PCM.
340 fn encode_block(&mut self, pcm: &[f32]) {
341 let channels = self.channels;
342 let granules = self.granules();
343 // Polyphase analysis, one channel at a time.
344 for ch in 0..channels {
345 let mut mono: Vec<f32> = Vec::with_capacity(pcm.len() / channels);
346 for frame in pcm.chunks(channels) {
347 mono.push(frame[ch]);
348 }
349 for chunk in mono.chunks(32) {
350 if chunk.len() < 32 {
351 break;
352 }
353 if let Some(slot) = self.analysis[ch].push(chunk) {
354 self.slots[ch].push(slot);
355 }
356 }
357 self.psy_push(ch, &mono);
358 }
359 // A granule is 18 slots; hold one back so block switching can look
360 // ahead at the next granule's energy.
361 let ready = self.slots[0].len() / 18;
362 if ready == 0 {
363 return;
364 }
365 for _ in 0..ready {
366 for ch in 0..channels {
367 let subband: Vec<[f32; 32]> = self.slots[ch].drain(..18).collect();
368 let energy: f32 = subband
369 .iter()
370 .flat_map(|slot| slot.iter())
371 .map(|v| v * v)
372 .sum();
373 let threshold = self.psy_threshold(ch);
374 self.pending.push(PendingGranule {
375 subband,
376 energy,
377 threshold,
378 });
379 }
380 }
381 // Emit whole frames while a lookahead granule remains.
382 let per_frame = granules * channels;
383 while self.pending.len() >= per_frame + channels {
384 self.emit_frame();
385 }
386 }
387
388 /// One FFT per granule of input, kept for the masking model.
389 fn psy_push(&mut self, ch: usize, mono: &[f32]) {
390 let n = 1024.min(mono.len());
391 let history = &mut self.psy_history[ch];
392 history.copy_within(n.., 0);
393 let keep = 1024 - n;
394 history[keep..].copy_from_slice(&mono[mono.len() - n..]);
395 }
396
397 /// Allowed noise per long scalefactor band, from the masking model.
398 fn psy_threshold(&mut self, ch: usize) -> Vec<f32> {
399 let mut block: Vec<f32> = self.psy_history[ch].clone();
400 self.fft_window.apply(&mut block);
401 let mut spectrum = vec![ec_dsp::Complex::<f32>::ZERO; 513];
402 self.fft.forward(&block, &mut spectrum);
403 let starts = long_starts(self.sample_rate);
404 let mut energy = vec![0.0f32; SFB_LONG];
405 for (band, slot) in energy.iter_mut().enumerate() {
406 // The 576 coefficients of a granule map onto 512 FFT bins.
407 let from = usize::from(starts[band]) * 512 / 576;
408 let to = (usize::from(starts[band + 1]) * 512 / 576).max(from + 1);
409 let mut sum = 0.0f32;
410 let mut log_sum = 0.0f32;
411 let mut count = 0.0f32;
412 for bin in &spectrum[from..to.min(512)] {
413 let power = bin.norm_sqr() + 1e-30;
414 sum += power;
415 log_sum += power.ln();
416 count += 1.0;
417 }
418 // Spectral flatness as a tonality proxy: a flat band is noise-like
419 // and masks less.
420 let flatness = if count > 0.0 {
421 ((log_sum / count).exp() / (sum / count)).clamp(0.0, 1.0)
422 } else {
423 1.0
424 };
425 let offset_db = 6.0 + 15.0 * (1.0 - flatness);
426 *slot = sum * 10f32.powf(-offset_db / 10.0);
427 }
428 // Spreading: masking leaks upward strongly and downward weakly.
429 let mut spread = energy.clone();
430 for band in 1..SFB_LONG {
431 let leak = spread[band - 1] * 0.0032; // about -25 dB per band
432 spread[band] = spread[band].max(leak);
433 }
434 for band in (0..SFB_LONG - 1).rev() {
435 let leak = spread[band + 1] * 0.1; // about -10 dB per band
436 spread[band] = spread[band].max(leak);
437 }
438 // Absolute threshold, coarse: hearing is least sensitive at the ends.
439 for (band, slot) in spread.iter_mut().enumerate() {
440 let rel = band as f32 / SFB_LONG as f32;
441 let floor = 1e-9 * (1.0 + 400.0 * (rel - 0.35).max(0.0).powi(2));
442 *slot = slot.max(floor);
443 }
444 spread
445 }
446
447 fn emit_frame(&mut self) {
448 let channels = self.channels;
449 let granules = self.granules();
450 let header = self.header();
451 let frame_len = header.frame_len().unwrap_or(0);
452 let capacity = frame_len - 4 - header.side_info_len();
453
454 // Window types: a granule whose successor is much louder starts the
455 // switch, the loud one is short, and the one after stops it.
456 let mut types = vec![0u8; granules * channels];
457 for gr in 0..granules {
458 for ch in 0..channels {
459 let index = gr * channels + ch;
460 let next = index + channels;
461 let here = self.pending[index].energy;
462 let there = self.pending.get(next).map_or(here, |g| g.energy);
463 if there > here * 8.0 + 1e-6 {
464 types[index] = 1; // start
465 }
466 }
467 }
468 for gr in 0..granules {
469 for ch in 0..channels {
470 let index = gr * channels + ch;
471 if index >= channels && types[index - channels] == 1 {
472 types[index] = 2; // short
473 } else if index >= 2 * channels && types[index - 2 * channels] == 2 {
474 types[index] = 3; // stop
475 }
476 }
477 }
478
479 let begin = self.assigned - self.used;
480 let budget_bits = (self.assigned + capacity - self.used) * 8;
481 let mut coded: Vec<CodedGranule> = Vec::with_capacity(granules * channels);
482 let share = budget_bits / (granules * channels).max(1);
483 for gr in 0..granules {
484 for ch in 0..channels {
485 let index = gr * channels + ch;
486 let granule = self.pending[index].clone();
487 let xr = self.mdct(ch, &granule.subband, types[index]);
488 let spent: usize = coded.iter().map(|c| c.part2_3_length as usize).sum();
489 let left = budget_bits.saturating_sub(spent);
490 let target = share.min(left).min(4095);
491 coded.push(quantise_granule(
492 &xr,
493 types[index],
494 target as u32,
495 &granule.threshold,
496 self.sample_rate,
497 ));
498 }
499 }
500 self.pending.drain(..granules * channels);
501
502 // Assemble the frame: header, side info, and this frame's window on
503 // the main-data stream.
504 let mut side = BitWriter::new();
505 side.write_bits(
506 begin as u32,
507 if self.version == Version::Mpeg1 { 9 } else { 8 },
508 );
509 let private = match (self.version == Version::Mpeg1, channels) {
510 (true, 1) => 5,
511 (true, _) => 3,
512 (false, 1) => 1,
513 (false, _) => 2,
514 };
515 side.write_bits(0, private);
516 if self.version == Version::Mpeg1 {
517 side.write_bits(0, 4 * channels as u32); // scfsi: never reuse
518 }
519 for granule in &coded {
520 side.write_bits(granule.part2_3_length, 12);
521 side.write_bits(granule.big_values, 9);
522 side.write_bits(granule.global_gain, 8);
523 side.write_bits(
524 granule.scalefac_compress,
525 if self.version == Version::Mpeg1 { 4 } else { 9 },
526 );
527 if granule.block_type == 0 {
528 side.write_bit(false);
529 for table in granule.table_select {
530 side.write_bits(u32::from(table), 5);
531 }
532 side.write_bits(granule.region0_count, 4);
533 side.write_bits(granule.region1_count, 3);
534 } else {
535 side.write_bit(true);
536 side.write_bits(u32::from(granule.block_type), 2);
537 side.write_bit(false); // mixed_block_flag
538 for table in &granule.table_select[..2] {
539 side.write_bits(u32::from(*table), 5);
540 }
541 side.write_bits(0, 9); // subblock_gain
542 }
543 if self.version == Version::Mpeg1 {
544 side.write_bit(false); // preflag
545 }
546 side.write_bit(granule.scalefac_scale);
547 side.write_bit(granule.count1table_select);
548 }
549 side.align_to_byte();
550 let side_bytes = side.into_bytes();
551 debug_assert_eq!(side_bytes.len(), header.side_info_len());
552
553 // Append the granule data to the stream at `used`, byte aligned.
554 let mut main = BitWriter::new();
555 for granule in &coded {
556 for bit in &granule.bits {
557 main.write_bit(*bit);
558 }
559 }
560 main.align_to_byte();
561 let main_bytes = main.into_bytes();
562 // Stream positions the reservoir cap skipped over are stuffing, not
563 // data, so they are zeros rather than a shorter stream.
564 if self.stream.len() < self.used {
565 self.stream.resize(self.used, 0);
566 }
567 self.stream.truncate(self.used);
568 self.stream.extend_from_slice(&main_bytes);
569 self.used += main_bytes.len();
570
571 self.queued
572 .push_back((header.to_bytes().to_vec(), side_bytes));
573 self.assigned += capacity;
574 // A queued frame can only go out once real granule data covers its
575 // whole payload; padding it early is what would strand the next
576 // frame's `main_data_begin` in bytes that were already written.
577 while !self.queued.is_empty() && self.stream.len() >= self.written + capacity {
578 let (head, side) = self.queued.pop_front().expect("queue is not empty");
579 let mut frame = Vec::with_capacity(frame_len);
580 frame.extend_from_slice(&head);
581 frame.extend_from_slice(&side);
582 frame.extend_from_slice(&self.stream[self.written..self.written + capacity]);
583 self.written += capacity;
584 self.ready.push_back(frame);
585 self.frames += 1;
586 }
587 // main_data_begin is nine bits, so the reservoir cannot reach further
588 // back than 511 bytes; anything older is dropped rather than pointed at.
589 if self.assigned > self.used + 511 {
590 self.used = self.assigned - 511;
591 }
592 }
593
594 /// Writes out whatever frames are still queued, padding the stream so the
595 /// last frame is complete.
596 fn flush_frames(&mut self) {
597 let header = self.header();
598 let frame_len = header.frame_len().unwrap_or(0);
599 let capacity = frame_len - 4 - header.side_info_len();
600 while let Some((head, side)) = self.queued.pop_front() {
601 if self.stream.len() < self.written + capacity {
602 self.stream.resize(self.written + capacity, 0);
603 }
604 let mut frame = Vec::with_capacity(frame_len);
605 frame.extend_from_slice(&head);
606 frame.extend_from_slice(&side);
607 frame.extend_from_slice(&self.stream[self.written..self.written + capacity]);
608 self.written += capacity;
609 self.ready.push_back(frame);
610 self.frames += 1;
611 }
612 }
613
614 /// One granule of subband samples to 576 spectral lines.
615 fn mdct(&mut self, ch: usize, subband: &[[f32; 32]], block_type: u8) -> Vec<f32> {
616 let mut xr = vec![0.0f32; 576];
617 let history = self.history[ch];
618 for sb in 0..32 {
619 // The transform window is the previous granule's 18 samples
620 // followed by this granule's, with the frequency inversion the
621 // decoder applies undone first.
622 let mut input = [0.0f32; 36];
623 for t in 0..18 {
624 let sign = if sb % 2 == 1 && t % 2 == 1 { -1.0 } else { 1.0 };
625 input[t] = history[t][sb] * sign;
626 input[18 + t] = subband[t][sb] * sign;
627 }
628 let out = &mut xr[sb * 18..sb * 18 + 18];
629 if block_type == 2 {
630 mdct_short(&input, out);
631 } else {
632 mdct_long(&input, block_type, out);
633 }
634 }
635 if block_type != 2 {
636 alias_expand(&mut xr, 32);
637 }
638 let mut store = [[0.0f32; 32]; 18];
639 store[..18].copy_from_slice(&subband[..18]);
640 self.history[ch] = store;
641 xr
642 }
643}
644
645/// Forward MDCT, 36 samples to 18 coefficients, scaled so the decoder's
646/// unscaled inverse reconstructs the input under overlap-add.
647fn mdct_long(input: &[f32; 36], block_type: u8, out: &mut [f32]) {
648 let window = &windows()[usize::from(block_type)];
649 let mut windowed = [0.0f32; 36];
650 for i in 0..36 {
651 windowed[i] = input[i] * window[i];
652 }
653 for (k, slot) in out.iter_mut().enumerate() {
654 let mut sum = 0.0f64;
655 for (n, value) in windowed.iter().enumerate() {
656 let angle = std::f64::consts::PI / 72.0 * ((2 * n + 19) * (2 * k + 1)) as f64;
657 sum += f64::from(*value) * angle.cos();
658 }
659 *slot = (sum / 9.0) as f32;
660 }
661}
662
663/// Forward MDCT for a short block: three 12-sample transforms, interleaved
664/// into the spectrum the way the decoder reads them back.
665fn mdct_short(input: &[f32; 36], out: &mut [f32]) {
666 let window = &windows()[2];
667 for w in 0..3 {
668 for k in 0..6 {
669 let mut sum = 0.0f64;
670 for n in 0..12 {
671 let sample = input[6 + 6 * w + n] * window[n];
672 let angle = std::f64::consts::PI / 24.0 * ((2 * n + 7) * (2 * k + 1)) as f64;
673 sum += f64::from(sample) * angle.cos();
674 }
675 out[k * 3 + w] = (sum / 3.0) as f32;
676 }
677 }
678}
679
680/// Quantises one granule: the rate loop inside the distortion loop.
681fn quantise_granule(
682 xr: &[f32],
683 block_type: u8,
684 target_bits: u32,
685 threshold: &[f32],
686 sample_rate: u32,
687) -> CodedGranule {
688 let mut scalefac = [0u8; SFB_LONG];
689 let mut best: Option<(CodedGranule, f64)> = None;
690 // The distortion loop. Two things end it: every band is under its masking
691 // threshold *and* the bits are spent, or no band can be amplified further.
692 // Spending the bits matters as much as the threshold does — a granule that
693 // stops early leaves the extra bitrate on the floor, which is what makes an
694 // encoder's quality flat across 128 and 320 kbit/s.
695 for _round in 0..20 {
696 let (granule, noise) = code_with(xr, block_type, target_bits, &scalefac, sample_rate);
697 let ratios: Vec<f64> = (0..SFB_LONG)
698 .map(|b| f64::from(noise[b]) / f64::from(threshold[b]).max(1e-30))
699 .collect();
700 let score: f64 = ratios.iter().sum();
701 let spent = granule.part2_3_length;
702 if best.as_ref().is_none_or(|(_, s)| score < *s) {
703 best = Some((granule, score));
704 }
705 if block_type == 2 {
706 break; // short blocks carry no long scalefactors here
707 }
708 if spent * 20 > target_bits * 19 {
709 break; // the budget is spent; amplifying now only coarsens
710 }
711 // Amplify the bands that are worst against their threshold.
712 let mut order: Vec<usize> = (0..SFB_LONG).filter(|&b| scalefac[b] < 15).collect();
713 order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a]));
714 let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect();
715 let chosen: Vec<usize> = if over.is_empty() {
716 order.iter().copied().take(3).collect()
717 } else {
718 over
719 };
720 if chosen.is_empty() {
721 break;
722 }
723 for band in chosen {
724 scalefac[band] += 1;
725 }
726 }
727 best.expect("at least one round runs").0
728}
729
730/// Quantises with a fixed scalefactor set, running the rate loop on
731/// `global_gain`, and reports the noise each band ends up with.
732fn code_with(
733 xr: &[f32],
734 block_type: u8,
735 budget_bits: u32,
736 scalefac: &[u8; SFB_LONG],
737 sample_rate: u32,
738) -> (CodedGranule, [f32; SFB_LONG]) {
739 let (slen1, slen2, compress) = scalefac_compress(scalefac);
740 // The scalefactors come out of the same budget as the spectrum does.
741 let scalefac_bits = if block_type == 2 {
742 0
743 } else {
744 slen1 * 11 + slen2 * 10
745 };
746 let target_bits = budget_bits.saturating_sub(scalefac_bits);
747 let peak = xr.iter().fold(0.0f32, |acc, v| acc.max(v.abs()));
748 // A starting gain that puts the loudest line near the top of the coded
749 // range: |xr| / 2^((g-210)/4) raised to 3/4 should land around 8000.
750 let start = if peak > 1e-20 {
751 (210.0 + 4.0 * (peak.log2() - 13.0 / 0.75)).round() as i32
752 } else {
753 210
754 };
755 let mut gain = start.clamp(0, 255);
756 let mut ix = vec![0i32; 576];
757 let mut coded;
758 // The rate loop runs both ways: down while there are bits to spare, up
759 // while the granule is too big for them. A line that saturates the coding
760 // range is not "cheap", it is clipped, so that check comes first.
761 let saturated = |ix: &[i32]| ix.iter().any(|v| v.abs() > 8191);
762 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
763 coded = code_spectrum(&ix, block_type, sample_rate);
764 loop {
765 if (saturated(&ix) || coded.0 > target_bits) && gain < 255 {
766 gain += 1;
767 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
768 coded = code_spectrum(&ix, block_type, sample_rate);
769 continue;
770 }
771 if saturated(&ix) || coded.0 > target_bits || gain == 0 {
772 break;
773 }
774 // Try one step quieter; keep it only if it still fits and stays
775 // inside the coding range.
776 let mut trial = ix.clone();
777 quantise(xr, gain - 1, scalefac, sample_rate, block_type, &mut trial);
778 let trial_coded = code_spectrum(&trial, block_type, sample_rate);
779 if trial_coded.0 > target_bits || saturated(&trial) {
780 break;
781 }
782 gain -= 1;
783 ix = trial;
784 coded = trial_coded;
785 }
786 // Last resort: if even the quietest legal gain will not fit the bits we
787 // were given, drop the top of the spectrum until it does. A granule that
788 // overruns its budget would corrupt the reservoir for every frame after
789 // it, which is far worse than a low-passed one.
790 let mut limit = 576usize;
791 while coded.0 > target_bits && limit > 4 {
792 limit = limit * 3 / 4;
793 for slot in ix.iter_mut().skip(limit) {
794 *slot = 0;
795 }
796 coded = code_spectrum(&ix, block_type, sample_rate);
797 }
798 let (_, big_values, tables, region0, region1, count1_select, bits) = coded;
799 let mut noise = [0.0f32; SFB_LONG];
800 let starts = long_starts(sample_rate);
801 let power = power43();
802 for band in 0..SFB_LONG {
803 let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1]));
804 let scale = band_gain(gain, scalefac[band], block_type);
805 let mut sum = 0.0f32;
806 for i in from..to.min(576) {
807 let magnitude = power[(ix[i].unsigned_abs() as usize).min(MAX_QUANT)] * scale;
808 let reconstructed = if ix[i] < 0 { -magnitude } else { magnitude };
809 sum += (xr[i] - reconstructed).powi(2);
810 }
811 noise[band] = sum;
812 }
813 let mut out = BitWriter::new();
814 for (band, value) in scalefac.iter().enumerate() {
815 let slen = if band < 11 { slen1 } else { slen2 };
816 if block_type != 2 {
817 out.write_bits(u32::from(*value), slen);
818 }
819 }
820 let scalefac_bits = out.bit_len() as u32;
821 let mut bits_out: Vec<bool> = Vec::with_capacity((scalefac_bits + bits.len() as u32) as usize);
822 let bytes = out.into_bytes();
823 for i in 0..scalefac_bits as usize {
824 bits_out.push((bytes[i / 8] >> (7 - i % 8)) & 1 == 1);
825 }
826 bits_out.extend_from_slice(&bits);
827 let granule = CodedGranule {
828 part2_3_length: bits_out.len() as u32,
829 bits: bits_out,
830 big_values,
831 global_gain: gain as u32,
832 scalefac_compress: compress,
833 block_type,
834 table_select: tables,
835 region0_count: region0,
836 region1_count: region1,
837 scalefac_scale: false,
838 count1table_select: count1_select,
839 };
840 (granule, noise)
841}
842
843fn band_gain(gain: i32, scalefac: u8, block_type: u8) -> f32 {
844 let base = (gain as f32 - 210.0) * 0.25;
845 if block_type == 2 {
846 base.exp2()
847 } else {
848 (base - 0.5 * f32::from(scalefac)).exp2()
849 }
850}
851
852/// The spectrum as integers, per the decoder's requantisation read backwards.
853fn quantise(
854 xr: &[f32],
855 gain: i32,
856 scalefac: &[u8; SFB_LONG],
857 sample_rate: u32,
858 block_type: u8,
859 ix: &mut [i32],
860) {
861 let starts = long_starts(sample_rate);
862 // 22 bands, not 21: the topmost band carries no transmitted scalefactor,
863 // but it does carry audio — zeroing it low-passes the encoder at 16 kHz.
864 for band in 0..22 {
865 let (from, to) = (
866 usize::from(starts[band]),
867 usize::from(starts[band + 1]).min(576),
868 );
869 let scalefac = if band < SFB_LONG { scalefac[band] } else { 0 };
870 let scale = 1.0 / band_gain(gain, scalefac, block_type);
871 for i in from..to {
872 let value = (xr[i].abs() * scale).powf(0.75);
873 let magnitude = (value + 0.4054).min(MAX_QUANT as f32) as i32;
874 ix[i] = if xr[i] < 0.0 { -magnitude } else { magnitude };
875 }
876 }
877}
878
879/// Chooses the region split, the tables and the count1 boundary, and writes the
880/// spectrum. Returns the bit cost first so the rate loop can stop early.
881#[allow(clippy::type_complexity)]
882fn code_spectrum(
883 ix: &[i32],
884 block_type: u8,
885 sample_rate: u32,
886) -> (u32, u32, [u8; 3], u32, u32, bool, Vec<bool>) {
887 // Trailing zeros are not coded at all; before them, a run of values in
888 // -1..=1 is coded four at a time.
889 let mut rzero = 576;
890 while rzero > 0 && ix[rzero - 1] == 0 {
891 rzero -= 1;
892 }
893 let count1_end = (rzero.div_ceil(4) * 4).min(576);
894 let mut count1_start = count1_end;
895 while count1_start >= 4
896 && ix[count1_start - 4..count1_start]
897 .iter()
898 .all(|v| v.abs() <= 1)
899 {
900 count1_start -= 4;
901 }
902 let big_end = count1_start;
903
904 let starts = long_starts(sample_rate);
905 let short = block_type == 2;
906 // Region boundaries land on band edges. Splitting the big-value region in
907 // three roughly equal parts is what makes the three tables specialise;
908 // searching every legal split costs far more than it saves.
909 let (region0, region1, bounds) = if short {
910 let first = usize::from(short_starts(sample_rate)[3]) * 3;
911 (8u32, 12u32, [first.min(big_end), big_end, big_end])
912 } else {
913 let band_at = |target: usize| -> usize {
914 (0..21)
915 .min_by_key(|&b| usize::from(starts[b + 1]).abs_diff(target))
916 .unwrap_or(7)
917 };
918 let r0 = band_at(big_end / 3).min(15);
919 let r1 = band_at(big_end * 2 / 3).saturating_sub(r0 + 1).min(7);
920 let a = usize::from(starts[(r0 + 1).min(21)]).min(big_end);
921 let b = usize::from(starts[(r0 + r1 + 2).min(21)]).min(big_end);
922 (r0 as u32, r1 as u32, [a, b.max(a), big_end])
923 };
924
925 let mut tables = [0u8; 3];
926 let mut writer = BitWriter::new();
927 let mut from = 0usize;
928 for (region, to) in bounds.iter().enumerate() {
929 let to = (*to).min(big_end);
930 if to > from {
931 let select = best_table(ix, from, to);
932 tables[region] = select;
933 let table = huffman::big_table(usize::from(select)).expect("table exists");
934 let mut i = from;
935 while i + 1 < to {
936 huffman::write_pair(&mut writer, table, ix[i], ix[i + 1]);
937 i += 2;
938 }
939 }
940 from = to;
941 }
942 // count1: try both tables, keep the cheaper.
943 let quads: Vec<[i32; 4]> = (big_end..count1_end)
944 .step_by(4)
945 .filter(|i| i + 4 <= 576)
946 .map(|i| [ix[i], ix[i + 1], ix[i + 2], ix[i + 3]])
947 .collect();
948 let cost = |select: bool| -> u32 {
949 quads
950 .iter()
951 .map(|quad| huffman::quad_bits(select, *quad))
952 .sum()
953 };
954 let count1_select = cost(true) < cost(false);
955 for quad in &quads {
956 huffman::write_quad(&mut writer, count1_select, *quad);
957 }
958 let bit_len = writer.bit_len() as usize;
959 let bytes = writer.into_bytes();
960 let mut bits = Vec::with_capacity(bit_len);
961 for i in 0..bit_len {
962 bits.push((bytes[i / 8] >> (7 - i % 8)) & 1 == 1);
963 }
964 (
965 bits.len() as u32,
966 (big_end / 2) as u32,
967 tables,
968 region0,
969 region1,
970 count1_select,
971 bits,
972 )
973}
974
975/// Tables that can code a region whose largest magnitude is `max`, cheapest
976/// candidates first. Anything above 15 needs an escape-coded table, and the
977/// escape tables differ only in how many linbits they spend.
978fn candidates(max: u32) -> &'static [u8] {
979 match max {
980 0..=1 => &[1, 2, 3, 5, 6, 7, 8, 9],
981 2 => &[2, 3, 5, 6, 7, 8, 9, 10],
982 3 => &[5, 6, 7, 8, 9, 10, 11, 12],
983 4..=5 => &[7, 8, 9, 10, 11, 12, 13, 15],
984 6..=7 => &[10, 11, 12, 13, 15],
985 8..=15 => &[13, 15, 16, 24],
986 16..=16 => &[16, 17, 18, 19, 20, 21, 22, 23, 24],
987 17..=18 => &[17, 18, 19, 20, 21, 22, 23, 24, 25],
988 19..=30 => &[18, 19, 20, 21, 22, 23, 25, 26, 27],
989 31..=78 => &[20, 21, 22, 23, 26, 27, 28, 29],
990 79..=270 => &[21, 22, 23, 28, 29, 30, 31],
991 271..=1038 => &[22, 23, 30, 31],
992 _ => &[23, 31],
993 }
994}
995
996/// The cheapest table for one region.
997fn best_table(ix: &[i32], from: usize, to: usize) -> u8 {
998 let max = ix[from..to]
999 .iter()
1000 .map(|v| v.unsigned_abs())
1001 .max()
1002 .unwrap_or(0);
1003 let mut best = (u32::MAX, 0u8);
1004 for &select in candidates(max) {
1005 let Ok(table) = huffman::big_table(usize::from(select)) else {
1006 continue;
1007 };
1008 if let Some(cost) = table_cost(ix, from, to, table)
1009 && cost < best.0
1010 {
1011 best = (cost, select);
1012 }
1013 }
1014 if best.1 == 0 {
1015 // Nothing in the shortlist fits, which only a value above the coding
1016 // range can cause; fall back to the widest escape table.
1017 return 23;
1018 }
1019 best.1
1020}
1021
1022fn table_cost(ix: &[i32], from: usize, to: usize, table: Table) -> Option<u32> {
1023 let mut sum = 0;
1024 let mut i = from;
1025 while i + 1 < to {
1026 sum += huffman::pair_bits(table, ix[i].unsigned_abs(), ix[i + 1].unsigned_abs())?;
1027 i += 2;
1028 }
1029 Some(sum)
1030}
1031
1032/// The `scalefac_compress` index whose two lengths hold these scalefactors.
1033fn scalefac_compress(scalefac: &[u8; SFB_LONG]) -> (u32, u32, u32) {
1034 let bits_for = |slice: &[u8]| -> u32 {
1035 let max = slice.iter().copied().max().unwrap_or(0);
1036 (0..=4u32).find(|n| max < (1 << n)).unwrap_or(4)
1037 };
1038 let need1 = bits_for(&scalefac[..11]);
1039 let need2 = bits_for(&scalefac[11..]);
1040 let mut best = (u32::MAX, 0u32, 0u32, 0u32);
1041 for (index, (slen1, slen2)) in SLEN.iter().enumerate() {
1042 if *slen1 >= need1 && *slen2 >= need2 {
1043 let cost = slen1 * 11 + slen2 * 10;
1044 if cost < best.0 {
1045 best = (cost, *slen1, *slen2, index as u32);
1046 }
1047 }
1048 }
1049 (best.1, best.2, best.3)
1050}
1051
1052#[cfg(test)]
1053mod tests {
1054 use super::*;
1055
1056 #[test]
1057 fn bitrates_snap_to_legal_values() {
1058 assert_eq!(snap_bitrate(Version::Mpeg1, 128), 128);
1059 assert_eq!(snap_bitrate(Version::Mpeg1, 130), 128);
1060 assert_eq!(snap_bitrate(Version::Mpeg1, 1000), 320);
1061 assert_eq!(snap_bitrate(Version::Mpeg2, 128), 128);
1062 assert_eq!(snap_bitrate(Version::Mpeg2, 320), 160);
1063 }
1064
1065 #[test]
1066 fn unsupported_rates_are_refused_by_name() {
1067 let err = Mp3Encode::new(96000, 2, 128).unwrap_err();
1068 assert!(format!("{err}").contains("96000 Hz"), "{err}");
1069 }
1070
1071 /// The encoder's whole analysis chain against the decoder's whole
1072 /// synthesis chain, quantisation left out: what comes back is what went
1073 /// in, delayed by the filterbank.
1074 #[test]
1075 fn analysis_chain_round_trips_through_the_decoder() {
1076 use crate::filterbank::{Imdct, Synthesis, alias_reduce};
1077 let imdct = Imdct::default();
1078 let mut analysis = Analysis::default();
1079 let mut synthesis = Synthesis::default();
1080 let n = 32 * 32 * 24;
1081 let input: Vec<f32> = (0..n)
1082 .map(|i| {
1083 let t = i as f32;
1084 0.4 * (t * 0.05).sin() + 0.2 * (t * 0.31).cos()
1085 })
1086 .collect();
1087 let mut slots: Vec<[f32; 32]> = Vec::new();
1088 for chunk in input.chunks(32) {
1089 if let Some(slot) = analysis.push(chunk) {
1090 slots.push(slot);
1091 }
1092 }
1093 let granules = slots.len() / 18;
1094 let mut history = [[0.0f32; 32]; 18];
1095 let mut overlap = [[0.0f32; 18]; 32];
1096 let mut output: Vec<f32> = Vec::new();
1097 for g in 0..granules {
1098 let granule = &slots[g * 18..g * 18 + 18];
1099 let mut xr = vec![0.0f32; 576];
1100 for sb in 0..32 {
1101 let mut window = [0.0f32; 36];
1102 for t in 0..18 {
1103 let sign = if sb % 2 == 1 && t % 2 == 1 { -1.0 } else { 1.0 };
1104 window[t] = history[t][sb] * sign;
1105 window[18 + t] = granule[t][sb] * sign;
1106 }
1107 mdct_long(&window, 0, &mut xr[sb * 18..sb * 18 + 18]);
1108 }
1109 alias_expand(&mut xr, 32);
1110 history.copy_from_slice(granule);
1111 // decoder side
1112 alias_reduce(&mut xr, 32);
1113 let mut out_slots = [[0.0f32; 32]; 18];
1114 let mut block = [0.0f32; 36];
1115 for sb in 0..32 {
1116 imdct.long(&xr[sb * 18..sb * 18 + 18], 0, &mut block);
1117 for t in 0..18 {
1118 let mut sample = block[t] + overlap[sb][t];
1119 overlap[sb][t] = block[18 + t];
1120 if sb % 2 == 1 && t % 2 == 1 {
1121 sample = -sample;
1122 }
1123 out_slots[t][sb] = sample;
1124 }
1125 }
1126 let mut pcm = [0.0f32; 32];
1127 for slot in &out_slots {
1128 synthesis.slot(slot, &mut pcm);
1129 output.extend_from_slice(&pcm);
1130 }
1131 }
1132 // Find the delay, then check the reconstruction is faithful. The
1133 // comparison starts past the filterbank's ramp-up, which is silence
1134 // sliding into the window rather than anything the transform got wrong.
1135 let (from, len) = (4096usize, 8192usize);
1136 let mut best = (f64::MIN, 0usize);
1137 for delay in 0..output.len().min(2048) {
1138 if delay + from + len > output.len() || from + len > input.len() {
1139 break;
1140 }
1141 let (mut ab, mut aa, mut bb) = (0.0f64, 0.0f64, 0.0f64);
1142 for i in from..from + len {
1143 let (x, y) = (output[delay + i] as f64, input[i] as f64);
1144 ab += x * y;
1145 aa += x * x;
1146 bb += y * y;
1147 }
1148 let corr = ab / (aa * bb).sqrt().max(1e-30);
1149 if corr > best.0 {
1150 best = (corr, delay);
1151 }
1152 }
1153 assert!(
1154 best.0 > 0.99999,
1155 "analysis/synthesis correlation {:.6} at delay {}",
1156 best.0,
1157 best.1
1158 );
1159 }
1160
1161 /// The forward MDCT and the decoder's inverse are a reconstructing pair:
1162 /// two overlapped granules of a signal come back as themselves.
1163 #[test]
1164 fn mdct_round_trips_under_overlap_add() {
1165 use crate::filterbank::Imdct;
1166 let imdct = Imdct::default();
1167 let signal: Vec<f32> = (0..72)
1168 .map(|i| ((i as f32) * 0.37).sin() + 0.3 * ((i as f32) * 1.1).cos())
1169 .collect();
1170 let mut output = vec![0.0f32; 72];
1171 let mut previous = [0.0f32; 18];
1172 for granule in 0..3 {
1173 let mut input = [0.0f32; 36];
1174 for (i, slot) in input.iter_mut().enumerate() {
1175 let index = granule * 18 + i;
1176 if index < signal.len() {
1177 *slot = signal[index];
1178 }
1179 }
1180 let mut spectrum = [0.0f32; 18];
1181 mdct_long(&input, 0, &mut spectrum);
1182 let mut block = [0.0f32; 36];
1183 imdct.long(&spectrum, 0, &mut block);
1184 for t in 0..18 {
1185 let index = granule * 18 + t;
1186 if index < output.len() {
1187 output[index] = block[t] + previous[t];
1188 }
1189 }
1190 previous.copy_from_slice(&block[18..]);
1191 }
1192 // The first granule has no predecessor, so compare from the second.
1193 let mut worst = 0.0f32;
1194 for i in 18..54 {
1195 worst = worst.max((output[i] - signal[i]).abs());
1196 }
1197 println!("mdct round trip worst absolute error {worst:e}");
1198 for i in 18..54 {
1199 assert!(
1200 (output[i] - signal[i]).abs() < 1e-5,
1201 "sample {i}: {} vs {}",
1202 output[i],
1203 signal[i]
1204 );
1205 }
1206 }
1207}