forge
Explore
Log in

Don't you dare go Hollow

Feed the CELT layer the input delayed by Fs/250 like libopus

Browse files at this commit

5d7f93b7de5f9c2bf45df23cdfcee5bd364545e8Ahmet Kaan GümüşParent: 5811863
  • feat
    • feed the CELT layer the input delayed by Fs/250 like libopus
Show full message
feat(opus): feed the CELT layer the input delayed by Fs/250 like libopus

The first quantity that differs between our CELT analysis chain and
libopus 1.6 on the same PCM is not a transform or a table: it is which
samples the frame's analysis window covers. libopus buffers
delay_compensation = Fs/250 (192 samples at 48 kHz) in opus_encoder.c
and hands celt_encode_with_ec that delayed stream, so its MDCT window
sits 4 ms behind the API frame; ours started at the frame boundary.

Measured on the reell attack frame (frame 2, 20 ms, LM=3, transient):
sum|X| 55.29 -> 46.20 against libopus's 46.23, band log-energies
4.349 3.049 3.876 3.670 3.986 4.892 4.797 2.437 ->
3.516 4.003 3.271 4.594 1.143 4.273 4.759 3.718 against libopus's
3.439 4.005 3.260 4.595 1.179 4.277 4.758 3.717.  On a steady frame
(frame 3) sum|X| 85.80 -> 87.43 against 87.42 and every band lands
within 0.011 log2 of libopus (was 0.06-0.21 apart).

EC_OPUS_X_DEBUG prints the chain stage by stage (pre-emphasis window,
freq, bandE, bandLogE, normalised X) for the same bisect.

