forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB9b67700Tahinli3 days ago4021 commits

lib.rs632 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(crate) mod celt_flp;
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 encoder::{Application, Encoder};
83pub use multistream::MultistreamDecoder;
84pub use multistream_enc::MultistreamEncoder;
85pub use packet::{Bandwidth, Mode, Packet, Toc};
86pub use range::{RangeDecoder, RangeEncoder};
87pub use silk::{SilkDecIndices, SilkDecoder, SilkFrameMode};
88
89use ec_core::{Error, Result};
90
91/// One Opus stream: mono or stereo, any mode, any frame size.
92///
93/// Feed whole Opus packets to [`Decoder::decode_float`]; the decoder tracks the
94/// inter-frame state (energy history, MDCT overlap, LPC memory) that Opus needs
95/// across packets, so packets must be delivered in order.
96#[derive(Clone, Debug)]
97pub struct Decoder {
98 sample_rate: u32,
99 /// Output channels, which may exceed what a given packet codes.
100 channels: usize,
101 downsample: usize,
102 celt: CeltDecoder,
103 /// Boxed because a `SilkDecoder` is 6512 bytes, 83% of what a `Decoder`
104 /// costs a caller taking one BY VALUE from `Decoder::new`. It is the
105 /// decoder's largest field and its only large one; `celt` is 1448.
106 /// `Stack`: crate::stack_budget.
107 silk: Box<SilkDecoder>,
108 /// The CELT overlap window, reused for redundancy cross-fades.
109 celt_window: Vec<f32>,
110 /// Per-frame scratch, allocated once: the SILK layer's output and the
111 /// redundancy frame.
112 silk_pcm: Vec<i16>,
113 /// The internal SILK rate and channel count of the last SILK frame, which
114 /// the SILK concealment reuses.
115 silk_rate: u32,
116 silk_channels: usize,
117 redundant: Vec<f32>,
118 prev_mode: Option<Mode>,
119 prev_redundancy: bool,
120 range_final: u32,
121 /// Samples per channel of the last packet, the default concealment length.
122 last_packet_size: usize,
123 /// Test hook: drop the (CELT, SILK) layer's output before the sum.
124 debug_mute: (bool, bool),
125}
126
127impl Decoder {
128 /// Test hook, not for production use: silences the CELT and/or SILK
129 /// layer's contribution to the output (the decoder state still advances)
130 /// so a hybrid packet's two layers can be measured one at a time.
131 #[doc(hidden)]
132 pub fn debug_mute_layers(&mut self, celt: bool, silk: bool) {
133 self.debug_mute = (celt, silk);
134 }
135
136 /// Decodes with the RFC 6716 reconstruction instead of the RFC 8251 one
137 /// (the default). Needed only to reproduce the RFC 6716 reference vectors.
138 pub fn set_legacy_rfc6716(&mut self, on: bool) {
139 self.celt.set_legacy_rfc6716(on);
140 }
141
142 /// Facts from the last decoded frame's CELT layer (diagnostic).
143 pub fn last_celt_diag(&self) -> &crate::celt::CeltDecDiag {
144 self.celt.last_diag()
145 }
146
147 /// A decoder for `channels` channels at `sample_rate`, which must be one of
148 /// 8000, 12000, 16000, 24000 or 48000 Hz.
149 pub fn new(sample_rate: u32, channels: usize) -> Result<Decoder> {
150 let downsample = match sample_rate {
151 48000 => 1,
152 24000 => 2,
153 16000 => 3,
154 12000 => 4,
155 8000 => 6,
156 _ => {
157 return Err(Error::unsupported(
158 format!("opus output rate {sample_rate}"),
159 "Opus decodes to 8, 12, 16, 24 or 48 kHz only",
160 ));
161 }
162 };
163 if !(1..=2).contains(&channels) {
164 return Err(Error::unsupported(
165 format!("{channels}-channel Opus stream"),
166 "one stream carries at most two channels; use MultistreamDecoder",
167 ));
168 }
169 Ok(Decoder {
170 sample_rate,
171 channels,
172 downsample,
173 celt: CeltDecoder::new(channels, downsample),
174 silk: Box::new(SilkDecoder::new(sample_rate, channels)),
175 celt_window: celt::overlap_window(),
176 silk_pcm: vec![0; 5760 * channels],
177 silk_rate: 16000,
178 silk_channels: 1,
179 redundant: vec![0.0; 240 * channels],
180 prev_mode: None,
181 prev_redundancy: false,
182 range_final: 0,
183 last_packet_size: 960 / downsample,
184 debug_mute: (false, false),
185 })
186 }
187
188 /// Output sample rate.
189 pub fn sample_rate(&self) -> u32 {
190 self.sample_rate
191 }
192
193 /// Output channels.
194 pub fn channels(&self) -> usize {
195 self.channels
196 }
197
198 /// The range coder state after the last packet. The RFC 6716 test vectors
199 /// carry this value per packet, which makes it a bit-exact conformance
200 /// check on everything the decoder read.
201 pub fn final_range(&self) -> u32 {
202 self.range_final
203 }
204
205 /// Drops all inter-packet state; call after a seek.
206 pub fn reset(&mut self) {
207 self.celt.reset();
208 self.silk.reset();
209 self.prev_mode = None;
210 self.prev_redundancy = false;
211 self.range_final = 0;
212 }
213
214 /// Decodes one packet into interleaved `f32`, returning samples per channel.
215 /// An empty `packet` is a lost one: it is concealed for the last packet's
216 /// duration (see [`Decoder::conceal`]).
217 ///
218 /// `out` must hold `channels * 120 ms` worth of samples for the general
219 /// case (5760 per channel at 48 kHz).
220 pub fn decode_float(&mut self, packet: &[u8], out: &mut [f32]) -> Result<usize> {
221 if packet.is_empty() {
222 return self.conceal(self.last_packet_size, out);
223 }
224 let (samples, _) = self.decode_impl(packet, out, false)?;
225 Ok(samples)
226 }
227
228 /// Decodes one self-delimited packet (RFC 6716, Appendix B), returning the
229 /// samples per channel and the bytes the packet occupied. This is what the
230 /// multistream framing needs for every stream but the last.
231 pub fn decode_self_delimited(
232 &mut self,
233 data: &[u8],
234 out: &mut [f32],
235 ) -> Result<(usize, usize)> {
236 self.decode_impl(data, out, true)
237 }
238
239 /// Conceals `frame_size` lost samples per channel (a multiple of 2.5 ms,
240 /// at most 120 ms), the equivalent of the reference's `decode(NULL)`.
241 /// CELT output decays towards background noise and SILK output is
242 /// extrapolated by the SILK PLC; the next real packet cross-fades in
243 /// through the MDCT overlap.
244 pub fn conceal(&mut self, frame_size: usize, out: &mut [f32]) -> Result<usize> {
245 let total_48k = frame_size * self.downsample;
246 if total_48k == 0 || !total_48k.is_multiple_of(120) || total_48k > 5760 {
247 return Err(Error::corrupt(format!(
248 "opus: conceal size {frame_size} is not a multiple of 2.5 ms up to 120 ms"
249 )));
250 }
251 let needed = frame_size * self.channels;
252 if out.len() < needed {
253 return Err(Error::corrupt(format!(
254 "opus: output buffer holds {} samples, concealment needs {needed}",
255 out.len()
256 )));
257 }
258 let mut done_48k = 0usize;
259 while done_48k < total_48k {
260 let left = total_48k - done_48k;
261 let sizes: &[usize] = match self.prev_mode {
262 Some(Mode::Silk | Mode::Hybrid) => &[960, 480],
263 _ => &[960, 480, 240, 120],
264 };
265 let chunk = sizes.iter().copied().find(|&c| c <= left).unwrap_or(120);
266 let a = done_48k / self.downsample * self.channels;
267 let b = (done_48k + chunk) / self.downsample * self.channels;
268 let dst = &mut out[a..b];
269 match self.prev_mode {
270 Some(Mode::Celt) => {
271 self.celt.conceal(dst, chunk)?;
272 }
273 Some(Mode::Silk | Mode::Hybrid) if chunk >= 480 => {
274 self.conceal_silk(dst, chunk)?;
275 }
276 _ => dst.fill(0.0),
277 }
278 done_48k += chunk;
279 }
280 Ok(frame_size)
281 }
282
283 /// Recovers a lost frame from the in-band FEC (SILK LBRR) carried in the packet
284 /// that follows it, like libopus `opus_decode(next_packet, frame_size, decode_fec=1)`.
285 /// Falls back to [`Decoder::conceal`] when `next_packet` carries no LBRR data.
286 /// Returns samples per channel (`frame_size`).
287 pub fn decode_fec(
288 &mut self,
289 next_packet: &[u8],
290 frame_size: usize,
291 out: &mut [f32],
292 ) -> Result<usize> {
293 if next_packet.is_empty() || frame_size * self.downsample > 5760 {
294 return self.conceal(frame_size, out);
295 }
296 let needed = frame_size * self.channels;
297 if out.len() < needed {
298 return Err(Error::corrupt(format!(
299 "opus: output buffer holds {} samples, FEC needs {needed}",
300 out.len()
301 )));
302 }
303 let parsed = Packet::parse(next_packet, false)?;
304 let toc = parsed.toc;
305 let mode = toc.mode();
306 let frame_48k = toc.frame_size_48k();
307 let packet_frame = frame_48k / self.downsample;
308 let Some(&first) = parsed.frames.first() else {
309 return self.conceal(frame_size, out);
310 };
311 if frame_size < packet_frame
312 || mode == Mode::Celt
313 || self.prev_mode == Some(Mode::Celt)
314 || first.len() <= 1
315 || !SilkDecoder::has_lbrr(first, (frame_48k / 48).max(10))
316 {
317 return self.conceal(frame_size, out);
318 }
319 let lead = frame_size - packet_frame;
320 if lead > 0 {
321 self.conceal(lead, &mut out[..lead * self.channels])?;
322 }
323 let dst = &mut out[lead * self.channels..needed];
324 self.range_final = self.decode_frame(first, dst, toc, frame_48k, true)?;
325 self.last_packet_size = frame_size;
326 Ok(frame_size)
327 }
328
329 fn decode_impl(
330 &mut self,
331 data: &[u8],
332 out: &mut [f32],
333 self_delimited: bool,
334 ) -> Result<(usize, usize)> {
335 let parsed = Packet::parse(data, self_delimited)?;
336 let toc = parsed.toc;
337 let frame_48k = toc.frame_size_48k();
338 let frame_out = frame_48k / self.downsample;
339 let needed = parsed.frames.len() * frame_out * self.channels;
340 if out.len() < needed {
341 return Err(Error::corrupt(format!(
342 "opus: output buffer holds {} samples, packet needs {needed}",
343 out.len()
344 )));
345 }
346 let mut done = 0usize;
347 let mut range = 0u32;
348 for frame in &parsed.frames {
349 let dst = &mut out[done * self.channels..(done + frame_out) * self.channels];
350 range = self.decode_frame(frame, dst, toc, frame_48k, false)?;
351 done += frame_out;
352 }
353 self.range_final = range;
354 self.last_packet_size = done;
355 Ok((done, parsed.consumed))
356 }
357
358 /// Decodes one Opus frame (one entropy-coded unit) of a packet.
359 ///
360 /// The three modes share this path: SILK fills the low band, CELT the high
361 /// one, and a hybrid frame is their sum. The order of everything read from
362 /// the range decoder here is normative — SILK, then the redundancy flags,
363 /// then CELT (RFC 6716, Sections 4.2, 4.5.1 and 4.3). With `fec` set, the
364 /// SILK layer decodes LBRR frames and the CELT layer is concealed instead.
365 fn decode_frame(
366 &mut self,
367 data: &[u8],
368 out: &mut [f32],
369 toc: Toc,
370 frame_48k: usize,
371 fec: bool,
372 ) -> Result<u32> {
373 let mode = toc.mode();
374 let stream_channels = toc.channels();
375 if data.len() <= 1 {
376 // DTX or a dropped frame: conceal it like a lost one.
377 let n = out.len() / self.channels;
378 if self.conceal(n, out).is_err() {
379 out.fill(0.0);
380 }
381 return Ok(0);
382 }
383 let mut dec = RangeDecoder::new(data);
384 let mut len = data.len();
385 let frame_out = frame_48k / self.downsample;
386 let f5 = 240 / self.downsample;
387 let f2_5 = 120 / self.downsample;
388
389 // --- SILK layer -----------------------------------------------------
390 let mut silk_pcm = core::mem::take(&mut self.silk_pcm);
391 silk_pcm.clear();
392 silk_pcm.resize(frame_out * self.channels, 0);
393 if mode != Mode::Celt {
394 if self.prev_mode == Some(Mode::Celt) {
395 self.silk.reset();
396 }
397 let internal_rate = if mode == Mode::Hybrid {
398 16000
399 } else {
400 match toc.bandwidth() {
401 Bandwidth::Narrow => 8000,
402 Bandwidth::Medium => 12000,
403 _ => 16000,
404 }
405 };
406 self.silk_rate = internal_rate;
407 self.silk_channels = stream_channels;
408 let payload_ms = (frame_48k / 48).max(10);
409 let mode = if fec {
410 SilkFrameMode::Lbrr
411 } else {
412 SilkFrameMode::Normal
413 };
414 let mut done = 0usize;
415 let mut first = true;
416 while done < frame_out {
417 let n = self.silk.decode(
418 &mut dec,
419 &mut silk_pcm[done * self.channels..],
420 payload_ms,
421 internal_rate,
422 stream_channels,
423 first,
424 mode,
425 )?;
426 if n == 0 {
427 break;
428 }
429 done += n;
430 first = false;
431 }
432 }
433
434 // --- Redundancy (Section 4.5.1) -------------------------------------
435 let mut redundancy = false;
436 let mut celt_to_silk = false;
437 let mut redundancy_bytes = 0usize;
438 if !fec
439 && mode != Mode::Celt
440 && dec.tell() as usize + 17 + 20 * usize::from(mode == Mode::Hybrid) <= 8 * len
441 {
442 redundancy = if mode == Mode::Hybrid {
443 dec.dec_bit_logp(12)
444 } else {
445 true
446 };
447 if redundancy {
448 celt_to_silk = dec.dec_bit_logp(1);
449 redundancy_bytes = if mode == Mode::Hybrid {
450 dec.dec_uint(256) as usize + 2
451 } else {
452 len - ((dec.tell() as usize + 7) >> 3)
453 };
454 if redundancy_bytes > len {
455 redundancy_bytes = 0;
456 redundancy = false;
457 } else {
458 len -= redundancy_bytes;
459 if len * 8 < dec.tell() as usize {
460 len = 0;
461 redundancy_bytes = 0;
462 redundancy = false;
463 }
464 dec.shrink(len);
465 }
466 }
467 }
468
469 let end_band = toc.bandwidth().celt_end_band();
470 let start_band = if mode == Mode::Celt { 0 } else { 17 };
471 let mut redundant = core::mem::take(&mut self.redundant);
472 redundant.clear();
473 redundant.resize(f5 * self.channels, 0.0);
474
475 // A redundancy frame that precedes the main one is decoded first.
476 let mut redundant_rng = 0u32;
477 if redundancy && celt_to_silk {
478 let tail = &data[len..len + redundancy_bytes];
479 let mut rdec = RangeDecoder::new(tail);
480 self.celt
481 .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?;
482 redundant_rng = rdec.range();
483 }
484
485 // --- CELT layer -----------------------------------------------------
486 if mode != Mode::Silk {
487 // A mode switch invalidates the MDCT overlap and energy history.
488 if self.prev_mode.is_some_and(|p| p != mode) && !self.prev_redundancy {
489 self.celt.reset();
490 }
491 if fec {
492 self.celt.set_conceal_bands(start_band, end_band);
493 self.celt.conceal(out, frame_48k.min(960))?;
494 } else {
495 self.celt.decode(
496 &mut dec,
497 out,
498 frame_48k.min(960),
499 start_band,
500 end_band,
501 stream_channels,
502 )?;
503 }
504 } else {
505 out.fill(0.0);
506 // Fade the CELT layer out when leaving hybrid, as the reference
507 // does, by decoding one silent 2.5 ms frame.
508 if self.prev_mode == Some(Mode::Hybrid) && !(redundancy && celt_to_silk) {
509 let silence = [0xFFu8, 0xFF];
510 let mut sdec = RangeDecoder::new(&silence);
511 let mut tmp = vec![0.0f32; f2_5 * self.channels];
512 self.celt
513 .decode(&mut sdec, &mut tmp, 120, 0, end_band, stream_channels)?;
514 }
515 }
516
517 // Sum the two layers.
518 if self.debug_mute.0 {
519 out.fill(0.0);
520 }
521 if mode != Mode::Celt && !self.debug_mute.1 {
522 for (o, s) in out.iter_mut().zip(silk_pcm.iter()) {
523 *o += *s as f32 * (1.0 / 32768.0);
524 }
525 }
526
527 // A redundancy frame that follows the main one is cross-faded in.
528 if redundancy && !celt_to_silk {
529 self.celt.reset();
530 let tail = &data[len..len + redundancy_bytes];
531 let mut rdec = RangeDecoder::new(tail);
532 self.celt
533 .decode(&mut rdec, &mut redundant, 240, 0, end_band, stream_channels)?;
534 redundant_rng = rdec.range();
535 let base = (frame_out - f2_5) * self.channels;
536 smooth_fade(
537 &mut out[base..],
538 &redundant[f2_5 * self.channels..],
539 f2_5,
540 self.channels,
541 &self.celt_window,
542 self.downsample,
543 );
544 }
545 if redundancy && celt_to_silk {
546 for c in 0..self.channels {
547 for i in 0..f2_5 {
548 out[self.channels * i + c] = redundant[self.channels * i + c];
549 }
550 }
551 // Then fade from the redundancy frame into the frame proper.
552 let split = f2_5 * self.channels;
553 for c in 0..self.channels {
554 for i in 0..f2_5 {
555 let w = {
556 let x = self.celt_window[i * self.downsample];
557 x * x
558 };
559 let idx = split + i * self.channels + c;
560 if idx < out.len() && idx < redundant.len() {
561 out[idx] = w * out[idx] + (1.0 - w) * redundant[idx];
562 }
563 }
564 }
565 }
566
567 self.prev_mode = Some(mode);
568 self.prev_redundancy = redundancy && !celt_to_silk;
569 self.silk_pcm = silk_pcm;
570 self.redundant = redundant;
571 Ok(dec.range() ^ redundant_rng)
572 }
573}
574
575impl Decoder {
576 /// Conceals `dst` (one chunk of 10 or 20 ms) with the SILK PLC, on top of
577 /// the CELT concealment in hybrid mode.
578 fn conceal_silk(&mut self, dst: &mut [f32], chunk: usize) -> Result<()> {
579 if self.prev_mode == Some(Mode::Hybrid) {
580 self.celt.conceal(dst, chunk)?;
581 } else {
582 dst.fill(0.0);
583 }
584 let mut pcm = core::mem::take(&mut self.silk_pcm);
585 let samples = chunk / self.downsample;
586 pcm.clear();
587 pcm.resize(samples * self.channels, 0);
588 let mut done = 0usize;
589 while done < samples {
590 let n = self.silk.decode(
591 &mut RangeDecoder::new(&[]),
592 &mut pcm[done * self.channels..],
593 chunk / 48,
594 self.silk_rate,
595 self.silk_channels,
596 true,
597 SilkFrameMode::Lost,
598 )?;
599 if n == 0 {
600 break;
601 }
602 done += n;
603 }
604 for (o, s) in dst.iter_mut().zip(pcm.iter()) {
605 *o += *s as f32 * (1.0 / 32768.0);
606 }
607 self.silk_pcm = pcm;
608 Ok(())
609 }
610}
611
612/// Cross-fades `b` over `a` across `overlap` samples using the CELT window,
613/// the shape the reference uses for redundancy and mode transitions.
614fn smooth_fade(
615 a: &mut [f32],
616 b: &[f32],
617 overlap: usize,
618 channels: usize,
619 window: &[f32],
620 downsample: usize,
621) {
622 let inc = downsample;
623 for c in 0..channels {
624 for i in 0..overlap {
625 let w = window[i * inc] * window[i * inc];
626 let idx = i * channels + c;
627 if idx < a.len() && idx < b.len() {
628 a[idx] = w * b[idx] + (1.0 - w) * a[idx];
629 }
630 }
631 }
632}