forge
Explore
Log in

Don't you dare go Hollow

Libopus dc_reject on the API input, and lag-dependent tests read look_ahead

Browse files at this commit

0151578356e0061225a91c7df907b4e6754318e4Ahmet Kaan GümüşParent: b1e155b
  • feat
    • libopus dc_reject on the API input, and lag-dependent tests read look_ahead
Show full message
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.rsmodified+30 -3
@@ -794,8 +794,10 @@ impl CeltEncoder {
794794 // .708->.703, reelo@96 .940->.872, dl8a .551/.374->.503/.346, hein
795795 // .855/.528->.771/.419), corr within +.0001 everywhere. The KEEP rule
796796 // is "err_ratio not worse on every row", so the search ships off.
797+ // `EC_OPUS_TWO_PASS=1` re-arms it for a sweep (lane opusx2 r2).
797798 const TWO_PASS_COARSE_ENERGY: bool = false;
798- let mut two_pass = TWO_PASS_COARSE_ENERGY;
799+ let mut two_pass =
800+ TWO_PASS_COARSE_ENERGY || std::env::var_os("EC_OPUS_TWO_PASS").is_some();
799801 let mut intra = self.force_intra
800802 || (!two_pass
801803 && self.delayed_intra > (2 * c * (end - start)) as f32
@@ -896,7 +898,7 @@ impl CeltEncoder {
896898 // --- Allocation trim ------------------------------------------------
897899 let mut alloc_trim = 5i32;
898900 if tell_frac + (6 << BITRES) <= total_bits_frac - total_boost {
899- alloc_trim = self.alloc_trim_analysis(end, lm, c, n);
901+ alloc_trim = self.alloc_trim_analysis(end, lm, c, n, tf_estimate);
900902 enc.enc_icdf(alloc_trim as usize, &TRIM_ICDF, 7);
901903 tell_frac = enc.tell_frac() as i32;
902904 }
@@ -1574,7 +1576,20 @@ impl CeltEncoder {
15741576 /// dl8a@64 .9889->.9879). The KEEP rule rejects it; this is the third
15751577 /// rejection of the same port (see `lanes/opus-trim-r2.{A,B}.sweep.txt`).
15761578 /// Do not re-port it without a fix for the transient rows first.
1577- fn alloc_trim_analysis(&mut self, end: usize, lm: usize, c: usize, n0: usize) -> i32 {
1579+ ///
1580+ /// `EC_OPUS_TRIM13=1` selects the continuous 1.3 form instead, for the
1581+ /// re-sweep on the aligned (delayed) spectrum the discrete ladder was
1582+ /// never measured against.
1583+ fn alloc_trim_analysis(
1584+ &mut self,
1585+ end: usize,
1586+ lm: usize,
1587+ c: usize,
1588+ n0: usize,
1589+ tf_estimate: f32,
1590+ ) -> i32 {
1591+ let cont = std::env::var_os("EC_OPUS_TRIM13").is_some();
1592+ let mut trim_f = 5.0f32;
15781593 let mut trim = 5i32;
15791594 if c == 2 {
15801595 let mut sum = 0.0f32;
@@ -1586,6 +1601,10 @@ impl CeltEncoder {
15861601 sum += partial;
15871602 }
15881603 sum *= 1.0 / 8.0;
1604+ if cont {
1605+ let sum_c = sum.abs().min(1.0);
1606+ trim_f += (0.75 * (1.001 - sum_c * sum_c).log2()).max(-4.0);
1607+ }
15891608 if sum > 0.995 {
15901609 trim -= 4;
15911610 } else if sum > 0.92 {
@@ -1619,6 +1638,14 @@ impl CeltEncoder {
16191638 * (2 + 2 * i as i32 - NB_BANDS as i32) as f32;
16201639 }
16211640 }
1641+ if cont {
1642+ // libopus divides the same sum by `C*(end-1)`; the ladder above
1643+ // carries an extra factor of two in its thresholds.
1644+ let diff = diff / (c * (end - 1)) as f32;
1645+ trim_f -= ((diff + 1.0) / 6.0).clamp(-2.0, 2.0);
1646+ trim_f -= 2.0 * tf_estimate;
1647+ return (trim_f + 0.5).floor().clamp(0.0, 10.0) as i32;
1648+ }
16221649 diff /= (2 * c * (end - 1)) as f32;
16231650 if diff > 2.0 {
16241651 trim -= 1;
crates/ec-opus/src/encoder.rsmodified+85 -34
@@ -116,6 +116,12 @@ pub struct Encoder {
116116 /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so
117117 /// the steady-state loop doesn't allocate a `Vec` per frame.
118118 silk_stuff: Vec<f32>,
119+ /// libopus `opus_encoder.c`'s `hp_mem`: the one-pole state of the
120+ /// [`Encoder::dc_reject`] filter every frame of API input goes through,
121+ /// one per channel.
122+ hp_mem: [f32; 2],
123+ /// Scratch space for that filter's output, sized once.
124+ hp_buf: Vec<f32>,
119125 }
120126
121127 /// SILK's internal sample rate (kHz) for a target bandwidth: Narrow → 8,
@@ -175,6 +181,8 @@ impl Encoder {
175181 silk_buf: [0u8; MAX_SILK_PACKET_BYTES],
176182 silk_delay: Vec::new(),
177183 silk_stuff: Vec::new(),
184+ hp_mem: [0.0; 2],
185+ hp_buf: Vec::new(),
178186 })
179187 }
180188
@@ -283,6 +291,7 @@ impl Encoder {
283291 self.silk_stereo_mb = None;
284292 self.silk_stereo_wb = None;
285293 self.silk_delay.clear();
294+ self.hp_mem = [0.0; 2];
286295 self.final_range = 0;
287296 }
288297
@@ -692,6 +701,32 @@ impl Encoder {
692701 BWS[idx].min(ceiling)
693702 }
694703
704+ /// libopus `opus_encoder.c`'s `dc_reject(pcm, 3, ...)`: a 3 Hz one-pole
705+ /// high-pass on the API input, applied once before *both* layers (libopus
706+ /// filters into `pcm_buf`, which is what `silk_Encode` and
707+ /// `celt_encode_with_ec` both read). `coef = 6.3 * cutoff / Fs` at the
708+ /// API rate; the output is the input minus a leaky integrator of it, and
709+ /// the integrator state carries across frames.
710+ ///
711+ /// libopus takes the `hp_cutoff` branch instead for
712+ /// `OPUS_APPLICATION_VOIP` (a bandwidth-dependent second-order section);
713+ /// not ported — every VoIP frame still gets this DC reject.
714+ fn dc_reject(&mut self, pcm: &[f32], frame_size: usize, out: &mut Vec<f32>) {
715+ let c = self.channels;
716+ let coef = 6.3 * 3.0 / self.sample_rate as f32;
717+ out.clear();
718+ out.resize(frame_size * c, 0.0);
719+ for ch in 0..c {
720+ let mut m = self.hp_mem[ch];
721+ for i in 0..frame_size {
722+ let x = pcm[i * c + ch];
723+ out[i * c + ch] = x - m;
724+ m += coef * (x - m);
725+ }
726+ self.hp_mem[ch] = m;
727+ }
728+ }
729+
695730 /// Encodes one frame — `frame_size` samples per channel of interleaved
696731 /// `f32` at the input rate, 2.5, 5, 10 or 20 ms of it — as a code-0 Opus
697732 /// packet in `out`, returning the packet length.
@@ -701,19 +736,27 @@ impl Encoder {
701736 frame_size: usize,
702737 out: &mut [u8],
703738 ) -> Result<usize> {
704- let (toc, payload) =
705- self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(1))?;
706- let n = payload.len();
707- if out.len() < 1 + n {
708- return Err(Error::corrupt(format!(
709- "opus encode: packet needs {} bytes, buffer holds {}",
710- 1 + n,
711- out.len()
712- )));
713- }
714- out[0] = toc;
715- out[1..1 + n].copy_from_slice(payload);
716- Ok(1 + n)
739+ let mut hp = std::mem::take(&mut self.hp_buf);
740+ self.dc_reject(pcm, frame_size, &mut hp);
741+ let r = match self.encode_toc_and_payload(&hp, frame_size, out.len().saturating_sub(1)) {
742+ Err(e) => Err(e),
743+ Ok((toc, payload)) => {
744+ let n = payload.len();
745+ if out.len() < 1 + n {
746+ Err(Error::corrupt(format!(
747+ "opus encode: packet needs {} bytes, buffer holds {}",
748+ 1 + n,
749+ out.len()
750+ )))
751+ } else {
752+ out[0] = toc;
753+ out[1..1 + n].copy_from_slice(payload);
754+ Ok(1 + n)
755+ }
756+ }
757+ };
758+ self.hp_buf = hp;
759+ r
717760 }
718761
719762 /// [`Encoder::encode_float`] from 16-bit samples.
@@ -731,27 +774,35 @@ impl Encoder {
731774 frame_size: usize,
732775 out: &mut [u8],
733776 ) -> Result<usize> {
734- let (toc, payload) =
735- self.encode_toc_and_payload(pcm, frame_size, out.len().saturating_sub(3))?;
736- let n = payload.len();
737- let len_bytes = if n < 252 { 1 } else { 2 };
738- if out.len() < 1 + len_bytes + n {
739- return Err(Error::corrupt(format!(
740- "opus encode: self-delimited packet needs {} bytes, buffer holds {}",
741- 1 + len_bytes + n,
742- out.len()
743- )));
744- }
745- out[0] = toc;
746- if n < 252 {
747- out[1] = n as u8;
748- } else {
749- let b0 = 252 + ((n - 252) & 3);
750- out[1] = b0 as u8;
751- out[2] = ((n - b0) / 4) as u8;
752- }
753- out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload);
754- Ok(1 + len_bytes + n)
777+ let mut hp = std::mem::take(&mut self.hp_buf);
778+ self.dc_reject(pcm, frame_size, &mut hp);
779+ let r = match self.encode_toc_and_payload(&hp, frame_size, out.len().saturating_sub(3)) {
780+ Err(e) => Err(e),
781+ Ok((toc, payload)) => {
782+ let n = payload.len();
783+ let len_bytes = if n < 252 { 1 } else { 2 };
784+ if out.len() < 1 + len_bytes + n {
785+ Err(Error::corrupt(format!(
786+ "opus encode: self-delimited packet needs {} bytes, buffer holds {}",
787+ 1 + len_bytes + n,
788+ out.len()
789+ )))
790+ } else {
791+ out[0] = toc;
792+ if n < 252 {
793+ out[1] = n as u8;
794+ } else {
795+ let b0 = 252 + ((n - 252) & 3);
796+ out[1] = b0 as u8;
797+ out[2] = ((n - b0) / 4) as u8;
798+ }
799+ out[1 + len_bytes..1 + len_bytes + n].copy_from_slice(payload);
800+ Ok(1 + len_bytes + n)
801+ }
802+ }
803+ };
804+ self.hp_buf = hp;
805+ r
755806 }
756807
757808 /// One hybrid frame (10 or 20 ms, mono or stereo, `bandwidth` SWB or FB)
crates/ec-opus/src/multistream_enc.rsmodified+7 -0
@@ -27,6 +27,13 @@ pub struct MultistreamEncoder {
2727 }
2828
2929 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+
3037 /// An encoder for `streams` elementary streams of which the first
3138 /// `coupled` are stereo, with `mapping` naming the coded channel each
3239 /// input channel feeds. Layout rules are the decoder's, checked the same
crates/ec-opus/tests/conformance.rsmodified+41 -23
@@ -864,17 +864,18 @@ fn roundtrip_own(
864864 (decoded, bytes)
865865 }
866866
867-/// Worst-channel correlation against the source with the encoder's
868-/// 120-sample delay removed.
869-fn delayed_corr(source: &[f32], decoded: &[f32], channels: usize) -> f64 {
870- const DELAY: usize = 120;
871- let n = (decoded.len() / channels).saturating_sub(DELAY);
867+/// Worst-channel correlation against the source with the encoder's own
868+/// delay removed — `delay` is [`Encoder::look_ahead`] for the frame size the
869+/// round trip used, never a constant (it moved 120 -> 312 when the CELT layer
870+/// took libopus's Fs/250 input delay).
871+fn delayed_corr(source: &[f32], decoded: &[f32], channels: usize, delay: usize) -> f64 {
872+ let n = (decoded.len() / channels).saturating_sub(delay);
872873 let n = n.min(source.len() / channels);
873874 let mut worst = 1.0f64;
874875 for c in 0..channels {
875876 let a: Vec<f32> = (0..n).map(|i| source[i * channels + c]).collect();
876877 let b: Vec<f32> = (0..n)
877- .map(|i| decoded[(i + DELAY) * channels + c])
878+ .map(|i| decoded[(i + delay) * channels + c])
878879 .collect();
879880 worst = worst.min(correlation(&a, &b));
880881 }
@@ -894,7 +895,7 @@ fn encoder_roundtrips_at_every_rate() {
894895 let mut enc = Encoder::new(48000, channels, Application::Audio).unwrap();
895896 enc.set_bitrate(kbps * 1000);
896897 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));
898899 let rate = bytes as f64 * 8.0 / 2.0 / 1000.0;
899900 println!("{channels} ch {kbps:>3} kbps: corr {corr:.4}, actual {rate:.1} kbps");
900901 let floor = if kbps < 64 { 0.8 } else { 0.9 };
@@ -1271,7 +1272,7 @@ fn encoder_frame_sizes_and_vbr() {
12711272 let mut enc = Encoder::new(48000, 2, Application::Audio).unwrap();
12721273 enc.set_bitrate(128_000);
12731274 let (decoded, _) = roundtrip_own(&mut enc, &pcm, 2, frame);
1274- let corr = delayed_corr(&pcm, &decoded, 2);
1275+ let corr = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(frame));
12751276 println!("frame {frame}: corr {corr:.4}");
12761277 assert!(corr >= 0.85, "frame {frame}: correlation {corr:.4}");
12771278 }
@@ -1279,7 +1280,7 @@ fn encoder_frame_sizes_and_vbr() {
12791280 enc.set_bitrate(128_000);
12801281 enc.set_vbr_constrained(true);
12811282 let (decoded, bytes) = roundtrip_own(&mut enc, &pcm, 2, 960);
1282- let corr = delayed_corr(&pcm, &decoded, 2);
1283+ let corr = delayed_corr(&pcm, &decoded, 2, enc.look_ahead(960));
12831284 let rate = bytes as f64 * 8.0 / 1.0 / 1000.0;
12841285 println!("cvbr 128k: corr {corr:.4}, actual {rate:.1} kbps");
12851286 assert!(corr >= 0.9, "cvbr: correlation {corr:.4}");
@@ -1405,10 +1406,10 @@ fn oracle_decodes_our_packets_across_the_rate_table() {
14051406 write_ogg_opus(
14061407 &path,
14071408 &packets,
1408- opus_head(channels, 120, None),
1409+ opus_head(channels, enc.look_ahead(960) as u16, None),
14091410 channels,
14101411 total,
1411- 120,
1412+ enc.look_ahead(960) as i64,
14121413 );
14131414 let Some(reference) = ffmpeg_decode(&path, channels) else {
14141415 eprintln!("ffmpeg unavailable, skipped");
@@ -1534,9 +1535,10 @@ fn five_one_encode_end_to_end() {
15341535 let len = enc.encode_float(&silence, 960, &mut out).expect("encode");
15351536 packets.push(out[..len].to_vec());
15361537 let (streams, coupled, mapping) = enc.layout();
1537- let head = opus_head(6, 120, Some((streams, coupled, mapping)));
1538+ let pre_skip = enc.look_ahead(960);
1539+ let head = opus_head(6, pre_skip as u16, Some((streams, coupled, mapping)));
15381540 let path = temp_path("5.1.opus");
1539- write_ogg_opus(&path, &packets, head, 6, total, 120);
1541+ write_ogg_opus(&path, &packets, head, 6, total, pre_skip as i64);
15401542 let Some(reference) = ffmpeg_decode(&path, 6) else {
15411543 eprintln!("ffmpeg unavailable, skipped");
15421544 let _ = fs::remove_file(&path);
@@ -1568,7 +1570,8 @@ fn ogg_opus_round_trip_duration_is_exact() {
15681570 enc.set_bitrate(128_000);
15691571 let packets = encode_packets(&mut enc, &pcm, 2);
15701572 let path = temp_path("duration.opus");
1571- write_ogg_opus(&path, &packets, opus_head(2, 120, None), 2, total, 120);
1573+ let pre_skip = enc.look_ahead(960);
1574+ write_ogg_opus(&path, &packets, opus_head(2, pre_skip as u16, None), 2, total, pre_skip as i64);
15721575 let probe = Command::new("ffprobe")
15731576 .args([
15741577 "-v",
@@ -1592,9 +1595,9 @@ fn ogg_opus_round_trip_duration_is_exact() {
15921595 .unwrap_or(0.0);
15931596 // ffprobe reports Ogg-Opus durations *including* the pre-skip — its
15941597 // own 3.000 s encode probes as 3.0065 (312/48000 more). Ours carries
1595- // a 120-sample pre-skip, so exact is 2.0025; the decoded sample
1596- // count below is the pre-skip-free half of the claim.
1597- let expected = (total as f64 + 120.0) / 48000.0;
1598+ // the same pre-skip our encoder advertises, so exact is 2.000 s plus
1599+ // it; the decoded sample count below is the pre-skip-free half.
1600+ let expected = (total as f64 + pre_skip as f64) / 48000.0;
15981601 assert!(
15991602 (dur - expected).abs() < 1e-6,
16001603 "ffprobe reports {dur} s, expected {expected} s (2.000 s + pre-skip)"
@@ -2525,6 +2528,9 @@ fn hybrid_layers_align() {
25252528 /// 20 ms FB hybrid at 32 kbps: decodes in our decoder range-exactly, tracks
25262529 /// the input full-band and in the SILK layer's band alone, and the reference
25272530 /// oracle decodes the packets to the same signal.
2531+///
2532+/// The delay [`hybrid_roundtrip`]'s encoder advertises for a 20 ms frame is
2533+/// [`Encoder::look_ahead`] of that same configuration, never a constant.
25282534 #[test]
25292535 fn hybrid_fb_roundtrip() {
25302536 for (name, pcm) in silk_sources() {
@@ -2542,9 +2548,14 @@ fn hybrid_fb_roundtrip() {
25422548 );
25432549 assert!(corr >= 0.95, "{name}: full-band corr {corr:.4}");
25442550 // +-3: the wav16 fixture is a pure tone, whose phase moves the peak.
2551+ let delay = {
2552+ let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();
2553+ e.set_bitrate(32_000);
2554+ e.look_ahead(960)
2555+ };
25452556 assert!(
2546- (117..=123).contains(&lag),
2547- "{name}: aligned at lag {lag}, not the documented 120"
2557+ (delay - 3..=delay + 3).contains(&lag),
2558+ "{name}: aligned at lag {lag}, not the advertised {delay}"
25482559 );
25492560 assert!(lb_corr >= 0.9, "{name}: low-band corr {lb_corr:.4}");
25502561 assert!(
@@ -2552,8 +2563,8 @@ fn hybrid_fb_roundtrip() {
25522563 "{name}: {kbps:.1} kbps for a 32 kbps CBR target"
25532564 );
25542565 if let Some(oracle) = oracle_decode(&format!("hybrid-{name}"), &packets, pcm.len()) {
2555- let n = oracle.len().min(decoded.len() - 120);
2556- let c = correlation(&oracle[..n], &decoded[120..120 + n]);
2566+ let n = oracle.len().min(decoded.len() - delay);
2567+ let c = correlation(&oracle[..n], &decoded[delay..delay + n]);
25572568 eprintln!("hybrid FB {name}: oracle vs ours corr {c:.4}");
25582569 assert!(c >= 0.95, "{name}: oracle corr {c:.4}");
25592570 }
@@ -2661,13 +2672,20 @@ fn hybrid_shapes_roundtrip() {
26612672 assert!(worst >= floor, "{tag}: worst corr {worst:.4}");
26622673 let total = pcm.len() / channels;
26632674 let path = temp_path(&format!("hybrid-{tag}.opus"));
2675+ // The pre-skip is what `hybrid_roundtrip_shape`'s own encoder
2676+ // advertises for this frame size, not a constant.
2677+ let pre_skip = {
2678+ let mut e = Encoder::new(48000, channels, Application::Voip).unwrap();
2679+ e.set_bitrate(bps);
2680+ e.look_ahead(frame)
2681+ };
26642682 write_ogg_opus(
26652683 &path,
26662684 &packets,
2667- opus_head(channels, 120, None),
2685+ opus_head(channels, pre_skip as u16, None),
26682686 channels,
26692687 total,
2670- 120,
2688+ pre_skip as i64,
26712689 );
26722690 if Command::new("ffmpeg").arg("-version").output().is_ok() {
26732691 let out = Command::new("ffmpeg")