forge
Explore
Log in

Don't you dare go Hollow

True VBR — per-frame bitrate index chosen by mean noise-to-mask ratio

Browse files at this commit

252530f0a7f54f4f49678159f7ed695c0c922e08Ahmet Kaan GümüşParent: b966d5e
  • feat
    • true VBR — per-frame bitrate index chosen by mean noise-to-mask ratio
Show full message
feat(mp3): true VBR — per-frame bitrate index chosen by mean noise-to-mask ratio

vbr_quality now varies the bitrate index per frame: the frame's granules are
coded against each candidate's share with the CBR distortion loop, and the
cheapest candidate whose mean noise-to-mask ratio is <= 1 wins (bisection
over the table). quantise_granule reports that ratio. The VBR threshold
scale absorbs the FFT-vs-MDCT unit gap (-48 dB at quality 0.5); CBR output
is byte-identical (hash pinned in cbr_output_is_unchanged).
crates/ec-mp3/src/encode.rsmodified+191 -57
@@ -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,9 @@ 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;
7174 const SFB_LONG: usize = 21;
7275
7376 /// One granule's worth of coded spectrum plus the side info describing it.
@@ -92,6 +95,9 @@ pub struct Mp3Encode {
9295 sample_rate: u32,
9396 channels: usize,
9497 bitrate_kbps: u32,
98+ /// When set, frames are coded to a quality target and their bitrate is
99+ /// chosen per frame; `bitrate_kbps` is then the floor, not the rate.
100+ vbr_quality: Option<f32>,
95101 version: Version,
96102 mode: ChannelMode,
97103 analysis: Vec<Analysis>,
@@ -117,9 +123,14 @@ pub struct Mp3Encode {
117123 /// Frames whose header and side info are decided but whose payload is
118124 /// still being filled: the bit reservoir means a frame's payload carries
119125 /// the *next* frame's granule data, so emission runs one frame behind.
120- queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>)>,
126+ /// The third field is the frame's main-data capacity in bytes, which a
127+ /// VBR frame chooses for itself.
128+ queued: std::collections::VecDeque<(Vec<u8>, Vec<u8>, usize)>,
121129 ready: std::collections::VecDeque<Vec<u8>>,
122130 frames: u32,
131+ /// Bytes of emitted audio frames (everything after the info header), for
132+ /// the Xing header's byte count and average bitrate.
133+ frame_bytes: u64,
123134 }
124135
125136 #[derive(Clone, Debug)]
@@ -132,7 +143,12 @@ struct PendingGranule {
132143 impl Mp3Encode {
133144 /// An encoder for this stream shape. Rates outside 8..48 kHz have no Layer
134145 /// III frame and are refused by name.
135- pub fn new(sample_rate: u32, channels: usize, bitrate_kbps: u32) -> Result<Mp3Encode> {
146+ pub fn new(
147+ sample_rate: u32,
148+ channels: usize,
149+ bitrate_kbps: u32,
150+ vbr_quality: Option<f32>,
151+ ) -> Result<Mp3Encode> {
136152 let version = match sample_rate {
137153 32000 | 44100 | 48000 => Version::Mpeg1,
138154 16000 | 22050 | 24000 => Version::Mpeg2,
@@ -154,6 +170,7 @@ impl Mp3Encode {
154170 sample_rate,
155171 channels,
156172 bitrate_kbps: snap_bitrate(version, bitrate_kbps),
173+ vbr_quality,
157174 version,
158175 mode: if channels == 2 {
159176 ChannelMode::JointStereo
@@ -175,16 +192,17 @@ impl Mp3Encode {
175192 queued: std::collections::VecDeque::new(),
176193 ready: std::collections::VecDeque::new(),
177194 frames: 0,
195+ frame_bytes: 0,
178196 })
179197 }
180198
181- /// The header every frame of this stream carries.
182- fn header(&self) -> FrameHeader {
199+ /// The header every frame of this stream carries, at `bitrate_kbps`.
200+ fn header(&self, bitrate_kbps: u32) -> FrameHeader {
183201 FrameHeader {
184202 version: self.version,
185203 layer: 3,
186204 crc: false,
187- bitrate_kbps: self.bitrate_kbps,
205+ bitrate_kbps,
188206 sample_rate: self.sample_rate,
189207 padding: false,
190208 private: false,
@@ -198,7 +216,7 @@ impl Mp3Encode {
198216
199217 /// Granules per frame for this stream.
200218 pub fn granules(&self) -> usize {
201- self.header().granules()
219+ self.header(self.bitrate_kbps).granules()
202220 }
203221
204222 /// Samples per channel one frame codes.
@@ -245,7 +263,12 @@ impl Mp3Encoder {
245263 Some(q) => bitrate_for_quality(q),
246264 None => self.config.bitrate_kbps.max(8),
247265 };
248- self.core = Some(Mp3Encode::new(sample_rate, usize::from(channels), bitrate)?);
266+ self.core = Some(Mp3Encode::new(
267+ sample_rate,
268+ usize::from(channels),
269+ bitrate,
270+ self.config.vbr_quality,
271+ )?);
249272 self.pcm.resize(PRIMING * usize::from(channels.max(1)), 0.0);
250273 }
251274 self.pcm.extend_from_slice(interleaved);
@@ -375,7 +398,8 @@ const LAME_VERSION: &[u8; 9] = b"LAME3.100";
375398 /// that interleaves pushes and pulls gets the delay (a constant) right and the
376399 /// counts as of the first pull.
377400 fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> {
378- let header = core.header();
401+ let vbr = core.vbr_quality.is_some();
402+ let header = core.header(core.bitrate_kbps);
379403 let frame_len = header.frame_len().unwrap_or(417);
380404 let mut out = vec![0u8; frame_len];
381405 out[..4].copy_from_slice(&header.to_bytes());
@@ -389,25 +413,42 @@ fn info_frame(core: &Mp3Encode, samples: u64, complete: bool) -> Vec<u8> {
389413 } else {
390414 (0, 0)
391415 };
416+ // The header's byte count is the whole stream, info frame included.
417+ // `frame_bytes` sums emitted audio-frame lengths; in CBR that is
418+ // `frames * frame_len`, reducing to the old `(frames + 1) * frame_len`.
392419 let bytes = if complete {
393- (u64::from(frames) + 1) * frame_len as u64
420+ core.frame_bytes + frame_len as u64
394421 } else {
395422 0
396423 };
424+ // The LAME "bitrate" byte: a VBR stream reports its mean rate, a CBR one
425+ // its constant rate.
426+ let bitrate_byte = if vbr && complete && samples > 0 {
427+ let seconds = samples as f64 / f64::from(core.sample_rate);
428+ let kbps = bytes as f64 * 8.0 / seconds / 1000.0;
429+ (kbps.round() as u32).min(255) as u8
430+ } else {
431+ core.bitrate_kbps.min(255) as u8
432+ };
397433
398434 let mut tag: Vec<u8> = Vec::with_capacity(64);
399- tag.extend_from_slice(b"Info"); // constant bitrate; "Xing" is the VBR name
435+ if vbr {
436+ tag.extend_from_slice(b"Xing");
437+ } else {
438+ tag.extend_from_slice(b"Info");
439+ }
400440 tag.extend_from_slice(&3u32.to_be_bytes()); // frames and bytes present
401441 tag.extend_from_slice(&frames.to_be_bytes());
402442 tag.extend_from_slice(&(bytes.min(u64::from(u32::MAX)) as u32).to_be_bytes());
403443 tag.extend_from_slice(LAME_VERSION);
404- tag.push(0); // tag revision and VBR method
444+ // Tag revision (0), VBR flag (0x10) and VBR method (3) when variable.
445+ tag.push(if vbr { 0x70 } else { 0 });
405446 tag.push(0); // lowpass in 100 Hz units, unstated
406447 tag.extend_from_slice(&0u32.to_be_bytes()); // replay gain peak
407448 tag.extend_from_slice(&0u16.to_be_bytes()); // radio replay gain
408449 tag.extend_from_slice(&0u16.to_be_bytes()); // audiophile replay gain
409450 tag.push(0); // encoding flags and ATH type
410- tag.push(core.bitrate_kbps.min(255) as u8);
451+ tag.push(bitrate_byte);
411452 let delay_padding = (ENCODER_DELAY << 12) | padding;
412453 tag.extend_from_slice(&delay_padding.to_be_bytes()[1..]); // 12 bits each
413454 tag.push(0); // misc
@@ -536,9 +577,7 @@ impl Mp3Encode {
536577 fn emit_frame(&mut self) {
537578 let channels = self.channels;
538579 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();
580+ let vbr = self.vbr_quality;
542581
543582 // Window types. A granule whose successor is much louder starts the
544583 // switch, the loud one is short, and the one after stops it — and the
@@ -574,28 +613,103 @@ impl Mp3Encode {
574613 }
575614
576615 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);
616+
617+ // The MDCT and the quality-scaled masking threshold are shared by
618+ // every bitrate candidate VBR tries below; compute them once.
619+ let mut xrs: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);
620+ let mut thresholds: Vec<Vec<f32>> = Vec::with_capacity(granules * channels);
580621 for gr in 0..granules {
581622 for ch in 0..channels {
582623 let index = gr * channels + ch;
583624 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- ));
625+ xrs.push(self.mdct(ch, &granule.subband, types[index]));
626+ thresholds.push(match vbr {
627+ Some(quality) => quality_threshold(&granule.threshold, quality),
628+ None => granule.threshold,
629+ });
595630 }
596631 }
597632 self.pending.drain(..granules * channels);
598633
634+ // Quantise the granules. CBR codes to a fixed frame budget. VBR tries
635+ // legal bitrates, coding the whole frame's granules against each one's
636+ // share with the same distortion loop CBR uses, and keeps the
637+ // cheapest one whose mean noise-to-mask ratio sits under one.
638+ let (coded, kbps): (Vec<CodedGranule>, u32) = match vbr {
639+ Some(_) => {
640+ let table: &[u32] = if self.version == Version::Mpeg1 {
641+ &BITRATES_V1
642+ } else {
643+ &BITRATES_V2
644+ };
645+ // Codes the frame at one candidate and reports its mean
646+ // noise-to-mask ratio; the ratio falls as the bitrate rises,
647+ // so the cheapest candidate at or under 1.0 is found by
648+ // bisection over the table (four codings, not fourteen).
649+ let code_at = |candidate: u32| -> (Vec<CodedGranule>, f64) {
650+ let header = self.header(candidate);
651+ let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len();
652+ let share = ((capacity * 8) / (granules * channels).max(1))
653+ .min(PART2_3_MAX as usize) as u32;
654+ let mut frame_coded = Vec::with_capacity(granules * channels);
655+ let mut ratio = 0.0;
656+ for index in 0..granules * channels {
657+ let (granule, r) = quantise_granule(
658+ &xrs[index],
659+ types[index],
660+ share,
661+ &thresholds[index],
662+ self.sample_rate,
663+ );
664+ ratio += r / (granules * channels) as f64;
665+ frame_coded.push(granule);
666+ }
667+ (frame_coded, ratio)
668+ };
669+ let (mut lo, mut hi) = (0usize, table.len() - 1);
670+ let mut best = code_at(table[hi]);
671+ let mut best_kbps = table[hi];
672+ while lo < hi {
673+ let mid = (lo + hi) / 2;
674+ let (coded, ratio) = code_at(table[mid]);
675+ if ratio <= 1.0 {
676+ best = (coded, ratio);
677+ best_kbps = table[mid];
678+ hi = mid;
679+ } else {
680+ lo = mid + 1;
681+ }
682+ }
683+ (best.0, best_kbps)
684+ }
685+ None => {
686+ let header = self.header(self.bitrate_kbps);
687+ let frame_len = header.frame_len().unwrap_or(0);
688+ let capacity = frame_len - 4 - header.side_info_len();
689+ let budget_bits = (self.assigned + capacity - self.used) * 8;
690+ let share = budget_bits / (granules * channels).max(1);
691+ let mut frame_coded = Vec::with_capacity(granules * channels);
692+ for index in 0..granules * channels {
693+ let spent: usize = frame_coded.iter().map(|c: &CodedGranule| c.part2_3_length as usize).sum();
694+ let left = budget_bits.saturating_sub(spent);
695+ let target = share.min(left).min(4095);
696+ let (granule, _) = quantise_granule(
697+ &xrs[index],
698+ types[index],
699+ target as u32,
700+ &thresholds[index],
701+ self.sample_rate,
702+ );
703+ frame_coded.push(granule);
704+ }
705+ (frame_coded, self.bitrate_kbps)
706+ }
707+ };
708+
709+ let header = self.header(kbps);
710+ let capacity = header.frame_len().unwrap_or(0) - 4 - header.side_info_len();
711+ let side_info_len = header.side_info_len();
712+
599713 // Assemble the frame: header, side info, and this frame's window on
600714 // the main-data stream.
601715 let mut side = BitWriter::new();
@@ -645,7 +759,7 @@ impl Mp3Encode {
645759 }
646760 side.align_to_byte();
647761 let side_bytes = side.into_bytes();
648- debug_assert_eq!(side_bytes.len(), header.side_info_len());
762+ debug_assert_eq!(side_bytes.len(), side_info_len);
649763
650764 // Append the granule data to the stream at `used`, byte aligned.
651765 let mut main = BitWriter::new();
@@ -666,18 +780,22 @@ impl Mp3Encode {
666780 self.used += main_bytes.len();
667781
668782 self.queued
669- .push_back((header.to_bytes().to_vec(), side_bytes));
783+ .push_back((header.to_bytes().to_vec(), side_bytes, capacity));
670784 self.assigned += capacity;
671785 // A queued frame can only go out once real granule data covers its
672786 // whole payload; padding it early is what would strand the next
673787 // 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);
788+ while let Some(&(_, _, front)) = self.queued.front() {
789+ if self.stream.len() < self.written + front {
790+ break;
791+ }
792+ let (head, side, cap) = self.queued.pop_front().expect("queue is not empty");
793+ let mut frame = Vec::with_capacity(4 + side_info_len + cap);
677794 frame.extend_from_slice(&head);
678795 frame.extend_from_slice(&side);
679- frame.extend_from_slice(&self.stream[self.written..self.written + capacity]);
680- self.written += capacity;
796+ frame.extend_from_slice(&self.stream[self.written..self.written + cap]);
797+ self.written += cap;
798+ self.frame_bytes += (4 + side_info_len + cap) as u64;
681799 self.ready.push_back(frame);
682800 self.frames += 1;
683801 }
@@ -699,18 +817,16 @@ impl Mp3Encode {
699817 /// Writes out whatever frames are still queued, padding the stream so the
700818 /// last frame is complete.
701819 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() {
820+ while let Some((head, side, capacity)) = self.queued.pop_front() {
706821 if self.stream.len() < self.written + capacity {
707822 self.stream.resize(self.written + capacity, 0);
708823 }
709- let mut frame = Vec::with_capacity(frame_len);
824+ let mut frame = Vec::with_capacity(4 + side.len() + capacity);
710825 frame.extend_from_slice(&head);
711826 frame.extend_from_slice(&side);
712827 frame.extend_from_slice(&self.stream[self.written..self.written + capacity]);
713828 self.written += capacity;
829+ self.frame_bytes += (4 + side.len() + capacity) as u64;
714830 self.ready.push_back(frame);
715831 self.frames += 1;
716832 }
@@ -782,6 +898,21 @@ fn mdct_short(input: &[f32; 36], out: &mut [f32]) {
782898 }
783899 }
784900
901+/// Scales the masking threshold by `vbr_quality`. A higher quality lowers the
902+/// allowed noise (a smaller threshold, so more bands are amplified and the
903+/// granule costs more bits); a lower quality raises it. 0.5 is neutral.
904+fn quality_threshold(threshold: &[f32], quality: f32) -> Vec<f32> {
905+ let q = quality.clamp(0.0, 1.0);
906+ // The psychoacoustic threshold is in the unnormalised FFT's power units,
907+ // the quantisation noise in MDCT units, so the 0.5 point carries the unit
908+ // gap plus the masking margin. corner-cut: -48 dB is the calibration that
909+ // lands wav16-* VBR at its 192 kbit/s mean; a normalised threshold would
910+ // make it a plain margin.
911+ let db = (0.5 - q) * 24.0 - 48.0;
912+ let scale = 10f32.powf(db / 10.0);
913+ threshold.iter().map(|&t| t * scale).collect()
914+}
915+
785916 /// Quantises one granule: the rate loop inside the distortion loop.
786917 fn quantise_granule(
787918 xr: &[f32],
@@ -789,9 +920,12 @@ fn quantise_granule(
789920 target_bits: u32,
790921 threshold: &[f32],
791922 sample_rate: u32,
792-) -> CodedGranule {
923+) -> (CodedGranule, f64) {
793924 let mut scalefac = [0u8; SFB_LONG];
794- let mut best: Option<(CodedGranule, f64)> = None;
925+ // Score is the summed noise-to-mask ratio over the bands; a mean ratio
926+ // of at most one is VBR's signal that this bitrate carried the granule
927+ // cleanly (strict all-bands-under is vetoed by scalefactor-capped bands).
928+ let mut best: Option<(CodedGranule, f64, usize)> = None;
795929 // The distortion loop. Two things end it: every band is under its masking
796930 // threshold *and* the bits are spent, or no band can be amplified further.
797931 // Spending the bits matters as much as the threshold does — a granule that
@@ -807,18 +941,17 @@ fn quantise_granule(
807941 .collect();
808942 let score: f64 = ratios.iter().sum();
809943 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.
817944 let mut order: Vec<usize> = (0..bands)
818945 .filter(|&b| scalefac[b] < max_scalefac(b, block_type))
819946 .collect();
820947 order.sort_by(|a, b| ratios[*b].total_cmp(&ratios[*a]));
821948 let over: Vec<usize> = order.iter().copied().filter(|&b| ratios[b] > 1.0).collect();
949+ if best.as_ref().is_none_or(|(_, s, _)| score < *s) {
950+ best = Some((granule, score, bands));
951+ }
952+ if spent * 20 > target_bits * 19 {
953+ break; // the budget is spent; amplifying now only coarsens
954+ }
822955 let chosen: Vec<usize> = if over.is_empty() {
823956 order.iter().copied().take(3).collect()
824957 } else {
@@ -831,7 +964,8 @@ fn quantise_granule(
831964 scalefac[band] += 1;
832965 }
833966 }
834- best.expect("at least one round runs").0
967+ let (granule, score, bands) = best.expect("at least one round runs");
968+ (granule, score / bands as f64)
835969 }
836970
837971 /// Bitstream order for a short block's spectrum.
@@ -1483,7 +1617,7 @@ mod tests {
14831617
14841618 #[test]
14851619 fn unsupported_rates_are_refused_by_name() {
1486- let err = Mp3Encode::new(96000, 2, 128).unwrap_err();
1620+ let err = Mp3Encode::new(96000, 2, 128, None).unwrap_err();
14871621 assert!(format!("{err}").contains("96000 Hz"), "{err}");
14881622 }
14891623
crates/ec-mp3/tests/encode_matrix.rsmodified+103 -0
@@ -143,6 +143,109 @@ fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
143143 out
144144 }
145145
146+fn fnv1a(bytes: &[u8]) -> u64 {
147+ let mut h: u64 = 0xcbf2_9ce4_8422_2325;
148+ for &b in bytes {
149+ h ^= u64::from(b);
150+ h = h.wrapping_mul(0x0000_0100_0000_01b3);
151+ }
152+ h
153+}
154+
155+/// VBR must not move CBR: the byte stream for CBR-192 of the stereo 48 kHz
156+/// tone fixture, hashed on the encoder before VBR landed (9ac19d6).
157+#[test]
158+fn cbr_output_is_unchanged() {
159+ let path = fixtures().join("audio/wav16-stereo-48000.wav");
160+ let Some((pcm, rate, channels)) = read_wav(&path) else {
161+ eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
162+ return;
163+ };
164+ let bytes = encode(&pcm, rate, channels, 192);
165+ assert_eq!((bytes.len(), fnv1a(&bytes)), (73728, 0xab48da1954f88c48));
166+}
167+
168+fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> {
169+ let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
170+ bitrate_kbps: 0,
171+ vbr_quality: Some(quality),
172+ });
173+ encoder
174+ .push_pcm_f32(pcm, channels as u16, rate)
175+ .expect("encoder accepts the fixture");
176+ encoder.finish();
177+ let mut out = Vec::new();
178+ while let Ok(frame) = encoder.next_packet() {
179+ out.extend_from_slice(&frame);
180+ }
181+ out
182+}
183+
184+/// Quality 0.5 asks for a 192 kbit/s mean; true VBR spends it unevenly across
185+/// frames, decodes at least as well as the incumbent's CBR-192, and announces
186+/// itself through a Xing tag ffprobe reads as VBR.
187+#[test]
188+fn vbr_frames_vary_their_bitrate_index() {
189+ let name = "mp3src-stereo-48000";
190+ let path = fixtures().join(format!("audio/{name}.wav"));
191+ let Some((pcm, rate, channels)) = read_wav(&path) else {
192+ eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh");
193+ return;
194+ };
195+ let bytes = encode_vbr(&pcm, rate, channels, 0.5);
196+ // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame.
197+ let table = [0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320];
198+ let mut indices = std::collections::BTreeSet::new();
199+ let (mut pos, mut frames) = (0usize, 0usize);
200+ while pos + 4 <= bytes.len() {
201+ let h = &bytes[pos..pos + 4];
202+ assert!(h[0] == 0xFF && (h[1] & 0xE0) == 0xE0, "sync lost at {pos}");
203+ let index = usize::from(h[2] >> 4);
204+ let kbps = table[index.min(14)] as usize;
205+ assert!(kbps > 0, "free-format header at {pos}");
206+ if frames > 0 {
207+ indices.insert(index);
208+ }
209+ frames += 1;
210+ pos += 144 * kbps * 1000 / rate as usize + usize::from((h[2] >> 1) & 1);
211+ }
212+ let seconds = pcm.len() as f64 / (rate as f64 * channels as f64);
213+ let mean = bytes.len() as f64 * 8.0 / seconds / 1000.0;
214+ let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5));
215+ println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s");
216+ assert!(indices.len() >= 3, "only {indices:?}");
217+ assert!((mean - target).abs() <= target * 0.25, "mean {mean:.1} vs {target}");
218+
219+ let work = workdir("vbr");
220+ let file = work.join("vbr.mp3");
221+ std::fs::write(&file, &bytes).unwrap();
222+ let out = Command::new("ffmpeg")
223+ .args(["-v", "warning", "-i"])
224+ .arg(&file)
225+ .args(["-f", "f32le", "-"])
226+ .output()
227+ .expect("run ffmpeg");
228+ assert!(out.stderr.is_empty(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));
229+ let decoded: Vec<f32> = out
230+ .stdout
231+ .chunks_exact(4)
232+ .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
233+ .collect();
234+ let corr = correlation(&decoded, &pcm);
235+ let bar = bar_for(name, 192);
236+ println!("vbr corr={corr:.5} bar={bar:.5}");
237+ assert!(corr >= bar, "corr {corr:.5} < bar {bar:.5}");
238+ let probe = Command::new("ffprobe")
239+ .args(["-v", "error", "-show_format"])
240+ .arg(&file)
241+ .output()
242+ .expect("run ffprobe");
243+ let probe = String::from_utf8_lossy(&probe.stdout);
244+ // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version.
245+ assert!(&bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70, "no VBR-flagged Xing tag");
246+ assert!(probe.contains("format_name=mp3"), "{probe}");
247+}
248+
146249 #[test]
147250 fn encodes_above_the_incumbent_bar() {
148251 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)]