forge
Explore
Log in

Don't you dare go Hollow

Look_ahead uses the same mono/20ms predicate dispatch does

Browse files at this commit

cbcbe53982abfbe14b3106915b9f4dfa3c3b1b33Ahmet Kaan GümüşParent: a6d0278
  • fix
    • look_ahead uses the same mono/20ms predicate dispatch does
Show full message
fix(opus-enc): look_ahead uses the same mono/20ms predicate dispatch does

look_ahead() consulted only wants_silk() (bitrate/application), not the
frame-size-and-channel check silk_choice()/hybrid_choice() apply before
encode_toc_and_payload actually picks a layer. A Voip/low-bitrate encoder
fed frame sizes other than 20 ms coded CELT but reported SILK's shorter
delay, throwing off the Ogg pre-skip by the difference. look_ahead now
takes the frame size and runs it through silk_choice, matching dispatch
exactly.

Also gives zero_stuff_mono a reusable Encoder-owned scratch buffer instead
of a Vec allocated per SILK/Hybrid frame — the zero-alloc steady-state
claim previously only held on the CELT path.
crates/ec-opus/src/encoder.rsmodified+67 -30
@@ -86,6 +86,9 @@ pub struct Encoder {
8686 silk_buf: [u8; MAX_FRAME_BYTES + 1],
8787 /// Hybrid: the last [`HYBRID_SILK_DELAY_48K`] samples of SILK-layer input.
8888 silk_delay: Vec<f32>,
89+ /// Scratch space for the zero-stuffed SILK/hybrid input, sized once so
90+ /// the steady-state loop doesn't allocate a `Vec` per frame.
91+ silk_stuff: Vec<f32>,
8992 }
9093
9194 impl Encoder {
@@ -129,6 +132,7 @@ impl Encoder {
129132 silk_wb: None,
130133 silk_buf: [0u8; MAX_FRAME_BYTES + 1],
131134 silk_delay: Vec::new(),
135+ silk_stuff: Vec::new(),
132136 })
133137 }
134138
@@ -150,24 +154,29 @@ impl Encoder {
150154 self.sample_rate
151155 }
152156
153- /// Encoder delay in *input* samples: the decoded stream lags the input by
157+ /// Encoder delay in *input* samples for a `frame_size`-sample (per
158+ /// channel, native rate) frame: the decoded stream lags the input by
154159 /// this much, and an Ogg-Opus pre-skip of `look_ahead * 48000/rate`
155160 /// cancels it exactly. CELT: one MDCT overlap, 120 samples at 48 kHz.
156- /// SILK (mono, when the application/bitrate or an explicit
157- /// [`Encoder::set_mode`] select it): [`SILK_LOOK_AHEAD_48K_NB`] or
158- /// [`SILK_LOOK_AHEAD_48K_WB`], the analysis-plus-synthesis resampler
159- /// round trip, click-measured per bandwidth. Hybrid: CELT's 120, the
160- /// SILK layer being delayed to meet it ([`HYBRID_SILK_DELAY_48K`]).
161- pub fn look_ahead(&self) -> usize {
162- if self.channels == 1 {
163- if let Some(wideband) = self.wants_silk() {
164- let delay = if wideband {
165- SILK_LOOK_AHEAD_48K_WB
166- } else {
167- SILK_LOOK_AHEAD_48K_NB
168- };
169- return delay / self.upsample;
170- }
161+ /// SILK (mono, 20 ms/960-sample-at-48k frames only, when the
162+ /// application/bitrate or an explicit [`Encoder::set_mode`] select it —
163+ /// the same [`Encoder::silk_choice`] predicate `encode_toc_and_payload`
164+ /// dispatches on, so this always matches which layer actually codes the
165+ /// frame): [`SILK_LOOK_AHEAD_48K_NB`] or [`SILK_LOOK_AHEAD_48K_WB`], the
166+ /// analysis-plus-synthesis resampler round trip, click-measured per
167+ /// bandwidth. Hybrid: CELT's 120, the SILK layer being delayed to meet
168+ /// it ([`HYBRID_SILK_DELAY_48K`]). Any other frame size (or SILK/Hybrid's
169+ /// mono, 20 ms requirement unmet) falls back to CELT here exactly as
170+ /// `encode_toc_and_payload` does.
171+ pub fn look_ahead(&self, frame_size: usize) -> usize {
172+ let frame_48k = frame_size * self.upsample;
173+ if let Some(wideband) = self.silk_choice(frame_48k) {
174+ let delay = if wideband {
175+ SILK_LOOK_AHEAD_48K_WB
176+ } else {
177+ SILK_LOOK_AHEAD_48K_NB
178+ };
179+ return delay / self.upsample;
171180 }
172181 120 / self.upsample
173182 }
@@ -290,17 +299,22 @@ impl Encoder {
290299 /// Zero-stuffs a mono, `frame_size`-sample native-rate frame up to
291300 /// `frame_size * upsample` samples at 48 kHz, the rate [`SilkEncoder`]
292301 /// takes — the same technique [`CeltEncoder::encode`] uses, scaled by
293- /// `upsample` so the passband gain survives the stuffing.
294- fn zero_stuff_mono(&self, pcm: &[f32], frame_size: usize) -> Vec<f32> {
295- let up = self.upsample;
296- if up == 1 {
297- return pcm[..frame_size].to_vec();
302+ /// `upsample` so the passband gain survives the stuffing. Writes into
303+ /// `out` (an `Encoder` scratch field, not a fresh `Vec` per call) rather
304+ /// than returning one, so the caller doesn't allocate every frame; the
305+ /// slots between the `upsample`-strided samples stay zero from one call
306+ /// to the next once `out` first grows to size, so only the strided
307+ /// samples themselves need rewriting.
308+ fn zero_stuff_mono(pcm: &[f32], frame_size: usize, upsample: usize, out: &mut Vec<f32>) {
309+ if upsample == 1 {
310+ out.clear();
311+ out.extend_from_slice(&pcm[..frame_size]);
312+ return;
298313 }
299- let mut out = vec![0f32; frame_size * up];
314+ out.resize(frame_size * upsample, 0.0);
300315 for i in 0..frame_size {
301- out[i * up] = pcm[i] * up as f32;
316+ out[i * upsample] = pcm[i] * upsample as f32;
302317 }
303- out
304318 }
305319
306320 /// Picks SILK or CELT for one frame and encodes it, returning the TOC
@@ -316,7 +330,7 @@ impl Encoder {
316330 ) -> Result<(u8, &[u8])> {
317331 let frame_48k = frame_size * self.upsample;
318332 if let Some(wideband) = self.silk_choice(frame_48k) {
319- let stuffed = self.zero_stuff_mono(pcm, frame_size);
333+ Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
320334 let enc = if wideband {
321335 self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true))
322336 } else {
@@ -326,7 +340,7 @@ impl Encoder {
326340 // Encoder's current target on every frame — cheap (an Option<u32>
327341 // store) and catches set_bitrate calls made between frames.
328342 enc.set_bitrate(self.bitrate);
329- let n = enc.encode_frame(&stuffed, &mut self.silk_buf)?;
343+ let n = enc.encode_frame(&self.silk_stuff, &mut self.silk_buf)?;
330344 self.final_range = enc.final_range();
331345 return Ok((self.silk_buf[0], &self.silk_buf[1..n]));
332346 }
@@ -492,13 +506,13 @@ impl Encoder {
492506 "opus encode: output buffer smaller than the minimum hybrid packet",
493507 ));
494508 }
495- let stuffed = self.zero_stuff_mono(pcm, frame_size);
509+ Self::zero_stuff_mono(pcm, frame_size, self.upsample, &mut self.silk_stuff);
496510 let d = HYBRID_SILK_DELAY_48K;
497511 self.silk_delay.resize(d, 0.0);
498512 let mut delayed = Vec::with_capacity(960);
499513 delayed.extend_from_slice(&self.silk_delay);
500- delayed.extend_from_slice(&stuffed[..960 - d]);
501- self.silk_delay.copy_from_slice(&stuffed[960 - d..]);
514+ delayed.extend_from_slice(&self.silk_stuff[..960 - d]);
515+ self.silk_delay.copy_from_slice(&self.silk_stuff[960 - d..]);
502516
503517 self.range.reset(cap);
504518 let silk = self.silk_wb.get_or_insert_with(|| SilkEncoder::new(true));
@@ -586,6 +600,29 @@ mod tests {
586600 let mut e = Encoder::new(24000, 2, Application::Audio).unwrap();
587601 e.set_bitrate(256_000);
588602 assert_eq!(e.auto_bandwidth(), Bandwidth::SuperWide);
589- assert_eq!(e.look_ahead(), 60);
603+ assert_eq!(e.look_ahead(960), 60);
604+ }
605+
606+ /// `look_ahead` must use the same mono/20 ms-frame predicate dispatch
607+ /// does (`silk_choice`/`hybrid_choice`), not just `wants_silk` — a
608+ /// non-20 ms frame (or stereo) codes as CELT regardless of the
609+ /// bitrate/application, so its look-ahead is CELT's 120, not SILK's.
610+ #[test]
611+ fn look_ahead_matches_the_frame_size_dispatch_actually_uses() {
612+ let mut e = Encoder::new(48000, 1, Application::Voip).unwrap();
613+ e.set_bitrate(8000);
614+ assert_eq!(e.look_ahead(480), 120, "sub-20ms frame falls back to CELT");
615+ assert_eq!(e.look_ahead(240), 120, "sub-20ms frame falls back to CELT");
616+ assert_eq!(e.look_ahead(960), 58, "20ms NB SILK");
617+
618+ e.set_bitrate(16000);
619+ assert_eq!(e.look_ahead(960), 50, "20ms WB SILK");
620+
621+ e.set_bitrate(32000);
622+ assert_eq!(e.look_ahead(960), 120, "20ms hybrid, CELT's overlap");
623+
624+ let mut e = Encoder::new(48000, 2, Application::Voip).unwrap();
625+ e.set_bitrate(8000);
626+ assert_eq!(e.look_ahead(960), 120, "stereo never codes as SILK/Hybrid");
590627 }
591628 }
crates/ec-opus/tests/conformance.rsmodified+8 -2
@@ -1110,7 +1110,7 @@ fn oracle_decodes_our_packets_across_the_rate_table() {
11101110 for kbps in [8u32, 12, 16] {
11111111 let mut enc = Encoder::new(48000, 1, Application::Voip).unwrap();
11121112 enc.set_bitrate(kbps * 1000);
1113- let pre_skip = enc.look_ahead() as u16;
1113+ let pre_skip = enc.look_ahead(960) as u16;
11141114 let packets = encode_packets(&mut enc, &pcm, 1);
11151115 let path = temp_path(&format!("silk-1ch-{kbps}k.opus"));
11161116 write_ogg_opus(
@@ -1346,6 +1346,12 @@ fn steady_state_encode_loop_zero_alloc() {
13461346 COUNTING_HERE.with(|c| c.set(false));
13471347 let n = ALLOCS.load(Ordering::SeqCst);
13481348 assert_eq!(n, 0, "5.1 encode allocated {n} times in steady state");
1349+
1350+ // Mono SILK (Voip, 12 kbps) is NOT asserted zero-alloc here: fixing
1351+ // `Encoder::zero_stuff_mono` to reuse a scratch buffer removed its
1352+ // per-frame Vec, but `SilkEncoder::encode_frame` itself (NLSF/LPC
1353+ // analysis, pitch search) allocates well beyond that one site — sweeping
1354+ // those is a separate, much larger effort than this defect's scope.
13491355 }
13501356
13511357 /// The throughput headline: encode speed in multiples of realtime, per
@@ -1770,7 +1776,7 @@ fn hybrid_layers_align() {
17701776 eprintln!("hybrid click: LB peak +{plb}, HB peak +{phb}, look_ahead {}", {
17711777 let mut e = enc.clone();
17721778 e.set_bitrate(32_000);
1773- e.look_ahead()
1779+ e.look_ahead(960)
17741780 });
17751781 assert!((plb - phb).abs() <= 2, "layers misaligned: LB +{plb} vs HB +{phb}");
17761782 assert!((phb - 120).abs() <= 2, "HB peak +{phb}, look_ahead 120");
shims/opus-rs/src/lib.rsmodified+5 -2
@@ -124,9 +124,12 @@ impl OpusEncoder {
124124
125125 /// Samples of encoder delay, at the input rate: the decoded stream lags
126126 /// the input by this much, and an Ogg-Opus pre-skip of it (scaled to
127- /// 48 kHz) cancels the lag exactly.
127+ /// 48 kHz) cancels the lag exactly. Reported for the canonical 20 ms
128+ /// frame (SILK and Hybrid, which shift the delay, only run at 20 ms
129+ /// anyway) — like the incumbent's `OPUS_GET_LOOKAHEAD`, which doesn't
130+ /// take a frame size either.
128131 pub fn look_ahead(&self) -> usize {
129- self.inner.look_ahead()
132+ self.inner.look_ahead(self.inner.sample_rate() as usize / 50)
130133 }
131134
132135 /// The range coder state after the last packet — the RFC 6716 Section 6