From 5d7f93b7de5f9c2bf45df23cdfcee5bd364545e8 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Ahmet=20Kaan=20G=C3=BCm=C3=BC=C5=9F?= Date: Sun, 6 Sep 2026 19:21:42 +0300 Subject: [PATCH] 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.rs | 51 ++++++++++++++++++++++++++++++++-- crates/ec-opus/src/encoder.rs | 14 +++++++--- 2 files changed, 59 insertions(+), 6 deletions(-) diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs index 2a2cabb8..0cee5e3f 100644 --- a/crates/ec-opus/src/celt_enc.rs +++ b/crates/ec-opus/src/celt_enc.rs @@ -78,6 +78,10 @@ const INV_TABLE: [u8; 128] = [ /// One forward-MDCT plan, the exact adjoint of the decoder's `ImdctPlan`: /// window-fold, pre-rotation, an `l/2`-point FFT and post-rotation, scaled by /// `2/l` so that decode(encode(x)) reconstructs at unit gain. +/// libopus `opus_encoder.c`'s `delay_compensation = Fs/250`: how far behind +/// the API frame the CELT analysis window sits, in 48 kHz samples. +const CELT_DELAY_48K: usize = 192; + #[derive(Clone, Debug)] struct MdctPlan { l: usize, @@ -382,6 +386,11 @@ pub struct CeltEncoder { plans: Vec, /// Preemphasised history, `channels * OVERLAP`. in_mem: Vec, + /// libopus `opus_encoder.c`'s `delay_buffer`: the CELT layer is fed the + /// input delayed by `delay_compensation = Fs/250` (192 samples at 48 kHz), + /// so its analysis window sits 4 ms behind the API frame. Interleaved, + /// `CELT_DELAY_48K / upsample` samples per channel. + delay_buf: Vec, preemph_mem: [f32; 2], /// Coarse-energy prediction state, `2 * NB_BANDS`. old_band_e: Vec, @@ -450,6 +459,7 @@ impl CeltEncoder { window: celt::overlap_window(), plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(), in_mem: vec![0.0; channels * OVERLAP], + delay_buf: vec![0.0; channels * CELT_DELAY_48K], preemph_mem: [0.0; 2], old_band_e: vec![0.0; 2 * NB_BANDS], delayed_intra: 1.0, @@ -509,6 +519,7 @@ impl CeltEncoder { /// Drops all inter-frame state. pub fn reset(&mut self) { self.in_mem.fill(0.0); + self.delay_buf.fill(0.0); self.preemph_mem = [0.0; 2]; self.old_band_e.fill(0.0); self.delayed_intra = 1.0; @@ -599,20 +610,29 @@ impl CeltEncoder { // --- Preemphasis ---------------------------------------------------- let stride = n + OVERLAP; let mut silence = true; + let mut delay = std::mem::take(&mut self.delay_buf); + let mut next_delay = [0.0f32; 2 * CELT_DELAY_48K]; for ch in 0..c { let base = ch * stride; self.in_buf[base..base + OVERLAP] .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]); let mut mem = self.preemph_mem[ch]; let up = self.upsample; + // `src(j)`: input sample `j` of the delayed stream libopus's CELT + // layer sees -- the `d` samples held over from the previous call + // first, then this frame's. + let d = CELT_DELAY_48K / up; + let src = |j: usize| { + if j < d { delay[j * c + ch] } else { pcm[(j - d) * c + ch] } + }; for i in 0..n { // Zero-stuffing to 48 kHz: the images above the input's own // Nyquist are never coded (the caller caps `end`) and the // decoder's decimation drops them. let mut x = if up == 1 { - pcm[i * c + ch] * SIG_SCALE + src(i) * SIG_SCALE } else if i.is_multiple_of(up) { - pcm[(i / up) * c + ch] * SIG_SCALE * up as f32 + src(i / up) * SIG_SCALE * up as f32 } else { 0.0 }; @@ -626,9 +646,15 @@ impl CeltEncoder { silence &= v == 0.0; } self.preemph_mem[ch] = mem; + for k in 0..d { + next_delay[k * c + ch] = src(in_n + k); + } self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP] .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]); } + delay[..c * (CELT_DELAY_48K / self.upsample)] + .copy_from_slice(&next_delay[..c * (CELT_DELAY_48K / self.upsample)]); + self.delay_buf = delay; // --- Silence flag (first symbol of the frame) ----------------------- // Only exists when CELT opens the stream (decoder: `tell == 1`); under @@ -711,6 +737,27 @@ impl CeltEncoder { } } + if std::env::var_os("EC_OPUS_X_DEBUG").is_some() { + let f: Vec = + self.in_buf[OVERLAP..OVERLAP + 16].iter().map(|v| format!("{v:.5}")).collect(); + let e: f64 = self.in_buf[..n + OVERLAP].iter().map(|v| *v as f64 * *v as f64).sum(); + let ovl: Vec = + self.in_buf[..4].iter().map(|v| format!("{v:.5}")).collect(); + eprintln!("XPRE {} | E {e:.6e} ovl {}", f.join(" "), ovl.join(" ")); + let fr: Vec = self.freq[..16].iter().map(|v| format!("{v:.5}")).collect(); + let be: Vec = self.band_e[..8].iter().map(|v| format!("{v:.5}")).collect(); + let bl: Vec = self.band_log_e[..8].iter().map(|v| format!("{v:.5}")).collect(); + eprintln!( + "XMDCT sb {short_blocks} {} | bandE {} | bandLogE {}", + fr.join(" "), + be.join(" "), + bl.join(" ") + ); + let sx: f64 = self.x[..n].iter().map(|v| v.abs() as f64).sum(); + let x0: Vec = self.x[..8].iter().map(|v| format!("{v:.5}")).collect(); + eprintln!("XNORM sumX {sx:.5} X0..8 {}", x0.join(" ")); + } + // --- Dynalloc analysis (offsets + spread_weight + importance) ----- self.offsets = [0; NB_BANDS]; let mut spread_weight = [0i32; NB_BANDS]; diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index 3530f265..c5a11bb4 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -40,11 +40,16 @@ const MAX_SILK_PACKET_BYTES: usize = 1 + 1 + 2 * 2 + 3 * MAX_FRAME_BYTES; const SILK_LOOK_AHEAD_48K_NB: usize = 58; const SILK_LOOK_AHEAD_48K_MB: usize = 54; const SILK_LOOK_AHEAD_48K_WB: usize = 50; +/// The CELT layer's own delay: one MDCT overlap (120) plus libopus's +/// `delay_compensation = Fs/250` (`CELT_DELAY_48K`, 192 at 48 kHz), which the +/// CELT encoder applies to its input so its analysis window sits where +/// libopus's does. +const CELT_LOOK_AHEAD_48K: usize = 120 + 192; /// How far the hybrid path delays the SILK layer's input so its output lines /// up with the CELT layer's at the decoder (which sums them as-is): CELT's -/// overlap (120) minus SILK's WB round trip, click-measured through the +/// delay minus SILK's WB round trip, click-measured through the /// decoder with one layer muted (`hybrid_layers_align` in conformance.rs). -const HYBRID_SILK_DELAY_48K: usize = 120 - SILK_LOOK_AHEAD_48K_WB; +const HYBRID_SILK_DELAY_48K: usize = CELT_LOOK_AHEAD_48K - SILK_LOOK_AHEAD_48K_WB; /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent. /// Was 8: at 16 kbps SILK takes 37 of the 40-byte budget, so 8 expanded /// 5133/6001 packets (+12.9% rate on the speech gate); libopus leaves CELT @@ -194,7 +199,8 @@ impl Encoder { /// Encoder delay in *input* samples for a `frame_size`-sample (per /// channel, native rate) frame: the decoded stream lags the input by /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate` - /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz. + /// cancels it exactly. CELT: one MDCT overlap plus the 192-sample input + /// delay compensation, 312 samples at 48 kHz. /// SILK (10, 20, 40 or 60 ms frames, when the application/bitrate or an /// explicit [`Encoder::set_mode`] select it — the same /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches @@ -213,7 +219,7 @@ impl Encoder { }; return delay / self.upsample; } - 120 / self.upsample + CELT_LOOK_AHEAD_48K / self.upsample } /// Forces the coded bandwidth; [`None`] (the default) picks it from the