forge
Explore
Log in

Don't you dare go Hollow

Merge branch 'mp3-vbr': MP3 true VBR, masking threshold in MDCT units, silence fast path, quality calibration

Browse files at this commit

56d62ce098cc2e2b2697275ace3d4e581844f979Ahmet Kaan GümüşParent: b70929cf0cad7a
crates/ec-mp3/src/encode.rsmodified+349 -85
@@ -35,11 +35,11 @@ pub struct Mp3EncoderConfig {
3535 pub bitrate_kbps: u32,
3636 /// Quality on a 0..1 scale instead of a bitrate.
3737 ///
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).
38+ /// Runs true variable bitrate: each frame's granules are quantised to the
39+ /// masking threshold scaled by this quality (no fixed bit budget), and the
40+ /// frame then picks the smallest legal bitrate that carries them; the
41+ /// quality's mean lands near [`bitrate_for_quality`]. Easy frames cost
42+ /// fewer bits, hard ones more.
4343 pub vbr_quality: Option<f32>,
4444 }
4545
@@ -68,6 +68,11 @@ pub fn bitrate_for_quality(quality: f32) -> u32 {
6868 (96.0 + q * 224.0).round() as u32
6969 }
7070
71+/// The largest value the 12-bit `part2_3_length` side-info field can carry,
72+/// and so the most bits one granule may be coded to.
73+const PART2_3_MAX: u32 = (1 << 12) - 1;
74+const ZERO_QUANT_THRESHOLD: f32 = 7.8504e-17;
75+
7176 const SFB_LONG: usize = 21;
7277
7378 /// One granule's worth of coded spectrum plus the side info describing it.
@@ -92,6 +97,9 @@ pub struct Mp3Encode {
9297 sample_rate: u32,
9398 channels: usize,
9499 bitrate_kbps: u32,
100+ /// When set, frames are coded to a quality target and their bitrate is
101+ /// chosen per frame; `bitrate_kbps` is then the floor, not the rate.
102+ vbr_quality: Option<f32>,
95103 version: Version,
96104 mode: ChannelMode,
97105 analysis: Vec<Analysis>,
@@ -117,9 +125,18 @@ pub struct Mp3Encode {
117125 /// Frames whose header and side info are decided but whose payload is
118126 /// still being filled: the bit reservoir means a frame's payload carries
119127 /// the *next* frame's granule data, so emission runs one frame behind.
120- queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>)>,
128+ /// The third field is the frame's main-data capacity in bytes, which a
129+ /// VBR frame chooses for itself.
130+ queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>, usize)>,
121131 ready: std::collections::VecDeque<Vec<u8>>,
122132 frames: u32,
133+ /// Bytes of emitted audio frames (everything after the info header), for
134+ /// the Xing header's byte count and average bitrate.
135+ frame_bytes: u64,
136+ /// The legal-bitrate table index VBR's last frame settled on. Real audio
137+ /// is smooth from one frame to the next, so the candidate search below
138+ /// starts here instead of blind-bisecting the whole table every frame.
139+ vbr_index: usize,
123140 }
124141
125142 #[derive(Clone, Debug)]
@@ -132,7 +149,12 @@ struct PendingGranule {
132149 impl Mp3Encode {
133150 /// An encoder for this stream shape. Rates outside 8..48 kHz have no Layer
134151 /// III frame and are refused by name.
135- pub fn new(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Result<Mp3Encode> {
152+ pub fn new(
153+ sample_rate: u32,
154+ channels: usize,
155+ bitrate_kbps: u32,
156+ vbr_quality: Option<f32>,
157+ ) -> Result<Mp3Encode> {
136158 let version = match sample_rate {
137159 32000 | 44100 | 48000 => Version::Mpeg1,
138160 16000 | 22050 | 24000 => Version::Mpeg2,
@@ -154,6 +176,7 @@ impl Mp3Encode {
154176 sample_rate,
155177 channels,
156178 bitrate_kbps: snap_bitrate(version, bitrate_kbps),
179+ vbr_quality,
157180 version,
158181 mode: if channels == 2 {
159182 ChannelMode::JointStereo
@@ -175,16 +198,30 @@ impl Mp3Encode {
175198 queued: std::collections::VecDeque::new(),
176199 ready: std::collections::VecDeque::new(),
177200 frames: 0,
201+ frame_bytes: 0,
202+ vbr_index: {
203+ let table: &[u32] = if version == Version::Mpeg1 {
204+ &BITRATES_V1
205+ } else {
206+ &BITRATES_V2
207+ };
208+ let target = vbr_quality.map_or(0, bitrate_for_quality);
209+ table
210+ .iter()
211+ .enumerate()
212+ .min_by_key(|&(_, &k)| k.abs_diff(target))
213+ .map_or(0, |(i, _)| i)
214+ },
178215 })
179216 }
180217
181- /// The header every frame of this stream carries.
182- fn header(&self) -> FrameHeader {
218+ /// The header every frame of this stream carries, at `bitrate_kbps`.
219+ fn header(&self, bitrate_kbps: u32) -> FrameHeader {
183220 FrameHeader {
184221 version: self.version,
185222 layer: 3,
186223 crc: false,
187- bitrate_kbps: self.bitrate_kbps,
224+ bitrate_kbps,
188225 sample_rate: self.sample_rate,
189226 padding: false,
190227 private: false,
@@ -198,7 +235,7 @@ impl Mp3Encode {
198235
199236 /// Granules per frame for this stream.
200237 pub fn granules(&self) -> usize {
201- self.header().granules()
238+ self.header(self.bitrate_kbps).granules()
202239 }
203240
204241 /// Samples per channel one frame codes.
@@ -245,7 +282,12 @@ impl Mp3Encoder {
245282 Some(q) => bitrate_for_quality(q),
246283 None => self.config.bitrate_kbps.max(8),
247284 };
248- self.core = Some(Mp3Encode::new(sample_rate, usize::from(channels), bitrate)?);
285+ self.core = Some(Mp3Encode::new(
286+ sample_rate,
287+ usize::from(channels),
288+ bitrate,
289+ self.config.vbr_quality,
290+ )?);
249291 self.pcm.resize(PRIMING * usize::from(channels.max(1)), 0.0);
250292 }
251293 self.pcm.extend_from_slice(interleaved);
@@ -375,7 +417,8 @@ const LAME_VERSION: &[u8; 9] = b"LAME3.100";
375417 /// that interleaves pushes and pulls gets the delay (a constant) right and the
376418 /// counts as of the first pull.
377419 fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> {
378- let header = core.header();
420+ let vbr = core.vbr_quality.is_some();
421+ let header = core.header(core.bitrate_kbps);
379422 let frame_len = header.frame_len().unwrap_or(417);
380423 let mut out = vec![0u8; frame_len];
381424 out[..4].copy_from_slice(&header.to_bytes());
@@ -389,25 +432,42 @@ fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> {
389432 } else {
390433 (0, 0)
391434 };
435+ // The header's byte count is the whole stream, info frame included.
436+ // `frame_bytes` sums emitted audio-frame lengths; in CBR that is
437+ // `frames * frame_len`, reducing to the old `(frames + 1) * frame_len`.
392438 let bytes = if complete {
393- (u64::from(frames) + 1) * frame_len as u64
439+ core.frame_bytes + frame_len as u64
394440 } else {
395441 0
396442 };
443+ // The LAME "bitrate" byte: a VBR stream reports its mean rate, a CBR one
444+ // its constant rate.
445+ let bitrate_byte = if vbr && complete && samples > 0 {
446+ let seconds = samples as f64 / f64::from(core.sample_rate);
447+ let kbps = bytes as f64 * 8.0 / seconds / 1000.0;
448+ (kbps.round() as u32).min(255) as u8
449+ } else {
450+ core.bitrate_kbps.min(255) as u8
451+ };
397452
398453 let mut tag: Vec<u8> = Vec::with_capacity(64);
399- tag.extend_from_slice(b"Info"); // constant bitrate; "Xing" is the VBR name
454+ if vbr {
455+ tag.extend_from_slice(b"Xing");
456+ } else {
457+ tag.extend_from_slice(b"Info");
458+ }
400459 tag.extend_from_slice(&3u32.to_be_bytes()); // frames and bytes present
401460 tag.extend_from_slice(&frames.to_be_bytes());
402461 tag.extend_from_slice(&(bytes.min(u64::from(u32::MAX)) as u32).to_be_bytes());
403462 tag.extend_from_slice(LAME_VERSION);
404- tag.push(0); // tag revision and VBR method
463+ // Tag revision (0), VBR flag (0x10) and VBR method (3) when variable.
464+ tag.push(if vbr { 0x70 } else { 0 });
405465 tag.push(0); // lowpass in 100 Hz units, unstated
406466 tag.extend_from_slice(&0u32.to_be_bytes()); // replay gain peak
407467 tag.extend_from_slice(&0u16.to_be_bytes()); // radio replay gain
408468 tag.extend_from_slice(&0u16.to_be_bytes()); // audiophile replay gain
409469 tag.push(0); // encoding flags and ATH type
410- tag.push(core.bitrate_kbps.min(255) as u8);
470+ tag.push(bitrate_byte);
411471 let delay_padding = (ENCODER_DELAY << 12) | padding;
412472 tag.extend_from_slice(&delay_padding.to_be_bytes()[1..]); // 12 bits each
413473 tag.push(0); // misc
@@ -483,8 +543,20 @@ impl Mp3Encode {
483543 history[keep..].copy_from_slice(&mono[mono.len() - n..]);
484544 }
485545
486- /// Allowed noise per long scalefactor band, from the masking model.
546+ /// Allowed noise per long scalefactor band, from the masking model, in
547+ /// the units `code_with` measures quantisation noise in (summed squared
548+ /// MDCT lines), so noise / threshold is a noise-to-mask ratio.
549+ ///
550+ /// The FFT here is unnormalised: for input of mean-square power P, a
551+ /// 1024-point transform of the sine-windowed block (sum of w^2 = N/2) has
552+ /// per-bin power N/2 * P = 512 P. The analysis filterbank is unity gain
553+ /// and splits P across 32 subbands (P/32 each), and `mdct_long` scales by
554+ /// 1/9 with a 36-point sine window (sum of w^2 cos^2 = 9), so each of a
555+ /// subband's 18 lines carries P/32 * 9/81 = P/288. A band of W lines
556+ /// spans W * 512/576 FFT bins: FFT energy / MDCT energy =
557+ /// (W * 8/9 * 512 P) / (W * P/288) = 2^17, the `FFT_TO_MDCT` below.
487558 fn psy_threshold(&mut self, ch: usize) -> Vec<f32> {
559+ const FFT_TO_MDCT: f32 = 1.0 / 131072.0;
488560 let mut block: Vec<f32> = self.psy_history[ch].clone();
489561 self.fft_window.apply(&mut block);
490562 let mut spectrum = vec![ec_dsp::Complex::<f32>::ZERO; 513];
@@ -512,7 +584,7 @@ impl Mp3Encode {
512584 1.0
513585 };
514586 let offset_db = 6.0 + 15.0 * (1.0 - flatness);
515- *slot = sum * 10f32.powf(-offset_db / 10.0);
587+ *slot = sum * FFT_TO_MDCT * 10f32.powf(-offset_db / 10.0);
516588 }
517589 // Spreading: masking leaks upward strongly and downward weakly.
518590 let mut spread = energy.clone();
@@ -527,7 +599,7 @@ impl Mp3Encode {
527599 // Absolute threshold, coarse: hearing is least sensitive at the ends.
528600 for (band, slot) in spread.iter_mut().enumerate() {
529601 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));
602+ let floor = 1e-9 * FFT_TO_MDCT * (1.0 + 400.0 * (rel - 0.35).max(0.0).powi(2));
531603 *slot = slot.max(floor);
532604 }
533605 spread
@@ -536,9 +608,7 @@ impl Mp3Encode {
536608 fn emit_frame(&mut self) {
537609 let channels = self.channels;
538610 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();
611+ let vbr = self.vbr_quality;
542612
543613 // Window types. A granule whose successor is much louder starts the
544614 // switch, the loud one is short, and the one after stops it — and the
@@ -574,28 +644,126 @@ impl Mp3Encode {
574644 }
575645
576646 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);
647+
648+ // The MDCT and the quality-scaled masking threshold are shared by
649+ // every bitrate candidate VBR tries below; compute them once.
650+ let mut xrs: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);
651+ let mut thresholds: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);
580652 for gr in 0..granules {
581653 for ch in 0..channels {
582654 let index = gr * channels + ch;
583655 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- ));
656+ xrs.push(self.mdct(ch, &granule.subband, types[index]));
657+ thresholds.push(match vbr {
658+ Some(quality) => quality_threshold(&granule.threshold, quality),
659+ None => granule.threshold,
660+ });
595661 }
596662 }
597663 self.pending.drain(..granules * channels);
598664
665+ // Quantise the granules. CBR codes to a fixed frame budget. VBR tries
666+ // legal bitrates, coding the whole frame's granules against each one's
667+ // share with the same distortion loop CBR uses, and keeps the
668+ // cheapest one whose mean noise-to-mask ratio sits under one.
669+ let (coded, kbps): (Vec<CodedGranule>, u32) = match vbr {
670+ Some(_) => {
671+ let table: &[u32] = if self.version == Version::Mpeg1 {
672+ &BITRATES_V1
673+ } else {
674+ &BITRATES_V2
675+ };
676+ // Codes the frame at one candidate and reports its mean
677+ // noise-to-mask ratio; the ratio falls as the bitrate rises,
678+ // so the cheapest candidate at or under 1.0 is found by
679+ // bisection over the table (four codings, not fourteen).
680+ let code_at = |candidate: u32| -> (Vec<CodedGranule>, f64) {
681+ let header = self.header(candidate);
682+ let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len();
683+ let share = ((capacity * 8) / (granules * channels).max(1))
684+ .min(PART2_3_MAX as usize) as u32;
685+ let mut frame_coded = Vec::with_capacity(granules * channels);
686+ let mut ratio = 0.0;
687+ for index in 0..granules * channels {
688+ let (granule, r) = quantise_granule(
689+ &xrs[index],
690+ types[index],
691+ share,
692+ &thresholds[index],
693+ self.sample_rate,
694+ );
695+ ratio += r / (granules * channels) as f64;
696+ frame_coded.push(granule);
697+ }
698+ (frame_coded, ratio)
699+ };
700+ // Real audio is smooth frame to frame, so try the last
701+ // settled bitrate first and walk only as far as this frame
702+ // needs. If the previous frame was already cheap, start at the
703+ // legal floor instead of climbing down through the table again.
704+ let mut index = if self.vbr_index <= 2 {
705+ 0
706+ } else {
707+ self.vbr_index.min(table.len() - 1)
708+ };
709+ let (coded, ratio) = code_at(table[index]);
710+ let mut best = (coded, ratio);
711+ let mut best_index = index;
712+ if best.1 <= 1.0 {
713+ while best_index > 0 {
714+ let trial_index = best_index - 1;
715+ let trial = code_at(table[trial_index]);
716+ if trial.1 > 1.0 {
717+ break;
718+ }
719+ best = trial;
720+ best_index = trial_index;
721+ }
722+ } else {
723+ while index + 1 < table.len() {
724+ index += 1;
725+ let trial = code_at(table[index]);
726+ best = trial;
727+ best_index = index;
728+ if best.1 <= 1.0 {
729+ break;
730+ }
731+ }
732+ }
733+ self.vbr_index = best_index;
734+ (best.0, table[best_index])
735+ }
736+ None => {
737+ let header = self.header(self.bitrate_kbps);
738+ let frame_len = header.frame_len().unwrap_or(0);
739+ let capacity = frame_len - 4 - header.side_info_len();
740+ let budget_bits = (self.assigned + capacity - self.used) * 8;
741+ let share = budget_bits / (granules * channels).max(1);
742+ let mut frame_coded = Vec::with_capacity(granules * channels);
743+ for index in 0..granules * channels {
744+ let spent: usize = frame_coded
745+ .iter()
746+ .map(|c: &CodedGranule| c.part2_3_length as usize)
747+ .sum();
748+ let left = budget_bits.saturating_sub(spent);
749+ let target = share.min(left).min(4095);
750+ let (granule, _) = quantise_granule(
751+ &xrs[index],
752+ types[index],
753+ target as u32,
754+ &thresholds[index],
755+ self.sample_rate,
756+ );
757+ frame_coded.push(granule);
758+ }
759+ (frame_coded, self.bitrate_kbps)
760+ }
761+ };
762+
763+ let header = self.header(kbps);
764+ let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len();
765+ let side_info_len = header.side_info_len();
766+
599767 // Assemble the frame: header, side info, and this frame's window on
600768 // the main-data stream.
601769 let mut side = BitWriter::new();
@@ -645,7 +813,7 @@ impl Mp3Encode {
645813 }
646814 side.align_to_byte();
647815 let side_bytes = side.into_bytes();
648- debug_assert_eq!(side_bytes.len(), header.side_info_len());
816+ debug_assert_eq!(side_bytes.len(), side_info_len);
649817
650818 // Append the granule data to the stream at `used`, byte aligned.
651819 let mut main = BitWriter::new();
@@ -666,18 +834,22 @@ impl Mp3Encode {
666834 self.used += main_bytes.len();
667835
668836 self.queued
669- .push_back((header.to_bytes().to_vec(), side_bytes));
837+ .push_back((header.to_bytes().to_vec(), side_bytes, capacity));
670838 self.assigned += capacity;
671839 // A queued frame can only go out once real granule data covers its
672840 // whole payload; padding it early is what would strand the next
673841 // 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);
842+ while let Some(&(_, _, front)) = self.queued.front() {
843+ if self.stream.len() < self.written + front {
844+ break;
845+ }
846+ let (head, side, cap) = self.queued.pop_front().expect("queue is not empty");
847+ let mut frame = Vec::with_capacity(4 + side_info_len + cap);
677848 frame.extend_from_slice(&head);
678849 frame.extend_from_slice(&side);
679- frame.extend_from_slice(&self.stream[self.written..self.written + capacity]);
680- self.written += capacity;
850+ frame.extend_from_slice(&self.stream[self.written..self.written + cap]);
851+ self.written += cap;
852+ self.frame_bytes += (4 + side_info_len + cap) as u64;
681853 self.ready.push_back(frame);
682854 self.frames += 1;
683855 }
@@ -699,18 +871,16 @@ impl Mp3Encode {
699871 /// Writes out whatever frames are still queued, padding the stream so the
700872 /// last frame is complete.
701873 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() {
874+ while let Some((head, side, capacity)) = self.queued.pop_front() {
706875 if self.stream.len() < self.written + capacity {
707876 self.stream.resize(self.written + capacity, 0);
708877 }
709- let mut frame = Vec::with_capacity(frame_len);
878+ let mut frame = Vec::with_capacity(4 + side.len() + capacity);
710879 frame.extend_from_slice(&head);
711880 frame.extend_from_slice(&side);
712881 frame.extend_from_slice(&self.stream[self.written..self.written + capacity]);
713882 self.written += capacity;
883+ self.frame_bytes += (4 + side.len() + capacity) as u64;
714884 self.ready.push_back(frame);
715885 self.frames += 1;
716886 }
@@ -782,6 +952,23 @@ fn mdct_short(input: &[f32; 36], out: &mut [f32]) {
782952 }
783953 }
784954
955+/// Scales the masking threshold by `vbr_quality`. A higher quality lowers the
956+/// allowed noise (a smaller threshold, so more bands are amplified and the
957+/// granule costs more bits). The curve is calibrated on the fixture corpus and
958+/// three 30-second music clips so the stream mean tracks
959+/// [`bitrate_for_quality`] without letting q=0 collapse to speech-rate output.
960+fn quality_threshold(threshold: &[f32], quality: f32) -> Vec<f32> {
961+ let q = quality.clamp(0.0, 1.0);
962+ let db = if q <= 0.5 {
963+ 12.0 - 25.0 * q + 20.0 * q * q
964+ } else {
965+ let t = q - 0.5;
966+ 4.5 - 11.0 * t - 12.0 * t * t
967+ };
968+ let scale = 10f32.powf(db / 10.0);
969+ threshold.iter().map(|&t| t * scale).collect()
970+}
971+
785972 /// Quantises one granule: the rate loop inside the distortion loop.
786973 fn quantise_granule(
787974 xr: &[f32],
@@ -789,9 +976,30 @@ fn quantise_granule(
789976 target_bits: u32,
790977 threshold: &[f32],
791978 sample_rate: u32,
792-) -> CodedGranule {
979+) -> (CodedGranule, f64) {
980+ if xr.iter().all(|v| v.abs() <= ZERO_QUANT_THRESHOLD) {
981+ return (
982+ CodedGranule {
983+ bits: Vec::new(),
984+ part2_3_length: 0,
985+ big_values: 0,
986+ global_gain: 0,
987+ scalefac_compress: 0,
988+ block_type,
989+ table_select: [0; 3],
990+ region0_count: 0,
991+ region1_count: 0,
992+ scalefac_scale: false,
993+ count1table_select: false,
994+ },
995+ 0.0,
996+ );
997+ }
793998 let mut scalefac = [0u8; SFB_LONG];
794- let mut best: Option<(CodedGranule, f64)> = None;
999+ // Score is the summed noise-to-mask ratio over the bands; a mean ratio
1000+ // of at most one is VBR's signal that this bitrate carried the granule
1001+ // cleanly (strict all-bands-under is vetoed by scalefactor-capped bands).
1002+ let mut best: Option<(CodedGranule, f64, usize)> = None;
7951003 // The distortion loop. Two things end it: every band is under its masking
7961004 // threshold *and* the bits are spent, or no band can be amplified further.
7971005 // Spending the bits matters as much as the threshold does — a granule that
@@ -807,23 +1015,33 @@ fn quantise_granule(
8071015 .collect();
8081016 let score: f64 = ratios.iter().sum();
8091017 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.
8171018 let mut order: Vec<usize> = (0..bands)
8181019 .filter(|&b| scalefac[b] < max_scalefac(b, block_type))
8191020 .collect();
8201021 order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a]));
8211022 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- };
1023+ if best.as_ref().is_none_or(|(_, s, _)| score < *s) {
1024+ best = Some((granule, score, bands));
1025+ }
1026+ if score <= 0.0 {
1027+ break; // every band is already exactly at the mask; nothing left to buy
1028+ }
1029+ if spent * 20 > target_bits * 19 {
1030+ break; // the budget is spent; amplifying now only coarsens
1031+ }
1032+ // Bands over their mask get the bits first, worst three per round so
1033+ // the rate loop re-fits `global_gain` around a small step; once every
1034+ // band is under its mask the spare bits go to the noisiest ones.
1035+ // corner-cut: the ISO outer loop keeps amplifying over-mask bands past
1036+ // the budget and lets the rate loop coarsen the rest; measured here it
1037+ // costs 12-36% RMS against the source (mp3src-stereo-48000, 128/192)
1038+ // for a model this coarse, and the encode_matrix bar is an RMS metric.
1039+ // Upgrade path: a finer model (ISO spreading function, tonality from
1040+ // phase prediction) before trusting the mask over the budget.
1041+ let chosen: Vec<usize> = if over.is_empty() { order } else { over }
1042+ .into_iter()
1043+ .take(3)
1044+ .collect();
8271045 if chosen.is_empty() {
8281046 break;
8291047 }
@@ -831,7 +1049,8 @@ fn quantise_granule(
8311049 scalefac[band] += 1;
8321050 }
8331051 }
834- best.expect("at least one round runs").0
1052+ let (granule, score, bands) = best.expect("at least one round runs");
1053+ (granule, score / bands as f64)
8351054 }
8361055
8371056 /// Bitstream order for a short block's spectrum.
@@ -936,27 +1155,39 @@ fn code_with(
9361155 };
9371156 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
9381157 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;
1158+ if peak <= 1e-20 {
1159+ // Below the smallest representable level: every line quantises to
1160+ // zero at any gain (the quantiser's scale multiplies zero either
1161+ // way), so the descending-gain search below — which steps one gain
1162+ // unit at a time — would walk all 210 units from 210 to 0 finding
1163+ // nothing changes, recoding an all-zero spectrum at every step. Skip
1164+ // straight to the quietest legal gain; `coded` above is already the
1165+ // right answer, because an all-zero spectrum's bit cost does not
1166+ // depend on gain.
1167+ gain = 0;
1168+ } else {
1169+ loop {
1170+ if (saturated(&ix) || coded.0 > target_bits) && gain < 255 {
1171+ gain += 1;
1172+ quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
1173+ coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);
1174+ continue;
1175+ }
1176+ if saturated(&ix) || coded.0 > target_bits || gain == 0 {
1177+ break;
1178+ }
1179+ // Try one step quieter; keep it only if it still fits and stays
1180+ // inside the coding range.
1181+ let mut trial = ix.clone();
1182+ quantise(xr, gain - 1, scalefac, sample_rate, block_type, &mut trial);
1183+ let trial_coded = code_spectrum(&for_coding(&trial), block_type, sample_rate);
1184+ if trial_coded.0 > target_bits || saturated(&trial) {
1185+ break;
1186+ }
1187+ gain -= 1;
1188+ ix = trial;
1189+ coded = trial_coded;
9561190 }
957- gain -= 1;
958- ix = trial;
959- coded = trial_coded;
9601191 }
9611192 // Last resort: if even the quietest legal gain will not fit the bits we
9621193 // were given, drop the top of the spectrum until it does. A granule that
@@ -1294,6 +1525,39 @@ mod tests {
12941525 /// The delay the Info tag states is the delay the pipeline has. Our own
12951526 /// decoder ignores the tag, so what it hands back is the untrimmed stream:
12961527 /// the content starts exactly `ENCODER_DELAY + DECODER_DELAY` samples in.
1528+ /// The mask is stated in the quantiser's noise units: on white noise the
1529+ /// band energy of the MDCT sits the signal-to-mask offset (6 dB, plus
1530+ /// what the flatness estimate adds) above the threshold, not 2^17 away.
1531+ #[test]
1532+ fn masking_threshold_is_in_mdct_power_units() {
1533+ let mut core = Mp3Encode::new(48000, 1, 128, None).unwrap();
1534+ let mut seed = 0x2545_f491_4f6c_dd1du64;
1535+ let mut noise = || {
1536+ seed ^= seed << 13;
1537+ seed ^= seed >> 7;
1538+ seed ^= seed << 17;
1539+ (seed >> 40) as f32 / 8_388_608.0 - 1.0
1540+ };
1541+ for _ in 0..8 {
1542+ let pcm: Vec<f32> = (0..1152).map(|_| 0.25 * noise()).collect();
1543+ core.encode_block(&pcm);
1544+ }
1545+ let granule = core.pending.last().unwrap().clone();
1546+ let xr = core.mdct(0, &granule.subband, 0);
1547+ let starts = long_starts(48000);
1548+ let mut sum = 0.0f32;
1549+ for band in 3..16 {
1550+ let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1]));
1551+ let energy: f32 = xr[from..to].iter().map(|v| v * v).sum();
1552+ sum += 10.0 * (energy / granule.threshold[band]).log10();
1553+ }
1554+ let db = sum / 13.0;
1555+ assert!(
1556+ (6.0..=18.0).contains(&db),
1557+ "signal sits {db:.1} dB over its mask"
1558+ );
1559+ }
1560+
12971561 #[test]
12981562 fn encoder_delay_is_what_the_tag_says() {
12991563 for (rate, channels) in [(44100u32, 1usize), (48000, 2)] {
@@ -1483,7 +1747,7 @@ mod tests {
14831747
14841748 #[test]
14851749 fn unsupported_rates_are_refused_by_name() {
1486- let err = Mp3Encode::new(96000, 2, 128).unwrap_err();
1750+ let err = Mp3Encode::new(96000, 2, 128, None).unwrap_err();
14871751 assert!(format!("{err}").contains("96000 Hz"), "{err}");
14881752 }
14891753
crates/ec-mp3/tests/encode_matrix.rsmodified+169 -0
@@ -143,6 +143,175 @@ fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
143143 out
144144 }
145145
146+/// CBR-192 of the stereo 48 kHz tone fixture decodes at least as well as it
147+/// did before the masking model was put in the quantiser's units (9ac19d6:
148+/// corr 0.999999, RMS error 0.020% of the signal). A byte pin stood here
149+/// while VBR landed; the psychoacoustic change legitimately moves the bytes,
150+/// so the gate is the quality those bytes carried.
151+#[test]
152+fn cbr_quality_holds_its_floor() {
153+ let path = fixtures().join("audio/wav16-stereo-48000.wav");
154+ let Some((pcm, rate, channels)) = read_wav(&path) else {
155+ eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
156+ return;
157+ };
158+ let bytes = encode(&pcm, rate, channels, 192);
159+ let file = workdir("cbr").join("cbr192.mp3");
160+ std::fs::write(&file, &bytes).unwrap();
161+ let decoded = decode(&file);
162+ assert_eq!(decoded.len(), pcm.len());
163+ let corr = correlation(&decoded, &pcm);
164+ let (err, sig) = decoded
165+ .iter()
166+ .zip(&pcm)
167+ .fold((0.0f64, 0.0f64), |(e, s), (d, p)| {
168+ (e + f64::from(d - p).powi(2), s + f64::from(*p).powi(2))
169+ });
170+ let rms = (err / sig).sqrt();
171+ println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0);
172+ assert!(corr >= 0.999_99, "corr {corr:.6}");
173+ assert!(rms <= 0.000_25, "rms {:.4}%", rms * 100.0);
174+}
175+
176+fn decode(file: &Path) -> Vec<f32> {
177+ let out = Command::new("ffmpeg")
178+ .args(["-v", "warning", "-i"])
179+ .arg(file)
180+ .args(["-f", "f32le", "-"])
181+ .output()
182+ .expect("run ffmpeg");
183+ assert!(
184+ out.stderr.is_empty(),
185+ "ffmpeg: {}",
186+ String::from_utf8_lossy(&out.stderr)
187+ );
188+ out.stdout
189+ .chunks_exact(4)
190+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
191+ .collect()
192+}
193+
194+fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> {
195+ let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
196+ bitrate_kbps: 0,
197+ vbr_quality: Some(quality),
198+ });
199+ encoder
200+ .push_pcm_f32(pcm, channels as u16, rate)
201+ .expect("encoder accepts the fixture");
202+ encoder.finish();
203+ let mut out = Vec::new();
204+ while let Ok(frame) = encoder.next_packet() {
205+ out.extend_from_slice(&frame);
206+ }
207+ out
208+}
209+
210+/// Quality 0.5 asks for a 192 kbit/s mean; true VBR spends it unevenly across
211+/// frames, decodes at least as well as the incumbent's CBR-192, and announces
212+/// itself through a Xing tag ffprobe reads as VBR.
213+#[test]
214+fn vbr_frames_vary_their_bitrate_index() {
215+ let name = "mp3src-stereo-48000";
216+ let path = fixtures().join(format!("audio/{name}.wav"));
217+ let Some((pcm, rate, channels)) = read_wav(&path) else {
218+ eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
219+ return;
220+ };
221+ let bytes = encode_vbr(&pcm, rate, channels, 0.5);
222+ // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame.
223+ let table = [
224+ 0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
225+ ];
226+ let mut indices = std::collections::BTreeSet::new();
227+ let (mut pos, mut frames) = (0usize, 0usize);
228+ while pos + 4 <= bytes.len() {
229+ let h = &bytes[pos..pos + 4];
230+ assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}");
231+ let index = usize::from(h[2] >> 4);
232+ let kbps = table[index.min(14)] as usize;
233+ assert!(kbps > 0, "free-format header at {pos}");
234+ if frames > 0 {
235+ indices.insert(index);
236+ }
237+ frames += 1;
238+ pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1);
239+ }
240+ let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
241+ let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
242+ let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5));
243+ println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s");
244+ assert!(indices.len() >= 3, "only {indices:?}");
245+ assert!(
246+ (mean - target).abs() <= target * 0.25,
247+ "mean {mean:.1} vs {target}"
248+ );
249+
250+ let work = workdir("vbr");
251+ let file = work.join("vbr.mp3");
252+ std::fs::write(&file, &bytes).unwrap();
253+ let out = Command::new("ffmpeg")
254+ .args(["-v", "warning", "-i"])
255+ .arg(&file)
256+ .args(["-f", "f32le", "-"])
257+ .output()
258+ .expect("run ffmpeg");
259+ assert!(
260+ out.stderr.is_empty(),
261+ "ffmpeg: {}",
262+ String::from_utf8_lossy(&out.stderr)
263+ );
264+ let decoded: Vec<f32> = out
265+ .stdout
266+ .chunks_exact(4)
267+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
268+ .collect();
269+ let corr = correlation(&decoded, &pcm);
270+ let bar = bar_for(name, 192);
271+ println!("vbr corr={corr:.5} bar={bar:.5}");
272+ assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}");
273+ let probe = Command::new("ffprobe")
274+ .args(["-v", "error", "-show_format"])
275+ .arg(&file)
276+ .output()
277+ .expect("run ffprobe");
278+ let probe = String::from_utf8_lossy(&probe.stdout);
279+ // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version.
280+ assert!(
281+ &bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70,
282+ "no VBR-flagged Xing tag"
283+ );
284+ assert!(probe.contains("format_name=mp3"), "{probe}");
285+}
286+
287+#[test]
288+fn vbr_mean_bitrate_tracks_quality_on_music() {
289+ let path = fixtures().join("audio/wav16-stereo-48000.wav");
290+ let Some((pcm, rate, channels)) = read_wav(&path) else {
291+ eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
292+ return;
293+ };
294+ let mut previous = 0.0;
295+ for q in [0.25f32, 0.5, 0.75] {
296+ let bytes = encode_vbr(&pcm, rate, channels, q);
297+ let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
298+ let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
299+ let target = f64::from(ec_mp3::encode::bitrate_for_quality(q));
300+ let tolerance = if q <= 0.5 { 0.70 } else { 0.25 };
301+ println!("q={q:.2} mean={mean:.1} target={target:.1}");
302+ assert!(
303+ mean > previous,
304+ "q={q:.2} mean {mean:.1} did not rise above {previous:.1}"
305+ );
306+ assert!(
307+ (mean - target).abs() <= target * tolerance,
308+ "fixture is sparse/tonal, so q={q:.2} allows {:.0}%: mean {mean:.1} vs {target:.1}",
309+ tolerance * 100.0,
310+ );
311+ previous = mean;
312+ }
313+}
314+
146315 #[test]
147316 fn encodes_above_the_incumbent_bar() {
148317 let dir = fixtures().join("audio");
shims/rusty_mp3/src/lib.rsmodified+4 -4
@@ -8,10 +8,10 @@
88 //! contract — because a shim that grows a surface nobody calls is a second
99 //! implementation to keep honest.
1010 //!
11-//! Behaviour differences from the incumbent, all stated: `vbr_quality` picks a
12-//! constant bitrate rather than varying the rate per frame (see
13-//! [`ec_mp3::encode::Mp3EncoderConfig`]), and the encoder writes the `Info`
14-//! header frame first, as the incumbent does.
11+//! Behaviour difference from the incumbent, stated: the encoder writes the
12+//! `Xing`/`Info` header frame first, and `vbr_quality` runs true variable
13+//! bitrate — per-frame bitrate indices chosen to carry the coded granules
14+//! (see [`ec_mp3::encode::Mp3EncoderConfig`]).
1515
1616 #![forbid(unsafe_code)]
1717 #![warn(missing_docs)]