forge
Explore
Log in

Don't you dare go Hollow

edith_codecs

Clone
★ 0

0 watching0 forksRust370.3 MiB86fb0f3Tahinli7 days ago3927 commits

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