Merge branch 'lane-opusx2' (d74bb155): libopus input alignment (Fs/250 CELT delay + dc_reject) behind a knob, off; lag tests read the encoder's look-ahead
Browse files at this commit11 changed files +469 -106
- crates/ec-opus/src/celt_enc.rs +73 -9
- crates/ec-opus/src/encoder.rs +181 -53
- crates/ec-opus/src/multistream_enc.rs +7 -0
- crates/ec-opus/tests/conformance.rs +95 -44
- lanes/opus-opusx2-r1.sweep.txt +17 -0
- lanes/opus-opusx2-r2.sweep.txt +16 -0
- lanes/opus-opusx2-r3.sweep.txt +16 -0
- lanes/opus-opusx2-r4.sweep.txt +16 -0
- lanes/opus-opusx2-r5.sweep.txt +16 -0
- lanes/opus-opusx2-r6.sweep.txt +16 -0
- lanes/opus-opusx2-r7.sweep.txt +16 -0
crates/ec-opus/src/celt_enc.rsmodified+73 -9
| @@ -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,14 @@ 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>, | ||
| 394 | + /// Whether that delay is applied at all — see | ||
| 395 | + /// [`crate::Encoder::set_libopus_input_alignment`] for why it ships off. | ||
| 396 | + align_input: bool, | ||
| 385 | preemph_mem: [f32; 2], | 397 | preemph_mem: [f32; 2], |
| 386 | /// Coarse-energy prediction state, `2 * NB_BANDS`. | 398 | /// Coarse-energy prediction state, `2 * NB_BANDS`. |
| 387 | old_band_e: Vec<f32>, | 399 | old_band_e: Vec<f32>, |
| @@ -450,6 +462,8 @@ impl CeltEncoder { | |||
| 450 | window: celt::overlap_window(), | 462 | window: celt::overlap_window(), |
| 451 | plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(), | 463 | plans: (0..4).map(|lm| MdctPlan::new(SHORT_MDCT << lm)).collect(), |
| 452 | in_mem: vec![0.0; channels * OVERLAP], | 464 | in_mem: vec![0.0; channels * OVERLAP], |
| 465 | + delay_buf: vec![0.0; channels * CELT_DELAY_48K], | ||
| 466 | + align_input: false, | ||
| 453 | preemph_mem: [0.0; 2], | 467 | preemph_mem: [0.0; 2], |
| 454 | old_band_e: vec![0.0; 2 * NB_BANDS], | 468 | old_band_e: vec![0.0; 2 * NB_BANDS], |
| 455 | delayed_intra: 1.0, | 469 | delayed_intra: 1.0, |
| @@ -506,9 +520,17 @@ impl CeltEncoder { | |||
| 506 | &self.last_diag | 520 | &self.last_diag |
| 507 | } | 521 | } |
| 508 | 522 | ||
| 523 | + /// Feeds the layer the input delayed by `CELT_DELAY_48K`, as libopus | ||
| 524 | + /// does; see [`crate::Encoder::set_libopus_input_alignment`]. | ||
| 525 | + pub fn set_align_input(&mut self, on: bool) { | ||
| 526 | + self.align_input = on; | ||
| 527 | + self.delay_buf.fill(0.0); | ||
| 528 | + } | ||
| 529 | + | ||
| 509 | /// Drops all inter-frame state. | 530 | /// Drops all inter-frame state. |
| 510 | pub fn reset(&mut self) { | 531 | pub fn reset(&mut self) { |
| 511 | self.in_mem.fill(0.0); | 532 | self.in_mem.fill(0.0); |
| 533 | + self.delay_buf.fill(0.0); | ||
| 512 | self.preemph_mem = [0.0; 2]; | 534 | self.preemph_mem = [0.0; 2]; |
| 513 | self.old_band_e.fill(0.0); | 535 | self.old_band_e.fill(0.0); |
| 514 | self.delayed_intra = 1.0; | 536 | self.delayed_intra = 1.0; |
| @@ -599,20 +621,29 @@ impl CeltEncoder { | |||
| 599 | // --- Preemphasis ---------------------------------------------------- | 621 | // --- Preemphasis ---------------------------------------------------- |
| 600 | let stride = n + OVERLAP; | 622 | let stride = n + OVERLAP; |
| 601 | let mut silence = true; | 623 | let mut silence = true; |
| 624 | + let mut delay = std::mem::take(&mut self.delay_buf); | ||
| 625 | + let mut next_delay = [0.0f32; 2 * CELT_DELAY_48K]; | ||
| 602 | for ch in 0..c { | 626 | for ch in 0..c { |
| 603 | let base = ch * stride; | 627 | let base = ch * stride; |
| 604 | self.in_buf[base..base + OVERLAP] | 628 | self.in_buf[base..base + OVERLAP] |
| 605 | .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]); | 629 | .copy_from_slice(&self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP]); |
| 606 | let mut mem = self.preemph_mem[ch]; | 630 | let mut mem = self.preemph_mem[ch]; |
| 607 | let up = self.upsample; | 631 | let up = self.upsample; |
| 632 | + // `src(j)`: input sample `j` of the delayed stream libopus's CELT | ||
| 633 | + // layer sees -- the `d` samples held over from the previous call | ||
| 634 | + // first, then this frame's. | ||
| 635 | + let d = if self.align_input { CELT_DELAY_48K / up } else { 0 }; | ||
| 636 | + let src = |j: usize| { | ||
| 637 | + if j < d { delay[j * c + ch] } else { pcm[(j - d) * c + ch] } | ||
| 638 | + }; | ||
| 608 | for i in 0..n { | 639 | for i in 0..n { |
| 609 | // Zero-stuffing to 48 kHz: the images above the input's own | 640 | // Zero-stuffing to 48 kHz: the images above the input's own |
| 610 | // Nyquist are never coded (the caller caps `end`) and the | 641 | // Nyquist are never coded (the caller caps `end`) and the |
| 611 | // decoder's decimation drops them. | 642 | // decoder's decimation drops them. |
| 612 | let mut x = if up == 1 { | 643 | let mut x = if up == 1 { |
| 613 | - pcm[i * c + ch] * SIG_SCALE | 644 | + src(i) * SIG_SCALE |
| 614 | } else if i.is_multiple_of(up) { | 645 | } else if i.is_multiple_of(up) { |
| 615 | - pcm[(i / up) * c + ch] * SIG_SCALE * up as f32 | 646 | + src(i / up) * SIG_SCALE * up as f32 |
| 616 | } else { | 647 | } else { |
| 617 | 0.0 | 648 | 0.0 |
| 618 | }; | 649 | }; |
| @@ -626,9 +657,17 @@ impl CeltEncoder { | |||
| 626 | silence &= v == 0.0; | 657 | silence &= v == 0.0; |
| 627 | } | 658 | } |
| 628 | self.preemph_mem[ch] = mem; | 659 | self.preemph_mem[ch] = mem; |
| 660 | + for k in 0..d { | ||
| 661 | + next_delay[k * c + ch] = src(in_n + k); | ||
| 662 | + } | ||
| 629 | self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP] | 663 | self.in_mem[ch * OVERLAP..(ch + 1) * OVERLAP] |
| 630 | .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]); | 664 | .copy_from_slice(&self.in_buf[base + n..base + n + OVERLAP]); |
| 631 | } | 665 | } |
| 666 | + if self.align_input { | ||
| 667 | + delay[..c * (CELT_DELAY_48K / self.upsample)] | ||
| 668 | + .copy_from_slice(&next_delay[..c * (CELT_DELAY_48K / self.upsample)]); | ||
| 669 | + } | ||
| 670 | + self.delay_buf = delay; | ||
| 632 | 671 | ||
| 633 | // --- Silence flag (first symbol of the frame) ----------------------- | 672 | // --- Silence flag (first symbol of the frame) ----------------------- |
| 634 | // Only exists when CELT opens the stream (decoder: `tell == 1`); under | 673 | // Only exists when CELT opens the stream (decoder: `tell == 1`); under |
| @@ -711,14 +750,12 @@ impl CeltEncoder { | |||
| 711 | } | 750 | } |
| 712 | } | 751 | } |
| 713 | 752 | ||
| 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() { | 753 | if std::env::var_os("EC_OPUS_X_DEBUG").is_some() { |
| 718 | let f: Vec<String> = | 754 | let f: Vec<String> = |
| 719 | self.in_buf[OVERLAP..OVERLAP + 16].iter().map(|v| format!("{v:.5}")).collect(); | 755 | 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(); | 756 | 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(); | 757 | + let ovl: Vec<String> = |
| 758 | + self.in_buf[..4].iter().map(|v| format!("{v:.5}")).collect(); | ||
| 722 | eprintln!("XPRE {} | E {e:.6e} ovl {}", f.join(" "), ovl.join(" ")); | 759 | 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(); | 760 | 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(); | 761 | let be: Vec<String> = self.band_e[..8].iter().map(|v| format!("{v:.5}")).collect(); |
| @@ -770,8 +807,10 @@ impl CeltEncoder { | |||
| 770 | // .708->.703, reelo@96 .940->.872, dl8a .551/.374->.503/.346, hein | 807 | // .708->.703, reelo@96 .940->.872, dl8a .551/.374->.503/.346, hein |
| 771 | // .855/.528->.771/.419), corr within +.0001 everywhere. The KEEP rule | 808 | // .855/.528->.771/.419), corr within +.0001 everywhere. The KEEP rule |
| 772 | // is "err_ratio not worse on every row", so the search ships off. | 809 | // is "err_ratio not worse on every row", so the search ships off. |
| 810 | + // `EC_OPUS_TWO_PASS=1` re-arms it for a sweep (lane opusx2 r2). | ||
| 773 | const TWO_PASS_COARSE_ENERGY: bool = false; | 811 | const TWO_PASS_COARSE_ENERGY: bool = false; |
| 774 | - let mut two_pass = TWO_PASS_COARSE_ENERGY; | 812 | + let mut two_pass = |
| 813 | + TWO_PASS_COARSE_ENERGY || std::env::var_os("EC_OPUS_TWO_PASS").is_some(); | ||
| 775 | let mut intra = self.force_intra | 814 | let mut intra = self.force_intra |
| 776 | || (!two_pass | 815 | || (!two_pass |
| 777 | && self.delayed_intra > (2 * c * (end - start)) as f32 | 816 | && self.delayed_intra > (2 * c * (end - start)) as f32 |
| @@ -872,7 +911,7 @@ impl CeltEncoder { | |||
| 872 | // --- Allocation trim ------------------------------------------------ | 911 | // --- Allocation trim ------------------------------------------------ |
| 873 | let mut alloc_trim = 5i32; | 912 | let mut alloc_trim = 5i32; |
| 874 | if tell_frac + (6 << BITRES) <= total_bits_frac - total_boost { | 913 | if tell_frac + (6 << BITRES) <= total_bits_frac - total_boost { |
| 875 | - alloc_trim = self.alloc_trim_analysis(end, lm, c, n); | 914 | + alloc_trim = self.alloc_trim_analysis(end, lm, c, n, tf_estimate); |
| 876 | enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7); | 915 | enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7); |
| 877 | tell_frac = enc.tell_frac() as i32; | 916 | tell_frac = enc.tell_frac() as i32; |
| 878 | } | 917 | } |
| @@ -1550,7 +1589,20 @@ impl CeltEncoder { | |||
| 1550 | /// dl8a@64 .9889->.9879). The KEEP rule rejects it; this is the third | 1589 | /// dl8a@64 .9889->.9879). The KEEP rule rejects it; this is the third |
| 1551 | /// rejection of the same port (see `lanes/opus-trim-r2.{A,B}.sweep.txt`). | 1590 | /// rejection of the same port (see `lanes/opus-trim-r2.{A,B}.sweep.txt`). |
| 1552 | /// Do not re-port it without a fix for the transient rows first. | 1591 | /// Do not re-port it without a fix for the transient rows first. |
| 1553 | - fn alloc_trim_analysis(&mut self, end: usize, lm: usize, c: usize, n0: usize) -> i32 { | 1592 | + /// |
| 1593 | + /// `EC_OPUS_TRIM13=1` selects the continuous 1.3 form instead, for the | ||
| 1594 | + /// re-sweep on the aligned (delayed) spectrum the discrete ladder was | ||
| 1595 | + /// never measured against. | ||
| 1596 | + fn alloc_trim_analysis( | ||
| 1597 | + &mut self, | ||
| 1598 | + end: usize, | ||
| 1599 | + lm: usize, | ||
| 1600 | + c: usize, | ||
| 1601 | + n0: usize, | ||
| 1602 | + tf_estimate: f32, | ||
| 1603 | + ) -> i32 { | ||
| 1604 | + let cont = std::env::var_os("EC_OPUS_TRIM13").is_some(); | ||
| 1605 | + let mut trim_f = 5.0f32; | ||
| 1554 | let mut trim = 5i32; | 1606 | let mut trim = 5i32; |
| 1555 | if c == 2 { | 1607 | if c == 2 { |
| 1556 | let mut sum = 0.0f32; | 1608 | let mut sum = 0.0f32; |
| @@ -1562,6 +1614,10 @@ impl CeltEncoder { | |||
| 1562 | sum += partial; | 1614 | sum += partial; |
| 1563 | } | 1615 | } |
| 1564 | sum *= 1.0 / 8.0; | 1616 | sum *= 1.0 / 8.0; |
| 1617 | + if cont { | ||
| 1618 | + let sum_c = sum.abs().min(1.0); | ||
| 1619 | + trim_f += (0.75 * (1.001 - sum_c * sum_c).log2()).max(-4.0); | ||
| 1620 | + } | ||
| 1565 | if sum > 0.995 { | 1621 | if sum > 0.995 { |
| 1566 | trim -= 4; | 1622 | trim -= 4; |
| 1567 | } else if sum > 0.92 { | 1623 | } else if sum > 0.92 { |
| @@ -1595,6 +1651,14 @@ impl CeltEncoder { | |||
| 1595 | * (2 + 2 * i as i32 - NB_BANDS as i32) as f32; | 1651 | * (2 + 2 * i as i32 - NB_BANDS as i32) as f32; |
| 1596 | } | 1652 | } |
| 1597 | } | 1653 | } |
| 1654 | + if cont { | ||
| 1655 | + // libopus divides the same sum by `C*(end-1)`; the ladder above | ||
| 1656 | + // carries an extra factor of two in its thresholds. | ||
| 1657 | + let diff = diff / (c * (end - 1)) as f32; | ||
| 1658 | + trim_f -= ((diff + 1.0) / 6.0).clamp(-2.0, 2.0); | ||
| 1659 | + trim_f -= 2.0 * tf_estimate; | ||
| 1660 | + return (trim_f + 0.5).floor().clamp(0.0, 10.0) as i32; | ||
| 1661 | + } | ||
| 1598 | diff /= (2 * c * (end - 1)) as f32; | 1662 | diff /= (2 * c * (end - 1)) as f32; |
| 1599 | if diff > 2.0 { | 1663 | if diff > 2.0 { |
| 1600 | trim -= 1; | 1664 | trim -= 1; |
crates/ec-opus/src/encoder.rsmodified+181 -53
| @@ -40,11 +40,12 @@ 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 | -/// How far the hybrid path delays the SILK layer's input so its output lines | 43 | +/// One MDCT overlap: the CELT layer's delay without libopus's input |
| 44 | -/// up with the CELT layer's at the decoder (which sums them as-is): CELT's | 44 | +/// alignment ([`Encoder::set_libopus_input_alignment`]), which adds |
| 45 | -/// overlap (120) minus SILK's WB round trip, click-measured through the | 45 | +/// `delay_compensation = Fs/250` (192 at 48 kHz) on top. |
| 46 | -/// decoder with one layer muted (`hybrid_layers_align` in conformance.rs). | 46 | +const CELT_OVERLAP_48K: usize = 120; |
| 47 | -const HYBRID_SILK_DELAY_48K: usize = 120 - SILK_LOOK_AHEAD_48K_WB; | 47 | +/// libopus `opus_encoder.c`'s `delay_compensation = Fs/250`. |
| 48 | +const CELT_DELAY_COMP_48K: usize = 192; | ||
| 48 | /// Bytes the CELT layer of a hybrid packet always keeps, whatever SILK spent. | 49 | /// 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 | 50 | /// 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 | 51 | /// 5133/6001 packets (+12.9% rate on the speech gate); libopus leaves CELT |
| @@ -106,11 +107,19 @@ pub struct Encoder { | |||
| 106 | /// Scratch space for the SILK packet payload, sized once so the steady-state | 107 | /// Scratch space for the SILK packet payload, sized once so the steady-state |
| 107 | /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. | 108 | /// loop (`steady_state_encode_loop_zero_alloc`) doesn't allocate. |
| 108 | silk_buf: [u8; MAX_SILK_PACKET_BYTES], | 109 | silk_buf: [u8; MAX_SILK_PACKET_BYTES], |
| 109 | - /// Hybrid: the last [`HYBRID_SILK_DELAY_48K`] samples of SILK-layer input. | 110 | + /// Hybrid: the last [`Encoder::hybrid_silk_delay_48k`] samples of SILK-layer input. |
| 110 | silk_delay: Vec<f32>, | 111 | silk_delay: Vec<f32>, |
| 111 | /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so | 112 | /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so |
| 112 | /// the steady-state loop doesn't allocate a `Vec` per frame. | 113 | /// the steady-state loop doesn't allocate a `Vec` per frame. |
| 113 | silk_stuff: Vec<f32>, | 114 | silk_stuff: Vec<f32>, |
| 115 | + /// [`Encoder::set_libopus_input_alignment`]: off by default. | ||
| 116 | + align_input: bool, | ||
| 117 | + /// libopus `opus_encoder.c`'s `hp_mem`: the one-pole state of the | ||
| 118 | + /// [`Encoder::dc_reject`] filter every frame of API input goes through, | ||
| 119 | + /// one per channel. | ||
| 120 | + hp_mem: [f32; 2], | ||
| 121 | + /// Scratch space for that filter's output, sized once. | ||
| 122 | + hp_buf: Vec<f32>, | ||
| 114 | } | 123 | } |
| 115 | 124 | ||
| 116 | /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, | 125 | /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, |
| @@ -149,7 +158,7 @@ impl Encoder { | |||
| 149 | "one stream carries at most two channels; use MultistreamEncoder", | 158 | "one stream carries at most two channels; use MultistreamEncoder", |
| 150 | )); | 159 | )); |
| 151 | } | 160 | } |
| 152 | - Ok(Encoder { | 161 | + let mut enc = Encoder { |
| 153 | celt: CeltEncoder::new(channels, upsample), | 162 | celt: CeltEncoder::new(channels, upsample), |
| 154 | range: RangeEncoder::new(), | 163 | range: RangeEncoder::new(), |
| 155 | sample_rate, | 164 | sample_rate, |
| @@ -170,7 +179,16 @@ impl Encoder { | |||
| 170 | silk_buf: [0u8; MAX_SILK_PACKET_BYTES], | 179 | silk_buf: [0u8; MAX_SILK_PACKET_BYTES], |
| 171 | silk_delay: Vec::new(), | 180 | silk_delay: Vec::new(), |
| 172 | silk_stuff: Vec::new(), | 181 | silk_stuff: Vec::new(), |
| 173 | - }) | 182 | + align_input: false, |
| 183 | + hp_mem: [0.0; 2], | ||
| 184 | + hp_buf: Vec::new(), | ||
| 185 | + }; | ||
| 186 | + // `EC_OPUS_ALIGN=1` turns the alignment on for a whole process — how | ||
| 187 | + // the gate rows at `set_libopus_input_alignment` were produced. | ||
| 188 | + if std::env::var_os("EC_OPUS_ALIGN").is_some() { | ||
| 189 | + enc.set_libopus_input_alignment(true); | ||
| 190 | + } | ||
| 191 | + Ok(enc) | ||
| 174 | } | 192 | } |
| 175 | 193 | ||
| 176 | /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and | 194 | /// Overrides the automatic SILK/Hybrid/CELT choice `wants_silk` and |
| @@ -194,14 +212,15 @@ impl Encoder { | |||
| 194 | /// Encoder delay in *input* samples for a `frame_size`-sample (per | 212 | /// Encoder delay in *input* samples for a `frame_size`-sample (per |
| 195 | /// channel, native rate) frame: the decoded stream lags the input by | 213 | /// 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` | 214 | /// 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. | 215 | + /// cancels it exactly. CELT: one MDCT overlap plus the 192-sample input |
| 216 | + /// delay compensation, 312 samples at 48 kHz. | ||
| 198 | /// SILK (10, 20, 40 or 60 ms frames, when the application/bitrate or an | 217 | /// SILK (10, 20, 40 or 60 ms frames, when the application/bitrate or an |
| 199 | /// explicit [`Encoder::set_mode`] select it — the same | 218 | /// explicit [`Encoder::set_mode`] select it — the same |
| 200 | /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches | 219 | /// [`Encoder::silk_choice`] predicate `encode_toc_and_payload` dispatches |
| 201 | /// on, so this always matches which layer actually codes the frame): | 220 | /// on, so this always matches which layer actually codes the frame): |
| 202 | /// [`SILK_LOOK_AHEAD_48K_NB`], [`SILK_LOOK_AHEAD_48K_MB`] or | 221 | /// [`SILK_LOOK_AHEAD_48K_NB`], [`SILK_LOOK_AHEAD_48K_MB`] or |
| 203 | /// [`SILK_LOOK_AHEAD_48K_WB`]. Hybrid: CELT's 120, the SILK layer being | 222 | /// [`SILK_LOOK_AHEAD_48K_WB`]. Hybrid: CELT's 120, the SILK layer being |
| 204 | - /// delayed to meet it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size | 223 | + /// delayed to meet it ([`Encoder::hybrid_silk_delay_48k`]). Any other frame size |
| 205 | /// falls back to CELT here exactly as `encode_toc_and_payload` does. | 224 | /// falls back to CELT here exactly as `encode_toc_and_payload` does. |
| 206 | pub fn look_ahead(&self, frame_size: usize) -> usize { | 225 | pub fn look_ahead(&self, frame_size: usize) -> usize { |
| 207 | let frame_48k = frame_size * self.upsample; | 226 | let frame_48k = frame_size * self.upsample; |
| @@ -213,7 +232,61 @@ impl Encoder { | |||
| 213 | }; | 232 | }; |
| 214 | return delay / self.upsample; | 233 | return delay / self.upsample; |
| 215 | } | 234 | } |
| 216 | - 120 / self.upsample | 235 | + self.celt_look_ahead_48k() / self.upsample |
| 236 | + } | ||
| 237 | + | ||
| 238 | + /// The CELT layer's delay in 48 kHz samples: one MDCT overlap, plus | ||
| 239 | + /// libopus's `delay_compensation` when the alignment is on. | ||
| 240 | + fn celt_look_ahead_48k(&self) -> usize { | ||
| 241 | + CELT_OVERLAP_48K + if self.align_input { CELT_DELAY_COMP_48K } else { 0 } | ||
| 242 | + } | ||
| 243 | + | ||
| 244 | + /// How far the hybrid path delays the SILK layer's input so its output | ||
| 245 | + /// lines up with the CELT layer's at the decoder (which sums them as-is): | ||
| 246 | + /// CELT's delay minus SILK's WB round trip, click-measured through the | ||
| 247 | + /// decoder with one layer muted (`hybrid_layers_align` in conformance.rs). | ||
| 248 | + fn hybrid_silk_delay_48k(&self) -> usize { | ||
| 249 | + self.celt_look_ahead_48k() - SILK_LOOK_AHEAD_48K_WB | ||
| 250 | + } | ||
| 251 | + | ||
| 252 | + /// Puts our CELT analysis window exactly where libopus's is: the layer is | ||
| 253 | + /// fed the input delayed by `delay_compensation = Fs/250` (192 samples at | ||
| 254 | + /// 48 kHz, `opus_encoder.c` ~:1955) and every frame first goes through | ||
| 255 | + /// libopus's 3 Hz `dc_reject`. The alignment is *exact* — on the reell | ||
| 256 | + /// attack frame (frame 2, 20 ms, LM=3, transient) our first eight band | ||
| 257 | + /// log-energies become | ||
| 258 | + /// 3.4386 4.0055 3.2603 4.5954 1.1790 4.2774 4.7584 3.7169 against | ||
| 259 | + /// libopus's 3.439 4.005 3.260 4.595 1.179 4.277 4.758 3.717, all eight | ||
| 260 | + /// within .0006 (the unaligned encoder is .06-.21 apart). | ||
| 261 | + /// | ||
| 262 | + /// It ships OFF because the 12-row library gate rejects it, and because | ||
| 263 | + /// re-tuning the constants that were fitted on the misaligned spectrum | ||
| 264 | + /// does not rescue it. Against the shipped rows | ||
| 265 | + /// (`lanes/opus-opustr2-r1.sweep.txt`), err_ratio: | ||
| 266 | + /// | ||
| 267 | + /// | arm | better | worse (blocking) | | ||
| 268 | + /// |---|---|---| | ||
| 269 | + /// | delay only (`opus-opusx-r1`) | 7 | nik@64 .708→.800, nik@96 .985→1.763, her@96 1.051→1.292, hein@64 .853→.980, hein@96 .528→1.602 | | ||
| 270 | + /// | delay + `dc_reject` (`opus-opusx2-r1`) | 5 | those, plus dl8a@64 .552→1.074, dl8a@96 .374→1.011 | | ||
| 271 | + /// | + two-pass coarse energy (`-r2`) | 5 | same 7 rows (nik@96 1.809, dl8a@64 1.200) | | ||
| 272 | + /// | + continuous 1.3 `alloc_trim` (`-r3`) | 5 | same 7, and corr worse by >.0005 on 9 rows | | ||
| 273 | + /// | + tf boost k=1.25 (`-r4`) | 5 | same 7 | | ||
| 274 | + /// | + tf boost k=1.5 (`-r5`) | 5 | same 7 | | ||
| 275 | + /// | + two-pass *and* k=1.25, the combined best (`-r7`) | 5 | same 7: nik@64 .773, nik@96 1.801, her@96 1.114, dl8a@64 1.181, dl8a@96 1.014, hein@64 .977, hein@96 1.398 | | ||
| 276 | + /// | ||
| 277 | + /// The best aligned arm on the KEEP rule is the delay alone without | ||
| 278 | + /// `dc_reject` (5 rows worse); every arm that adds `dc_reject` puts dl8a | ||
| 279 | + /// in the blocking set too. | ||
| 280 | + /// | ||
| 281 | + /// The blocking set (nik, her@96, dl8a, hein) is the same in every arm and | ||
| 282 | + /// no arm moves any of those rows back towards its shipped value, so the | ||
| 283 | + /// misfit is not one of the swept constants. Turning this on also costs | ||
| 284 | + /// 4 ms of algorithmic delay: [`Encoder::look_ahead`] for a CELT frame | ||
| 285 | + /// becomes 312, not 120, and the Ogg pre-skip must follow it. | ||
| 286 | + pub fn set_libopus_input_alignment(&mut self, on: bool) { | ||
| 287 | + self.align_input = on; | ||
| 288 | + self.celt.set_align_input(on); | ||
| 289 | + self.hp_mem = [0.0; 2]; | ||
| 217 | } | 290 | } |
| 218 | 291 | ||
| 219 | /// Forces the coded bandwidth; [`None`] (the default) picks it from the | 292 | /// Forces the coded bandwidth; [`None`] (the default) picks it from the |
| @@ -277,6 +350,7 @@ impl Encoder { | |||
| 277 | self.silk_stereo_mb = None; | 350 | self.silk_stereo_mb = None; |
| 278 | self.silk_stereo_wb = None; | 351 | self.silk_stereo_wb = None; |
| 279 | self.silk_delay.clear(); | 352 | self.silk_delay.clear(); |
| 353 | + self.hp_mem = [0.0; 2]; | ||
| 280 | self.final_range = 0; | 354 | self.final_range = 0; |
| 281 | } | 355 | } |
| 282 | 356 | ||
| @@ -686,6 +760,38 @@ impl Encoder { | |||
| 686 | BWS[idx].min(ceiling) | 760 | BWS[idx].min(ceiling) |
| 687 | } | 761 | } |
| 688 | 762 | ||
| 763 | + /// libopus `opus_encoder.c`'s `dc_reject(pcm, 3, ...)`: a 3 Hz one-pole | ||
| 764 | + /// high-pass on the API input, applied once before *both* layers (libopus | ||
| 765 | + /// filters into `pcm_buf`, which is what `silk_Encode` and | ||
| 766 | + /// `celt_encode_with_ec` both read). `coef = 6.3 * cutoff / Fs` at the | ||
| 767 | + /// API rate; the output is the input minus a leaky integrator of it, and | ||
| 768 | + /// the integrator state carries across frames. | ||
| 769 | + /// | ||
| 770 | + /// libopus takes the `hp_cutoff` branch instead for | ||
| 771 | + /// `OPUS_APPLICATION_VOIP` (a bandwidth-dependent second-order section); | ||
| 772 | + /// not ported — every VoIP frame still gets this DC reject. | ||
| 773 | + /// Ships off with the alignment knob: `dc_reject` alone (without the | ||
| 774 | + /// input delay) has never been measured on the library gate. | ||
| 775 | + fn dc_reject<'a>(&mut self, pcm: &'a [f32], frame_size: usize, out: &'a mut Vec<f32>) -> &'a [f32] { | ||
| 776 | + if !self.align_input { | ||
| 777 | + return pcm; | ||
| 778 | + } | ||
| 779 | + let c = self.channels; | ||
| 780 | + let coef = 6.3 * 3.0 / self.sample_rate as f32; | ||
| 781 | + out.clear(); | ||
| 782 | + out.resize(frame_size * c, 0.0); | ||
| 783 | + for ch in 0..c { | ||
| 784 | + let mut m = self.hp_mem[ch]; | ||
| 785 | + for i in 0..frame_size { | ||
| 786 | + let x = pcm[i * c + ch]; | ||
| 787 | + out[i * c + ch] = x - m; | ||
| 788 | + m += coef * (x - m); | ||
| 789 | + } | ||
| 790 | + self.hp_mem[ch] = m; | ||
| 791 | + } | ||
| 792 | + out | ||
| 793 | + } | ||
| 794 | + | ||
| 689 | /// Encodes one frame — `frame_size` samples per channel of interleaved | 795 | /// Encodes one frame — `frame_size` samples per channel of interleaved |
| 690 | /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus | 796 | /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus |
| 691 | /// packet in `out`, returning the packet length. | 797 | /// packet in `out`, returning the packet length. |
| @@ -695,19 +801,27 @@ impl Encoder { | |||
| 695 | frame_size: usize, | 801 | frame_size: usize, |
| 696 | out: &mut [u8], | 802 | out: &mut [u8], |
| 697 | ) -> Result<usize> { | 803 | ) -> Result<usize> { |
| 698 | - let (toc, payload) = | 804 | + let mut hp = std::mem::take(&mut self.hp_buf); |
| 699 | - self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?; | 805 | + let input = self.dc_reject(pcm, frame_size, &mut hp); |
| 700 | - let n = payload.len(); | 806 | + let r = match self.encode_toc_and_payload(input, frame_size, out.len().saturating_sub(1)) { |
| 701 | - if out.len() < 1 + n { | 807 | + Err(e) => Err(e), |
| 702 | - return Err(Error::corrupt(format!( | 808 | + Ok((toc, payload)) => { |
| 703 | - "opus encode: packet needs {} bytes, buffer holds {}", | 809 | + let n = payload.len(); |
| 704 | - 1 + n, | 810 | + if out.len() < 1 + n { |
| 705 | - out.len() | 811 | + Err(Error::corrupt(format!( |
| 706 | - ))); | 812 | + "opus encode: packet needs {} bytes, buffer holds {}", |
| 707 | - } | 813 | + 1 + n, |
| 708 | - out[0] = toc; | 814 | + out.len() |
| 709 | - out[1..1 + n].copy_from_slice(payload); | 815 | + ))) |
| 710 | - Ok(1 + n) | 816 | + } else { |
| 817 | + out[0] = toc; | ||
| 818 | + out[1..1 + n].copy_from_slice(payload); | ||
| 819 | + Ok(1 + n) | ||
| 820 | + } | ||
| 821 | + } | ||
| 822 | + }; | ||
| 823 | + self.hp_buf = hp; | ||
| 824 | + r | ||
| 711 | } | 825 | } |
| 712 | 826 | ||
| 713 | /// [`Encoder::encode_float`] from 16-bit samples. | 827 | /// [`Encoder::encode_float`] from 16-bit samples. |
| @@ -725,33 +839,41 @@ impl Encoder { | |||
| 725 | frame_size: usize, | 839 | frame_size: usize, |
| 726 | out: &mut [u8], | 840 | out: &mut [u8], |
| 727 | ) -> Result<usize> { | 841 | ) -> Result<usize> { |
| 728 | - let (toc, payload) = | 842 | + let mut hp = std::mem::take(&mut self.hp_buf); |
| 729 | - self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?; | 843 | + let input = self.dc_reject(pcm, frame_size, &mut hp); |
| 730 | - let n = payload.len(); | 844 | + let r = match self.encode_toc_and_payload(input, frame_size, out.len().saturating_sub(3)) { |
| 731 | - let len_bytes = if n < 252 { 1 } else { 2 }; | 845 | + Err(e) => Err(e), |
| 732 | - if out.len() < 1 + len_bytes + n { | 846 | + Ok((toc, payload)) => { |
| 733 | - return Err(Error::corrupt(format!( | 847 | + let n = payload.len(); |
| 734 | - "opus encode: self-delimited packet needs {} bytes, buffer holds {}", | 848 | + let len_bytes = if n < 252 { 1 } else { 2 }; |
| 735 | - 1 + len_bytes + n, | 849 | + if out.len() < 1 + len_bytes + n { |
| 736 | - out.len() | 850 | + Err(Error::corrupt(format!( |
| 737 | - ))); | 851 | + "opus encode: self-delimited packet needs {} bytes, buffer holds {}", |
| 738 | - } | 852 | + 1 + len_bytes + n, |
| 739 | - out[0] = toc; | 853 | + out.len() |
| 740 | - if n < 252 { | 854 | + ))) |
| 741 | - out[1] = n as u8; | 855 | + } else { |
| 742 | - } else { | 856 | + out[0] = toc; |
| 743 | - let b0 = 252 + ((n - 252) & 3); | 857 | + if n < 252 { |
| 744 | - out[1] = b0 as u8; | 858 | + out[1] = n as u8; |
| 745 | - out[2] = ((n - b0) / 4) as u8; | 859 | + } else { |
| 746 | - } | 860 | + let b0 = 252 + ((n - 252) & 3); |
| 747 | - out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload); | 861 | + out[1] = b0 as u8; |
| 748 | - Ok(1 + len_bytes + n) | 862 | + out[2] = ((n - b0) / 4) as u8; |
| 863 | + } | ||
| 864 | + out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload); | ||
| 865 | + Ok(1 + len_bytes + n) | ||
| 866 | + } | ||
| 867 | + } | ||
| 868 | + }; | ||
| 869 | + self.hp_buf = hp; | ||
| 870 | + r | ||
| 749 | } | 871 | } |
| 750 | 872 | ||
| 751 | /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB) | 873 | /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB) |
| 752 | /// into the internal range coder, returning its byte length: the SILK | 874 | /// into the internal range coder, returning its byte length: the SILK |
| 753 | /// layer's symbols (WB, 16 kHz internal, fed the input delayed by | 875 | /// layer's symbols (WB, 16 kHz internal, fed the input delayed by |
| 754 | - /// [`HYBRID_SILK_DELAY_48K`]), the no-redundancy flag under the decoder's | 876 | + /// [`Encoder::hybrid_silk_delay_48k`]), the no-redundancy flag under the decoder's |
| 755 | /// exact presence rule, then the CELT layer from band 17 in the same | 877 | /// exact presence rule, then the CELT layer from band 17 in the same |
| 756 | /// coder. CBR: the packet is the bitrate's size unless SILK alone needs | 878 | /// coder. CBR: the packet is the bitrate's size unless SILK alone needs |
| 757 | /// more, in which case CELT keeps [`HYBRID_CELT_MIN_BYTES`] on top. | 879 | /// more, in which case CELT keeps [`HYBRID_CELT_MIN_BYTES`] on top. |
| @@ -777,7 +899,7 @@ impl Encoder { | |||
| 777 | } else { | 899 | } else { |
| 778 | Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); | 900 | Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff); |
| 779 | } | 901 | } |
| 780 | - let d = HYBRID_SILK_DELAY_48K * self.channels; | 902 | + let d = self.hybrid_silk_delay_48k() * self.channels; |
| 781 | if self.silk_delay.len() != d { | 903 | if self.silk_delay.len() != d { |
| 782 | self.silk_delay.clear(); | 904 | self.silk_delay.clear(); |
| 783 | self.silk_delay.resize(d, 0.0); | 905 | self.silk_delay.resize(d, 0.0); |
| @@ -896,33 +1018,39 @@ mod tests { | |||
| 896 | let mut e = Encoder::new(24000, 2, Application::Audio).unwrap(); | 1018 | let mut e = Encoder::new(24000, 2, Application::Audio).unwrap(); |
| 897 | e.set_bitrate(256_000); | 1019 | e.set_bitrate(256_000); |
| 898 | assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); | 1020 | assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide); |
| 899 | - assert_eq!(e.look_ahead(960), 60); | 1021 | + assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K / 2); |
| 900 | } | 1022 | } |
| 901 | 1023 | ||
| 902 | /// `look_ahead` must use the same 10-or-20 ms-frame predicate dispatch | 1024 | /// `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 ms | 1025 | /// 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 and | 1026 | /// frames still code as CELT, while 10/20 ms speech follows SILK and |
| 905 | - /// hybrid follows CELT's overlap. | 1027 | + /// hybrid follows CELT's delay. |
| 906 | #[test] | 1028 | #[test] |
| 907 | fn look_ahead_matches_the_frame_size_dispatch_actually_uses() { | 1029 | fn look_ahead_matches_the_frame_size_dispatch_actually_uses() { |
| 908 | let mut e = Encoder::new(48000, 1, Application::Voip).unwrap(); | 1030 | let mut e = Encoder::new(48000, 1, Application::Voip).unwrap(); |
| 909 | e.set_bitrate(8000); | 1031 | e.set_bitrate(8000); |
| 910 | assert_eq!(e.look_ahead(480), 58, "10ms NB SILK"); | 1032 | assert_eq!(e.look_ahead(480), 58, "10ms NB SILK"); |
| 911 | - assert_eq!(e.look_ahead(240), 120, "5ms frame falls back to CELT"); | 1033 | + assert_eq!(e.look_ahead(240), CELT_OVERLAP_48K, "5ms frame falls back to CELT"); |
| 912 | assert_eq!(e.look_ahead(960), 58, "20ms NB SILK"); | 1034 | assert_eq!(e.look_ahead(960), 58, "20ms NB SILK"); |
| 913 | 1035 | ||
| 914 | // 16k VoIP is hybrid-FB since the libopus threshold port (CELT overlap). | 1036 | // 16k VoIP is hybrid-FB since the libopus threshold port (CELT overlap). |
| 915 | e.set_bitrate(16000); | 1037 | e.set_bitrate(16000); |
| 916 | - assert_eq!(e.look_ahead(960), 120, "20ms hybrid FB"); | 1038 | + assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K, "20ms hybrid FB"); |
| 917 | 1039 | ||
| 918 | e.set_bitrate(32000); | 1040 | e.set_bitrate(32000); |
| 919 | - assert_eq!(e.look_ahead(960), 120, "20ms hybrid, CELT's overlap"); | 1041 | + assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K, "20ms hybrid, CELT's delay"); |
| 920 | 1042 | ||
| 921 | let mut e = Encoder::new(48000, 2, Application::Voip).unwrap(); | 1043 | let mut e = Encoder::new(48000, 2, Application::Voip).unwrap(); |
| 922 | e.set_bitrate(8000); | 1044 | e.set_bitrate(8000); |
| 923 | assert_eq!(e.look_ahead(960), 58, "stereo 20ms NB SILK"); | 1045 | assert_eq!(e.look_ahead(960), 58, "stereo 20ms NB SILK"); |
| 924 | e.set_bitrate(64_000); | 1046 | e.set_bitrate(64_000); |
| 925 | - assert_eq!(e.look_ahead(960), 120, "stereo 20ms hybrid"); | 1047 | + assert_eq!(e.look_ahead(960), CELT_OVERLAP_48K, "stereo 20ms hybrid"); |
| 1048 | + e.set_libopus_input_alignment(true); | ||
| 1049 | + assert_eq!( | ||
| 1050 | + e.look_ahead(960), | ||
| 1051 | + CELT_OVERLAP_48K + CELT_DELAY_COMP_48K, | ||
| 1052 | + "the alignment adds libopus's delay_compensation to the advertised delay" | ||
| 1053 | + ); | ||
| 926 | } | 1054 | } |
| 927 | 1055 | ||
| 928 | #[test] | 1056 | #[test] |
crates/ec-opus/src/multistream_enc.rsmodified+7 -0
| @@ -27,6 +27,13 @@ pub struct MultistreamEncoder { | |||
| 27 | } | 27 | } |
| 28 | 28 | ||
| 29 | impl MultistreamEncoder { | 29 | impl MultistreamEncoder { |
| 30 | + /// The encoder delay each stream carries for a `frame_size` frame — the | ||
| 31 | + /// per-stream [`Encoder::look_ahead`], which every stream shares, and so | ||
| 32 | + /// the Ogg-Opus pre-skip a multistream file must carry. | ||
| 33 | + pub fn look_ahead(&self, frame_size: usize) -> usize { | ||
| 34 | + self.streams[0].look_ahead(frame_size) | ||
| 35 | + } | ||
| 36 | + | ||
| 30 | /// An encoder for `streams` elementary streams of which the first | 37 | /// An encoder for `streams` elementary streams of which the first |
| 31 | /// `coupled` are stereo, with `mapping` naming the coded channel each | 38 | /// `coupled` are stereo, with `mapping` naming the coded channel each |
| 32 | /// input channel feeds. Layout rules are the decoder's, checked the same | 39 | /// input channel feeds. Layout rules are the decoder's, checked the same |
crates/ec-opus/tests/conformance.rsmodified+95 -44
| @@ -864,17 +864,18 @@ fn roundtrip_own( | |||
| 864 | (decoded, bytes) | 864 | (decoded, bytes) |
| 865 | } | 865 | } |
| 866 | 866 | ||
| 867 | -/// Worst-channel correlation against the source with the encoder's | 867 | +/// Worst-channel correlation against the source with the encoder's own |
| 868 | -/// 120-sample delay removed. | 868 | +/// delay removed — `delay` is [`Encoder::look_ahead`] for the frame size the |
| 869 | -fn delayed_corr(source: &[f32], decoded: &[f32], channels: usize) -> f64 { | 869 | +/// round trip used, never a constant (it moved 120 -> 312 when the CELT layer |
| 870 | - const DELAY: usize = 120; | 870 | +/// took libopus's Fs/250 input delay). |
| 871 | - let n = (decoded.len() / channels).saturating_sub(DELAY); | 871 | +fn delayed_corr(source: &[f32], decoded: &[f32], channels: usize, delay: usize) -> f64 { |
| 872 | + let n = (decoded.len() / channels).saturating_sub(delay); | ||
| 872 | let n = n.min(source.len() / channels); | 873 | let n = n.min(source.len() / channels); |
| 873 | let mut worst = 1.0f64; | 874 | let mut worst = 1.0f64; |
| 874 | for c in 0..channels { | 875 | for c in 0..channels { |
| 875 | let a: Vec<f32> = (0..n).map(|i| source[i * channels + c]).collect(); | 876 | let a: Vec<f32> = (0..n).map(|i| source[i * channels + c]).collect(); |
| 876 | let b: Vec<f32> = (0..n) | 877 | let b: Vec<f32> = (0..n) |
| 877 | - .map(|i| decoded[(i + DELAY) * channels + c]) | 878 | + .map(|i| decoded[(i + delay) * channels + c]) |
| 878 | .collect(); | 879 | .collect(); |
| 879 | worst = worst.min(correlation(&a, &b)); | 880 | worst = worst.min(correlation(&a, &b)); |
| 880 | } | 881 | } |
| @@ -894,7 +895,7 @@ fn encoder_roundtrips_at_every_rate() { | |||
| 894 | let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); | 895 | let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); |
| 895 | enc.set_bitrate(kbps * 1000); | 896 | enc.set_bitrate(kbps * 1000); |
| 896 | let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, channels, 960); | 897 | let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, channels, 960); |
| 897 | - let corr = delayed_corr(&pcm, &decoded, channels); | 898 | + let corr = delayed_corr(&pcm, &decoded, channels, enc.look_ahead(960)); |
| 898 | let rate = bytes as f64 * 8.0 / 2.0 / 1000.0; | 899 | let rate = bytes as f64 * 8.0 / 2.0 / 1000.0; |
| 899 | println!("{channels} ch {kbps:>3} kbps: corr {corr:.4}, actual {rate:.1} kbps"); | 900 | println!("{channels} ch {kbps:>3} kbps: corr {corr:.4}, actual {rate:.1} kbps"); |
| 900 | let floor = if kbps < 64 { 0.8 } else { 0.9 }; | 901 | let floor = if kbps < 64 { 0.8 } else { 0.9 }; |
| @@ -906,6 +907,30 @@ fn encoder_roundtrips_at_every_rate() { | |||
| 906 | } | 907 | } |
| 907 | } | 908 | } |
| 908 | 909 | ||
| 910 | +/// The libopus input alignment ([`Encoder::set_libopus_input_alignment`]): | ||
| 911 | +/// with it on the CELT layer's advertised delay grows by libopus's | ||
| 912 | +/// `delay_compensation`, and the decoded signal tracks the source at exactly | ||
| 913 | +/// that lag and not at the old one — the knob is usable, not just present. | ||
| 914 | +/// It ships off; the gate tables that rejected it are at the setter. | ||
| 915 | +#[test] | ||
| 916 | +fn libopus_input_alignment_delays_and_still_decodes() { | ||
| 917 | + let pcm = test_signal(2, 1.0); | ||
| 918 | + let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); | ||
| 919 | + enc.set_bitrate(128_000); | ||
| 920 | + assert_eq!(enc.look_ahead(960), 120, "default: one MDCT overlap"); | ||
| 921 | + enc.set_libopus_input_alignment(true); | ||
| 922 | + assert_eq!(enc.look_ahead(960), 312, "overlap + delay_compensation"); | ||
| 923 | + let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, 960); | ||
| 924 | + let aligned = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(960)); | ||
| 925 | + let old = delayed_corr(&pcm, &decoded, 2, 120); | ||
| 926 | + println!("aligned: corr at 312 {aligned:.4}, at 120 {old:.4}"); | ||
| 927 | + assert!(aligned >= 0.85, "aligned round trip corr {aligned:.4}"); | ||
| 928 | + assert!( | ||
| 929 | + aligned > old, | ||
| 930 | + "advertised delay 312 correlates {aligned:.4}, worse than the old 120 ({old:.4})" | ||
| 931 | + ); | ||
| 932 | +} | ||
| 933 | + | ||
| 909 | #[test] | 934 | #[test] |
| 910 | // Expectations are libopus 1.6's (opus_encoder.c mode_thresholds and the | 935 | // Expectations are libopus 1.6's (opus_encoder.c mode_thresholds and the |
| 911 | // voice/music bandwidth tables blended by voice_est) since lane opus-mode; | 936 | // voice/music bandwidth tables blended by voice_est) since lane opus-mode; |
| @@ -1271,7 +1296,7 @@ fn encoder_frame_sizes_and_vbr() { | |||
| 1271 | let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); | 1296 | let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); |
| 1272 | enc.set_bitrate(128_000); | 1297 | enc.set_bitrate(128_000); |
| 1273 | let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame); | 1298 | let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame); |
| 1274 | - let corr = delayed_corr(&pcm, &decoded, 2); | 1299 | + let corr = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(frame)); |
| 1275 | println!("frame {frame}: corr {corr:.4}"); | 1300 | println!("frame {frame}: corr {corr:.4}"); |
| 1276 | assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}"); | 1301 | assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}"); |
| 1277 | } | 1302 | } |
| @@ -1279,7 +1304,7 @@ fn encoder_frame_sizes_and_vbr() { | |||
| 1279 | enc.set_bitrate(128_000); | 1304 | enc.set_bitrate(128_000); |
| 1280 | enc.set_vbr_constrained(true); | 1305 | enc.set_vbr_constrained(true); |
| 1281 | let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960); | 1306 | let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960); |
| 1282 | - let corr = delayed_corr(&pcm, &decoded, 2); | 1307 | + let corr = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(960)); |
| 1283 | let rate = bytes as f64 * 8.0 / 1.0 / 1000.0; | 1308 | let rate = bytes as f64 * 8.0 / 1.0 / 1000.0; |
| 1284 | println!("cvbr 128k: corr {corr:.4}, actual {rate:.1} kbps"); | 1309 | println!("cvbr 128k: corr {corr:.4}, actual {rate:.1} kbps"); |
| 1285 | assert!(corr >= 0.9, "cvbr: correlation {corr:.4}"); | 1310 | assert!(corr >= 0.9, "cvbr: correlation {corr:.4}"); |
| @@ -1303,8 +1328,9 @@ use ec_ogg::OggMuxer; | |||
| 1303 | 1328 | ||
| 1304 | /// The RFC 7845 identification header for this encoder — built by the crate's | 1329 | /// 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. | 1330 | /// 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 overlap | 1331 | +/// `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. | 1332 | +/// plus its input delay compensation, for every CELT call site; SILK's own |
| 1333 | +/// delay for SILK. | ||
| 1308 | fn opus_head(channels: usize, pre_skip: u16, layout: Option<(usize, usize, &[u8])>) -> Vec<u8> { | 1334 | fn opus_head(channels: usize, pre_skip: u16, layout: Option<(usize, usize, &[u8])>) -> Vec<u8> { |
| 1309 | let mapping = | 1335 | let mapping = |
| 1310 | layout.map(|(streams, coupled, table)| (1u8, streams as u8, coupled as u8, table)); | 1336 | layout.map(|(streams, coupled, table)| (1u8, streams as u8, coupled as u8, table)); |
| @@ -1404,10 +1430,10 @@ fn oracle_decodes_our_packets_across_the_rate_table() { | |||
| 1404 | write_ogg_opus( | 1430 | write_ogg_opus( |
| 1405 | &path, | 1431 | &path, |
| 1406 | &packets, | 1432 | &packets, |
| 1407 | - opus_head(channels, 120, None), | 1433 | + opus_head(channels, enc.look_ahead(960) as u16, None), |
| 1408 | channels, | 1434 | channels, |
| 1409 | total, | 1435 | total, |
| 1410 | - 120, | 1436 | + enc.look_ahead(960) as i64, |
| 1411 | ); | 1437 | ); |
| 1412 | let Some(reference) = ffmpeg_decode(&path, channels) else { | 1438 | let Some(reference) = ffmpeg_decode(&path, channels) else { |
| 1413 | eprintln!("ffmpeg unavailable, skipped"); | 1439 | eprintln!("ffmpeg unavailable, skipped"); |
| @@ -1533,9 +1559,10 @@ fn five_one_encode_end_to_end() { | |||
| 1533 | let len = enc.encode_float(&silence, 960, &mut out).expect("encode"); | 1559 | let len = enc.encode_float(&silence, 960, &mut out).expect("encode"); |
| 1534 | packets.push(out[..len].to_vec()); | 1560 | packets.push(out[..len].to_vec()); |
| 1535 | let (streams, coupled, mapping) = enc.layout(); | 1561 | let (streams, coupled, mapping) = enc.layout(); |
| 1536 | - let head = opus_head(6, 120, Some((streams, coupled, mapping))); | 1562 | + let pre_skip = enc.look_ahead(960); |
| 1563 | + let head = opus_head(6, pre_skip as u16, Some((streams, coupled, mapping))); | ||
| 1537 | let path = temp_path("5.1.opus"); | 1564 | let path = temp_path("5.1.opus"); |
| 1538 | - write_ogg_opus(&path, &packets, head, 6, total, 120); | 1565 | + write_ogg_opus(&path, &packets, head, 6, total, pre_skip as i64); |
| 1539 | let Some(reference) = ffmpeg_decode(&path, 6) else { | 1566 | let Some(reference) = ffmpeg_decode(&path, 6) else { |
| 1540 | eprintln!("ffmpeg unavailable, skipped"); | 1567 | eprintln!("ffmpeg unavailable, skipped"); |
| 1541 | let _ = fs::remove_file(&path); | 1568 | let _ = fs::remove_file(&path); |
| @@ -1567,7 +1594,8 @@ fn ogg_opus_round_trip_duration_is_exact() { | |||
| 1567 | enc.set_bitrate(128_000); | 1594 | enc.set_bitrate(128_000); |
| 1568 | let packets = encode_packets(&mut enc, &pcm, 2); | 1595 | let packets = encode_packets(&mut enc, &pcm, 2); |
| 1569 | let path = temp_path("duration.opus"); | 1596 | let path = temp_path("duration.opus"); |
| 1570 | - write_ogg_opus(&path, &packets, opus_head(2, 120, None), 2, total, 120); | 1597 | + let pre_skip = enc.look_ahead(960); |
| 1598 | + write_ogg_opus(&path, &packets, opus_head(2, pre_skip as u16, None), 2, total, pre_skip as i64); | ||
| 1571 | let probe = Command::new("ffprobe") | 1599 | let probe = Command::new("ffprobe") |
| 1572 | .args([ | 1600 | .args([ |
| 1573 | "-v", | 1601 | "-v", |
| @@ -1591,9 +1619,9 @@ fn ogg_opus_round_trip_duration_is_exact() { | |||
| 1591 | .unwrap_or(0.0); | 1619 | .unwrap_or(0.0); |
| 1592 | // ffprobe reports Ogg-Opus durations *including* the pre-skip — its | 1620 | // ffprobe reports Ogg-Opus durations *including* the pre-skip — its |
| 1593 | // own 3.000 s encode probes as 3.0065 (312/48000 more). Ours carries | 1621 | // own 3.000 s encode probes as 3.0065 (312/48000 more). Ours carries |
| 1594 | - // a 120-sample pre-skip, so exact is 2.0025; the decoded sample | 1622 | + // the same pre-skip our encoder advertises, so exact is 2.000 s plus |
| 1595 | - // count below is the pre-skip-free half of the claim. | 1623 | + // it; the decoded sample count below is the pre-skip-free half. |
| 1596 | - let expected = (total as f64 + 120.0) / 48000.0; | 1624 | + let expected = (total as f64 + pre_skip as f64) / 48000.0; |
| 1597 | assert!( | 1625 | assert!( |
| 1598 | (dur - expected).abs() < 1e-6, | 1626 | (dur - expected).abs() < 1e-6, |
| 1599 | "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)" | 1627 | "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)" |
| @@ -2081,7 +2109,7 @@ fn silk_mediumband_and_10ms_roundtrip() { | |||
| 2081 | frame_ms == 10 || voiced > 0, | 2109 | frame_ms == 10 || voiced > 0, |
| 2082 | "{tag}: no frame coded with LTP" | 2110 | "{tag}: no frame coded with LTP" |
| 2083 | ); | 2111 | ); |
| 2084 | - if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len()) { | 2112 | + if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120) { |
| 2085 | let (c, _) = aligned_corr(&oracle, &decoded, 2000); | 2113 | let (c, _) = aligned_corr(&oracle, &decoded, 2000); |
| 2086 | assert!(c >= 0.99, "{tag}: our decode vs oracle decode corr {c:.4}"); | 2114 | assert!(c >= 0.99, "{tag}: our decode vs oracle decode corr {c:.4}"); |
| 2087 | } | 2115 | } |
| @@ -2131,7 +2159,7 @@ fn silk_multiframe_packets_roundtrip() { | |||
| 2131 | ); | 2159 | ); |
| 2132 | assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}"); | 2160 | assert!(corr >= floor, "{tag}: corr {corr:.4} below {floor:.4}"); |
| 2133 | assert!(voiced > 0, "{tag}: no frame coded with LTP"); | 2161 | assert!(voiced > 0, "{tag}: no frame coded with LTP"); |
| 2134 | - if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len()) { | 2162 | + if let Some(oracle) = oracle_decode(&format!("silk-{tag}"), &packets, pcm.len(), 120) { |
| 2135 | let (c, _) = aligned_corr(&oracle, &decoded, 2500); | 2163 | let (c, _) = aligned_corr(&oracle, &decoded, 2500); |
| 2136 | assert!( | 2164 | assert!( |
| 2137 | c >= 0.99, | 2165 | c >= 0.99, |
| @@ -2338,12 +2366,21 @@ fn silk_compares_to_celt_on_speech_at_speech_rates() { | |||
| 2338 | } | 2366 | } |
| 2339 | 2367 | ||
| 2340 | /// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg. | 2368 | /// Reference oracle decode of `packets` as Ogg-Opus, or `None` without ffmpeg. |
| 2341 | -fn oracle_decode(name: &str, packets: &[Vec<u8>], samples: usize) -> Option<Vec<f32>> { | 2369 | +/// `pre_skip` must be the encoder's advertised [`Encoder::look_ahead`] for |
| 2370 | +/// these packets: it is what the oracle trims off the front, so a caller that | ||
| 2371 | +/// compares sample-for-sample against its own decode at that same offset only | ||
| 2372 | +/// lines up when the two agree. | ||
| 2373 | +fn oracle_decode( | ||
| 2374 | + name: &str, | ||
| 2375 | + packets: &[Vec<u8>], | ||
| 2376 | + samples: usize, | ||
| 2377 | + pre_skip: usize, | ||
| 2378 | +) -> Option<Vec<f32>> { | ||
| 2342 | if Command::new("ffmpeg").arg("-version").output().is_err() { | 2379 | if Command::new("ffmpeg").arg("-version").output().is_err() { |
| 2343 | return None; | 2380 | return None; |
| 2344 | } | 2381 | } |
| 2345 | let path = temp_path(&format!("{name}.opus")); | 2382 | let path = temp_path(&format!("{name}.opus")); |
| 2346 | - write_ogg_opus(&path, packets, opus_head(1, 120, None), 1, samples, 120); | 2383 | + write_ogg_opus(&path, packets, opus_head(1, pre_skip as u16, None), 1, samples, pre_skip as i64); |
| 2347 | let out = Command::new("ffmpeg") | 2384 | let out = Command::new("ffmpeg") |
| 2348 | .args(["-v", "warning", "-c:a", "libopus", "-i"]) | 2385 | .args(["-v", "warning", "-c:a", "libopus", "-i"]) |
| 2349 | .arg(&path) | 2386 | .arg(&path) |
| @@ -2390,7 +2427,7 @@ fn silk_nsq_improves_quality_at_equal_rate() { | |||
| 2390 | "{name}: corr {corr:.4} (floor {floor}) at {kbps:.1} kbps" | 2427 | "{name}: corr {corr:.4} (floor {floor}) at {kbps:.1} kbps" |
| 2391 | )); | 2428 | )); |
| 2392 | } | 2429 | } |
| 2393 | - if let Some(oracle) = oracle_decode(&format!("silk-nsq-{name}"), &packets, pcm.len()) { | 2430 | + if let Some(oracle) = oracle_decode(&format!("silk-nsq-{name}"), &packets, pcm.len(), 120) { |
| 2394 | let (c, _) = aligned_corr(&oracle, &decoded, 2000); | 2431 | let (c, _) = aligned_corr(&oracle, &decoded, 2000); |
| 2395 | assert!(c >= 0.99, "{name}: our decode vs oracle decode corr {c:.4}"); | 2432 | assert!(c >= 0.99, "{name}: our decode vs oracle decode corr {c:.4}"); |
| 2396 | } | 2433 | } |
| @@ -2485,6 +2522,15 @@ fn hybrid_roundtrip( | |||
| 2485 | /// The two layers of a hybrid packet reach the decoder's output at the same | 2522 | /// The two layers of a hybrid packet reach the decoder's output at the same |
| 2486 | /// delay: a click's low-band-only and high-band-only peaks coincide at the | 2523 | /// delay: a click's low-band-only and high-band-only peaks coincide at the |
| 2487 | /// encoder's documented look-ahead. | 2524 | /// encoder's documented look-ahead. |
| 2525 | +/// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame — | ||
| 2526 | +/// [`Encoder::look_ahead`] of that same configuration, so the lag assertions | ||
| 2527 | +/// track the layer's real delay instead of a constant. | ||
| 2528 | +fn hybrid_delay(bps: u32) -> usize { | ||
| 2529 | + let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap(); | ||
| 2530 | + enc.set_bitrate(bps); | ||
| 2531 | + enc.look_ahead(960) | ||
| 2532 | +} | ||
| 2533 | + | ||
| 2488 | #[test] | 2534 | #[test] |
| 2489 | fn hybrid_layers_align() { | 2535 | fn hybrid_layers_align() { |
| 2490 | let mut click = vec![0f32; 48000]; | 2536 | let mut click = vec![0f32; 48000]; |
| @@ -2500,29 +2546,26 @@ fn hybrid_layers_align() { | |||
| 2500 | }; | 2546 | }; |
| 2501 | let (lb, _) = hybrid_roundtrip(&click, 32_000, None, (true, false)); | 2547 | let (lb, _) = hybrid_roundtrip(&click, 32_000, None, (true, false)); |
| 2502 | let (hb, _) = hybrid_roundtrip(&click, 32_000, None, (false, true)); | 2548 | let (hb, _) = hybrid_roundtrip(&click, 32_000, None, (false, true)); |
| 2503 | - let enc = Encoder::new(48000, 1, Application::Voip).unwrap(); | 2549 | + let delay = hybrid_delay(32_000) as i64; |
| 2504 | let (plb, phb) = (peak(&lb) as i64 - at as i64, peak(&hb) as i64 - at as i64); | 2550 | let (plb, phb) = (peak(&lb) as i64 - at as i64, peak(&hb) as i64 - at as i64); |
| 2505 | - eprintln!( | 2551 | + eprintln!("hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {delay}"); |
| 2506 | - "hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {}", | 2552 | + // A fullband CELT click lands at exactly the encoder's advertised delay |
| 2507 | - { | 2553 | + // (`celt_click_peak_offset`); the band-limited HB layer's main lobe sits |
| 2508 | - let mut e = enc.clone(); | 2554 | + // up to 2 samples early once transient frames keep their short blocks, |
| 2509 | - e.set_bitrate(32_000); | 2555 | + // and SILK lands one sample late. |
| 2510 | - e.look_ahead(960) | ||
| 2511 | - } | ||
| 2512 | - ); | ||
| 2513 | - // A fullband CELT click lands at exactly +120 (`celt_click_peak_offset`); | ||
| 2514 | - // 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. | ||
| 2516 | assert!( | 2556 | assert!( |
| 2517 | (plb - phb).abs() <= 3, | 2557 | (plb - phb).abs() <= 3, |
| 2518 | "layers misaligned: LB +{plb} vs HB +{phb}" | 2558 | "layers misaligned: LB +{plb} vs HB +{phb}" |
| 2519 | ); | 2559 | ); |
| 2520 | - assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120"); | 2560 | + assert!((phb - delay).abs() <= 2, "HB peak +{phb}, look_ahead {delay}"); |
| 2521 | } | 2561 | } |
| 2522 | 2562 | ||
| 2523 | /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks | 2563 | /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks |
| 2524 | /// the input full-band and in the SILK layer's band alone, and the reference | 2564 | /// the input full-band and in the SILK layer's band alone, and the reference |
| 2525 | /// oracle decodes the packets to the same signal. | 2565 | /// oracle decodes the packets to the same signal. |
| 2566 | +/// | ||
| 2567 | +/// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame is | ||
| 2568 | +/// [`Encoder::look_ahead`] of that same configuration, never a constant. | ||
| 2526 | #[test] | 2569 | #[test] |
| 2527 | fn hybrid_fb_roundtrip() { | 2570 | fn hybrid_fb_roundtrip() { |
| 2528 | for (name, pcm) in silk_sources() { | 2571 | for (name, pcm) in silk_sources() { |
| @@ -2540,18 +2583,19 @@ fn hybrid_fb_roundtrip() { | |||
| 2540 | ); | 2583 | ); |
| 2541 | assert!(corr >= 0.95, "{name}: full-band corr {corr:.4}"); | 2584 | assert!(corr >= 0.95, "{name}: full-band corr {corr:.4}"); |
| 2542 | // +-3: the wav16 fixture is a pure tone, whose phase moves the peak. | 2585 | // +-3: the wav16 fixture is a pure tone, whose phase moves the peak. |
| 2586 | + let delay = hybrid_delay(32_000); | ||
| 2543 | assert!( | 2587 | assert!( |
| 2544 | - (117..=123).contains(&lag), | 2588 | + (delay - 3..=delay + 3).contains(&lag), |
| 2545 | - "{name}: aligned at lag {lag}, not the documented 120" | 2589 | + "{name}: aligned at lag {lag}, not the advertised {delay}" |
| 2546 | ); | 2590 | ); |
| 2547 | assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}"); | 2591 | assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}"); |
| 2548 | assert!( | 2592 | assert!( |
| 2549 | (28.0..=36.0).contains(&kbps), | 2593 | (28.0..=36.0).contains(&kbps), |
| 2550 | "{name}: {kbps:.1} kbps for a 32 kbps CBR target" | 2594 | "{name}: {kbps:.1} kbps for a 32 kbps CBR target" |
| 2551 | ); | 2595 | ); |
| 2552 | - if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len()) { | 2596 | + if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len(), delay) { |
| 2553 | - let n = oracle.len().min(decoded.len() - 120); | 2597 | + let n = oracle.len().min(decoded.len() - delay); |
| 2554 | - let c = correlation(&oracle[..n], &decoded[120..120 + n]); | 2598 | + let c = correlation(&oracle[..n], &decoded[delay..delay + n]); |
| 2555 | eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}"); | 2599 | eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}"); |
| 2556 | assert!(c >= 0.95, "{name}: oracle corr {c:.4}"); | 2600 | assert!(c >= 0.95, "{name}: oracle corr {c:.4}"); |
| 2557 | } | 2601 | } |
| @@ -2659,13 +2703,20 @@ fn hybrid_shapes_roundtrip() { | |||
| 2659 | assert!(worst >= floor, "{tag}: worst corr {worst:.4}"); | 2703 | assert!(worst >= floor, "{tag}: worst corr {worst:.4}"); |
| 2660 | let total = pcm.len() / channels; | 2704 | let total = pcm.len() / channels; |
| 2661 | let path = temp_path(&format!("hybrid-{tag}.opus")); | 2705 | let path = temp_path(&format!("hybrid-{tag}.opus")); |
| 2706 | + // The pre-skip is what `hybrid_roundtrip_shape`'s own encoder | ||
| 2707 | + // advertises for this frame size, not a constant. | ||
| 2708 | + let pre_skip = { | ||
| 2709 | + let mut e = Encoder::new(48000, channels, Application::Voip).unwrap(); | ||
| 2710 | + e.set_bitrate(bps); | ||
| 2711 | + e.look_ahead(frame) | ||
| 2712 | + }; | ||
| 2662 | write_ogg_opus( | 2713 | write_ogg_opus( |
| 2663 | &path, | 2714 | &path, |
| 2664 | &packets, | 2715 | &packets, |
| 2665 | - opus_head(channels, 120, None), | 2716 | + opus_head(channels, pre_skip as u16, None), |
| 2666 | channels, | 2717 | channels, |
| 2667 | total, | 2718 | total, |
| 2668 | - 120, | 2719 | + pre_skip as i64, |
| 2669 | ); | 2720 | ); |
| 2670 | if Command::new("ffmpeg").arg("-version").output().is_ok() { | 2721 | if Command::new("ffmpeg").arg("-version").output().is_ok() { |
| 2671 | let out = Command::new("ffmpeg") | 2722 | let out = Command::new("ffmpeg") |
lanes/opus-opusx2-r1.sweep.txtadded+17 -0
| @@ -0,0 +1,17 @@ | |||
| 1 | +# lane-opusx2 r1: CELT input delayed by Fs/250 + libopus dc_reject (3 Hz) on the API input | ||
| 2 | +# baseline lanes/opus-opustr2-r1.sweep.txt (shipped); delay-only arm = lanes/opus-opusx-r1.sweep.txt | ||
| 3 | +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) | ||
| 4 | +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo | ||
| 5 | +# 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 | ||
| 6 | +nik 64 69.1 69.2 -0.1 0.9883 0.9864 -0.0020 -116.02 -154.78 0.805 0.9766 0.9745 0 0 | ||
| 7 | +nik 96 100.9 101.0 -0.1 0.9944 0.9940 -0.0003 -111.04 -31.55 1.780 0.9888 0.9888 0 0 | ||
| 8 | +reelo 64 63.6 63.6 -0.0 0.9887 0.9866 -0.0021 -172.14 -123.36 1.301 0.9708 0.9686 0 0 | ||
| 9 | +reelo 96 93.4 93.9 -0.5 0.9943 0.9937 -0.0006 -101.22 -125.18 0.866 0.9875 0.9854 0 0 | ||
| 10 | +her 64 67.6 67.9 -0.4 0.9828 0.9794 -0.0033 -333.52 -339.00 0.980 0.9474 0.9406 0 0 | ||
| 11 | +her 96 101.0 101.5 -0.5 0.9916 0.9902 -0.0014 -248.38 -191.50 1.293 0.9770 0.9728 0 0 | ||
| 12 | +reell 64 71.3 71.3 -0.0 0.9904 0.9880 -0.0024 -264.15 -128.39 1.920 0.9714 0.9644 0 0 | ||
| 13 | +reell 96 105.3 105.4 -0.0 0.9952 0.9948 -0.0004 -271.16 -29.16 3.980 0.9853 0.9804 0 0 | ||
| 14 | +dl8a 64 65.7 65.8 -0.1 0.9885 0.9865 -0.0020 -399.15 -378.84 1.074 0.9787 0.9723 0 0 | ||
| 15 | +dl8a 96 96.6 96.8 -0.3 0.9938 0.9934 -0.0004 -426.78 -423.47 1.011 0.9876 0.9864 0 0 | ||
| 16 | +hein 64 64.8 64.9 -0.2 0.9887 0.9874 -0.0013 -383.53 -388.31 0.983 0.9345 0.9148 0 0 | ||
| 17 | +hein 96 86.8 86.9 -0.2 0.9944 0.9930 -0.0014 -351.66 -246.46 1.513 0.9701 0.9499 0 0 | ||
lanes/opus-opusx2-r2.sweep.txtadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +# lane-opusx2 r2: EC_OPUS_TWO_PASS=1 (libopus two-pass coarse energy) (on the aligned tree: Fs/250 delay + dc_reject) | ||
| 2 | +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) | ||
| 3 | +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo | ||
| 4 | +# 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 | ||
| 5 | +nik 64 69.1 69.2 -0.1 0.9884 0.9864 -0.0020 -114.86 -154.78 0.799 0.9767 0.9745 0 0 | ||
| 6 | +nik 96 100.9 101.0 -0.1 0.9944 0.9940 -0.0003 -113.73 -31.55 1.809 0.9889 0.9888 0 0 | ||
| 7 | +reelo 64 63.6 63.6 -0.0 0.9888 0.9866 -0.0021 -168.90 -123.36 1.280 0.9708 0.9686 0 0 | ||
| 8 | +reelo 96 93.4 93.9 -0.5 0.9943 0.9937 -0.0006 -98.26 -125.18 0.850 0.9874 0.9854 0 0 | ||
| 9 | +her 64 67.7 67.9 -0.4 0.9828 0.9794 -0.0034 -342.89 -339.00 1.015 0.9477 0.9406 0 0 | ||
| 10 | +her 96 101.0 101.5 -0.5 0.9916 0.9902 -0.0014 -245.44 -191.50 1.277 0.9773 0.9728 0 0 | ||
| 11 | +reell 64 71.3 71.3 -0.0 0.9904 0.9880 -0.0024 -270.85 -128.39 1.974 0.9715 0.9644 0 0 | ||
| 12 | +reell 96 105.3 105.4 -0.0 0.9952 0.9948 -0.0004 -271.17 -29.16 3.980 0.9853 0.9804 0 0 | ||
| 13 | +dl8a 64 65.7 65.8 -0.1 0.9885 0.9865 -0.0020 -431.62 -378.84 1.200 0.9784 0.9723 0 0 | ||
| 14 | +dl8a 96 96.6 96.8 -0.3 0.9938 0.9934 -0.0004 -429.71 -423.47 1.021 0.9877 0.9864 0 0 | ||
| 15 | +hein 64 64.8 64.9 -0.1 0.9889 0.9874 -0.0016 -398.79 -388.31 1.037 0.9355 0.9148 0 0 | ||
| 16 | +hein 96 86.8 86.9 -0.2 0.9945 0.9930 -0.0015 -348.20 -246.46 1.494 0.9705 0.9499 0 0 | ||
lanes/opus-opusx2-r3.sweep.txtadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +# lane-opusx2 r3: EC_OPUS_TRIM13=1 (continuous 1.3 alloc_trim) (on the aligned tree: Fs/250 delay + dc_reject) | ||
| 2 | +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) | ||
| 3 | +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo | ||
| 4 | +# 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 | ||
| 5 | +nik 64 69.1 69.2 -0.1 0.9875 0.9864 -0.0011 -117.01 -154.78 0.810 0.9760 0.9745 0 0 | ||
| 6 | +nik 96 100.9 101.0 -0.1 0.9938 0.9940 +0.0003 -128.36 -31.55 1.971 0.9880 0.9888 0 0 | ||
| 7 | +reelo 64 63.6 63.6 -0.0 0.9883 0.9866 -0.0017 -157.11 -123.36 1.204 0.9707 0.9686 0 0 | ||
| 8 | +reelo 96 93.4 93.9 -0.5 0.9940 0.9937 -0.0002 -74.67 -125.18 0.726 0.9866 0.9854 0 0 | ||
| 9 | +her 64 67.6 67.9 -0.4 0.9820 0.9794 -0.0026 -334.21 -339.00 0.982 0.9455 0.9406 0 0 | ||
| 10 | +her 96 101.0 101.5 -0.5 0.9911 0.9902 -0.0008 -251.84 -191.50 1.312 0.9757 0.9728 0 0 | ||
| 11 | +reell 64 71.3 71.3 -0.0 0.9896 0.9880 -0.0016 -268.76 -128.39 1.957 0.9704 0.9644 0 0 | ||
| 12 | +reell 96 105.3 105.4 -0.0 0.9947 0.9948 +0.0001 -265.83 -29.16 3.893 0.9845 0.9804 0 0 | ||
| 13 | +dl8a 64 65.7 65.8 -0.1 0.9874 0.9865 -0.0009 -387.57 -378.84 1.031 0.9762 0.9723 0 0 | ||
| 14 | +dl8a 96 96.6 96.8 -0.3 0.9931 0.9934 +0.0003 -413.74 -423.47 0.967 0.9858 0.9864 0 0 | ||
| 15 | +hein 64 64.8 64.9 -0.2 0.9886 0.9874 -0.0012 -383.53 -388.31 0.983 0.9345 0.9148 0 0 | ||
| 16 | +hein 96 86.8 86.9 -0.2 0.9944 0.9930 -0.0014 -351.67 -246.46 1.513 0.9699 0.9499 0 0 | ||
lanes/opus-opusx2-r4.sweep.txtadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +# lane-opusx2 r4: EC_OPUS_TF_K=1.25 (CVBR tf boost) (on the aligned tree: Fs/250 delay + dc_reject) | ||
| 2 | +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) | ||
| 3 | +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo | ||
| 4 | +# 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 | ||
| 5 | +nik 64 69.1 69.2 -0.1 0.9883 0.9864 -0.0020 -110.52 -154.78 0.779 0.9765 0.9745 0 0 | ||
| 6 | +nik 96 100.9 101.0 -0.1 0.9943 0.9940 -0.0003 -111.87 -31.55 1.789 0.9888 0.9888 0 0 | ||
| 7 | +reelo 64 63.5 63.6 -0.1 0.9887 0.9866 -0.0020 -180.92 -123.36 1.359 0.9704 0.9686 0 0 | ||
| 8 | +reelo 96 93.3 93.9 -0.6 0.9942 0.9937 -0.0005 -90.05 -125.18 0.806 0.9870 0.9854 0 0 | ||
| 9 | +her 64 67.5 67.9 -0.6 0.9826 0.9794 -0.0032 -311.93 -339.00 0.903 0.9471 0.9406 0 0 | ||
| 10 | +her 96 100.7 101.5 -0.7 0.9914 0.9902 -0.0012 -230.30 -191.50 1.195 0.9765 0.9728 0 0 | ||
| 11 | +reell 64 71.3 71.3 -0.0 0.9904 0.9880 -0.0024 -269.89 -128.39 1.966 0.9712 0.9644 0 0 | ||
| 12 | +reell 96 105.3 105.4 -0.0 0.9952 0.9948 -0.0004 -263.44 -29.16 3.855 0.9852 0.9804 0 0 | ||
| 13 | +dl8a 64 65.6 65.8 -0.2 0.9884 0.9865 -0.0020 -424.09 -378.84 1.170 0.9791 0.9723 0 0 | ||
| 14 | +dl8a 96 96.4 96.8 -0.4 0.9937 0.9934 -0.0003 -434.84 -423.47 1.039 0.9872 0.9864 0 0 | ||
| 15 | +hein 64 64.7 64.9 -0.3 0.9882 0.9874 -0.0008 -376.99 -388.31 0.961 0.9314 0.9148 0 0 | ||
| 16 | +hein 96 86.7 86.9 -0.3 0.9941 0.9930 -0.0011 -363.54 -246.46 1.580 0.9677 0.9499 0 0 | ||
lanes/opus-opusx2-r5.sweep.txtadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +# lane-opusx2 r5: EC_OPUS_TF_K=1.5 (CVBR tf boost) (on the aligned tree: Fs/250 delay + dc_reject) | ||
| 2 | +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) | ||
| 3 | +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo | ||
| 4 | +# 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 | ||
| 5 | +nik 64 69.1 69.2 -0.2 0.9883 0.9864 -0.0019 -155.70 -154.78 1.005 0.9765 0.9745 0 0 | ||
| 6 | +nik 96 100.8 101.0 -0.2 0.9943 0.9940 -0.0003 -111.16 -31.55 1.781 0.9888 0.9888 0 0 | ||
| 7 | +reelo 64 63.5 63.6 -0.2 0.9886 0.9866 -0.0020 -179.06 -123.36 1.347 0.9699 0.9686 0 0 | ||
| 8 | +reelo 96 93.2 93.9 -0.7 0.9942 0.9937 -0.0004 -89.99 -125.18 0.805 0.9869 0.9854 0 0 | ||
| 9 | +her 64 67.5 67.9 -0.7 0.9825 0.9794 -0.0030 -347.44 -339.00 1.032 0.9466 0.9406 0 0 | ||
| 10 | +her 96 100.7 101.5 -0.8 0.9913 0.9902 -0.0011 -247.70 -191.50 1.289 0.9760 0.9728 0 0 | ||
| 11 | +reell 64 71.3 71.3 -0.0 0.9904 0.9880 -0.0024 -272.52 -128.39 1.987 0.9710 0.9644 0 0 | ||
| 12 | +reell 96 105.3 105.4 -0.0 0.9952 0.9948 -0.0004 -261.59 -29.16 3.825 0.9849 0.9804 0 0 | ||
| 13 | +dl8a 64 65.5 65.8 -0.4 0.9883 0.9865 -0.0019 -394.10 -378.84 1.055 0.9784 0.9723 0 0 | ||
| 14 | +dl8a 96 96.3 96.8 -0.5 0.9936 0.9934 -0.0002 -406.85 -423.47 0.945 0.9865 0.9864 0 0 | ||
| 15 | +hein 64 64.6 64.9 -0.4 0.9876 0.9874 -0.0003 -374.22 -388.31 0.951 0.9258 0.9148 0 0 | ||
| 16 | +hein 96 86.5 86.9 -0.4 0.9938 0.9930 -0.0007 -373.59 -246.46 1.638 0.9651 0.9499 0 0 | ||
lanes/opus-opusx2-r6.sweep.txtadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +# lane-opusx2 r6: DEFAULTS (alignment knob off) -- regression check that the shipped path is untouched | ||
| 2 | +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) | ||
| 3 | +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo | ||
| 4 | +# 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 | ||
| 5 | +nik 64 69.1 69.2 -0.1 0.9887 0.9864 -0.0024 -95.23 -154.78 0.708 0.9766 0.9745 0 0 | ||
| 6 | +nik 96 100.9 101.0 -0.1 0.9947 0.9940 -0.0007 -29.86 -31.55 0.985 0.9889 0.9888 0 0 | ||
| 7 | +reelo 64 63.6 63.6 -0.0 0.9893 0.9866 -0.0027 -202.82 -123.36 1.510 0.9702 0.9686 0 0 | ||
| 8 | +reelo 96 93.4 93.9 -0.5 0.9947 0.9937 -0.0009 -114.74 -125.18 0.940 0.9862 0.9854 0 0 | ||
| 9 | +her 64 67.7 67.9 -0.4 0.9834 0.9794 -0.0040 -365.72 -339.00 1.103 0.9477 0.9406 0 0 | ||
| 10 | +her 96 101.0 101.5 -0.5 0.9914 0.9902 -0.0012 -202.07 -191.50 1.051 0.9728 0.9728 0 0 | ||
| 11 | +reell 64 71.3 71.3 -0.0 0.9908 0.9880 -0.0029 -351.70 -128.39 2.697 0.9721 0.9644 0 0 | ||
| 12 | +reell 96 105.3 105.4 -0.0 0.9956 0.9948 -0.0008 -301.83 -29.16 4.499 0.9856 0.9804 0 0 | ||
| 13 | +dl8a 64 65.7 65.8 -0.1 0.9889 0.9865 -0.0025 -227.54 -378.84 0.552 0.9787 0.9723 0 0 | ||
| 14 | +dl8a 96 96.5 96.8 -0.3 0.9942 0.9934 -0.0009 -177.70 -423.47 0.374 0.9881 0.9864 0 0 | ||
| 15 | +hein 64 64.8 64.9 -0.2 0.9888 0.9874 -0.0014 -344.06 -388.31 0.853 0.9318 0.9148 0 0 | ||
| 16 | +hein 96 86.8 86.9 -0.2 0.9946 0.9930 -0.0016 -117.91 -246.46 0.528 0.9689 0.9499 0 0 | ||
lanes/opus-opusx2-r7.sweep.txtadded+16 -0
| @@ -0,0 +1,16 @@ | |||
| 1 | +# lane-opusx2 r7: aligned tree + two-pass coarse energy + tf boost k=1.25 (combined winners) | ||
| 2 | +# ec-opus encoder vs ffmpeg libopus — encoders-only gate (r1) | ||
| 3 | +# both bitstreams decoded by ec-opus; 120s cap; VBR; 48kHz stereo | ||
| 4 | +# 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 | ||
| 5 | +nik 64 69.1 69.2 -0.1 0.9883 0.9864 -0.0020 -109.28 -154.78 0.773 0.9766 0.9745 0 0 | ||
| 6 | +nik 96 100.9 101.0 -0.1 0.9943 0.9940 -0.0003 -113.00 -31.55 1.801 0.9889 0.9888 0 0 | ||
| 7 | +reelo 64 63.5 63.6 -0.1 0.9887 0.9866 -0.0020 -177.31 -123.36 1.335 0.9701 0.9686 0 0 | ||
| 8 | +reelo 96 93.3 93.9 -0.6 0.9943 0.9937 -0.0005 -89.23 -125.18 0.801 0.9870 0.9854 0 0 | ||
| 9 | +her 64 67.6 67.9 -0.5 0.9827 0.9794 -0.0033 -309.55 -339.00 0.894 0.9475 0.9406 0 0 | ||
| 10 | +her 96 100.7 101.5 -0.7 0.9915 0.9902 -0.0012 -214.59 -191.50 1.114 0.9768 0.9728 0 0 | ||
| 11 | +reell 64 71.3 71.3 -0.0 0.9904 0.9880 -0.0024 -271.04 -128.39 1.975 0.9712 0.9644 0 0 | ||
| 12 | +reell 96 105.3 105.4 -0.0 0.9952 0.9948 -0.0004 -262.90 -29.16 3.846 0.9852 0.9804 0 0 | ||
| 13 | +dl8a 64 65.7 65.8 -0.2 0.9885 0.9865 -0.0020 -426.86 -378.84 1.181 0.9789 0.9723 0 0 | ||
| 14 | +dl8a 96 96.4 96.8 -0.4 0.9937 0.9934 -0.0003 -427.68 -423.47 1.014 0.9871 0.9864 0 0 | ||
| 15 | +hein 64 64.7 64.9 -0.3 0.9884 0.9874 -0.0010 -381.78 -388.31 0.977 0.9320 0.9148 0 0 | ||
| 16 | +hein 96 86.7 86.9 -0.3 0.9942 0.9930 -0.0012 -330.35 -246.46 1.398 0.9681 0.9499 0 0 | ||