forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB3d2e08fTahinli7 days ago3929 commits

lib.rs633 lines, 24.4 KiBHistoryRawDownload
1//! Opus decoding (RFC 6716, with the RFC 8251 corrections).
2//!
3//! Opus is two codecs behind one entropy coder: a linear-prediction layer
4//! (SILK) for speech up to 8 kHz of bandwidth, and an MDCT layer (CELT) for
5//! everything above that and for music. A packet's table-of-contents byte picks
6//! one of them or both, and this crate decodes all three cases plus the
7//! multistream framing that carries 5.1 and 7.1.
8//!
9//! Contracts worth knowing before implementing against this crate:
10//!
11//! - **The FFT is never optional.** CELT synthesis runs an `N/4`-point FFT
12//! through [`ec_dsp`], never a direct-form DFT. An incumbent Opus decoder in
13//! this product shipped its FFT behind a default-off feature and ran at 0.95x
14//! realtime on 5.1; there is no such switch here, and no code path that could
15//! answer to one. (CELT's transform sizes are `15*2^k`, so [`ec_dsp::Mdct`]
16//! itself — power-of-two only — cannot serve them; [`celt`] wraps
17//! [`ec_dsp::Fft`] with one radix-3/radix-5 stage instead.)
18//! - **Malformed input is an error, never a panic.** Framing rules `[R1]`..`[R7]`
19//! are checked in [`packet`], and the range decoder feeds zeros past the end
20//! of a truncated frame exactly as Section 4.1.2.1 requires.
21//! - **Output is `f32`, interleaved, at the rate you asked for.** 48, 24, 16,
22//! 12 and 8 kHz are supported; SILK's internal rate is resampled up (by the
23//! normative resampler in [`silk`]) and CELT decimates on the way out.
24//! - **Packet loss concealment.** [`Decoder::conceal`] (or an empty packet to
25//! [`Decoder::decode_float`]) extends the last frame: a CELT frame gets
26//! pitch-periodic LPC extension for the first losses, then decaying
27//! band-shaped noise; a SILK or hybrid frame is concealed by the SILK PLC (a
28//! port of libopus `silk/PLC.c`, without comfort noise). A one-byte (DTX)
29//! frame inside a packet is concealed the same way. [`Decoder::decode_fec`]
30//! recovers a lost SILK or hybrid frame from the in-band FEC of the next
31//! packet.
32//!
33//! The crate also carries the family's Opus *encoder* — [`Encoder`] for one
34//! stream, [`MultistreamEncoder`] for surround — CELT-only, fullband, mono
35//! and stereo, every rate from 16 to 510 kbps, CBR and constrained VBR.
36//!
37//! **Why the incumbent encoder collapsed above ~128-165 kbps** (the measured
38//! record this crate replaces; edith `engine/Cargo.toml:124-140` and
39//! `export.rs:1834`): its packets above that rate were decodable only by its
40//! *own* decoder — correlation 0.06 against the reference decoder at 256 kbps while its
41//! internal round trip read 0.999 — and the rate the cliff sat at moved with
42//! the content. That signature — self-consistent, world-divergent, at a
43//! *bits-per-band* threshold — is a shared encode/decode convention error in
44//! exactly the code CELT only exercises when a band's budget is large: the
45//! over-32-bit-codeword band split (RFC 6716 Section 4.3.4.1: a band whose bit
46//! demand exceeds its cache row is halved recursively, with an entropy-coded
47//! angle and a rebalance of the leftover bits). An encoder whose split
48//! bookkeeping (`tell`-derived budgets, rebalance, theta pdf selection)
49//! drifts one bit from the normative derivation still decodes its own output
50//! — both halves share the drift — but a conformant decoder desynchronises,
51//! and the threshold moves with content because the split only triggers on
52//! loud, flat bands. Content-dependence is also why mono broke at *every*
53//! rate: half the coefficients means every band hits the split threshold at
54//! half the bitrate. This encoder mirrors the reference's allocation
55//! arithmetic symbol for symbol, and the tests hold the closed loop to it:
56//! every packet is range-state-exact against this crate's own
57//! RFC-vector-verified decoder, and the reference decoder (via the oracle) plus the reference
58//! `opus_demo` decoder read the same packets at correlation >= 0.99 across
59//! the whole rate table, mono, stereo and 5.1 alike.
60//!
61//! No unsafe, no allocation on the per-frame path beyond the codecs' own
62//! buffers, no dependencies outside the family.
63
64#![forbid(unsafe_code)]
65#![warn(missing_docs)]
66
67pub(crate) mod analysis;
68pub mod celt;
69pub mod celt_enc;
70pub mod encoder;
71pub mod multistream;
72pub mod multistream_enc;
73pub mod ogg;
74pub mod packet;
75pub mod range;
76pub mod silk;
77pub(crate) mod silk_fix;
78pub(crate) mod silk_flp;
79mod stack_budget;
80
81pub use celt::CeltDecoder;
82pub use celt_enc::CeltFrameDiag;
83pub use encoder::{Application, Encoder};
84pub use multistream::MultistreamDecoder;
85pub use multistream_enc::MultistreamEncoder;
86pub use packet::{Bandwidth, Mode, Packet, Toc};
87pub use range::{RangeDecoder, RangeEncoder};
88pub use silk::{SilkDecIndices, SilkDecoder, SilkFrameMode};
89
90use ec_core::{Error, Result};
91
92/// One Opus stream: mono or stereo, any mode, any frame size.
93///
94/// Feed whole Opus packets to [`Decoder::decode_float`]; the decoder tracks the
95/// inter-frame state (energy history, MDCT overlap, LPC memory) that Opus needs
96/// across packets, so packets must be delivered in order.
97#[derive(Clone, Debug)]
98pub struct Decoder {
99 sample_rate: u32,
100 /// Output channels, which may exceed what a given packet codes.
101 channels: usize,
102 downsample: usize,
103 celt: CeltDecoder,
104 /// Boxed because a `SilkDecoder` is 6512 bytes, 83% of what a `Decoder`
105 /// costs a caller taking one BY VALUE from `Decoder::new`. It is the
106 /// decoder's largest field and its only large one; `celt` is 1448.
107 /// `Stack`: crate::stack_budget.
108 silk: Box<SilkDecoder>,
109 /// The CELT overlap window, reused for redundancy cross-fades.
110 celt_window: Vec<f32>,
111 /// Per-frame scratch, allocated once: the SILK layer's output and the
112 /// redundancy frame.
113 silk_pcm: Vec<i16>,
114 /// The internal SILK rate and channel count of the last SILK frame, which
115 /// the SILK concealment reuses.
116 silk_rate: u32,
117 silk_channels: usize,
118 redundant: Vec<f32>,
119 prev_mode: Option<Mode>,
120 prev_redundancy: bool,
121 range_final: u32,
122 /// Samples per channel of the last packet, the default concealment length.
123 last_packet_size: usize,
124 /// Test hook: drop the (CELT, SILK) layer's output before the sum.
125 debug_mute: (bool, bool),
126}
127
128impl Decoder {
129 /// Test hook, not for production use: silences the CELT and/or SILK
130 /// layer's contribution to the output (the decoder state still advances)
131 /// so a hybrid packet's two layers can be measured one at a time.
132 #[doc(hidden)]
133 pub fn debug_mute_layers(&mut self, celt: bool, silk: bool) {
134 self.debug_mute = (celt, silk);
135 }
136
137 /// Decodes with the RFC 6716 reconstruction instead of the RFC 8251 one
138 /// (the default). Needed only to reproduce the RFC 6716 reference vectors.
139 pub fn set_legacy_rfc6716(&mut self, on: bool) {
140 self.celt.set_legacy_rfc6716(on);
141 }
142
143 /// Facts from the last decoded frame's CELT layer (diagnostic).
144 pub fn last_celt_diag(&self) -> &crate::celt::CeltDecDiag {
145 self.celt.last_diag()
146 }
147
148 /// A decoder for `channels` channels at `sample_rate`, which must be one of
149 /// 8000, 12000, 16000, 24000 or 48000 Hz.
150 pub fn new(sample_rate: u32, channels: usize) -> Result<Decoder> {
151 let downsample = match sample_rate {
152 48000 => 1,
153 24000 => 2,
154 16000 => 3,
155 12000 => 4,
156 8000 => 6,
157 _ => {
158 return Err(Error::unsupported(
159 format!("opus output rate {sample_rate}"),
160 "Opus decodes to 8, 12, 16, 24 or 48 kHz only",
161 ));
162 }
163 };
164 if !(1..=2).contains(&channels) {
165 return Err(Error::unsupported(
166 format!("{channels}-channel Opus stream"),
167 "one stream carries at most two channels; use MultistreamDecoder",
168 ));
169 }
170 Ok(Decoder {
171 sample_rate,
172 channels,
173 downsample,
174 celt: CeltDecoder::new(channels, downsample),
175 silk: Box::new(SilkDecoder::new(sample_rate, channels)),
176 celt_window: celt::overlap_window(),
177 silk_pcm: vec![0; 5760 * channels],
178 silk_rate: 16000,
179 silk_channels: 1,
180 redundant: vec![0.0; 240 * channels],
181 prev_mode: None,
182 prev_redundancy: false,
183 range_final: 0,
184 last_packet_size: 960 / downsample,
185 debug_mute: (false, false),
186 })
187 }
188
189 /// Output sample rate.
190 pub fn sample_rate(&self) -> u32 {
191 self.sample_rate
192 }
193
194 /// Output channels.
195 pub fn channels(&self) -> usize {
196 self.channels
197 }
198
199 /// The range coder state after the last packet. The RFC 6716 test vectors
200 /// carry this value per packet, which makes it a bit-exact conformance
201 /// check on everything the decoder read.
202 pub fn final_range(&self) -> u32 {
203 self.range_final
204 }
205
206 /// Drops all inter-packet state; call after a seek.
207 pub fn reset(&mut self) {
208 self.celt.reset();
209 self.silk.reset();
210 self.prev_mode = None;
211 self.prev_redundancy = false;
212 self.range_final = 0;
213 }
214
215 /// Decodes one packet into interleaved `f32`, returning samples per channel.
216 /// An empty `packet` is a lost one: it is concealed for the last packet's
217 /// duration (see [`Decoder::conceal`]).
218 ///
219 /// `out` must hold `channels * 120 ms` worth of samples for the general
220 /// case (5760 per channel at 48 kHz).
221 pub fn decode_float(&mut self, packet: &[u8], out: &mut [f32]) -> Result<usize> {
222 if packet.is_empty() {
223 return self.conceal(self.last_packet_size, out);
224 }
225 let (samples, _) = self.decode_impl(packet, out, false)?;
226 Ok(samples)
227 }
228
229 /// Decodes one self-delimited packet (RFC 6716, Appendix B), returning the
230 /// samples per channel and the bytes the packet occupied. This is what the
231 /// multistream framing needs for every stream but the last.
232 pub fn decode_self_delimited(
233 &mut self,
234 data: &[u8],
235 out: &mut [f32],
236 ) -> Result<(usize, usize)> {
237 self.decode_impl(data, out, true)
238 }
239
240 /// Conceals `frame_size` lost samples per channel (a multiple of 2.5 ms,
241 /// at most 120 ms), the equivalent of the reference's `decode(NULL)`.
242 /// CELT output decays towards background noise and SILK output is
243 /// extrapolated by the SILK PLC; the next real packet cross-fades in
244 /// through the MDCT overlap.
245 pub fn conceal(&mut self, frame_size: usize, out: &mut [f32]) -> Result<usize> {
246 let total_48k = frame_size * self.downsample;
247 if total_48k == 0 || !total_48k.is_multiple_of(120) || total_48k > 5760 {
248 return Err(Error::corrupt(format!(
249 "opus: conceal size {frame_size} is not a multiple of 2.5 ms up to 120 ms"
250 )));
251 }
252 let needed = frame_size * self.channels;
253 if out.len() < needed {
254 return Err(Error::corrupt(format!(
255 "opus: output buffer holds {} samples, concealment needs {needed}",
256 out.len()
257 )));
258 }
259 let mut done_48k = 0usize;
260 while done_48k < total_48k {
261 let left = total_48k - done_48k;
262 let sizes: &[usize] = match self.prev_mode {
263 Some(Mode::Silk | Mode::Hybrid) => &[960, 480],
264 _ => &[960, 480, 240, 120],
265 };
266 let chunk = sizes.iter().copied().find(|&c| c <= left).unwrap_or(120);
267 let a = done_48k / self.downsample * self.channels;
268 let b = (done_48k + chunk) / self.downsample * self.channels;
269 let dst = &mut out[a..b];
270 match self.prev_mode {
271 Some(Mode::Celt) => {
272 self.celt.conceal(dst, chunk)?;
273 }
274 Some(Mode::Silk | Mode::Hybrid) if chunk >= 480 => {
275 self.conceal_silk(dst, chunk)?;
276 }
277 _ => dst.fill(0.0),
278 }
279 done_48k += chunk;
280 }
281 Ok(frame_size)
282 }
283
284 /// Recovers a lost frame from the in-band FEC (SILK LBRR) carried in the packet
285 /// that follows it, like libopus `opus_decode(next_packet, frame_size, decode_fec=1)`.
286 /// Falls back to [`Decoder::conceal`] when `next_packet` carries no LBRR data.
287 /// Returns samples per channel (`frame_size`).
288 pub fn decode_fec(
289 &mut self,
290 next_packet: &[u8],
291 frame_size: usize,
292 out: &mut [f32],
293 ) -> Result<usize> {
294 if next_packet.is_empty() || frame_size * self.downsample > 5760 {
295 return self.conceal(frame_size, out);
296 }
297 let needed = frame_size * self.channels;
298 if out.len() < needed {
299 return Err(Error::corrupt(format!(
300 "opus: output buffer holds {} samples, FEC needs {needed}",
301 out.len()
302 )));
303 }
304 let parsed = Packet::parse(next_packet, false)?;
305 let toc = parsed.toc;
306 let mode = toc.mode();
307 let frame_48k = toc.frame_size_48k();
308 let packet_frame = frame_48k / self.downsample;
309 let Some(&first) = parsed.frames.first() else {
310 return self.conceal(frame_size, out);
311 };
312 if frame_size < packet_frame
313 || mode == Mode::Celt
314 || self.prev_mode == Some(Mode::Celt)
315 || first.len() <= 1
316 || !SilkDecoder::has_lbrr(first, (frame_48k / 48).max(10))
317 {
318 return self.conceal(frame_size, out);
319 }
320 let lead = frame_size - packet_frame;
321 if lead > 0 {
322 self.conceal(lead, &mut out[..lead * self.channels])?;
323 }
324 let dst = &mut out[lead * self.channels..needed];
325 self.range_final = self.decode_frame(first, dst, toc, frame_48k, true)?;
326 self.last_packet_size = frame_size;
327 Ok(frame_size)
328 }
329
330 fn decode_impl(
331 &mut self,
332 data: &[u8],
333 out: &mut [f32],
334 self_delimited: bool,
335 ) -> Result<(usize, usize)> {
336 let parsed = Packet::parse(data, self_delimited)?;
337 let toc = parsed.toc;
338 let frame_48k = toc.frame_size_48k();
339 let frame_out = frame_48k / self.downsample;
340 let needed = parsed.frames.len() * frame_out * self.channels;
341 if out.len() < needed {
342 return Err(Error::corrupt(format!(
343 "opus: output buffer holds {} samples, packet needs {needed}",
344 out.len()
345 )));
346 }
347 let mut done = 0usize;
348 let mut range = 0u32;
349 for frame in &parsed.frames {
350 let dst = &mut out[done * self.channels..(done + frame_out) * self.channels];
351 range = self.decode_frame(frame, dst, toc, frame_48k, false)?;
352 done += frame_out;
353 }
354 self.range_final = range;
355 self.last_packet_size = done;
356 Ok((done, parsed.consumed))
357 }
358
359 /// Decodes one Opus frame (one entropy-coded unit) of a packet.
360 ///
361 /// The three modes share this path: SILK fills the low band, CELT the high
362 /// one, and a hybrid frame is their sum. The order of everything read from
363 /// the range decoder here is normative — SILK, then the redundancy flags,
364 /// then CELT (RFC 6716, Sections 4.2, 4.5.1 and 4.3). With `fec` set, the
365 /// SILK layer decodes LBRR frames and the CELT layer is concealed instead.
366 fn decode_frame(
367 &mut self,
368 data: &[u8],
369 out: &mut [f32],
370 toc: Toc,
371 frame_48k: usize,
372 fec: bool,
373 ) -> Result<u32> {
374 let mode = toc.mode();
375 let stream_channels = toc.channels();
376 if data.len() <= 1 {
377 // DTX or a dropped frame: conceal it like a lost one.
378 let n = out.len() / self.channels;
379 if self.conceal(n, out).is_err() {
380 out.fill(0.0);
381 }
382 return Ok(0);
383 }
384 let mut dec = RangeDecoder::new(data);
385 let mut len = data.len();
386 let frame_out = frame_48k / self.downsample;
387 let f5 = 240 / self.downsample;
388 let f2_5 = 120 / self.downsample;
389
390 // --- SILK layer -----------------------------------------------------
391 let mut silk_pcm = core::mem::take(&mut self.silk_pcm);
392 silk_pcm.clear();
393 silk_pcm.resize(frame_out * self.channels, 0);
394 if mode != Mode::Celt {
395 if self.prev_mode == Some(Mode::Celt) {
396 self.silk.reset();
397 }
398 let internal_rate = if mode == Mode::Hybrid {
399 16000
400 } else {
401 match toc.bandwidth() {
402 Bandwidth::Narrow => 8000,
403 Bandwidth::Medium => 12000,
404 _ => 16000,
405 }
406 };
407 self.silk_rate = internal_rate;
408 self.silk_channels = stream_channels;
409 let payload_ms = (frame_48k / 48).max(10);
410 let mode = if fec {
411 SilkFrameMode::Lbrr
412 } else {
413 SilkFrameMode::Normal
414 };
415 let mut done = 0usize;
416 let mut first = true;
417 while done < frame_out {
418 let n = self.silk.decode(
419 &mut dec,
420 &mut silk_pcm[done * self.channels..],
421 payload_ms,
422 internal_rate,
423 stream_channels,
424 first,
425 mode,
426 )?;
427 if n == 0 {
428 break;
429 }
430 done += n;
431 first = false;
432 }
433 }
434
435 // --- Redundancy (Section 4.5.1) -------------------------------------
436 let mut redundancy = false;
437 let mut celt_to_silk = false;
438 let mut redundancy_bytes = 0usize;
439 if !fec
440 && mode != Mode::Celt
441 && dec.tell() as usize + 17 + 20 * usize::from(mode == Mode::Hybrid) <= 8 * len
442 {
443 redundancy = if mode == Mode::Hybrid {
444 dec.dec_bit_logp(12)
445 } else {
446 true
447 };
448 if redundancy {
449 celt_to_silk = dec.dec_bit_logp(1);
450 redundancy_bytes = if mode == Mode::Hybrid {
451 dec.dec_uint(256) as usize + 2
452 } else {
453 len - ((dec.tell() as usize + 7) >> 3)
454 };
455 if redundancy_bytes > len {
456 redundancy_bytes = 0;
457 redundancy = false;
458 } else {
459 len -= redundancy_bytes;
460 if len * 8 < dec.tell() as usize {
461 len = 0;
462 redundancy_bytes = 0;
463 redundancy = false;
464 }
465 dec.shrink(len);
466 }
467 }
468 }
469
470 let end_band = toc.bandwidth().celt_end_band();
471 let start_band = if mode == Mode::Celt { 0 } else { 17 };
472 let mut redundant = core::mem::take(&mut self.redundant);
473 redundant.clear();
474 redundant.resize(f5 * self.channels, 0.0);
475
476 // A redundancy frame that precedes the main one is decoded first.
477 let mut redundant_rng = 0u32;
478 if redundancy && celt_to_silk {
479 let tail = &data[len..len + redundancy_bytes];
480 let mut rdec = RangeDecoder::new(tail);
481 self.celt
482 .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?;
483 redundant_rng = rdec.range();
484 }
485
486 // --- CELT layer -----------------------------------------------------
487 if mode != Mode::Silk {
488 // A mode switch invalidates the MDCT overlap and energy history.
489 if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy {
490 self.celt.reset();
491 }
492 if fec {
493 self.celt.set_conceal_bands(start_band, end_band);
494 self.celt.conceal(out, frame_48k.min(960))?;
495 } else {
496 self.celt.decode(
497 &mut dec,
498 out,
499 frame_48k.min(960),
500 start_band,
501 end_band,
502 stream_channels,
503 )?;
504 }
505 } else {
506 out.fill(0.0);
507 // Fade the CELT layer out when leaving hybrid, as the reference
508 // does, by decoding one silent 2.5 ms frame.
509 if self.prev_mode == Some(Mode::Hybrid) && !(redundancy && celt_to_silk) {
510 let silence = [0xFFu8, 0xFF];
511 let mut sdec = RangeDecoder::new(&silence);
512 let mut tmp = vec![0.0f32; f2_5 * self.channels];
513 self.celt
514 .decode(&mut sdec, &mut tmp, 120, 0, end_band, stream_channels)?;
515 }
516 }
517
518 // Sum the two layers.
519 if self.debug_mute.0 {
520 out.fill(0.0);
521 }
522 if mode != Mode::Celt && !self.debug_mute.1 {
523 for (o, s) in out.iter_mut().zip(silk_pcm.iter()) {
524 *o += *s as f32 * (1.0 / 32768.0);
525 }
526 }
527
528 // A redundancy frame that follows the main one is cross-faded in.
529 if redundancy && !celt_to_silk {
530 self.celt.reset();
531 let tail = &data[len..len + redundancy_bytes];
532 let mut rdec = RangeDecoder::new(tail);
533 self.celt
534 .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?;
535 redundant_rng = rdec.range();
536 let base = (frame_out - f2_5) * self.channels;
537 smooth_fade(
538 &mut out[base..],
539 &redundant[f2_5 * self.channels..],
540 f2_5,
541 self.channels,
542 &self.celt_window,
543 self.downsample,
544 );
545 }
546 if redundancy && celt_to_silk {
547 for c in 0..self.channels {
548 for i in 0..f2_5 {
549 out[self.channels * i + c] = redundant[self.channels * i + c];
550 }
551 }
552 // Then fade from the redundancy frame into the frame proper.
553 let split = f2_5 * self.channels;
554 for c in 0..self.channels {
555 for i in 0..f2_5 {
556 let w = {
557 let x = self.celt_window[i * self.downsample];
558 x * x
559 };
560 let idx = split + i * self.channels + c;
561 if idx < out.len() && idx < redundant.len() {
562 out[idx] = w * out[idx] + (1.0 - w) * redundant[idx];
563 }
564 }
565 }
566 }
567
568 self.prev_mode = Some(mode);
569 self.prev_redundancy = redundancy && !celt_to_silk;
570 self.silk_pcm = silk_pcm;
571 self.redundant = redundant;
572 Ok(dec.range() ^ redundant_rng)
573 }
574}
575
576impl Decoder {
577 /// Conceals `dst` (one chunk of 10 or 20 ms) with the SILK PLC, on top of
578 /// the CELT concealment in hybrid mode.
579 fn conceal_silk(&mut self, dst: &mut [f32], chunk: usize) -> Result<()> {
580 if self.prev_mode == Some(Mode::Hybrid) {
581 self.celt.conceal(dst, chunk)?;
582 } else {
583 dst.fill(0.0);
584 }
585 let mut pcm = core::mem::take(&mut self.silk_pcm);
586 let samples = chunk / self.downsample;
587 pcm.clear();
588 pcm.resize(samples * self.channels, 0);
589 let mut done = 0usize;
590 while done < samples {
591 let n = self.silk.decode(
592 &mut RangeDecoder::new(&[]),
593 &mut pcm[done * self.channels..],
594 chunk / 48,
595 self.silk_rate,
596 self.silk_channels,
597 true,
598 SilkFrameMode::Lost,
599 )?;
600 if n == 0 {
601 break;
602 }
603 done += n;
604 }
605 for (o, s) in dst.iter_mut().zip(pcm.iter()) {
606 *o += *s as f32 * (1.0 / 32768.0);
607 }
608 self.silk_pcm = pcm;
609 Ok(())
610 }
611}
612
613/// Cross-fades `b` over `a` across `overlap` samples using the CELT window,
614/// the shape the reference uses for redundancy and mode transitions.
615fn smooth_fade(
616 a: &mut [f32],
617 b: &[f32],
618 overlap: usize,
619 channels: usize,
620 window: &[f32],
621 downsample: usize,
622) {
623 let inc = downsample;
624 for c in 0..channels {
625 for i in 0..overlap {
626 let w = window[i * inc] * window[i * inc];
627 let idx = i * channels + c;
628 if idx < a.len() && idx < b.len() {
629 a[idx] = w * b[idx] + (1.0 - w) * a[idx];
630 }
631 }
632 }
633}