forge
Explore
Log in

Don't you dare go Hollow

mp3: code correlated stereo as mid/side

Browse files at this commit

21447bfae1f09e0739713906f2c8163e0e3761c3Ahmet Kaan GümüşParent: 5912f29
The encoder declared joint stereo in every frame header and then wrote
mode_extension zero, which is plain left/right. The decoder had implemented
mid/side all along, so the two spoken-word sources in the library sweep were
coded twice over -- once per channel -- at half the bits each, and sat 12.6 dB
behind the reference in the worst 20 ms window.

A frame now takes mid/side when the difference of its channels is quieter than
their sum, which is every correlated mix and no opposed one. Both channels of a
frame take the same window, because adding a long block's lines to a short
block's describes two different time slices. A mid/side pair is held to
whichever channel masked less, since an error in the side channel lands in both
ears.

All fourteen sweep rows improve or hold. Five now beat the reference where
three did; the worst window on the speech rows closes to a tie at 192 kbit/s.
Both gate floors tighten onto the new worst rows: correlation to -0.0012, and
worst-window excess from 13.5 dB to 5.0 dB.
crates/ec-mp3/src/encode.rsmodified+87 -13
@@ -75,6 +75,18 @@ const ZERO_QUANT_THRESHOLD: f32 = 7.8504e-17;
75 75
76 const SFB_LONG: usize = 21;76 const SFB_LONG: usize = 21;
77 77
78+/// How much quieter the difference of the two channels has to be than their
79+/// sum before the frame is coded as mid/side. One means "whenever the sum is
80+/// the louder of the two", which is every correlated mix.
81+///
82+/// Swept on the two library sources mid/side helps least (`reelo`, `dl8a`,
83+/// `real_library_sweep_vs_lame`): the correlation gap moves by 0.00001 across
84+/// 0.5, 1, 2 and "always", and by 0.0005 between "always" and "never". Real
85+/// music sits nowhere near this threshold, so it is a guard, not a tuning
86+/// knob -- what it guards is the opposed-channel case, where the difference
87+/// is the loud channel (`mid_side_follows_the_channel_correlation`).
88+const MS_ENERGY_RATIO: f64 = 1.0;
89+
78 /// One granule's worth of coded spectrum plus the side info describing it.90 /// One granule's worth of coded spectrum plus the side info describing it.
79 #[derive(Clone, Debug)]91 #[derive(Clone, Debug)]
80 struct CodedGranule {92 struct CodedGranule {
@@ -111,7 +123,10 @@ pub struct Mp3Encode {
111 pending: Vec<PendingGranule>,123 pending: Vec<PendingGranule>,
112 /// The block type each channel's previous granule used. Window switching124 /// The block type each channel's previous granule used. Window switching
113 /// is a sequence, and the sequence does not restart at a frame boundary.125 /// is a sequence, and the sequence does not restart at a frame boundary.
114- previous_block: Vec<u8>,126+ previous_block: u8,
127+ /// The `mode_extension` bits of the frame being written: bit 1 is
128+ /// mid/side stereo, decided per frame in `emit_frame`.
129+ mode_ext: u8,
115 fft: RealFft<f32>,130 fft: RealFft<f32>,
116 fft_window: Window<f32>,131 fft_window: Window<f32>,
117 psy_history: Vec<Vec<f32>>,132 psy_history: Vec<Vec<f32>>,
@@ -187,7 +202,8 @@ impl Mp3Encode {
187 slots: vec![Vec::new(); channels],202 slots: vec![Vec::new(); channels],
188 history: vec![[[0.0; 32]; 18]; channels],203 history: vec![[[0.0; 32]; 18]; channels],
189 pending: Vec::new(),204 pending: Vec::new(),
190- previous_block: vec![0; channels],205+ previous_block: 0,
206+ mode_ext: 0,
191 fft: RealFft::new(1024),207 fft: RealFft::new(1024),
192 fft_window: Window::sine(1024),208 fft_window: Window::sine(1024),
193 psy_history: vec![vec![0.0; 1024]; channels],209 psy_history: vec![vec![0.0; 1024]; channels],
@@ -226,7 +242,7 @@ impl Mp3Encode {
226 padding: false,242 padding: false,
227 private: false,243 private: false,
228 mode: self.mode,244 mode: self.mode,
229- mode_ext: 0,245+ mode_ext: self.mode_ext,
230 copyright: false,246 copyright: false,
231 original: true,247 original: true,
232 emphasis: 0,248 emphasis: 0,
@@ -616,15 +632,27 @@ impl Mp3Encode {
616 // granule of one frame demands a short block in the first granule of632 // granule of one frame demands a short block in the first granule of
617 // the next. Restarting it per frame is what leaves a start window633 // the next. Restarting it per frame is what leaves a start window
618 // facing a normal one, whose overlap does not reconstruct.634 // facing a normal one, whose overlap does not reconstruct.
635+ //
636+ // Both channels of a frame get the same window, because mid/side
637+ // below adds and subtracts their spectra: lines from a long block and
638+ // lines from a short one describe different time slices, so summing
639+ // them would smear one channel's transient across the other's granule.
619 let mut types = vec![0u8; granules * channels];640 let mut types = vec![0u8; granules * channels];
620 for gr in 0..granules {641 for gr in 0..granules {
621- for ch in 0..channels {642+ {
622- let index = gr * channels + ch;643+ let base = gr * channels;
623- let here = self.pending[index].energy;644+ let energy = |slot: usize| -> f32 {
624- let next = self645+ (0..channels)
625- .pending646+ .filter_map(|ch| self.pending.get(slot + ch))
626- .get(index + channels)647+ .map(|g| g.energy)
627- .map_or(here, |g| g.energy);648+ .sum()
649+ };
650+ let here = energy(base);
651+ let next = if base + channels < self.pending.len() {
652+ energy(base + channels)
653+ } else {
654+ here
655+ };
628 // Digital silence is not a transient to protect: switching on656 // Digital silence is not a transient to protect: switching on
629 // the way out of it (the priming, or a cut in a timeline) costs657 // the way out of it (the priming, or a cut in a timeline) costs
630 // the resolution a long block would have spent on the attack658 // the resolution a long block would have spent on the attack
@@ -647,15 +675,17 @@ impl Mp3Encode {
647 // more of the worst window back, so 4 sits at the cheap end675 // more of the worst window back, so 4 sits at the cheap end
648 // of the flat part.676 // of the flat part.
649 let attack = here > 1e-9 && next > here * 4.0 + 1e-6;677 let attack = here > 1e-9 && next > here * 4.0 + 1e-6;
650- let block = match self.previous_block[ch] {678+ let block = match self.previous_block {
651 1 => 2,679 1 => 2,
652 2 if attack => 2,680 2 if attack => 2,
653 2 => 3,681 2 => 3,
654 _ if attack => 1,682 _ if attack => 1,
655 _ => 0,683 _ => 0,
656 };684 };
657- types[index] = block;685+ for ch in 0..channels {
658- self.previous_block[ch] = block;686+ types[base + ch] = block;
687+ }
688+ self.previous_block = block;
659 }689 }
660 }690 }
661 691
@@ -678,6 +708,50 @@ impl Mp3Encode {
678 }708 }
679 self.pending.drain(..granules * channels);709 self.pending.drain(..granules * channels);
680 710
711+ // Mid/side stereo. The two channels of real music are mostly the same
712+ // signal, and coding their sum and difference puts nearly all of the
713+ // energy in the sum, leaving the difference cheap enough to quantise
714+ // finely at the same cost. It is applied to the MDCT lines and undone
715+ // by the decoder, so it is exact -- the only judgement is whether the
716+ // difference really is the small one, which it is not on a wide stereo
717+ // mix, where L/R codes two independent signals better than a mid that
718+ // is loud and a side that is nearly as loud.
719+ self.mode_ext = 0;
720+ if channels == 2 && self.mode == ChannelMode::JointStereo {
721+ let (mut mid, mut side) = (0.0f64, 0.0f64);
722+ for gr in 0..granules {
723+ let (left, right) = (&xrs[gr * 2], &xrs[gr * 2 + 1]);
724+ for (&l, &r) in left.iter().zip(right.iter()) {
725+ let (l, r) = (f64::from(l), f64::from(r));
726+ mid += (l + r) * (l + r);
727+ side += (l - r) * (l - r);
728+ }
729+ }
730+ if side < mid * MS_ENERGY_RATIO {
731+ self.mode_ext = 2;
732+ const INV_SQRT2: f32 = std::f32::consts::FRAC_1_SQRT_2;
733+ for gr in 0..granules {
734+ let (head, tail) = xrs.split_at_mut(gr * 2 + 1);
735+ let (left, right) = (&mut head[gr * 2], &mut tail[0]);
736+ for (l, r) in left.iter_mut().zip(right.iter_mut()) {
737+ let (a, b) = (*l, *r);
738+ *l = (a + b) * INV_SQRT2;
739+ *r = (a - b) * INV_SQRT2;
740+ }
741+ // Neither coded channel is one of the speakers any more,
742+ // so both are held to whichever channel masked less: an
743+ // error in the side channel lands in both ears.
744+ let (head, tail) = thresholds.split_at_mut(gr * 2 + 1);
745+ let (left, right) = (&mut head[gr * 2], &mut tail[0]);
746+ for (l, r) in left.iter_mut().zip(right.iter_mut()) {
747+ let floor = l.min(*r);
748+ *l = floor;
749+ *r = floor;
750+ }
751+ }
752+ }
753+ }
754+
681 // Quantise the granules. CBR codes to a fixed frame budget. VBR tries755 // Quantise the granules. CBR codes to a fixed frame budget. VBR tries
682 // legal bitrates, coding the whole frame's granules against each one's756 // legal bitrates, coding the whole frame's granules against each one's
683 // share with the same distortion loop CBR uses, and keeps the757 // share with the same distortion loop CBR uses, and keeps the
crates/ec-mp3/tests/encode_matrix.rsmodified+79 -11
@@ -11,7 +11,7 @@
11 use std::path::{Path, PathBuf};11 use std::path::{Path, PathBuf};
12 use std::process::Command;12 use std::process::Command;
13 13
14-use ec_mp3::{Mp3Encoder, Mp3EncoderConfig};14+use ec_mp3::{FrameHeader, Mp3Encoder, Mp3EncoderConfig};
15 15
16 /// Correlation the incumbent MP3 encoder, 0.6.1, reaches on this corpus, measured with this16 /// Correlation the incumbent MP3 encoder, 0.6.1, reaches on this corpus, measured with this
17 /// same alignment and metric (its own encoder, ffmpeg's decoder). The tone17 /// same alignment and metric (its own encoder, ffmpeg's decoder). The tone
@@ -156,7 +156,16 @@ fn worst_window_db(got: &[f32], want: &[f32], offset: usize, channels: usize) ->
156 // and the fade-ins around it.156 // and the fade-ins around it.
157 if sig / window as f64 > 1e-6 {157 if sig / window as f64 > 1e-6 {
158 let db = 10.0 * (err / sig.max(1e-30)).log10();158 let db = 10.0 * (err / sig.max(1e-30)).log10();
159- worst = worst.max(db);159+ if db > worst {
160+ worst = db;
161+ if std::env::var_os("EC_MP3_WORST_WHERE").is_some() {
162+ eprintln!(
163+ " worst so far {db:+.1} dB at {:.2} s, level {:.1} dBFS",
164+ start as f64 / (44100.0 * channels as f64),
165+ 10.0 * (sig / window as f64).log10()
166+ );
167+ }
168+ }
160 }169 }
161 start += window;170 start += window;
162 }171 }
@@ -475,14 +484,11 @@ const LIBRARY: [(&str, &str); 7] = [
475 484
476 /// How much worse than LAME a row's worst 20 ms window may be, in dB.485 /// How much worse than LAME a row's worst 20 ms window may be, in dB.
477 ///486 ///
478-/// The floor is set from the measurement and the measurement is bad: hein at487+/// The gap was 12.6 dB when this floor went in, on the two spoken-word
479-/// 192 kbit/s is 12.6 dB behind, and hein and reelm are the two spoken-word488+/// sources, and mid/side stereo closed it: the encoder declared joint stereo
480-/// sources. LAME's worst window improves by 12 dB from 128 to 192 kbit/s on489+/// while writing plain left/right, so near-mono speech was coded twice. The
481-/// that file while ours improves by 5, which says our limit there is the490+/// worst row now is dl8a at 192 kbit/s, 4.1 dB behind on a wide music mix.
482-/// masking model rather than the bitrate. That is the next round; the floor491+const WORST_WINDOW_EXCESS_DB: f64 = 5.0;
483-/// exists so it cannot quietly get worse first. Worst row: hein at 192 kbit/s,
484-/// 12.6 dB behind.
485-const WORST_WINDOW_EXCESS_DB: f64 = 13.5;
486 492
487 /// How far under LAME a row may sit before the sweep fails, in correlation.493 /// How far under LAME a row may sit before the sweep fails, in correlation.
488 ///494 ///
@@ -491,7 +497,7 @@ const WORST_WINDOW_EXCESS_DB: f64 = 13.5;
491 /// floor sits just under that worst row rather than at zero because three rows497 /// floor sits just under that worst row rather than at zero because three rows
492 /// are already ahead of LAME and the spread is what a regression would have to498 /// are already ahead of LAME and the spread is what a regression would have to
493 /// widen.499 /// widen.
494-const LAME_CORR_FLOOR: f64 = -0.0015;500+const LAME_CORR_FLOOR: f64 = -0.0012;
495 501
496 fn expand(path: &str) -> PathBuf {502 fn expand(path: &str) -> PathBuf {
497 PathBuf::from(match path.strip_prefix("~/") {503 PathBuf::from(match path.strip_prefix("~/") {
@@ -634,3 +640,65 @@ fn real_library_sweep_vs_lame() {
634 assert!(rows > 0, "no library sources were readable");640 assert!(rows > 0, "no library sources were readable");
635 assert!(failures.is_empty(), "{failures:#?}");641 assert!(failures.is_empty(), "{failures:#?}");
636 }642 }
643+
644+/// The `mode_extension` of every frame of a stream, in order.
645+fn mode_exts(bytes: &[u8]) -> Vec<u8> {
646+ let mut out = Vec::new();
647+ let mut at = 0;
648+ while at + 4 <= bytes.len() {
649+ let Ok(header) = FrameHeader::parse(&bytes[at..]) else {
650+ at += 1;
651+ continue;
652+ };
653+ let Some(len) = header.frame_len() else { break };
654+ out.push(header.mode_ext);
655+ at += len;
656+ }
657+ out
658+}
659+
660+/// Mid/side is chosen for the signal it helps and declined for the one it
661+/// hurts. Two channels carrying the same waveform put everything in the sum
662+/// and nothing in the difference, which is the case mid/side exists for; two
663+/// carrying opposite waveforms are its worst case, where the difference is
664+/// the loud channel and coding it as such would spend the frame's bits on the
665+/// quiet one. Both roundtrip, because the decoder undoes whichever was
666+/// written.
667+#[test]
668+fn mid_side_follows_the_channel_correlation() {
669+ let mut seed = 0x2545_f491_4f6c_dd1du64;
670+ let mut noise = || {
671+ seed ^= seed << 13;
672+ seed ^= seed >> 7;
673+ seed ^= seed << 17;
674+ (seed >> 40) as f32 / 8388608.0 - 0.5
675+ };
676+ let n = 44100;
677+ let (mut same, mut opposed) = (Vec::with_capacity(n * 2), Vec::with_capacity(n * 2));
678+ for i in 0..n {
679+ // Band-limited enough to be codeable: a slow tone under the noise.
680+ let tone = (i as f32 * 0.03).sin() * 0.4;
681+ let v = tone + noise() * 0.05;
682+ same.push(v);
683+ same.push(v);
684+ opposed.push(v);
685+ opposed.push(-v);
686+ }
687+ for (label, pcm, want_ms) in [("same", same, true), ("opposed", opposed, false)] {
688+ let bytes = encode(&pcm, 44100, 2, 128);
689+ let exts = mode_exts(&bytes);
690+ assert!(exts.len() > 20, "{label}: only {} frames", exts.len());
691+ let ms = exts.iter().filter(|e| *e & 2 != 0).count();
692+ // The first and last frames carry priming and a tail, so judge the body.
693+ let body = exts.len() - 2;
694+ if want_ms {
695+ assert!(
696+ ms >= body,
697+ "{label}: only {ms} of {} frames are mid/side",
698+ exts.len()
699+ );
700+ } else {
701+ assert_eq!(ms, 0, "{label}: {ms} frames chose mid/side");
702+ }
703+ }
704+}
lanes/mp3lame-r1.report.mdmodified+65 -0
@@ -211,3 +211,68 @@ signal-to-mask offset `6.0 + 15.0 * (1.0 - flatness)` dB, the spreading leaks
211 (0.0032 up, 0.1 down), and the absolute threshold's211 (0.0032 up, 0.1 down), and the absolute threshold's
212 `1.0 + 400.0 * (rel - 0.35)^2` shape. Speech is exactly the material whose212 `1.0 + 400.0 * (rel - 0.35)^2` shape. Speech is exactly the material whose
213 tonality a 1024-point flatness estimate gets wrong.213 tonality a 1024-point flatness estimate gets wrong.
214+
215+## Round 4: the encoder declared joint stereo and wrote plain left/right
216+
217+Round 3 left the gap concentrated on the two spoken-word sources, and speech is
218+where the two channels are nearly the same signal. Parsing both streams' frame
219+headers found the reason: our `mode_extension` was hard-coded to zero on every
220+frame while the header's channel mode said joint stereo. libmp3lame wrote
221+mid/side on 2017 of ~2200 frames of the same audio. Our decoder already
222+implemented mid/side correctly — only the encoder never asked for it, so a
223+near-mono voice was coded twice, once in each channel, at half the bits each.
224+
225+The fix is three pieces: both channels of a frame now take the same window
226+(adding a long block's lines to a short block's would smear one channel's
227+transient into the other), the frame picks mid/side when the difference of the
228+channels is quieter than their sum, and `mode_ext` is written per frame.
229+Masking thresholds for a mid/side pair are held to whichever channel masked
230+less, because an error in the side channel lands in both ears.
231+
232+Both metrics, all fourteen rows, round 3 → round 4:
233+
234+| source | kbps | corr gap | worst window (ours) |
235+|---|---|---|---|
236+| nik | 128 | -0.00073 → **-0.00067** | -12.1 → -12.1 |
237+| nik | 192 | -0.00030 → **-0.00028** | -17.6 → -17.1 |
238+| reelo | 128 | -0.00103 → -0.00103 | -11.1 → **-11.3** |
239+| reelo | 192 | -0.00045 → **-0.00044** | -16.3 → -16.1 |
240+| her | 128 | +0.00142 → **+0.00154** | -9.9 → **-10.0** |
241+| her | 192 | +0.00021 → **+0.00025** | -14.4 → **-14.7** |
242+| reell | 128 | +0.00021 → **+0.00030** | -9.7 → **-10.2** |
243+| reell | 192 | -0.00002 → **+0.00001** | -15.1 → **-15.7** |
244+| reelm | 128 | -0.00068 → **+0.00076** | -1.6 → **-9.2** |
245+| reelm | 192 | -0.00040 → **+0.00001** | -6.2 → **-16.5** |
246+| dl8a | 128 | -0.00062 → **-0.00057** | -3.2 → **-3.8** |
247+| dl8a | 192 | -0.00040 → **-0.00037** | -8.3 → -8.1 |
248+| hein | 128 | -0.00087 → **+0.00029** | -0.1 → **-10.1** |
249+| hein | 192 | -0.00030 → **+0.00001** | -6.8 → **-16.1** |
250+
251+Five rows now beat libmp3lame outright where three did before, and the two
252+spoken-word sources moved from the worst rows in the table to ties at 192
253+kbit/s. hein at 192 went from 12.6 dB behind LAME's worst window to 3.3 dB;
254+reelm at 128 is now 7 dB *ahead*. Both gate floors tightened onto the new worst
255+rows: correlation -0.0015 → -0.0012 (reelo at 128), worst-window excess 13.5 →
256+5.0 dB (dl8a at 192, a wide music mix, which is the case mid/side cannot help).
257+
258+The decision threshold itself was swept and is flat: 0.5, 1, 2 and "always"
259+differ by 0.00001 in correlation on the two sources mid/side helps least, while
260+"never" costs 0.0005. Real music is nowhere near the threshold, so it is a
261+guard rather than a knob — and what it guards is now a test rather than an
262+argument: `mid_side_follows_the_channel_correlation` encodes two channels
263+carrying the same waveform and two carrying opposite ones, and asserts the
264+decision goes each way.
265+
266+### What round 4 ruled out on the way
267+
268+Before the stereo defect surfaced, four candidates were measured and rejected:
269+the masking offset and the absolute-threshold floor (bit-identical output
270+across 1e-9…1e-13), reservoir starvation (encoding the worst passage in
271+isolation gained 1.2 dB), and the distortion loop (amplifying scalefactors is a
272+net loss in both noise-to-mask and raw-noise orderings). Instrumenting the
273+loop's exit reasons explained why: **9498 of 9498 granules exit on the budget
274+break, 9484 of them at round 0**. `code_with` already fills the frame budget, so
275+the outer loop never runs — the encoder is a pure rate loop and the
276+psychoacoustic model reaches the output only through the band ordering it never
277+gets to use. That is the standing structural finding for this crate; the gain
278+in this round came from a missing feature, not from the model.