The layer's algorithmic delay grows by 192 samples: look_ahead() for a
CELT frame is 312, not 120, and the hybrid path's SILK delay follows it.
crates/ec-opus/src/celt_enc.rsmodified+49 -2
@@ -78,6 +78,10 @@ const INV_TABLE: [u8; 128] = [
7878 /// One forward-MDCT plan, the exact adjoint of the decoder's `ImdctPlan`:
7979 /// window-fold, pre-rotation, an `l/2`-point FFT and post-rotation, scaled by
8080 /// `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+
8185 #[derive(Clone, Debug)]
8286 struct MdctPlan {
8387 l: usize,
@@ -382,6 +386,11 @@ pub struct CeltEncoder {
382386 plans: Vec<MdctPlan>,
383387 /// Preemphasised history, `channels * OVERLAP`.
384388 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>,
385394 preemph_mem: [f32; 2],
386395 /// Coarse-energy prediction state, `2 * NB_BANDS`.
387396 old_band_e: Vec<f32>,
@@ -450,6 +459,7 @@ impl CeltEncoder {
450459 window: celt::overlap_window(),
451460 plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(),
452461 in_mem: vec![0.0; channels * OVERLAP],
462+ delay_buf: vec![0.0; channels * CELT_DELAY_48K],
453463 preemph_mem: [0.0; 2],
454464 old_band_e: vec![0.0; 2 * NB_BANDS],
455465 delayed_intra: 1.0,
@@ -509,6 +519,7 @@ impl CeltEncoder {
509519 /// Drops all inter-frame state.
510520 pub fn reset(&mut self) {
511521 self.in_mem.fill(0.0);
522+ self.delay_buf.fill(0.0);
512523 self.preemph_mem = [0.0; 2];
513524 self.old_band_e.fill(0.0);
514525 self.delayed_intra = 1.0;
@@ -599,20 +610,29 @@ impl CeltEncoder {
599610 // --- Preemphasis ----------------------------------------------------
600611 let stride = n + OVERLAP;
601612 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];
602615 for ch in 0..c {
603616 let base = ch * stride;
604617 self.in_buf[base..base + OVERLAP]
605618 .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]);
606619 let mut mem = self.preemph_mem[ch];
607620 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+ };
608628 for i in 0..n {
609629 // Zero-stuffing to 48 kHz: the images above the input's own
610630 // Nyquist are never coded (the caller caps `end`) and the
611631 // decoder's decimation drops them.
612632 let mut x = if up == 1 {
613- pcm[i * c + ch] * SIG_SCALE
633+ src(i) * SIG_SCALE
614634 } else if i.is_multiple_of(up) {
615- pcm[(i / up) * c + ch] * SIG_SCALE * up as f32
635+ src(i / up) * SIG_SCALE * up as f32
616636 } else {
617637 0.0
618638 };
@@ -626,9 +646,15 @@ impl CeltEncoder {
626646 silence &= v == 0.0;
627647 }
628648 self.preemph_mem[ch] = mem;
649+ for k in 0..d {
650+ next_delay[k * c + ch] = src(in_n + k);
651+ }
629652 self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]
630653 .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]);
631654 }
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;
632658
633659 // --- Silence flag (first symbol of the frame) -----------------------
634660 // Only exists when CELT opens the stream (decoder: `tell == 1`); under
@@ -711,6 +737,27 @@ impl CeltEncoder {
711737 }
712738 }
713739
740+ if std::env::var_os("EC_OPUS_X_DEBUG").is_some() {
741+ let f: Vec<String> =
742+ self.in_buf[OVERLAP..OVERLAP + 16].iter().map(|v| format!("{v:.5}")).collect();
743+ let e: f64 = self.in_buf[..n + OVERLAP].iter().map(|v| *v as f64 * *v as f64).sum();
744+ let ovl: Vec<String> =
745+ self.in_buf[..4].iter().map(|v| format!("{v:.5}")).collect();
746+ eprintln!("XPRE {} | E {e:.6e} ovl {}", f.join(" "), ovl.join(" "));
747+ let fr: Vec<String> = self.freq[..16].iter().map(|v| format!("{v:.5}")).collect();
748+ let be: Vec<String> = self.band_e[..8].iter().map(|v| format!("{v:.5}")).collect();
749+ let bl: Vec<String> = self.band_log_e[..8].iter().map(|v| format!("{v:.5}")).collect();
750+ eprintln!(
751+ "XMDCT sb {short_blocks} {} | bandE {} | bandLogE {}",
752+ fr.join(" "),
753+ be.join(" "),
754+ bl.join(" ")
755+ );
756+ let sx: f64 = self.x[..n].iter().map(|v| v.abs() as f64).sum();
757+ let x0: Vec<String> = self.x[..8].iter().map(|v| format!("{v:.5}")).collect();
758+ eprintln!("XNORM sumX {sx:.5} X0..8 {}", x0.join(" "));
759+ }
760+
714761 // --- Dynalloc analysis (offsets + spread_weight + importance) -----
715762 self.offsets = [0; NB_BANDS];
716763 let mut spread_weight = [0i32; NB_BANDS];
crates/ec-opus/src/encoder.rsmodified+10 -4
@@ -40,11 +40,16 @@ const MAX_SILK_PACKET_BYTES: usize = 1 + 1 + 2 * 2 + 3 * MAX_FRAME_BYTES;
4040 const SILK_LOOK_AHEAD_48K_NB: usize = 58;
4141 const SILK_LOOK_AHEAD_48K_MB: usize = 54;
4242 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;
4348 /// How far the hybrid path delays the SILK layer's input so its output lines
4449 /// 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 the
50+/// delay minus SILK's WB round trip, click-measured through the
4651 /// 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;
4853 /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent.
4954 /// Was 8: at 16 kbps SILK takes 37 of the 40-byte budget, so 8 expanded
5055 /// 5133/6001 packets (+12.9% rate on the speech gate); libopus leaves CELT
@@ -194,7 +199,8 @@ impl Encoder {
194199 /// Encoder delay in *input* samples for a `frame_size`-sample (per
195200 /// channel, native rate) frame: the decoded stream lags the input by
196201 /// 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.
198204 /// SILK (10, 20, 40 or 60 ms frames, when the application/bitrate or an
199205 /// explicit [`Encoder::set_mode`] select it — the same
200206 /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches
@@ -213,7 +219,7 @@ impl Encoder {
213219 };
214220 return delay / self.upsample;
215221 }
216- 120 / self.upsample
222+ CELT_LOOK_AHEAD_48K / self.upsample
217223 }
218224
219225 /// Forces the coded bandwidth; [`None`] (the default) picks it from the