forge
Explore
Log in

Don't you dare go Hollow

Speed up VBR silence

Browse files at this commit

f0cad7af0fcbb1030934cd592b559b587c377e76Ahmet Kaan GümüşParent: 60c1bbb
  • fix
    • speed up VBR silence
Show full message
fix(mp3): speed up VBR silence

Add a zero-granule fast path, make VBR candidate search local to the previous frame, and recalibrate the quality threshold curve on music clips.
crates/ec-mp3/src/encode.rsmodified+122 -44
@@ -71,6 +71,8 @@ pub fn bitrate_for_quality(quality: f32) -> u32 {
71 /// The largest value the 12-bit `part2_3_length` side-info field can carry,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.72 /// and so the most bits one granule may be coded to.
73 const PART2_3_MAX: u32 = (1 << 12) - 1;73 const PART2_3_MAX: u32 = (1 << 12) - 1;
74+const ZERO_QUANT_THRESHOLD: f32 = 7.8504e-17;
75+
74 const SFB_LONG: usize = 21;76 const SFB_LONG: usize = 21;
75 77
76 /// One granule's worth of coded spectrum plus the side info describing it.78 /// One granule's worth of coded spectrum plus the side info describing it.
@@ -131,6 +133,10 @@ pub struct Mp3Encode {
131 /// Bytes of emitted audio frames (everything after the info header), for133 /// Bytes of emitted audio frames (everything after the info header), for
132 /// the Xing header's byte count and average bitrate.134 /// the Xing header's byte count and average bitrate.
133 frame_bytes: u64,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,
134 }140 }
135 141
136 #[derive(Clone, Debug)]142 #[derive(Clone, Debug)]
@@ -193,6 +199,19 @@ impl Mp3Encode {
193 ready: std::collections::VecDeque::new(),199 ready: std::collections::VecDeque::new(),
194 frames: 0,200 frames: 0,
195 frame_bytes: 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+ },
196 })215 })
197 }216 }
198 217
@@ -678,21 +697,41 @@ impl Mp3Encode {
678 }697 }
679 (frame_coded, ratio)698 (frame_coded, ratio)
680 };699 };
681- let (mut lo, mut hi) = (0usize, table.len() - 1);700+ // Real audio is smooth frame to frame, so try the last
682- let mut best = code_at(table[hi]);701+ // settled bitrate first and walk only as far as this frame
683- let mut best_kbps = table[hi];702+ // needs. If the previous frame was already cheap, start at the
684- while lo < hi {703+ // legal floor instead of climbing down through the table again.
685- let mid = (lo + hi) / 2;704+ let mut index = if self.vbr_index <= 2 {
686- let (coded, ratio) = code_at(table[mid]);705+ 0
687- if ratio <= 1.0 {706+ } else {
688- best = (coded, ratio);707+ self.vbr_index.min(table.len() - 1)
689- best_kbps = table[mid];708+ };
690- hi = mid;709+ let (coded, ratio) = code_at(table[index]);
691- } else {710+ let mut best = (coded, ratio);
692- lo = mid + 1;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+ }
693 }731 }
694 }732 }
695- (best.0, best_kbps)733+ self.vbr_index = best_index;
734+ (best.0, table[best_index])
696 }735 }
697 None => {736 None => {
698 let header = self.header(self.bitrate_kbps);737 let header = self.header(self.bitrate_kbps);
@@ -702,7 +741,10 @@ impl Mp3Encode {
702 let share = budget_bits / (granules * channels).max(1);741 let share = budget_bits / (granules * channels).max(1);
703 let mut frame_coded = Vec::with_capacity(granules * channels);742 let mut frame_coded = Vec::with_capacity(granules * channels);
704 for index in 0..granules * channels {743 for index in 0..granules * channels {
705- let spent: usize = frame_coded.iter().map(|c: &CodedGranule| c.part2_3_length as usize).sum();744+ let spent: usize = frame_coded
745+ .iter()
746+ .map(|c: &CodedGranule| c.part2_3_length as usize)
747+ .sum();
706 let left = budget_bits.saturating_sub(spent);748 let left = budget_bits.saturating_sub(spent);
707 let target = share.min(left).min(4095);749 let target = share.min(left).min(4095);
708 let (granule, _) = quantise_granule(750 let (granule, _) = quantise_granule(
@@ -912,17 +954,17 @@ fn mdct_short(input: &[f32; 36], out: &mut [f32]) {
912 954
913 /// Scales the masking threshold by `vbr_quality`. A higher quality lowers the955 /// Scales the masking threshold by `vbr_quality`. A higher quality lowers the
914 /// allowed noise (a smaller threshold, so more bands are amplified and the956 /// allowed noise (a smaller threshold, so more bands are amplified and the
915-/// granule costs more bits); a lower quality raises it. 0.5 is neutral.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.
916 fn quality_threshold(threshold: &[f32], quality: f32) -> Vec<f32> {960 fn quality_threshold(threshold: &[f32], quality: f32) -> Vec<f32> {
917 let q = quality.clamp(0.0, 1.0);961 let q = quality.clamp(0.0, 1.0);
918- // The mapping: 24 dB of noise-to-mask margin across the quality range.962+ let db = if q <= 0.5 {
919- // Its centre sits 4 dB over the mask, because the model's mask is963+ 12.0 - 25.0 * q + 20.0 * q * q
920- // conservative (its flatness-derived offset lands 11-13 dB under white964+ } else {
921- // noise where 6 dB is the noise-like figure); 4 dB is what puts q = 0.5965+ let t = q - 0.5;
922- // at `bitrate_for_quality(0.5)` on mp3src-stereo-48000 and two real966+ 4.5 - 11.0 * t - 12.0 * t * t
923- // stereo tracks (210-225 kbit/s, decoding above the CBR-192 bar; 5 dB967+ };
924- // gave 195-208 but slipped under that bar, 6 dB gave 170-189).
925- let db = (0.5 - q) * 24.0 + 4.0;
926 let scale = 10f32.powf(db / 10.0);968 let scale = 10f32.powf(db / 10.0);
927 threshold.iter().map(|&t| t * scale).collect()969 threshold.iter().map(|&t| t * scale).collect()
928 }970 }
@@ -935,6 +977,24 @@ fn quantise_granule(
935 threshold: &[f32],977 threshold: &[f32],
936 sample_rate: u32,978 sample_rate: u32,
937 ) -> (CodedGranule, f64) {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+ }
938 let mut scalefac = [0u8; SFB_LONG];998 let mut scalefac = [0u8; SFB_LONG];
939 // Score is the summed noise-to-mask ratio over the bands; a mean ratio999 // Score is the summed noise-to-mask ratio over the bands; a mean ratio
940 // of at most one is VBR's signal that this bitrate carried the granule1000 // of at most one is VBR's signal that this bitrate carried the granule
@@ -963,6 +1023,9 @@ fn quantise_granule(
963 if best.as_ref().is_none_or(|(_, s, _)| score < *s) {1023 if best.as_ref().is_none_or(|(_, s, _)| score < *s) {
964 best = Some((granule, score, bands));1024 best = Some((granule, score, bands));
965 }1025 }
1026+ if score <= 0.0 {
1027+ break; // every band is already exactly at the mask; nothing left to buy
1028+ }
966 if spent * 20 > target_bits * 19 {1029 if spent * 20 > target_bits * 19 {
967 break; // the budget is spent; amplifying now only coarsens1030 break; // the budget is spent; amplifying now only coarsens
968 }1031 }
@@ -1092,27 +1155,39 @@ fn code_with(
1092 };1155 };
1093 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);1156 quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
1094 coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);1157 coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);
1095- loop {1158+ if peak <= 1e-20 {
1096- if (saturated(&ix) || coded.0 > target_bits) && gain < 255 {1159+ // Below the smallest representable level: every line quantises to
1097- gain += 1;1160+ // zero at any gain (the quantiser's scale multiplies zero either
1098- quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);1161+ // way), so the descending-gain search below — which steps one gain
1099- coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);1162+ // unit at a time — would walk all 210 units from 210 to 0 finding
1100- continue;1163+ // nothing changes, recoding an all-zero spectrum at every step. Skip
1101- }1164+ // straight to the quietest legal gain; `coded` above is already the
1102- if saturated(&ix) || coded.0 > target_bits || gain == 0 {1165+ // right answer, because an all-zero spectrum's bit cost does not
1103- break;1166+ // depend on gain.
1104- }1167+ gain = 0;
1105- // Try one step quieter; keep it only if it still fits and stays1168+ } else {
1106- // inside the coding range.1169+ loop {
1107- let mut trial = ix.clone();1170+ if (saturated(&ix) || coded.0 > target_bits) && gain < 255 {
1108- quantise(xr, gain - 1, scalefac, sample_rate, block_type, &mut trial);1171+ gain += 1;
1109- let trial_coded = code_spectrum(&for_coding(&trial), block_type, sample_rate);1172+ quantise(xr, gain, scalefac, sample_rate, block_type, &mut ix);
1110- if trial_coded.0 > target_bits || saturated(&trial) {1173+ coded = code_spectrum(&for_coding(&ix), block_type, sample_rate);
1111- break;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;
1112 }1190 }
1113- gain -= 1;
1114- ix = trial;
1115- coded = trial_coded;
1116 }1191 }
1117 // Last resort: if even the quietest legal gain will not fit the bits we1192 // Last resort: if even the quietest legal gain will not fit the bits we
1118 // were given, drop the top of the spectrum until it does. A granule that1193 // were given, drop the top of the spectrum until it does. A granule that
@@ -1477,7 +1552,10 @@ mod tests {
1477 sum += 10.0 * (energy / granule.threshold[band]).log10();1552 sum += 10.0 * (energy / granule.threshold[band]).log10();
1478 }1553 }
1479 let db = sum / 13.0;1554 let db = sum / 13.0;
1480- assert!((6.0..=18.0).contains(&db), "signal sits {db:.1} dB over its mask");1555+ assert!(
1556+ (6.0..=18.0).contains(&db),
1557+ "signal sits {db:.1} dB over its mask"
1558+ );
1481 }1559 }
1482 1560
1483 #[test]1561 #[test]
crates/ec-mp3/tests/encode_matrix.rsmodified+55 -8
@@ -161,9 +161,12 @@ fn cbr_quality_holds_its_floor() {
161 let decoded = decode(&file);161 let decoded = decode(&file);
162 assert_eq!(decoded.len(), pcm.len());162 assert_eq!(decoded.len(), pcm.len());
163 let corr = correlation(&decoded, &pcm);163 let corr = correlation(&decoded, &pcm);
164- let (err, sig) = decoded.iter().zip(&pcm).fold((0.0f64, 0.0f64), |(e, s), (d, p)| {164+ let (err, sig) = decoded
165- (e + f64::from(d - p).powi(2), s + f64::from(*p).powi(2))165+ .iter()
166- });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+ });
167 let rms = (err / sig).sqrt();170 let rms = (err / sig).sqrt();
168 println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0);171 println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0);
169 assert!(corr >= 0.999_99, "corr {corr:.6}");172 assert!(corr >= 0.999_99, "corr {corr:.6}");
@@ -177,7 +180,11 @@ fn decode(file: &Path) -> Vec<f32> {
177 .args(["-f", "f32le", "-"])180 .args(["-f", "f32le", "-"])
178 .output()181 .output()
179 .expect("run ffmpeg");182 .expect("run ffmpeg");
180- assert!(out.stderr.is_empty(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));183+ assert!(
184+ out.stderr.is_empty(),
185+ "ffmpeg: {}",
186+ String::from_utf8_lossy(&out.stderr)
187+ );
181 out.stdout188 out.stdout
182 .chunks_exact(4)189 .chunks_exact(4)
183 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))190 .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]]))
@@ -213,7 +220,9 @@ fn vbr_frames_vary_their_bitrate_index() {
213 };220 };
214 let bytes = encode_vbr(&pcm, rate, channels, 0.5);221 let bytes = encode_vbr(&pcm, rate, channels, 0.5);
215 // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame.222 // Walk the frame headers (MPEG-1, Layer III), skipping the Xing frame.
216- let table = [0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320];223+ let table = [
224+ 0u32, 32, 40, 48, 56, 64, 80, 96, 112, 128, 160, 192, 224, 256, 320,
225+ ];
217 let mut indices = std::collections::BTreeSet::new();226 let mut indices = std::collections::BTreeSet::new();
218 let (mut pos, mut frames) = (0usize, 0usize);227 let (mut pos, mut frames) = (0usize, 0usize);
219 while pos + 4 <= bytes.len() {228 while pos + 4 <= bytes.len() {
@@ -233,7 +242,10 @@ fn vbr_frames_vary_their_bitrate_index() {
233 let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5));242 let target = f64::from(ec_mp3::encode::bitrate_for_quality(0.5));
234 println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s");243 println!("vbr frames={frames} indices={indices:?} mean={mean:.1} kbit/s");
235 assert!(indices.len() >= 3, "only {indices:?}");244 assert!(indices.len() >= 3, "only {indices:?}");
236- assert!((mean - target).abs() <= target * 0.25, "mean {mean:.1} vs {target}");245+ assert!(
246+ (mean - target).abs() <= target * 0.25,
247+ "mean {mean:.1} vs {target}"
248+ );
237 249
238 let work = workdir("vbr");250 let work = workdir("vbr");
239 let file = work.join("vbr.mp3");251 let file = work.join("vbr.mp3");
@@ -244,7 +256,11 @@ fn vbr_frames_vary_their_bitrate_index() {
244 .args(["-f", "f32le", "-"])256 .args(["-f", "f32le", "-"])
245 .output()257 .output()
246 .expect("run ffmpeg");258 .expect("run ffmpeg");
247- assert!(out.stderr.is_empty(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr));259+ assert!(
260+ out.stderr.is_empty(),
261+ "ffmpeg: {}",
262+ String::from_utf8_lossy(&out.stderr)
263+ );
248 let decoded: Vec<f32> = out264 let decoded: Vec<f32> = out
249 .stdout265 .stdout
250 .chunks_exact(4)266 .chunks_exact(4)
@@ -261,10 +277,41 @@ fn vbr_frames_vary_their_bitrate_index() {
261 .expect("run ffprobe");277 .expect("run ffprobe");
262 let probe = String::from_utf8_lossy(&probe.stdout);278 let probe = String::from_utf8_lossy(&probe.stdout);
263 // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version.279 // "Xing" (not "Info") plus the VBR-method byte after the 9-byte version.
264- assert!(&bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70, "no VBR-flagged Xing tag");280+ assert!(
281+ &bytes[36..40] == b"Xing" && bytes[36 + 16 + 9] == 0x70,
282+ "no VBR-flagged Xing tag"
283+ );
265 assert!(probe.contains("format_name=mp3"), "{probe}");284 assert!(probe.contains("format_name=mp3"), "{probe}");
266 }285 }
267 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+
268 #[test]315 #[test]
269 fn encodes_above_the_incumbent_bar() {316 fn encodes_above_the_incumbent_bar() {
270 let dir = fixtures().join("audio");317 let dir = fixtures().join("audio");