forge
Explore
Log in

Don't you dare go Hollow

Wake the block switcher, and measure what it is for

Browse files at this commit

4ca031182b0ef0672a6f3f9ef7ddbd938bc5830fAhmet Kaan GümüşParent: e722375
  • fix
    • wake the block switcher, and measure what it is for
Show full message
fix(mp3): wake the block switcher, and measure what it is for

The switcher decided a granule was a transient when the next granule's total
energy grew eightfold. A granule is 13 ms, and music meets that about once a
minute: counting block types in our own coded streams found one short granule
in 9196, against libmp3lame's 88 over the same audio. It has been dead code
since it was written.

Sweeping the constant over 2 through 32 moved whole-file correlation by
0.00004, which is the second half of the finding: the crate's quality gate
cannot see pre-echo at all. A few milliseconds of noise smeared backwards
before an attack disappears into a minute of correlation, and a gate like that
would have accepted the switcher being deleted.

So the sweep now also reports the worst 20 ms error-to-signal ratio, for ours
and for the reference, skipping windows under -60 dBFS. Against that metric the
constant is not flat: at the shipped 8.0 one window of a real file carries more
error energy than signal (+1.1 dB), the curve is flat from 1.6 to 4, and the
cliff sits between 4 and 8. The shipped value was just past the edge of it.
4.0 lands, at the cheap end of the flat part.

