forge
Explore
Log in

Don't you dare go Hollow

Revert "revert(opus): drop the Fs/250 CELT input delay, keep the EC_OPUS_X_DEBUG bisect"

Browse files at this commit

b1e155b5539295a3675ceb32886e370a335fc513Ahmet Kaan GümüşParent: 682c080
This reverts commit 901c6ac3a87baf445fcdc07171b4cd49cf19ef93.
crates/ec-opus/src/celt_enc.rsmodified+30 -6
@@ -78,6 +78,10 @@ const INV_TABLE: [u8; 128] = [
78 /// One forward-MDCT plan, the exact adjoint of the decoder's `ImdctPlan`:78 /// One forward-MDCT plan, the exact adjoint of the decoder's `ImdctPlan`:
79 /// window-fold, pre-rotation, an `l/2`-point FFT and post-rotation, scaled by79 /// window-fold, pre-rotation, an `l/2`-point FFT and post-rotation, scaled by
80 /// `2/l` so that decode(encode(x)) reconstructs at unit gain.80 /// `2/l` so that decode(encode(x)) reconstructs at unit gain.
81+/// libopus `opus_encoder.c`'s `delay_compensation = Fs/250`: how far behind
82+/// the API frame the CELT analysis window sits, in 48 kHz samples.
83+const CELT_DELAY_48K: usize = 192;
84+
81 #[derive(Clone, Debug)]85 #[derive(Clone, Debug)]
82 struct MdctPlan {86 struct MdctPlan {
83 l: usize,87 l: usize,
@@ -382,6 +386,11 @@ pub struct CeltEncoder {
382 plans: Vec<MdctPlan>,386 plans: Vec<MdctPlan>,
383 /// Preemphasised history, `channels * OVERLAP`.387 /// Preemphasised history, `channels * OVERLAP`.
384 in_mem: Vec<f32>,388 in_mem: Vec<f32>,
389+ /// libopus `opus_encoder.c`'s `delay_buffer`: the CELT layer is fed the
390+ /// input delayed by `delay_compensation = Fs/250` (192 samples at 48 kHz),
391+ /// so its analysis window sits 4 ms behind the API frame. Interleaved,
392+ /// `CELT_DELAY_48K / upsample` samples per channel.
393+ delay_buf: Vec<f32>,
385 preemph_mem: [f32; 2],394 preemph_mem: [f32; 2],
386 /// Coarse-energy prediction state, `2 * NB_BANDS`.395 /// Coarse-energy prediction state, `2 * NB_BANDS`.
387 old_band_e: Vec<f32>,396 old_band_e: Vec<f32>,
@@ -450,6 +459,7 @@ impl CeltEncoder {
450 window: celt::overlap_window(),459 window: celt::overlap_window(),
451 plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(),460 plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(),
452 in_mem: vec![0.0; channels * OVERLAP],461 in_mem: vec![0.0; channels * OVERLAP],
462+ delay_buf: vec![0.0; channels * CELT_DELAY_48K],
453 preemph_mem: [0.0; 2],463 preemph_mem: [0.0; 2],
454 old_band_e: vec![0.0; 2 * NB_BANDS],464 old_band_e: vec![0.0; 2 * NB_BANDS],
455 delayed_intra: 1.0,465 delayed_intra: 1.0,
@@ -509,6 +519,7 @@ impl CeltEncoder {
509 /// Drops all inter-frame state.519 /// Drops all inter-frame state.
510 pub fn reset(&mut self) {520 pub fn reset(&mut self) {
511 self.in_mem.fill(0.0);521 self.in_mem.fill(0.0);
522+ self.delay_buf.fill(0.0);
512 self.preemph_mem = [0.0; 2];523 self.preemph_mem = [0.0; 2];
513 self.old_band_e.fill(0.0);524 self.old_band_e.fill(0.0);
514 self.delayed_intra = 1.0;525 self.delayed_intra = 1.0;
@@ -599,20 +610,29 @@ impl CeltEncoder {
599 // --- Preemphasis ----------------------------------------------------610 // --- Preemphasis ----------------------------------------------------
600 let stride = n + OVERLAP;611 let stride = n + OVERLAP;
601 let mut silence = true;612 let mut silence = true;
613+ let mut delay = std::mem::take(&mut self.delay_buf);
614+ let mut next_delay = [0.0f32; 2 * CELT_DELAY_48K];
602 for ch in 0..c {615 for ch in 0..c {
603 let base = ch * stride;616 let base = ch * stride;
604 self.in_buf[base..base + OVERLAP]617 self.in_buf[base..base + OVERLAP]
605 .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]);618 .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]);
606 let mut mem = self.preemph_mem[ch];619 let mut mem = self.preemph_mem[ch];
607 let up = self.upsample;620 let up = self.upsample;
621+ // `src(j)`: input sample `j` of the delayed stream libopus's CELT
622+ // layer sees -- the `d` samples held over from the previous call
623+ // first, then this frame's.
624+ let d = CELT_DELAY_48K / up;
625+ let src = |j: usize| {
626+ if j < d { delay[j * c + ch] } else { pcm[(j - d) * c + ch] }
627+ };
608 for i in 0..n {628 for i in 0..n {
609 // Zero-stuffing to 48 kHz: the images above the input's own629 // Zero-stuffing to 48 kHz: the images above the input's own
610 // Nyquist are never coded (the caller caps `end`) and the630 // Nyquist are never coded (the caller caps `end`) and the
611 // decoder's decimation drops them.631 // decoder's decimation drops them.
612 let mut x = if up == 1 {632 let mut x = if up == 1 {
613- pcm[i * c + ch] * SIG_SCALE633+ src(i) * SIG_SCALE
614 } else if i.is_multiple_of(up) {634 } else if i.is_multiple_of(up) {
615- pcm[(i / up) * c + ch] * SIG_SCALE * up as f32635+ src(i / up) * SIG_SCALE * up as f32
616 } else {636 } else {
617 0.0637 0.0
618 };638 };
@@ -626,9 +646,15 @@ impl CeltEncoder {
626 silence &= v == 0.0;646 silence &= v == 0.0;
627 }647 }
628 self.preemph_mem[ch] = mem;648 self.preemph_mem[ch] = mem;
649+ for k in 0..d {
650+ next_delay[k * c + ch] = src(in_n + k);
651+ }
629 self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]652 self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]
630 .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]);653 .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]);
631 }654 }
655+ delay[..c * (CELT_DELAY_48K / self.upsample)]
656+ .copy_from_slice(&next_delay[..c * (CELT_DELAY_48K / self.upsample)]);
657+ self.delay_buf = delay;
632 658
633 // --- Silence flag (first symbol of the frame) -----------------------659 // --- Silence flag (first symbol of the frame) -----------------------
634 // Only exists when CELT opens the stream (decoder: `tell == 1`); under660 // Only exists when CELT opens the stream (decoder: `tell == 1`); under
@@ -711,14 +737,12 @@ impl CeltEncoder {
711 }737 }
712 }738 }
713 739
714- // `EC_OPUS_X_DEBUG`: the analysis chain stage by stage for a bisect
715- // against libopus on the same PCM -- the pre-emphasised window, the
716- // MDCT output, the band energies and the normalised `X`.
717 if std::env::var_os("EC_OPUS_X_DEBUG").is_some() {740 if std::env::var_os("EC_OPUS_X_DEBUG").is_some() {
718 let f: Vec<String> =741 let f: Vec<String> =
719 self.in_buf[OVERLAP..OVERLAP + 16].iter().map(|v| format!("{v:.5}")).collect();742 self.in_buf[OVERLAP..OVERLAP + 16].iter().map(|v| format!("{v:.5}")).collect();
720 let e: f64 = self.in_buf[..n + OVERLAP].iter().map(|v| *v as f64 * *v as f64).sum();743 let e: f64 = self.in_buf[..n + OVERLAP].iter().map(|v| *v as f64 * *v as f64).sum();
721- let ovl: Vec<String> = self.in_buf[..4].iter().map(|v| format!("{v:.5}")).collect();744+ let ovl: Vec<String> =
745+ self.in_buf[..4].iter().map(|v| format!("{v:.5}")).collect();
722 eprintln!("XPRE {} | E {e:.6e} ovl {}", f.join(" "), ovl.join(" "));746 eprintln!("XPRE {} | E {e:.6e} ovl {}", f.join(" "), ovl.join(" "));
723 let fr: Vec<String> = self.freq[..16].iter().map(|v| format!("{v:.5}")).collect();747 let fr: Vec<String> = self.freq[..16].iter().map(|v| format!("{v:.5}")).collect();
724 let be: Vec<String> = self.band_e[..8].iter().map(|v| format!("{v:.5}")).collect();748 let be: Vec<String> = self.band_e[..8].iter().map(|v| format!("{v:.5}")).collect();
crates/ec-opus/src/encoder.rsmodified+16 -10
@@ -40,11 +40,16 @@ const MAX_SILK_PACKET_BYTES: usize = 1 + 1 + 2 * 2 + 3 * MAX_FRAME_BYTES;
40 const SILK_LOOK_AHEAD_48K_NB: usize = 58;40 const SILK_LOOK_AHEAD_48K_NB: usize = 58;
41 const SILK_LOOK_AHEAD_48K_MB: usize = 54;41 const SILK_LOOK_AHEAD_48K_MB: usize = 54;
42 const SILK_LOOK_AHEAD_48K_WB: usize = 50;42 const SILK_LOOK_AHEAD_48K_WB: usize = 50;
43+/// The CELT layer's own delay: one MDCT overlap (120) plus libopus's
44+/// `delay_compensation = Fs/250` (`CELT_DELAY_48K`, 192 at 48 kHz), which the
45+/// CELT encoder applies to its input so its analysis window sits where
46+/// libopus's does.
47+const CELT_LOOK_AHEAD_48K: usize = 120 + 192;
43 /// How far the hybrid path delays the SILK layer's input so its output lines48 /// How far the hybrid path delays the SILK layer's input so its output lines
44 /// up with the CELT layer's at the decoder (which sums them as-is): CELT's49 /// up with the CELT layer's at the decoder (which sums them as-is): CELT's
45-/// overlap (120) minus SILK's WB round trip, click-measured through the50+/// delay minus SILK's WB round trip, click-measured through the
46 /// decoder with one layer muted (`hybrid_layers_align` in conformance.rs).51 /// decoder with one layer muted (`hybrid_layers_align` in conformance.rs).
47-const HYBRID_SILK_DELAY_48K: usize = 120 - SILK_LOOK_AHEAD_48K_WB;52+const HYBRID_SILK_DELAY_48K: usize = CELT_LOOK_AHEAD_48K - SILK_LOOK_AHEAD_48K_WB;
48 /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent.53 /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent.
49 /// Was 8: at 16 kbps SILK takes 37 of the 40-byte budget, so 8 expanded54 /// Was 8: at 16 kbps SILK takes 37 of the 40-byte budget, so 8 expanded
50 /// 5133/6001 packets (+12.9% rate on the speech gate); libopus leaves CELT55 /// 5133/6001 packets (+12.9% rate on the speech gate); libopus leaves CELT
@@ -194,7 +199,8 @@ impl Encoder {
194 /// Encoder delay in *input* samples for a `frame_size`-sample (per199 /// Encoder delay in *input* samples for a `frame_size`-sample (per
195 /// channel, native rate) frame: the decoded stream lags the input by200 /// channel, native rate) frame: the decoded stream lags the input by
196 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`201 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`
197- /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz.202+ /// cancels it exactly. CELT: one MDCT overlap plus the 192-sample input
203+ /// delay compensation, 312 samples at 48 kHz.
198 /// SILK (10, 20, 40 or 60 ms frames, when the application/bitrate or an204 /// SILK (10, 20, 40 or 60 ms frames, when the application/bitrate or an
199 /// explicit [`Encoder::set_mode`] select it — the same205 /// explicit [`Encoder::set_mode`] select it — the same
200 /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches206 /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches
@@ -213,7 +219,7 @@ impl Encoder {
213 };219 };
214 return delay / self.upsample;220 return delay / self.upsample;
215 }221 }
216- 120 / self.upsample222+ CELT_LOOK_AHEAD_48K / self.upsample
217 }223 }
218 224
219 /// Forces the coded bandwidth; [`None`] (the default) picks it from the225 /// Forces the coded bandwidth; [`None`] (the default) picks it from the
@@ -896,33 +902,33 @@ mod tests {
896 let mut e = Encoder::new(24000, 2, Application::Audio).unwrap();902 let mut e = Encoder::new(24000, 2, Application::Audio).unwrap();
897 e.set_bitrate(256_000);903 e.set_bitrate(256_000);
898 assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);904 assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);
899- assert_eq!(e.look_ahead(960), 60);905+ assert_eq!(e.look_ahead(960), CELT_LOOK_AHEAD_48K / 2);
900 }906 }
901 907
902 /// `look_ahead` must use the same 10-or-20 ms-frame predicate dispatch908 /// `look_ahead` must use the same 10-or-20 ms-frame predicate dispatch
903 /// does (`silk_choice`/`hybrid_choice`), not just `wants_silk`: 2.5/5 ms909 /// does (`silk_choice`/`hybrid_choice`), not just `wants_silk`: 2.5/5 ms
904 /// frames still code as CELT, while 10/20 ms speech follows SILK and910 /// frames still code as CELT, while 10/20 ms speech follows SILK and
905- /// hybrid follows CELT's overlap.911+ /// hybrid follows CELT's delay.
906 #[test]912 #[test]
907 fn look_ahead_matches_the_frame_size_dispatch_actually_uses() {913 fn look_ahead_matches_the_frame_size_dispatch_actually_uses() {
908 let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();914 let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();
909 e.set_bitrate(8000);915 e.set_bitrate(8000);
910 assert_eq!(e.look_ahead(480), 58, "10ms NB SILK");916 assert_eq!(e.look_ahead(480), 58, "10ms NB SILK");
911- assert_eq!(e.look_ahead(240), 120, "5ms frame falls back to CELT");917+ assert_eq!(e.look_ahead(240), CELT_LOOK_AHEAD_48K, "5ms frame falls back to CELT");
912 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");918 assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");
913 919
914 // 16k VoIP is hybrid-FB since the libopus threshold port (CELT overlap).920 // 16k VoIP is hybrid-FB since the libopus threshold port (CELT overlap).
915 e.set_bitrate(16000);921 e.set_bitrate(16000);
916- assert_eq!(e.look_ahead(960), 120, "20ms hybrid FB");922+ assert_eq!(e.look_ahead(960), CELT_LOOK_AHEAD_48K, "20ms hybrid FB");
917 923
918 e.set_bitrate(32000);924 e.set_bitrate(32000);
919- assert_eq!(e.look_ahead(960), 120, "20ms hybrid, CELT's overlap");925+ assert_eq!(e.look_ahead(960), CELT_LOOK_AHEAD_48K, "20ms hybrid, CELT's delay");
920 926
921 let mut e = Encoder::new(48000, 2, Application::Voip).unwrap();927 let mut e = Encoder::new(48000, 2, Application::Voip).unwrap();
922 e.set_bitrate(8000);928 e.set_bitrate(8000);
923 assert_eq!(e.look_ahead(960), 58, "stereo 20ms NB SILK");929 assert_eq!(e.look_ahead(960), 58, "stereo 20ms NB SILK");
924 e.set_bitrate(64_000);930 e.set_bitrate(64_000);
925- assert_eq!(e.look_ahead(960), 120, "stereo 20ms hybrid");931+ assert_eq!(e.look_ahead(960), CELT_LOOK_AHEAD_48K, "stereo 20ms hybrid");
926 }932 }
927 933
928 #[test]934 #[test]
crates/ec-opus/tests/conformance.rsmodified+6 -4
@@ -1303,8 +1303,9 @@ use ec_ogg::OggMuxer;
1303 1303
1304 /// The RFC 7845 identification header for this encoder — built by the crate's1304 /// The RFC 7845 identification header for this encoder — built by the crate's
1305 /// own [`ec_opus::ogg`] helper, so a muxer and the encoder cannot disagree.1305 /// own [`ec_opus::ogg`] helper, so a muxer and the encoder cannot disagree.
1306-/// `pre_skip` is the encoder's [`Encoder::look_ahead`]: 120, the CELT overlap1306+/// `pre_skip` is the encoder's [`Encoder::look_ahead`]: 312, the CELT overlap
1307-/// delay, for every CELT call site; SILK's own (larger) delay for SILK.1307+/// plus its input delay compensation, for every CELT call site; SILK's own
1308+/// delay for SILK.
1308 fn opus_head(channels: usize, pre_skip: u16, layout: Option<(usize, usize, &[u8])>) -> Vec<u8> {1309 fn opus_head(channels: usize, pre_skip: u16, layout: Option<(usize, usize, &[u8])>) -> Vec<u8> {
1309 let mapping =1310 let mapping =
1310 layout.map(|(streams, coupled, table)| (1u8, streams as u8, coupled as u8, table));1311 layout.map(|(streams, coupled, table)| (1u8, streams as u8, coupled as u8, table));
@@ -2510,14 +2511,15 @@ fn hybrid_layers_align() {
2510 e.look_ahead(960)2511 e.look_ahead(960)
2511 }2512 }
2512 );2513 );
2513- // A fullband CELT click lands at exactly +120 (`celt_click_peak_offset`);2514+ // A fullband CELT click lands at exactly +312 (`celt_click_peak_offset`:
2515+ // the MDCT overlap plus the 192-sample input delay compensation);
2514 // the band-limited HB layer's main lobe sits up to 2 samples early once2516 // the band-limited HB layer's main lobe sits up to 2 samples early once
2515 // transient frames keep their short blocks, and SILK lands at +121.2517 // transient frames keep their short blocks, and SILK lands at +121.
2516 assert!(2518 assert!(
2517 (plb - phb).abs() <= 3,2519 (plb - phb).abs() <= 3,
2518 "layers misaligned: LB +{plb} vs HB +{phb}"2520 "layers misaligned: LB +{plb} vs HB +{phb}"
2519 );2521 );
2520- assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120");2522+ assert!((phb - 312).abs() <= 2, "HB peak +{phb}, look_ahead 312");
2521 }2523 }
2522 2524
2523 /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks2525 /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks
lanes/opus-gate-r1.sweep.txtmodified+12 -12
@@ -1,15 +1,15 @@
1 # ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)1 # ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1)
2 # both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo2 # both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo
3 # source kbps ours_kbps ref_kbps rate% corr_ours corr_ref gap Q_ours Q_ref err_ratio minsec_ours minsec_ref drop_ours drop_ref3 # source kbps ours_kbps ref_kbps rate% corr_ours corr_ref gap Q_ours Q_ref err_ratio minsec_ours minsec_ref drop_ours drop_ref
4-nik 64 69.1 69.2 -0.1 0.9887 0.9864 -0.0023 -80.86 -154.78 0.643 0.9767 0.9745 0 04+nik 64 69.1 69.2 -0.1 0.9887 0.9864 -0.0023 -114.88 -154.78 0.800 0.9769 0.9745 0 0
5-nik 96 100.9 101.0 -0.1 0.9947 0.9940 -0.0007 -26.28 -31.55 0.954 0.9886 0.9888 0 05+nik 96 100.9 101.0 -0.1 0.9947 0.9940 -0.0007 -109.44 -31.55 1.763 0.9891 0.9888 0 0
6-reelo 64 63.5 63.6 -0.1 0.9893 0.9866 -0.0026 -202.81 -123.36 1.509 0.9699 0.9686 0 06+reelo 64 63.6 63.6 -0.0 0.9894 0.9866 -0.0028 -170.07 -123.36 1.287 0.9709 0.9686 0 0
7-reelo 96 93.3 93.9 -0.6 0.9946 0.9937 -0.0008 -112.54 -125.18 0.928 0.9861 0.9854 0 07+reelo 96 93.4 93.9 -0.5 0.9950 0.9937 -0.0013 -100.39 -125.18 0.861 0.9875 0.9854 0 0
8-her 64 67.6 67.9 -0.6 0.9833 0.9794 -0.0039 -366.18 -339.00 1.104 0.9471 0.9406 0 08+her 64 67.6 67.9 -0.4 0.9837 0.9794 -0.0042 -333.52 -339.00 0.980 0.9481 0.9406 0 0
9-her 96 100.8 101.5 -0.7 0.9913 0.9902 -0.0010 -206.21 -191.50 1.072 0.9724 0.9728 0 09+her 96 101.0 101.5 -0.5 0.9925 0.9902 -0.0022 -248.22 -191.50 1.292 0.9774 0.9728 0 0
10-reell 64 71.3 71.3 -0.0 0.9908 0.9880 -0.0028 -198.89 -128.39 1.440 0.9718 0.9644 0 010+reell 64 71.3 71.3 -0.0 0.9908 0.9880 -0.0028 -263.61 -128.39 1.916 0.9717 0.9644 0 0
11-reell 96 105.3 105.4 -0.0 0.9956 0.9948 -0.0008 -169.83 -29.16 2.516 0.9854 0.9804 0 011+reell 96 105.3 105.4 -0.0 0.9956 0.9948 -0.0008 -266.25 -29.16 3.900 0.9856 0.9804 0 0
12-dl8a 64 65.7 65.8 -0.2 0.9889 0.9865 -0.0024 -221.23 -378.84 0.536 0.9794 0.9723 0 012+dl8a 64 65.7 65.8 -0.1 0.9890 0.9865 -0.0025 -204.82 -378.84 0.498 0.9789 0.9723 0 0
13-dl8a 96 96.5 96.8 -0.4 0.9942 0.9934 -0.0008 -144.33 -423.47 0.315 0.9878 0.9864 0 013+dl8a 96 96.6 96.8 -0.3 0.9943 0.9934 -0.0009 -170.45 -423.47 0.361 0.9882 0.9864 0 0
14-hein 64 64.7 64.9 -0.3 0.9883 0.9874 -0.0009 -115.57 -388.31 0.302 0.9286 0.9148 0 014+hein 64 64.8 64.9 -0.2 0.9888 0.9874 -0.0014 -382.47 -388.31 0.980 0.9345 0.9148 0 0
15-hein 96 86.7 86.9 -0.3 0.9942 0.9930 -0.0012 -105.73 -246.46 0.490 0.9664 0.9499 0 015+hein 96 86.8 86.9 -0.2 0.9945 0.9930 -0.0015 -367.35 -246.46 1.602 0.9700 0.9499 0 0