State the masking threshold in MDCT power units so NMR means something
Browse files at this commit60c1bbb502c5088ce3db69dad6eaa86679c5e4ebParent: 252530f- fix
- state the masking threshold in MDCT power units so NMR means something
2 changed files +98 -27
- crates/ec-mp3/src/encode.rs +66 -14
- crates/ec-mp3/tests/encode_matrix.rs +32 -13
crates/ec-mp3/src/encode.rsmodified+66 -14
| @@ -524,8 +524,20 @@ impl Mp3Encode { | ||
| 524 | 524 | history[keep..].copy_from_slice(&mono[mono.len() - n..]); |
| 525 | 525 | } |
| 526 | 526 | |
| 527 | - /// Allowed noise per long scalefactor band, from the masking model. | |
| 527 | + /// Allowed noise per long scalefactor band, from the masking model, in | |
| 528 | + /// the units `code_with` measures quantisation noise in (summed squared | |
| 529 | + /// MDCT lines), so noise / threshold is a noise-to-mask ratio. | |
| 530 | + /// | |
| 531 | + /// The FFT here is unnormalised: for input of mean-square power P, a | |
| 532 | + /// 1024-point transform of the sine-windowed block (sum of w^2 = N/2) has | |
| 533 | + /// per-bin power N/2 * P = 512 P. The analysis filterbank is unity gain | |
| 534 | + /// and splits P across 32 subbands (P/32 each), and `mdct_long` scales by | |
| 535 | + /// 1/9 with a 36-point sine window (sum of w^2 cos^2 = 9), so each of a | |
| 536 | + /// subband's 18 lines carries P/32 * 9/81 = P/288. A band of W lines | |
| 537 | + /// spans W * 512/576 FFT bins: FFT energy / MDCT energy = | |
| 538 | + /// (W * 8/9 * 512 P) / (W * P/288) = 2^17, the `FFT_TO_MDCT` below. | |
| 528 | 539 | fn psy_threshold(&mut self, ch: usize) -> Vec<f32> { |
| 540 | + const FFT_TO_MDCT: f32 = 1.0 / 131072.0; | |
| 529 | 541 | let mut block: Vec<f32> = self.psy_history[ch].clone(); |
| 530 | 542 | self.fft_window.apply(&mut block); |
| 531 | 543 | let mut spectrum = vec![ec_dsp::Complex::<f32>::ZERO; 513]; |
| @@ -553,7 +565,7 @@ impl Mp3Encode { | ||
| 553 | 565 | 1.0 |
| 554 | 566 | }; |
| 555 | 567 | let offset_db = 6.0 + 15.0 * (1.0 - flatness); |
| 556 | - *slot = sum * 10f32.powf(-offset_db / 10.0); | |
| 568 | + *slot = sum * FFT_TO_MDCT * 10f32.powf(-offset_db / 10.0); | |
| 557 | 569 | } |
| 558 | 570 | // Spreading: masking leaks upward strongly and downward weakly. |
| 559 | 571 | let mut spread = energy.clone(); |
| @@ -568,7 +580,7 @@ impl Mp3Encode { | ||
| 568 | 580 | // Absolute threshold, coarse: hearing is least sensitive at the ends. |
| 569 | 581 | for (band, slot) in spread.iter_mut().enumerate() { |
| 570 | 582 | let rel = band as f32 / SFB_LONG as f32; |
| 571 | - let floor = 1e-9 * (1.0 + 400.0 * (rel - 0.35).max(0.0).powi(2)); | |
| 583 | + let floor = 1e-9 * FFT_TO_MDCT * (1.0 + 400.0 * (rel - 0.35).max(0.0).powi(2)); | |
| 572 | 584 | *slot = slot.max(floor); |
| 573 | 585 | } |
| 574 | 586 | spread |
| @@ -903,12 +915,14 @@ fn mdct_short(input: &[f32; 36], out: &mut [f32]) { | ||
| 903 | 915 | /// granule costs more bits); a lower quality raises it. 0.5 is neutral. |
| 904 | 916 | fn quality_threshold(threshold: &[f32], quality: f32) -> Vec<f32> { |
| 905 | 917 | 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; | |
| 918 | + // The mapping: 24 dB of noise-to-mask margin across the quality range. | |
| 919 | + // Its centre sits 4 dB over the mask, because the model's mask is | |
| 920 | + // conservative (its flatness-derived offset lands 11-13 dB under white | |
| 921 | + // noise where 6 dB is the noise-like figure); 4 dB is what puts q = 0.5 | |
| 922 | + // at `bitrate_for_quality(0.5)` on mp3src-stereo-48000 and two real | |
| 923 | + // stereo tracks (210-225 kbit/s, decoding above the CBR-192 bar; 5 dB | |
| 924 | + // gave 195-208 but slipped under that bar, 6 dB gave 170-189). | |
| 925 | + let db = (0.5 - q) * 24.0 + 4.0; | |
| 912 | 926 | let scale = 10f32.powf(db / 10.0); |
| 913 | 927 | threshold.iter().map(|&t| t * scale).collect() |
| 914 | 928 | } |
| @@ -952,11 +966,19 @@ fn quantise_granule( | ||
| 952 | 966 | if spent * 20 > target_bits * 19 { |
| 953 | 967 | break; // the budget is spent; amplifying now only coarsens |
| 954 | 968 | } |
| 955 | - let chosen: Vec<usize> = if over.is_empty() { | |
| 956 | - order.iter().copied().take(3).collect() | |
| 957 | - } else { | |
| 958 | - over | |
| 959 | - }; | |
| 969 | + // Bands over their mask get the bits first, worst three per round so | |
| 970 | + // the rate loop re-fits `global_gain` around a small step; once every | |
| 971 | + // band is under its mask the spare bits go to the noisiest ones. | |
| 972 | + // corner-cut: the ISO outer loop keeps amplifying over-mask bands past | |
| 973 | + // the budget and lets the rate loop coarsen the rest; measured here it | |
| 974 | + // costs 12-36% RMS against the source (mp3src-stereo-48000, 128/192) | |
| 975 | + // for a model this coarse, and the encode_matrix bar is an RMS metric. | |
| 976 | + // Upgrade path: a finer model (ISO spreading function, tonality from | |
| 977 | + // phase prediction) before trusting the mask over the budget. | |
| 978 | + let chosen: Vec<usize> = if over.is_empty() { order } else { over } | |
| 979 | + .into_iter() | |
| 980 | + .take(3) | |
| 981 | + .collect(); | |
| 960 | 982 | if chosen.is_empty() { |
| 961 | 983 | break; |
| 962 | 984 | } |
| @@ -1428,6 +1450,36 @@ mod tests { | ||
| 1428 | 1450 | /// The delay the Info tag states is the delay the pipeline has. Our own |
| 1429 | 1451 | /// decoder ignores the tag, so what it hands back is the untrimmed stream: |
| 1430 | 1452 | /// the content starts exactly `ENCODER_DELAY + DECODER_DELAY` samples in. |
| 1453 | + /// The mask is stated in the quantiser's noise units: on white noise the | |
| 1454 | + /// band energy of the MDCT sits the signal-to-mask offset (6 dB, plus | |
| 1455 | + /// what the flatness estimate adds) above the threshold, not 2^17 away. | |
| 1456 | + #[test] | |
| 1457 | + fn masking_threshold_is_in_mdct_power_units() { | |
| 1458 | + let mut core = Mp3Encode::new(48000, 1, 128, None).unwrap(); | |
| 1459 | + let mut seed = 0x2545_f491_4f6c_dd1du64; | |
| 1460 | + let mut noise = || { | |
| 1461 | + seed ^= seed << 13; | |
| 1462 | + seed ^= seed >> 7; | |
| 1463 | + seed ^= seed << 17; | |
| 1464 | + (seed >> 40) as f32 / 8_388_608.0 - 1.0 | |
| 1465 | + }; | |
| 1466 | + for _ in 0..8 { | |
| 1467 | + let pcm: Vec<f32> = (0..1152).map(|_| 0.25 * noise()).collect(); | |
| 1468 | + core.encode_block(&pcm); | |
| 1469 | + } | |
| 1470 | + let granule = core.pending.last().unwrap().clone(); | |
| 1471 | + let xr = core.mdct(0, &granule.subband, 0); | |
| 1472 | + let starts = long_starts(48000); | |
| 1473 | + let mut sum = 0.0f32; | |
| 1474 | + for band in 3..16 { | |
| 1475 | + let (from, to) = (usize::from(starts[band]), usize::from(starts[band + 1])); | |
| 1476 | + let energy: f32 = xr[from..to].iter().map(|v| v * v).sum(); | |
| 1477 | + sum += 10.0 * (energy / granule.threshold[band]).log10(); | |
| 1478 | + } | |
| 1479 | + let db = sum / 13.0; | |
| 1480 | + assert!((6.0..=18.0).contains(&db), "signal sits {db:.1} dB over its mask"); | |
| 1481 | + } | |
| 1482 | + | |
| 1431 | 1483 | #[test] |
| 1432 | 1484 | fn encoder_delay_is_what_the_tag_says() { |
| 1433 | 1485 | for (rate, channels) in [(44100u32, 1usize), (48000, 2)] { |
crates/ec-mp3/tests/encode_matrix.rsmodified+32 -13
| @@ -143,26 +143,45 @@ fn encode(pcm: &[f32], rate: u32, channels: usize, kbps: u32) -> Vec<u8> { | ||
| 143 | 143 | out |
| 144 | 144 | } |
| 145 | 145 | |
| 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). | |
| 146 | +/// CBR-192 of the stereo 48 kHz tone fixture decodes at least as well as it | |
| 147 | +/// did before the masking model was put in the quantiser's units (9ac19d6: | |
| 148 | +/// corr 0.999999, RMS error 0.020% of the signal). A byte pin stood here | |
| 149 | +/// while VBR landed; the psychoacoustic change legitimately moves the bytes, | |
| 150 | +/// so the gate is the quality those bytes carried. | |
| 157 | 151 | #[test] |
| 158 | -fn cbr_output_is_unchanged() { | |
| 152 | +fn cbr_quality_holds_its_floor() { | |
| 159 | 153 | let path = fixtures().join("audio/wav16-stereo-48000.wav"); |
| 160 | 154 | let Some((pcm, rate, channels)) = read_wav(&path) else { |
| 161 | 155 | eprintln!("no WAV fixtures: run scripts/gen-fixtures.sh"); |
| 162 | 156 | return; |
| 163 | 157 | }; |
| 164 | 158 | let bytes = encode(&pcm, rate, channels, 192); |
| 165 | - assert_eq!((bytes.len(), fnv1a(&bytes)), (73728, 0xab48da1954f88c48)); | |
| 159 | + let file = workdir("cbr").join("cbr192.mp3"); | |
| 160 | + std::fs::write(&file, &bytes).unwrap(); | |
| 161 | + let decoded = decode(&file); | |
| 162 | + assert_eq!(decoded.len(), pcm.len()); | |
| 163 | + let corr = correlation(&decoded, &pcm); | |
| 164 | + let (err, sig) = decoded.iter().zip(&pcm).fold((0.0f64, 0.0f64), |(e, s), (d, p)| { | |
| 165 | + (e + f64::from(d - p).powi(2), s + f64::from(*p).powi(2)) | |
| 166 | + }); | |
| 167 | + let rms = (err / sig).sqrt(); | |
| 168 | + println!("cbr192 corr={corr:.6} rms={:.4}%", rms * 100.0); | |
| 169 | + assert!(corr >= 0.999_99, "corr {corr:.6}"); | |
| 170 | + assert!(rms <= 0.000_25, "rms {:.4}%", rms * 100.0); | |
| 171 | +} | |
| 172 | + | |
| 173 | +fn decode(file: &Path) -> Vec<f32> { | |
| 174 | + let out = Command::new("ffmpeg") | |
| 175 | + .args(["-v", "warning", "-i"]) | |
| 176 | + .arg(file) | |
| 177 | + .args(["-f", "f32le", "-"]) | |
| 178 | + .output() | |
| 179 | + .expect("run ffmpeg"); | |
| 180 | + assert!(out.stderr.is_empty(), "ffmpeg: {}", String::from_utf8_lossy(&out.stderr)); | |
| 181 | + out.stdout | |
| 182 | + .chunks_exact(4) | |
| 183 | + .map(|b| f32::from_le_bytes([b[0], b[1], b[2], b[3]])) | |
| 184 | + .collect() | |
| 166 | 185 | } |
| 167 | 186 | |
| 168 | 187 | fn encode_vbr(pcm: &[f32], rate: u32, channels: usize, quality: f32) -> Vec<u8> { |