The new gate's floor is set from the measurement and the measurement is
unflattering: we lead the reference in the worst window on all four music
sources and trail it on all three speech ones, worst by 14 dB. On those, the
worst window barely improves when the bitrate rises by half, so the limit is
the masking model rather than the bits. That is the next round.
crates/ec-mp3/src/encode.rsmodified+17 -1
@@ -630,7 +630,23 @@ impl Mp3Encode {
630 // the resolution a long block would have spent on the attack630 // the resolution a long block would have spent on the attack
631 // itself, and there is no pre-echo to hide when nothing631 // itself, and there is no pre-echo to hide when nothing
632 // precedes it.632 // precedes it.
633- let attack = here > 1e-9 && next > here * 8.0 + 1e-6;633+ // How much louder the next granule has to be to count as an
634+ // attack. Swept against the worst 20 ms error-to-signal ratio
635+ // on real music (`real_library_sweep_vs_lame`), because
636+ // whole-file correlation cannot see pre-echo at all:
637+ //
638+ // ratio 1.3 1.6 2 3 4 8
639+ // dl8a@128 -2.3 -3.3 -3.3 -3.3 -3.3 +1.1 dB
640+ // dl8a@192 -6.7 -6.7 -6.7 -7.8 -7.8 -4.2 dB
641+ //
642+ // Flat from 1.6 to 4 and then a cliff: at 8 a whole granule
643+ // has to grow eightfold in total energy, which music does
644+ // about once a minute -- one short granule in 9196, against
645+ // libmp3lame's 88 over the same audio. Below 1.6 the extra
646+ // short blocks start costing correlation without buying any
647+ // more of the worst window back, so 4 sits at the cheap end
648+ // of the flat part.
649+ let attack = here > 1e-9 && next > here * 4.0 + 1e-6;
634 let block = match self.previous_block[ch] {650 let block = match self.previous_block[ch] {
635 1 => 2,651 1 => 2,
636 2 if attack => 2,652 2 if attack => 2,
crates/ec-mp3/tests/encode_matrix.rsmodified+76 -6
@@ -127,6 +127,42 @@ fn aligned(got: &[f32], want: &[f32], channels: usize) -> (f64, usize) {
127 best127 best
128 }128 }
129 129
130+/// Worst short-window error energy, relative to the source, over the file.
131+///
132+/// Whole-file correlation cannot see pre-echo: quantisation noise smeared
133+/// backwards across a 576-sample granule before an attack is a few
134+/// milliseconds of audible hash inside a minute of otherwise clean signal, and
135+/// integrating over the minute divides it away. Measured on this crate, going
136+/// from one short block per 9196 granules to 526 of them moved whole-file
137+/// correlation by 0.00004 -- in the wrong direction -- while changing exactly
138+/// the thing short blocks exist to fix. So the sweep also reports the worst
139+/// window: error energy over source energy, in dB, over 20 ms windows,
140+/// which is the scale a transient's pre-echo lives on.
141+fn worst_window_db(got: &[f32], want: &[f32], offset: usize, channels: usize) -> f64 {
142+ let window = 20 * 44100 / 1000 * channels;
143+ let skip = 1152 * channels;
144+ let n = (got.len() - offset).min(want.len());
145+ let mut worst = f64::MIN;
146+ let mut start = skip;
147+ while start + window + skip <= n {
148+ let (mut err, mut sig) = (0.0f64, 0.0f64);
149+ for i in start..start + window {
150+ let d = f64::from(got[offset + i]) - f64::from(want[i]);
151+ err += d * d;
152+ sig += f64::from(want[i]) * f64::from(want[i]);
153+ }
154+ // A window with no signal in it has no pre-echo to hide, and its
155+ // ratio would be meaningless; the -60 dBFS gate skips digital silence
156+ // and the fade-ins around it.
157+ if sig / window as f64 > 1e-6 {
158+ let db = 10.0 * (err / sig.max(1e-30)).log10();
159+ worst = worst.max(db);
160+ }
161+ start += window;
162+ }
163+ worst
164+}
165+
130 fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {166 fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> {
131 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {167 let mut encoder = Mp3Encoder::new(Mp3EncoderConfig {
132 bitrate_kbps: kbps,168 bitrate_kbps: kbps,
@@ -437,6 +473,16 @@ const LIBRARY: [(&str, &str); 7] = [
437 ),473 ),
438 ];474 ];
439 475
476+/// How much worse than LAME a row's worst 20 ms window may be, in dB.
477+///
478+/// The floor is set from the measurement and the measurement is bad: hein at
479+/// 192 kbit/s is 14.0 dB behind, and hein and reelm are the two spoken-word
480+/// sources. LAME's worst window improves by 12 dB from 128 to 192 kbit/s on
481+/// that file while ours improves by 5, which says our limit there is the
482+/// masking model rather than the bitrate. That is the next round; the floor
483+/// exists so it cannot quietly get worse first.
484+const WORST_WINDOW_EXCESS_DB: f64 = 15.0;
485+
440 /// How far under LAME a row may sit before the sweep fails, in correlation.486 /// How far under LAME a row may sit before the sweep fails, in correlation.
441 ///487 ///
442 /// The first measurement (60 s of each source, 44.1 kHz stereo, CBR) put every488 /// The first measurement (60 s of each source, 44.1 kHz stereo, CBR) put every
@@ -497,12 +543,27 @@ fn real_library_sweep_vs_lame() {
497 let seconds = 60u32;543 let seconds = 60u32;
498 let work = workdir("lame-sweep");544 let work = workdir("lame-sweep");
499 println!(545 println!(
500- "{:<7} {:>5} {:>9} {:>9} {:>8} {:>9} {:>9}",546+ "{:<7} {:>5} {:>9} {:>9} {:>8} {:>8} {:>8} {:>8} {:>8}",
501- "source", "kbps", "corr_ours", "corr_lame", "gap", "ours_kb", "lame_kb"547+ "source",
548+ "kbps",
549+ "corr_ours",
550+ "corr_lame",
551+ "gap",
552+ "wworst_o",
553+ "wworst_r",
554+ "ours_kb",
555+ "lame_kb"
502 );556 );
503 let mut rows = 0;557 let mut rows = 0;
504 let mut failures = Vec::new();558 let mut failures = Vec::new();
559+ // `EC_MP3_SWEEP_ONLY=reelo,dl8a` narrows the sweep to named sources, so a
560+ // constant can be swept against the rows it moves without paying for the
561+ // rows it does not.
562+ let only = std::env::var("EC_MP3_SWEEP_ONLY").unwrap_or_default();
505 for (name, src) in LIBRARY {563 for (name, src) in LIBRARY {
564+ if !only.is_empty() && !only.split(',').any(|w| w.trim() == name) {
565+ continue;
566+ }
506 let src = expand(src);567 let src = expand(src);
507 if !src.exists() {568 if !src.exists() {
508 println!("{name:<7} SKIP (missing)");569 println!("{name:<7} SKIP (missing)");
@@ -540,16 +601,19 @@ fn real_library_sweep_vs_lame() {
540 assert!(status.success(), "libmp3lame encode of {name} at {kbps}k");601 assert!(status.success(), "libmp3lame encode of {name} at {kbps}k");
541 // Both decoded by the same decoder and aligned the same way: an602 // Both decoded by the same decoder and aligned the same way: an
542 // encoder delay is not a quality difference.603 // encoder delay is not a quality difference.
543- let corr_of = |file: &Path| -> f64 {604+ let measure = |file: &Path| -> (f64, f64) {
544 let decoded = decode(file);605 let decoded = decode(file);
545- aligned(&decoded, &pcm, 2).0606+ let (corr, offset) = aligned(&decoded, &pcm, 2);
607+ (corr, worst_window_db(&decoded, &pcm, offset, 2))
546 };608 };
547- let (ours_corr, lame_corr) = (corr_of(&ours_file), corr_of(&lame_file));609+ let ((ours_corr, ours_worst), (lame_corr, lame_worst)) =
610+ (measure(&ours_file), measure(&lame_file));
548 let kb =611 let kb =
549 |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0;612 |p: &Path| std::fs::metadata(p).expect("size").len() as f64 * 8.0 / secs / 1000.0;
550 let gap = ours_corr - lame_corr;613 let gap = ours_corr - lame_corr;
551 println!(614 println!(
552- "{name:<7} {kbps:>5} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} {:>9.1} {:>9.1}",615+ "{name:<7} {kbps:>5} {ours_corr:>9.5} {lame_corr:>9.5} {gap:>+8.5} \
616+ {ours_worst:>+8.1} {lame_worst:>+8.1} {:>8.1} {:>8.1}",
553 kb(&ours_file),617 kb(&ours_file),
554 kb(&lame_file)618 kb(&lame_file)
555 );619 );
@@ -559,6 +623,12 @@ fn real_library_sweep_vs_lame() {
559 "{name} at {kbps} kbit/s: {ours_corr:.5} against LAME's {lame_corr:.5}"623 "{name} at {kbps} kbit/s: {ours_corr:.5} against LAME's {lame_corr:.5}"
560 ));624 ));
561 }625 }
626+ if ours_worst - lame_worst > WORST_WINDOW_EXCESS_DB {
627+ failures.push(format!(
628+ "{name} at {kbps} kbit/s: worst window {ours_worst:.1} dB \
629+ against LAME's {lame_worst:.1} dB"
630+ ));
631+ }
562 }632 }
563 }633 }
564 assert!(rows > 0, "no library sources were readable");634 assert!(rows > 0, "no library sources were readable");
lanes/mp3lame-r1.report.mdmodified+89 -0
@@ -61,3 +61,92 @@ psychoacoustic model.
61 VBR. `encode_vbr` exists and `Mp3EncoderConfig::vbr_quality` is honoured, but61 VBR. `encode_vbr` exists and `Mp3EncoderConfig::vbr_quality` is honoured, but
62 LAME's `-q`/`-V` scale does not map onto ours, so a matched-rate comparison62 LAME's `-q`/`-V` scale does not map onto ours, so a matched-rate comparison
63 needs a rate-matching search before it means anything. That is its own slice.63 needs a rate-matching search before it means anything. That is its own slice.
64+
65+## Round 2: the block switcher was inert, and the gate could not see it
66+
67+The 128-versus-192 shape pointed at bit allocation, and the first constant on
68+that path is the one that decides a granule is a transient:
69+`next_granule_energy > here * 8.0`, on whole-granule totals. Sweeping it over
70+2, 4, 8, 16, 32 moved the correlation of the three worst sources by 0.00004
71+across the whole range, and 8 through 32 were bit-identical.
72+
73+Counting block types in the coded streams explains why, and turns up something
74+worse than a mistuned constant:
75+
76+| stream | long | start | short | stop |
77+|--------|-----:|------:|------:|-----:|
78+| ours, reelo @128 | 9193 | 1 | **1** | 1 |
79+| libmp3lame, same | 8988 | 58 | **88** | 58 |
80+| ours, her @128 | 9190 | 2 | **2** | 2 |
81+| libmp3lame, same | 8948 | 72 | **102** | 70 |
82+
83+One short granule in 9196. A granule is 576 samples, 13 ms; requiring its
84+*total* energy to grow eightfold is a condition music meets about once a
85+minute. The switcher has been dead code since it was written.
86+
87+Forcing it awake at ratio 2 produces 526 short granules and moves whole-file
88+correlation by 0.00004, in the wrong direction. That is the finding: **the
89+crate's quality gate is structurally blind to the thing short blocks exist to
90+fix.** Pre-echo is a few milliseconds of noise smeared backwards before an
91+attack; correlating over a minute divides it away. A gate like that would have
92+accepted the switcher being deleted outright.
93+
94+### The metric the gate was missing
95+
96+`worst_window_db` now reports the worst 20 ms error-to-signal ratio in each
97+file, for ours and for LAME, skipping windows under -60 dBFS so silence does
98+not produce a ratio out of nothing. Against it the constant is not flat at all:
99+
100+| ratio | 1.3 | 1.6 | 2 | 3 | 4 | 8 |
101+|-------|----:|----:|--:|--:|--:|--:|
102+| dl8a @128 | -2.3 | -3.3 | -3.3 | -3.3 | -3.3 | **+1.1** |
103+| dl8a @192 | -6.7 | -6.7 | -6.7 | -7.8 | -7.8 | **-4.2** |
104+
105+At the shipped value one 20 ms window of dl8a carries more error energy than
106+signal. The curve is flat from 1.6 to 4 and falls off a cliff between 4 and 8,
107+so the shipped 8.0 sat just past the edge of a cliff nothing could see. Below
108+1.6 the extra short blocks cost correlation without buying back any more of the
109+worst window. **4.0 lands**, at the cheap end of the flat part.
110+
111+## Where the lane stands after round 2
112+
113+| source | kbit/s | corr ours | corr LAME | gap | worst 20 ms ours | worst LAME |
114+|--------|-------:|----------:|----------:|----:|-----------------:|-----------:|
115+| nik | 128 | 0.99789 | 0.99888 | -0.00099 | -11.4 | -11.2 |
116+| nik | 192 | 0.99950 | 0.99982 | -0.00032 | -17.7 | -17.2 |
117+| reelo | 128 | 0.99717 | 0.99855 | -0.00138 | -10.3 | -9.3 |
118+| reelo | 192 | 0.99927 | 0.99976 | -0.00049 | -16.3 | -16.1 |
119+| her | 128 | 0.99680 | 0.99565 | +0.00115 | -9.8 | -5.4 |
120+| her | 192 | 0.99901 | 0.99883 | +0.00018 | -14.7 | -11.1 |
121+| reell | 128 | 0.99855 | 0.99849 | +0.00006 | -9.3 | -6.1 |
122+| reell | 192 | 0.99966 | 0.99969 | -0.00003 | -15.2 | -11.7 |
123+| reelm | 128 | 0.99815 | 0.99897 | -0.00082 | -1.5 | -2.0 |
124+| reelm | 192 | 0.99951 | 0.99994 | -0.00042 | **-3.4** | **-13.2** |
125+| dl8a | 128 | 0.99625 | 0.99737 | -0.00111 | -3.3 | -6.0 |
126+| dl8a | 192 | 0.99894 | 0.99940 | -0.00046 | -7.8 | -12.2 |
127+| hein | 128 | 0.99858 | 0.99958 | -0.00101 | **-0.1** | **-7.6** |
128+| hein | 192 | 0.99964 | 0.99996 | -0.00032 | **-5.4** | **-19.4** |
129+
130+We are ahead of LAME in the worst window on all four music sources and behind
131+on all three where the material is speech or speech-dominated. The tell is what
132+happens between the two rates: on hein, LAME's worst window improves by 11.8 dB
133+for 50% more bits and ours improves by 5.3. A worst window that will not
134+improve when handed more bits is not short of bits. It is the masking model
135+letting a band go, or the distortion loop declining to buy it back.
136+
137+## Round 3, named
138+
139+Three candidates, in order of what the round-2 evidence points at:
140+
141+1. The distortion loop's stop conditions -- `for _round in 0..20`, three bands
142+ amplified per round, and the `spent * 20 > target_bits * 19` budget break.
143+ The comment on that break already admits it is a corner cut against the ISO
144+ outer loop, and a budget break is exactly what would cap the worst window
145+ while bits go unspent.
146+2. The masking offset, `6.0 + 15.0 * (1.0 - flatness)` dB. Speech is the
147+ material whose flatness estimate a 1024-point FFT gets most wrong.
148+3. The spreading leaks, 0.0032 upward and 0.1 downward, and the absolute
149+ threshold's `1.0 + 400.0 * (rel - 0.35)^2` shape.
150+
151+None of the three has been swept. All of them predate the only metric that can
152+price them.