Feed the CELT layer the input delayed by Fs/250 like libopus
Browse files at this commit5d7f93b7de5f9c2bf45df23cdfcee5bd364545e8Parent: 5811863- feat
- feed the CELT layer the input delayed by Fs/250 like libopus
2 changed files +59 -6
crates/ec-opus/src/celt_enc.rsmodified+49 -2
| @@ -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 by | 79 | /// 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 own | 629 | // Zero-stuffing to 48 kHz: the images above the input's own |
| 610 | // Nyquist are never coded (the caller caps `end`) and the | 630 | // 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_SCALE | 633 | + 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 f32 | 635 | + src(i / up) * SIG_SCALE * up as f32 |
| 616 | } else { | 636 | } else { |
| 617 | 0.0 | 637 | 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`); under | 660 | // Only exists when CELT opens the stream (decoder: `tell == 1`); under |
| @@ -711,6 +737,27 @@ impl CeltEncoder { | |||
| 711 | } | 737 | } |
| 712 | } | 738 | } |
| 713 | 739 | ||
| 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 | + | ||
| 714 | // --- Dynalloc analysis (offsets + spread_weight + importance) ----- | 761 | // --- Dynalloc analysis (offsets + spread_weight + importance) ----- |
| 715 | self.offsets = [0; NB_BANDS]; | 762 | self.offsets = [0; NB_BANDS]; |
| 716 | let mut spread_weight = [0i32; NB_BANDS]; | 763 | 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; | |||
| 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 lines | 48 | /// 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's | 49 | /// 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 |
| 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 expanded | 54 | /// 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 CELT | 55 | /// 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 (per | 199 | /// Encoder delay in *input* samples for a `frame_size`-sample (per |
| 195 | /// channel, native rate) frame: the decoded stream lags the input by | 200 | /// 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 an | 204 | /// SILK (10, 20, 40 or 60 ms frames, when the application/bitrate or an |
| 199 | /// explicit [`Encoder::set_mode`] select it — the same | 205 | /// explicit [`Encoder::set_mode`] select it — the same |
| 200 | /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches | 206 | /// [`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.upsample | 222 | + CELT_LOOK_AHEAD_48K / self.upsample |
| 217 | } | 223 | } |
| 218 | 224 | ||
| 219 | /// Forces the coded bandwidth; [`None`] (the default) picks it from the | 225 | /// Forces the coded bandwidth; [`None`] (the default) picks it from the |