diff --git a/crates/ec-mp3/src/encode.rs b/crates/ec-mp3/src/encode.rs index 6f5b5db2..5b3f6608 100644 --- a/crates/ec-mp3/src/encode.rs +++ b/crates/ec-mp3/src/encode.rs @@ -75,6 +75,18 @@ const ZERO_QUANT_THRESHOLD: f32 = 7.8504e-17; const SFB_LONG: usize = 21; +/// How much quieter the difference of the two channels has to be than their +/// sum before the frame is coded as mid/side. One means "whenever the sum is +/// the louder of the two", which is every correlated mix. +/// +/// Swept on the two library sources mid/side helps least (`reelo`, `dl8a`, +/// `real_library_sweep_vs_lame`): the correlation gap moves by 0.00001 across +/// 0.5, 1, 2 and "always", and by 0.0005 between "always" and "never". Real +/// music sits nowhere near this threshold, so it is a guard, not a tuning +/// knob -- what it guards is the opposed-channel case, where the difference +/// is the loud channel (`mid_side_follows_the_channel_correlation`). +const MS_ENERGY_RATIO: f64 = 1.0; + /// One granule's worth of coded spectrum plus the side info describing it. #[derive(Clone, Debug)] struct CodedGranule { @@ -111,7 +123,10 @@ pub struct Mp3Encode { pending: Vec, /// The block type each channel's previous granule used. Window switching /// is a sequence, and the sequence does not restart at a frame boundary. - previous_block: Vec, + previous_block: u8, + /// The `mode_extension` bits of the frame being written: bit 1 is + /// mid/side stereo, decided per frame in `emit_frame`. + mode_ext: u8, fft: RealFft, fft_window: Window, psy_history: Vec>, @@ -187,7 +202,8 @@ impl Mp3Encode { slots: vec![Vec::new(); channels], history: vec![[[0.0; 32]; 18]; channels], pending: Vec::new(), - previous_block: vec![0; channels], + previous_block: 0, + mode_ext: 0, fft: RealFft::new(1024), fft_window: Window::sine(1024), psy_history: vec![vec![0.0; 1024]; channels], @@ -226,7 +242,7 @@ impl Mp3Encode { padding: false, private: false, mode: self.mode, - mode_ext: 0, + mode_ext: self.mode_ext, copyright: false, original: true, emphasis: 0, @@ -616,15 +632,27 @@ impl Mp3Encode { // granule of one frame demands a short block in the first granule of // the next. Restarting it per frame is what leaves a start window // facing a normal one, whose overlap does not reconstruct. + // + // Both channels of a frame get the same window, because mid/side + // below adds and subtracts their spectra: lines from a long block and + // lines from a short one describe different time slices, so summing + // them would smear one channel's transient across the other's granule. let mut types = vec![0u8; granules * channels]; for gr in 0..granules { - for ch in 0..channels { - let index = gr * channels + ch; - let here = self.pending[index].energy; - let next = self - .pending - .get(index + channels) - .map_or(here, |g| g.energy); + { + let base = gr * channels; + let energy = |slot: usize| -> f32 { + (0..channels) + .filter_map(|ch| self.pending.get(slot + ch)) + .map(|g| g.energy) + .sum() + }; + let here = energy(base); + let next = if base + channels < self.pending.len() { + energy(base + channels) + } else { + here + }; // Digital silence is not a transient to protect: switching on // the way out of it (the priming, or a cut in a timeline) costs // the resolution a long block would have spent on the attack @@ -647,15 +675,17 @@ impl Mp3Encode { // more of the worst window back, so 4 sits at the cheap end // of the flat part. let attack = here > 1e-9 && next > here * 4.0 + 1e-6; - let block = match self.previous_block[ch] { + let block = match self.previous_block { 1 => 2, 2 if attack => 2, 2 => 3, _ if attack => 1, _ => 0, }; - types[index] = block; - self.previous_block[ch] = block; + for ch in 0..channels { + types[base + ch] = block; + } + self.previous_block = block; } } @@ -678,6 +708,50 @@ impl Mp3Encode { } self.pending.drain(..granules * channels); + // Mid/side stereo. The two channels of real music are mostly the same + // signal, and coding their sum and difference puts nearly all of the + // energy in the sum, leaving the difference cheap enough to quantise + // finely at the same cost. It is applied to the MDCT lines and undone + // by the decoder, so it is exact -- the only judgement is whether the + // difference really is the small one, which it is not on a wide stereo + // mix, where L/R codes two independent signals better than a mid that + // is loud and a side that is nearly as loud. + self.mode_ext = 0; + if channels == 2 && self.mode == ChannelMode::JointStereo { + let (mut mid, mut side) = (0.0f64, 0.0f64); + for gr in 0..granules { + let (left, right) = (&xrs[gr * 2], &xrs[gr * 2 + 1]); + for (&l, &r) in left.iter().zip(right.iter()) { + let (l, r) = (f64::from(l), f64::from(r)); + mid += (l + r) * (l + r); + side += (l - r) * (l - r); + } + } + if side < mid * MS_ENERGY_RATIO { + self.mode_ext = 2; + const INV_SQRT2: f32 = std::f32::consts::FRAC_1_SQRT_2; + for gr in 0..granules { + let (head, tail) = xrs.split_at_mut(gr * 2 + 1); + let (left, right) = (&mut head[gr * 2], &mut tail[0]); + for (l, r) in left.iter_mut().zip(right.iter_mut()) { + let (a, b) = (*l, *r); + *l = (a + b) * INV_SQRT2; + *r = (a - b) * INV_SQRT2; + } + // Neither coded channel is one of the speakers any more, + // so both are held to whichever channel masked less: an + // error in the side channel lands in both ears. + let (head, tail) = thresholds.split_at_mut(gr * 2 + 1); + let (left, right) = (&mut head[gr * 2], &mut tail[0]); + for (l, r) in left.iter_mut().zip(right.iter_mut()) { + let floor = l.min(*r); + *l = floor; + *r = floor; + } + } + } + } + // Quantise the granules. CBR codes to a fixed frame budget. VBR tries // legal bitrates, coding the whole frame's granules against each one's // share with the same distortion loop CBR uses, and keeps the diff --git a/crates/ec-mp3/tests/encode_matrix.rs b/crates/ec-mp3/tests/encode_matrix.rs index a56a9e55..cd43be54 100644 --- a/crates/ec-mp3/tests/encode_matrix.rs +++ b/crates/ec-mp3/tests/encode_matrix.rs @@ -11,7 +11,7 @@ use std::path::{Path, PathBuf}; use std::process::Command; -use ec_mp3::{Mp3Encoder, Mp3EncoderConfig}; +use ec_mp3::{FrameHeader, Mp3Encoder, Mp3EncoderConfig}; /// Correlation the incumbent MP3 encoder, 0.6.1, reaches on this corpus, measured with this /// 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) -> // and the fade-ins around it. if sig / window as f64 > 1e-6 { let db = 10.0 * (err / sig.max(1e-30)).log10(); - worst = worst.max(db); + if db > worst { + worst = db; + if std::env::var_os("EC_MP3_WORST_WHERE").is_some() { + eprintln!( + " worst so far {db:+.1} dB at {:.2} s, level {:.1} dBFS", + start as f64 / (44100.0 * channels as f64), + 10.0 * (sig / window as f64).log10() + ); + } + } } start += window; } @@ -475,14 +484,11 @@ const LIBRARY: [(&str, &str); 7] = [ /// How much worse than LAME a row's worst 20 ms window may be, in dB. /// -/// The floor is set from the measurement and the measurement is bad: hein at -/// 192 kbit/s is 12.6 dB behind, and hein and reelm are the two spoken-word -/// sources. LAME's worst window improves by 12 dB from 128 to 192 kbit/s on -/// that file while ours improves by 5, which says our limit there is the -/// masking model rather than the bitrate. That is the next round; the floor -/// exists so it cannot quietly get worse first. Worst row: hein at 192 kbit/s, -/// 12.6 dB behind. -const WORST_WINDOW_EXCESS_DB: f64 = 13.5; +/// The gap was 12.6 dB when this floor went in, on the two spoken-word +/// sources, and mid/side stereo closed it: the encoder declared joint stereo +/// while writing plain left/right, so near-mono speech was coded twice. The +/// worst row now is dl8a at 192 kbit/s, 4.1 dB behind on a wide music mix. +const WORST_WINDOW_EXCESS_DB: f64 = 5.0; /// How far under LAME a row may sit before the sweep fails, in correlation. /// @@ -491,7 +497,7 @@ const WORST_WINDOW_EXCESS_DB: f64 = 13.5; /// floor sits just under that worst row rather than at zero because three rows /// are already ahead of LAME and the spread is what a regression would have to /// widen. -const LAME_CORR_FLOOR: f64 = -0.0015; +const LAME_CORR_FLOOR: f64 = -0.0012; fn expand(path: &str) -> PathBuf { PathBuf::from(match path.strip_prefix("~/") { @@ -634,3 +640,65 @@ fn real_library_sweep_vs_lame() { assert!(rows > 0, "no library sources were readable"); assert!(failures.is_empty(), "{failures:#?}"); } + +/// The `mode_extension` of every frame of a stream, in order. +fn mode_exts(bytes: &[u8]) -> Vec { + let mut out = Vec::new(); + let mut at = 0; + while at + 4 <= bytes.len() { + let Ok(header) = FrameHeader::parse(&bytes[at..]) else { + at += 1; + continue; + }; + let Some(len) = header.frame_len() else { break }; + out.push(header.mode_ext); + at += len; + } + out +} + +/// Mid/side is chosen for the signal it helps and declined for the one it +/// hurts. Two channels carrying the same waveform put everything in the sum +/// and nothing in the difference, which is the case mid/side exists for; two +/// carrying opposite waveforms are its worst case, where the difference is +/// the loud channel and coding it as such would spend the frame's bits on the +/// quiet one. Both roundtrip, because the decoder undoes whichever was +/// written. +#[test] +fn mid_side_follows_the_channel_correlation() { + let mut seed = 0x2545_f491_4f6c_dd1du64; + let mut noise = || { + seed ^= seed << 13; + seed ^= seed >> 7; + seed ^= seed << 17; + (seed >> 40) as f32 / 8388608.0 - 0.5 + }; + let n = 44100; + let (mut same, mut opposed) = (Vec::with_capacity(n * 2), Vec::with_capacity(n * 2)); + for i in 0..n { + // Band-limited enough to be codeable: a slow tone under the noise. + let tone = (i as f32 * 0.03).sin() * 0.4; + let v = tone + noise() * 0.05; + same.push(v); + same.push(v); + opposed.push(v); + opposed.push(-v); + } + for (label, pcm, want_ms) in [("same", same, true), ("opposed", opposed, false)] { + let bytes = encode(&pcm, 44100, 2, 128); + let exts = mode_exts(&bytes); + assert!(exts.len() > 20, "{label}: only {} frames", exts.len()); + let ms = exts.iter().filter(|e| *e & 2 != 0).count(); + // The first and last frames carry priming and a tail, so judge the body. + let body = exts.len() - 2; + if want_ms { + assert!( + ms >= body, + "{label}: only {ms} of {} frames are mid/side", + exts.len() + ); + } else { + assert_eq!(ms, 0, "{label}: {ms} frames chose mid/side"); + } + } +} diff --git a/lanes/mp3lame-r1.report.md b/lanes/mp3lame-r1.report.md index 4f3fdd51..f85ec01b 100644 --- a/lanes/mp3lame-r1.report.md +++ b/lanes/mp3lame-r1.report.md @@ -211,3 +211,68 @@ signal-to-mask offset `6.0 + 15.0 * (1.0 - flatness)` dB, the spreading leaks (0.0032 up, 0.1 down), and the absolute threshold's `1.0 + 400.0 * (rel - 0.35)^2` shape. Speech is exactly the material whose tonality a 1024-point flatness estimate gets wrong. + +## Round 4: the encoder declared joint stereo and wrote plain left/right + +Round 3 left the gap concentrated on the two spoken-word sources, and speech is +where the two channels are nearly the same signal. Parsing both streams' frame +headers found the reason: our `mode_extension` was hard-coded to zero on every +frame while the header's channel mode said joint stereo. libmp3lame wrote +mid/side on 2017 of ~2200 frames of the same audio. Our decoder already +implemented mid/side correctly — only the encoder never asked for it, so a +near-mono voice was coded twice, once in each channel, at half the bits each. + +The fix is three pieces: both channels of a frame now take the same window +(adding a long block's lines to a short block's would smear one channel's +transient into the other), the frame picks mid/side when the difference of the +channels is quieter than their sum, and `mode_ext` is written per frame. +Masking thresholds for a mid/side pair are held to whichever channel masked +less, because an error in the side channel lands in both ears. + +Both metrics, all fourteen rows, round 3 → round 4: + +| source | kbps | corr gap | worst window (ours) | +|---|---|---|---| +| nik | 128 | -0.00073 → **-0.00067** | -12.1 → -12.1 | +| nik | 192 | -0.00030 → **-0.00028** | -17.6 → -17.1 | +| reelo | 128 | -0.00103 → -0.00103 | -11.1 → **-11.3** | +| reelo | 192 | -0.00045 → **-0.00044** | -16.3 → -16.1 | +| her | 128 | +0.00142 → **+0.00154** | -9.9 → **-10.0** | +| her | 192 | +0.00021 → **+0.00025** | -14.4 → **-14.7** | +| reell | 128 | +0.00021 → **+0.00030** | -9.7 → **-10.2** | +| reell | 192 | -0.00002 → **+0.00001** | -15.1 → **-15.7** | +| reelm | 128 | -0.00068 → **+0.00076** | -1.6 → **-9.2** | +| reelm | 192 | -0.00040 → **+0.00001** | -6.2 → **-16.5** | +| dl8a | 128 | -0.00062 → **-0.00057** | -3.2 → **-3.8** | +| dl8a | 192 | -0.00040 → **-0.00037** | -8.3 → -8.1 | +| hein | 128 | -0.00087 → **+0.00029** | -0.1 → **-10.1** | +| hein | 192 | -0.00030 → **+0.00001** | -6.8 → **-16.1** | + +Five rows now beat libmp3lame outright where three did before, and the two +spoken-word sources moved from the worst rows in the table to ties at 192 +kbit/s. hein at 192 went from 12.6 dB behind LAME's worst window to 3.3 dB; +reelm at 128 is now 7 dB *ahead*. Both gate floors tightened onto the new worst +rows: correlation -0.0015 → -0.0012 (reelo at 128), worst-window excess 13.5 → +5.0 dB (dl8a at 192, a wide music mix, which is the case mid/side cannot help). + +The decision threshold itself was swept and is flat: 0.5, 1, 2 and "always" +differ by 0.00001 in correlation on the two sources mid/side helps least, while +"never" costs 0.0005. Real music is nowhere near the threshold, so it is a +guard rather than a knob — and what it guards is now a test rather than an +argument: `mid_side_follows_the_channel_correlation` encodes two channels +carrying the same waveform and two carrying opposite ones, and asserts the +decision goes each way. + +### What round 4 ruled out on the way + +Before the stereo defect surfaced, four candidates were measured and rejected: +the masking offset and the absolute-threshold floor (bit-identical output +across 1e-9…1e-13), reservoir starvation (encoding the worst passage in +isolation gained 1.2 dB), and the distortion loop (amplifying scalefactors is a +net loss in both noise-to-mask and raw-noise orderings). Instrumenting the +loop's exit reasons explained why: **9498 of 9498 granules exit on the budget +break, 9484 of them at round 0**. `code_with` already fills the frame budget, so +the outer loop never runs — the encoder is a pure rate loop and the +psychoacoustic model reaches the output only through the band ordering it never +gets to use. That is the standing structural finding for this crate; the gain +in this round came from a missing feature, not from the model.