From 0151578356e0061225a91c7df907b4e6754318e4 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:49:13 +0300 Subject: [PATCH] feat(opus): libopus dc_reject on the API input, and lag-dependent tests read look_ahead The CELT input delay is back (revert of the revert): the analysis window now sits where libopus's does. On top of it, opus_encoder.c's dc_reject -- a 3 Hz one-pole (coef = 6.3*cutoff/Fs, y = x - m, m = coef*x + (1-coef)*m, state per channel across frames) -- runs once on the API input before both layers, the way libopus filters into pcm_buf that silk_Encode and celt_encode_with_ec both read. libopus takes hp_cutoff instead for VOIP; not ported. The seven tests that compared at a hardcoded 120-sample lag now read the encoder's advertised look_ahead for the frame size they used, so they follow the layer's real delay: delayed_corr takes it as an argument, the Ogg pre-skip and the duration expectation come from look_ahead, and the hybrid lag window is centred on it. MultistreamEncoder grew look_ahead for the 5.1 file. Sweep knobs for the re-tune on the aligned spectrum: EC_OPUS_TWO_PASS, EC_OPUS_TRIM13 (the continuous 1.3 alloc_trim form). --- crates/ec-opus/src/celt_enc.rs | 33 ++++++- crates/ec-opus/src/encoder.rs | 119 ++++++++++++++++++-------- crates/ec-opus/src/multistream_enc.rs | 7 ++ crates/ec-opus/tests/conformance.rs | 64 +++++++++----- 4 files changed, 163 insertions(+), 60 deletions(-) diff --git a/crates/ec-opus/src/celt_enc.rs b/crates/ec-opus/src/celt_enc.rs index 0cee5e3f..a314f8a1 100644 --- a/crates/ec-opus/src/celt_enc.rs +++ b/crates/ec-opus/src/celt_enc.rs @@ -794,8 +794,10 @@ impl CeltEncoder { // .708->.703, reelo@96 .940->.872, dl8a .551/.374->.503/.346, hein // .855/.528->.771/.419), corr within +.0001 everywhere. The KEEP rule // is "err_ratio not worse on every row", so the search ships off. + // `EC_OPUS_TWO_PASS=1` re-arms it for a sweep (lane opusx2 r2). const TWO_PASS_COARSE_ENERGY: bool = false; - let mut two_pass = TWO_PASS_COARSE_ENERGY; + let mut two_pass = + TWO_PASS_COARSE_ENERGY || std::env::var_os("EC_OPUS_TWO_PASS").is_some(); let mut intra = self.force_intra || (!two_pass && self.delayed_intra > (2 * c * (end - start)) as f32 @@ -896,7 +898,7 @@ impl CeltEncoder { // --- Allocation trim ------------------------------------------------ let mut alloc_trim = 5i32; if tell_frac + (6 << BITRES) <= total_bits_frac - total_boost { - alloc_trim = self.alloc_trim_analysis(end, lm, c, n); + alloc_trim = self.alloc_trim_analysis(end, lm, c, n, tf_estimate); enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7); tell_frac = enc.tell_frac() as i32; } @@ -1574,7 +1576,20 @@ impl CeltEncoder { /// dl8a@64 .9889->.9879). The KEEP rule rejects it; this is the third /// rejection of the same port (see `lanes/opus-trim-r2.{A,B}.sweep.txt`). /// Do not re-port it without a fix for the transient rows first. - fn alloc_trim_analysis(&mut self, end: usize, lm: usize, c: usize, n0: usize) -> i32 { + /// + /// `EC_OPUS_TRIM13=1` selects the continuous 1.3 form instead, for the + /// re-sweep on the aligned (delayed) spectrum the discrete ladder was + /// never measured against. + fn alloc_trim_analysis( + &mut self, + end: usize, + lm: usize, + c: usize, + n0: usize, + tf_estimate: f32, + ) -> i32 { + let cont = std::env::var_os("EC_OPUS_TRIM13").is_some(); + let mut trim_f = 5.0f32; let mut trim = 5i32; if c == 2 { let mut sum = 0.0f32; @@ -1586,6 +1601,10 @@ impl CeltEncoder { sum += partial; } sum *= 1.0 / 8.0; + if cont { + let sum_c = sum.abs().min(1.0); + trim_f += (0.75 * (1.001 - sum_c * sum_c).log2()).max(-4.0); + } if sum > 0.995 { trim -= 4; } else if sum > 0.92 { @@ -1619,6 +1638,14 @@ impl CeltEncoder { * (2 + 2 * i as i32 - NB_BANDS as i32) as f32; } } + if cont { + // libopus divides the same sum by `C*(end-1)`; the ladder above + // carries an extra factor of two in its thresholds. + let diff = diff / (c * (end - 1)) as f32; + trim_f -= ((diff + 1.0) / 6.0).clamp(-2.0, 2.0); + trim_f -= 2.0 * tf_estimate; + return (trim_f + 0.5).floor().clamp(0.0, 10.0) as i32; + } diff /= (2 * c * (end - 1)) as f32; if diff > 2.0 { trim -= 1; diff --git a/crates/ec-opus/src/encoder.rs b/crates/ec-opus/src/encoder.rs index c7f92bda..cce43dbe 100644 --- a/crates/ec-opus/src/encoder.rs +++ b/crates/ec-opus/src/encoder.rs @@ -116,6 +116,12 @@ pub struct Encoder { /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so /// the steady-state loop doesn't allocate a `Vec` per frame. silk_stuff: Vec, + /// libopus `opus_encoder.c`'s `hp_mem`: the one-pole state of the + /// [`Encoder::dc_reject`] filter every frame of API input goes through, + /// one per channel. + hp_mem: [f32; 2], + /// Scratch space for that filter's output, sized once. + hp_buf: Vec, } /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8, @@ -175,6 +181,8 @@ impl Encoder { silk_buf: [0u8; MAX_SILK_PACKET_BYTES], silk_delay: Vec::new(), silk_stuff: Vec::new(), + hp_mem: [0.0; 2], + hp_buf: Vec::new(), }) } @@ -283,6 +291,7 @@ impl Encoder { self.silk_stereo_mb = None; self.silk_stereo_wb = None; self.silk_delay.clear(); + self.hp_mem = [0.0; 2]; self.final_range = 0; } @@ -692,6 +701,32 @@ impl Encoder { BWS[idx].min(ceiling) } + /// libopus `opus_encoder.c`'s `dc_reject(pcm, 3, ...)`: a 3 Hz one-pole + /// high-pass on the API input, applied once before *both* layers (libopus + /// filters into `pcm_buf`, which is what `silk_Encode` and + /// `celt_encode_with_ec` both read). `coef = 6.3 * cutoff / Fs` at the + /// API rate; the output is the input minus a leaky integrator of it, and + /// the integrator state carries across frames. + /// + /// libopus takes the `hp_cutoff` branch instead for + /// `OPUS_APPLICATION_VOIP` (a bandwidth-dependent second-order section); + /// not ported — every VoIP frame still gets this DC reject. + fn dc_reject(&mut self, pcm: &[f32], frame_size: usize, out: &mut Vec) { + let c = self.channels; + let coef = 6.3 * 3.0 / self.sample_rate as f32; + out.clear(); + out.resize(frame_size * c, 0.0); + for ch in 0..c { + let mut m = self.hp_mem[ch]; + for i in 0..frame_size { + let x = pcm[i * c + ch]; + out[i * c + ch] = x - m; + m += coef * (x - m); + } + self.hp_mem[ch] = m; + } + } + /// Encodes one frame — `frame_size` samples per channel of interleaved /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus /// packet in `out`, returning the packet length. @@ -701,19 +736,27 @@ impl Encoder { frame_size: usize, out: &mut [u8], ) -> Result { - let (toc, payload) = - self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?; - let n = payload.len(); - if out.len() < 1 + n { - return Err(Error::corrupt(format!( - "opus encode: packet needs {} bytes, buffer holds {}", - 1 + n, - out.len() - ))); - } - out[0] = toc; - out[1..1 + n].copy_from_slice(payload); - Ok(1 + n) + let mut hp = std::mem::take(&mut self.hp_buf); + self.dc_reject(pcm, frame_size, &mut hp); + let r = match self.encode_toc_and_payload(&hp, frame_size, out.len().saturating_sub(1)) { + Err(e) => Err(e), + Ok((toc, payload)) => { + let n = payload.len(); + if out.len() < 1 + n { + Err(Error::corrupt(format!( + "opus encode: packet needs {} bytes, buffer holds {}", + 1 + n, + out.len() + ))) + } else { + out[0] = toc; + out[1..1 + n].copy_from_slice(payload); + Ok(1 + n) + } + } + }; + self.hp_buf = hp; + r } /// [`Encoder::encode_float`] from 16-bit samples. @@ -731,27 +774,35 @@ impl Encoder { frame_size: usize, out: &mut [u8], ) -> Result { - let (toc, payload) = - self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?; - let n = payload.len(); - let len_bytes = if n < 252 { 1 } else { 2 }; - if out.len() < 1 + len_bytes + n { - return Err(Error::corrupt(format!( - "opus encode: self-delimited packet needs {} bytes, buffer holds {}", - 1 + len_bytes + n, - out.len() - ))); - } - out[0] = toc; - if n < 252 { - out[1] = n as u8; - } else { - let b0 = 252 + ((n - 252) & 3); - out[1] = b0 as u8; - out[2] = ((n - b0) / 4) as u8; - } - out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload); - Ok(1 + len_bytes + n) + let mut hp = std::mem::take(&mut self.hp_buf); + self.dc_reject(pcm, frame_size, &mut hp); + let r = match self.encode_toc_and_payload(&hp, frame_size, out.len().saturating_sub(3)) { + Err(e) => Err(e), + Ok((toc, payload)) => { + let n = payload.len(); + let len_bytes = if n < 252 { 1 } else { 2 }; + if out.len() < 1 + len_bytes + n { + Err(Error::corrupt(format!( + "opus encode: self-delimited packet needs {} bytes, buffer holds {}", + 1 + len_bytes + n, + out.len() + ))) + } else { + out[0] = toc; + if n < 252 { + out[1] = n as u8; + } else { + let b0 = 252 + ((n - 252) & 3); + out[1] = b0 as u8; + out[2] = ((n - b0) / 4) as u8; + } + out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload); + Ok(1 + len_bytes + n) + } + } + }; + self.hp_buf = hp; + r } /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB) diff --git a/crates/ec-opus/src/multistream_enc.rs b/crates/ec-opus/src/multistream_enc.rs index 99a3ee67..dfe8f9a7 100644 --- a/crates/ec-opus/src/multistream_enc.rs +++ b/crates/ec-opus/src/multistream_enc.rs @@ -27,6 +27,13 @@ pub struct MultistreamEncoder { } impl MultistreamEncoder { + /// The encoder delay each stream carries for a `frame_size` frame — the + /// per-stream [`Encoder::look_ahead`], which every stream shares, and so + /// the Ogg-Opus pre-skip a multistream file must carry. + pub fn look_ahead(&self, frame_size: usize) -> usize { + self.streams[0].look_ahead(frame_size) + } + /// An encoder for `streams` elementary streams of which the first /// `coupled` are stereo, with `mapping` naming the coded channel each /// input channel feeds. Layout rules are the decoder's, checked the same diff --git a/crates/ec-opus/tests/conformance.rs b/crates/ec-opus/tests/conformance.rs index d40f9fc3..1f5c1942 100644 --- a/crates/ec-opus/tests/conformance.rs +++ b/crates/ec-opus/tests/conformance.rs @@ -864,17 +864,18 @@ fn roundtrip_own( (decoded, bytes) } -/// Worst-channel correlation against the source with the encoder's -/// 120-sample delay removed. -fn delayed_corr(source: &[f32], decoded: &[f32], channels: usize) -> f64 { - const DELAY: usize = 120; - let n = (decoded.len() / channels).saturating_sub(DELAY); +/// Worst-channel correlation against the source with the encoder's own +/// delay removed — `delay` is [`Encoder::look_ahead`] for the frame size the +/// round trip used, never a constant (it moved 120 -> 312 when the CELT layer +/// took libopus's Fs/250 input delay). +fn delayed_corr(source: &[f32], decoded: &[f32], channels: usize, delay: usize) -> f64 { + let n = (decoded.len() / channels).saturating_sub(delay); let n = n.min(source.len() / channels); let mut worst = 1.0f64; for c in 0..channels { let a: Vec = (0..n).map(|i| source[i * channels + c]).collect(); let b: Vec = (0..n) - .map(|i| decoded[(i + DELAY) * channels + c]) + .map(|i| decoded[(i + delay) * channels + c]) .collect(); worst = worst.min(correlation(&a, &b)); } @@ -894,7 +895,7 @@ fn encoder_roundtrips_at_every_rate() { let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap(); enc.set_bitrate(kbps * 1000); let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, channels, 960); - let corr = delayed_corr(&pcm, &decoded, channels); + let corr = delayed_corr(&pcm, &decoded, channels, enc.look_ahead(960)); let rate = bytes as f64 * 8.0 / 2.0 / 1000.0; println!("{channels} ch {kbps:>3} kbps: corr {corr:.4}, actual {rate:.1} kbps"); let floor = if kbps < 64 { 0.8 } else { 0.9 }; @@ -1271,7 +1272,7 @@ fn encoder_frame_sizes_and_vbr() { let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap(); enc.set_bitrate(128_000); let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame); - let corr = delayed_corr(&pcm, &decoded, 2); + let corr = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(frame)); println!("frame {frame}: corr {corr:.4}"); assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}"); } @@ -1279,7 +1280,7 @@ fn encoder_frame_sizes_and_vbr() { enc.set_bitrate(128_000); enc.set_vbr_constrained(true); let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960); - let corr = delayed_corr(&pcm, &decoded, 2); + let corr = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(960)); let rate = bytes as f64 * 8.0 / 1.0 / 1000.0; println!("cvbr 128k: corr {corr:.4}, actual {rate:.1} kbps"); assert!(corr >= 0.9, "cvbr: correlation {corr:.4}"); @@ -1405,10 +1406,10 @@ fn oracle_decodes_our_packets_across_the_rate_table() { write_ogg_opus( &path, &packets, - opus_head(channels, 120, None), + opus_head(channels, enc.look_ahead(960) as u16, None), channels, total, - 120, + enc.look_ahead(960) as i64, ); let Some(reference) = ffmpeg_decode(&path, channels) else { eprintln!("ffmpeg unavailable, skipped"); @@ -1534,9 +1535,10 @@ fn five_one_encode_end_to_end() { let len = enc.encode_float(&silence, 960, &mut out).expect("encode"); packets.push(out[..len].to_vec()); let (streams, coupled, mapping) = enc.layout(); - let head = opus_head(6, 120, Some((streams, coupled, mapping))); + let pre_skip = enc.look_ahead(960); + let head = opus_head(6, pre_skip as u16, Some((streams, coupled, mapping))); let path = temp_path("5.1.opus"); - write_ogg_opus(&path, &packets, head, 6, total, 120); + write_ogg_opus(&path, &packets, head, 6, total, pre_skip as i64); let Some(reference) = ffmpeg_decode(&path, 6) else { eprintln!("ffmpeg unavailable, skipped"); let _ = fs::remove_file(&path); @@ -1568,7 +1570,8 @@ fn ogg_opus_round_trip_duration_is_exact() { enc.set_bitrate(128_000); let packets = encode_packets(&mut enc, &pcm, 2); let path = temp_path("duration.opus"); - write_ogg_opus(&path, &packets, opus_head(2, 120, None), 2, total, 120); + let pre_skip = enc.look_ahead(960); + write_ogg_opus(&path, &packets, opus_head(2, pre_skip as u16, None), 2, total, pre_skip as i64); let probe = Command::new("ffprobe") .args([ "-v", @@ -1592,9 +1595,9 @@ fn ogg_opus_round_trip_duration_is_exact() { .unwrap_or(0.0); // ffprobe reports Ogg-Opus durations *including* the pre-skip — its // own 3.000 s encode probes as 3.0065 (312/48000 more). Ours carries - // a 120-sample pre-skip, so exact is 2.0025; the decoded sample - // count below is the pre-skip-free half of the claim. - let expected = (total as f64 + 120.0) / 48000.0; + // the same pre-skip our encoder advertises, so exact is 2.000 s plus + // it; the decoded sample count below is the pre-skip-free half. + let expected = (total as f64 + pre_skip as f64) / 48000.0; assert!( (dur - expected).abs() < 1e-6, "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)" @@ -2525,6 +2528,9 @@ fn hybrid_layers_align() { /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks /// the input full-band and in the SILK layer's band alone, and the reference /// oracle decodes the packets to the same signal. +/// +/// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame is +/// [`Encoder::look_ahead`] of that same configuration, never a constant. #[test] fn hybrid_fb_roundtrip() { for (name, pcm) in silk_sources() { @@ -2542,9 +2548,14 @@ fn hybrid_fb_roundtrip() { ); assert!(corr >= 0.95, "{name}: full-band corr {corr:.4}"); // +-3: the wav16 fixture is a pure tone, whose phase moves the peak. + let delay = { + let mut e = Encoder::new(48000, 1, Application::Voip).unwrap(); + e.set_bitrate(32_000); + e.look_ahead(960) + }; assert!( - (117..=123).contains(&lag), - "{name}: aligned at lag {lag}, not the documented 120" + (delay - 3..=delay + 3).contains(&lag), + "{name}: aligned at lag {lag}, not the advertised {delay}" ); assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}"); assert!( @@ -2552,8 +2563,8 @@ fn hybrid_fb_roundtrip() { "{name}: {kbps:.1} kbps for a 32 kbps CBR target" ); if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len()) { - let n = oracle.len().min(decoded.len() - 120); - let c = correlation(&oracle[..n], &decoded[120..120 + n]); + let n = oracle.len().min(decoded.len() - delay); + let c = correlation(&oracle[..n], &decoded[delay..delay + n]); eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}"); assert!(c >= 0.95, "{name}: oracle corr {c:.4}"); } @@ -2661,13 +2672,20 @@ fn hybrid_shapes_roundtrip() { assert!(worst >= floor, "{tag}: worst corr {worst:.4}"); let total = pcm.len() / channels; let path = temp_path(&format!("hybrid-{tag}.opus")); + // The pre-skip is what `hybrid_roundtrip_shape`'s own encoder + // advertises for this frame size, not a constant. + let pre_skip = { + let mut e = Encoder::new(48000, channels, Application::Voip).unwrap(); + e.set_bitrate(bps); + e.look_ahead(frame) + }; write_ogg_opus( &path, &packets, - opus_head(channels, 120, None), + opus_head(channels, pre_skip as u16, None), channels, total, - 120, + pre_skip as i64, ); if Command::new("ffmpeg").arg("-version").output().is_ok() { let out = Command::new("ffmpeg")