kessel-audio 0.2.2

A real-time voice audio pipeline in pure Rust: devices, echo cancellation, noise suppression and gain control, Opus, jitter buffers with loss concealment, mixing and levels.
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
//! Echo cancellation, noise suppression and gain control (sonora, a pure
//! Rust port of WebRTC's audio processing module), and the caller's
//! capture stage between them.
//!
//! The playback mix is the echo reference: every 10 ms block the engine
//! plays is passed to [`Apm::render`] before it reaches the device.

use crate::error::AudioError;
use crate::frame::{BLOCK_SAMPLES, SAMPLE_RATE};
use crate::stage::{
    CaptureStage, CaptureStageStats, StageRunner, TransientEvent, DEFAULT_STAGE_GRACE,
};
use sonora::config::{
    AdaptiveDigital, EchoCanceller, FixedDigital, GainController2, HighPassFilter,
    MaxProcessingRate, NoiseSuppression, NoiseSuppressionLevel, Pipeline,
};
use std::time::Duration;

/// Noise-suppression strength.
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NoiseSuppressionStrength {
    /// About 6 dB.
    Low,
    /// About 12 dB (the default).
    Moderate,
    /// About 18 dB.
    High,
    /// About 21 dB.
    VeryHigh,
}

/// Which processing runs on the capture path.
///
/// `#[non_exhaustive]`: start from [`ProcessingConfig::default`] or
/// [`ProcessingConfig::off`], then set fields or use the `with_` methods.
#[non_exhaustive]
pub struct ProcessingConfig {
    /// Acoustic echo cancellation (AEC3) against the playback mix.
    pub echo_cancellation: bool,
    /// Noise suppression, or `None` for off. Turn it off when a
    /// [`capture_stage`](Self::capture_stage) removes noise: two
    /// suppressors in a row add artefacts for no gain. The engine doesn't
    /// decide that for you.
    pub noise_suppression: Option<NoiseSuppressionStrength>,
    /// Automatic gain control (AGC2 adaptive digital, plus its limiter).
    pub gain_control: bool,
    /// The high-pass filter (removes DC and rumble below about 100 Hz).
    /// Echo cancellation turns it on regardless.
    pub high_pass: bool,
    /// The caller's own processing, after the high-pass filter, echo
    /// cancellation and noise suppression (if set) and before gain control.
    /// See [`CaptureStage`] for the rules, the time budget and the bypass.
    /// Levels, VAD and DTX read the signal after the stage and gain control.
    ///
    /// `None` (the default) runs exactly what 0.1 ran. With a stage, echo
    /// cancellation and gain control run in two sonora instances with the
    /// stage between them.
    pub capture_stage: Option<Box<dyn CaptureStage>>,
    /// The step-down floor: sonora's noise suppression at this strength
    /// stands in while the capture stage is bypassed (over budget or a
    /// fault), and stops again when a retry brings the stage back. The
    /// switch crossfades over one 10 ms block and keeps the stage's timing.
    /// Default `Some(Moderate)`, as 0.1 runs it.
    ///
    /// It only applies with a stage set and
    /// [`noise_suppression`](Self::noise_suppression) `None` (otherwise
    /// noise suppression already runs before the stage). The suppressor
    /// runs on every block in its own sonora instance, so it is converged
    /// the moment it is needed; it allocates nothing per block, and costs
    /// its band split and merge on top of the suppression 0.1 ran: about
    /// 0.5% of a core (50–54 µs per 10 ms block, measured on x86-64). Its own delay (334 samples,
    /// 7 ms) is taken out of the stage's latency, so the timing holds for a
    /// stage with at least that much latency (a shorter one: the suppressed
    /// signal is that much later). `None` turns the floor off: a bypassed
    /// stage leaves no suppression.
    ///
    /// Known behaviour: the phone backend's raw mode
    /// (`PhoneMode::Raw`, iOS and Android) never runs this floor, whatever
    /// it is set to, as it runs no noise suppression at all. A capture stage
    /// on raw capture that is bypassed leaves the signal unsuppressed until
    /// its retry. That only matters for a stage that removes noise on raw
    /// capture.
    pub stage_fallback_noise_suppression: Option<NoiseSuppressionStrength>,
    /// The capture stage's grace window: for this long (in capture, rounded
    /// up to 10 ms blocks) after a
    /// [`TransientEvent`] ([`crate::AudioEngine::transient_event`]), the
    /// stage's start or a capture stream (re)start, slow calls don't count
    /// toward a strike; they are still timed and reported (see
    /// [`CaptureStage`]). Default [`DEFAULT_STAGE_GRACE`] (1.5 s); at most
    /// [`crate::MAX_STAGE_GRACE`] (10 s), or [`crate::AudioEngine::start`]
    /// refuses the config. `Duration::ZERO` turns the grace off: the budget
    /// applies from the first call, as in 0.2.1. Only applies with a stage
    /// set.
    pub stage_grace: Duration,
}

impl std::fmt::Debug for ProcessingConfig {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("ProcessingConfig")
            .field("echo_cancellation", &self.echo_cancellation)
            .field("noise_suppression", &self.noise_suppression)
            .field("gain_control", &self.gain_control)
            .field("high_pass", &self.high_pass)
            .field(
                "capture_stage_latency",
                &self.capture_stage.as_ref().map(|s| s.latency_samples()),
            )
            .field(
                "stage_fallback_noise_suppression",
                &self.stage_fallback_noise_suppression,
            )
            .field("stage_grace", &self.stage_grace)
            .finish()
    }
}

impl Default for ProcessingConfig {
    /// Everything on: AEC3, moderate noise suppression, AGC2 and the
    /// high-pass filter. No capture stage.
    fn default() -> Self {
        ProcessingConfig {
            echo_cancellation: true,
            noise_suppression: Some(NoiseSuppressionStrength::Moderate),
            gain_control: true,
            high_pass: true,
            capture_stage: None,
            stage_fallback_noise_suppression: Some(NoiseSuppressionStrength::Moderate),
            stage_grace: DEFAULT_STAGE_GRACE,
        }
    }
}

impl ProcessingConfig {
    /// No processing at all: capture passes through unchanged.
    pub fn off() -> Self {
        ProcessingConfig {
            echo_cancellation: false,
            noise_suppression: None,
            gain_control: false,
            high_pass: false,
            capture_stage: None,
            stage_fallback_noise_suppression: Some(NoiseSuppressionStrength::Moderate),
            stage_grace: DEFAULT_STAGE_GRACE,
        }
    }

    /// Set the [`capture_stage`](Self::capture_stage). Noise suppression
    /// stays as it is: turn it off with
    /// [`with_noise_suppression(None)`](Self::with_noise_suppression) if the
    /// stage removes noise.
    pub fn with_capture_stage(mut self, stage: Box<dyn CaptureStage>) -> Self {
        self.capture_stage = Some(stage);
        self
    }

    /// Set [`noise_suppression`](Self::noise_suppression).
    pub fn with_noise_suppression(mut self, ns: Option<NoiseSuppressionStrength>) -> Self {
        self.noise_suppression = ns;
        self
    }

    /// Set [`echo_cancellation`](Self::echo_cancellation).
    pub fn with_echo_cancellation(mut self, on: bool) -> Self {
        self.echo_cancellation = on;
        self
    }

    /// Set [`gain_control`](Self::gain_control).
    pub fn with_gain_control(mut self, on: bool) -> Self {
        self.gain_control = on;
        self
    }

    /// Set [`high_pass`](Self::high_pass).
    pub fn with_high_pass(mut self, on: bool) -> Self {
        self.high_pass = on;
        self
    }

    /// Set
    /// [`stage_fallback_noise_suppression`](Self::stage_fallback_noise_suppression).
    pub fn with_stage_fallback_noise_suppression(
        mut self,
        ns: Option<NoiseSuppressionStrength>,
    ) -> Self {
        self.stage_fallback_noise_suppression = ns;
        self
    }

    /// Set [`stage_grace`](Self::stage_grace).
    pub fn with_stage_grace(mut self, grace: Duration) -> Self {
        self.stage_grace = grace;
        self
    }

    /// What sonora runs: everything but the stage.
    pub(crate) fn settings(&self) -> ApmSettings {
        ApmSettings {
            echo_cancellation: self.echo_cancellation,
            noise_suppression: self.noise_suppression,
            gain_control: self.gain_control,
            high_pass: self.high_pass,
            stage_fallback_ns: self.stage_fallback_noise_suppression,
        }
    }
}

/// [`ProcessingConfig`] without the stage: what sonora runs.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ApmSettings {
    pub(crate) echo_cancellation: bool,
    pub(crate) noise_suppression: Option<NoiseSuppressionStrength>,
    pub(crate) gain_control: bool,
    pub(crate) high_pass: bool,
    /// Only used with a stage (see
    /// [`ProcessingConfig::stage_fallback_noise_suppression`]).
    pub(crate) stage_fallback_ns: Option<NoiseSuppressionStrength>,
}

impl ApmSettings {
    fn any(&self) -> bool {
        self.echo_cancellation
            || self.noise_suppression.is_some()
            || self.gain_control
            || self.high_pass
    }
}

impl From<&ProcessingConfig> for ApmSettings {
    fn from(c: &ProcessingConfig) -> Self {
        c.settings()
    }
}

impl From<ProcessingConfig> for ApmSettings {
    fn from(c: ProcessingConfig) -> Self {
        c.settings()
    }
}

/// AGC2 adaptive-digital headroom, in dB.
///
/// With WebRTC's default of 5 dB, sonora 0.2.0 settles 0.7 to 1.6 dB
/// quieter than the C++ WebRTC library. Measured on LibriSpeech speech
/// against the C++ library (5.0 / 4.0 / 3.4 / 3.0 dB swept), 4 dB matches
/// it best: AGC2 alone at -40 and -30 dBFS input lands at -22.8 and
/// -23.0 dBFS (C++: -23.1, -23.1); the full chain on near-end speech at
/// -23.5 dBFS (C++: -22.9) and in double talk at -25.5 dBFS (C++: -25.4).
/// Every level is within 0.6 dB of the C++ library, against up to 1.6 dB
/// with 5 dB. Quiet (-50 dBFS) and loud (-20 dBFS) input are unaffected.
pub const AGC2_HEADROOM_DB: f32 = 4.0;

/// One sonora instance for `cfg`, or `None` if it would do nothing.
fn build(cfg: &ApmSettings, headroom_db: f32) -> Option<sonora::AudioProcessing> {
    if !cfg.any() {
        return None;
    }
    let config = sonora::Config {
        pipeline: Pipeline {
            maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz,
            multi_channel_render: false,
            multi_channel_capture: false,
            ..Pipeline::default()
        },
        high_pass_filter: (cfg.high_pass || cfg.echo_cancellation).then(HighPassFilter::default),
        echo_canceller: cfg.echo_cancellation.then(EchoCanceller::default),
        noise_suppression: cfg.noise_suppression.map(|s| NoiseSuppression {
            level: match s {
                NoiseSuppressionStrength::Low => NoiseSuppressionLevel::Low,
                NoiseSuppressionStrength::Moderate => NoiseSuppressionLevel::Moderate,
                NoiseSuppressionStrength::High => NoiseSuppressionLevel::High,
                NoiseSuppressionStrength::VeryHigh => NoiseSuppressionLevel::VeryHigh,
            },
            analyze_linear_aec_output_when_available: false,
        }),
        gain_controller2: cfg.gain_control.then(|| GainController2 {
            input_volume_controller: false,
            adaptive_digital: Some(AdaptiveDigital {
                headroom_db,
                ..AdaptiveDigital::default()
            }),
            fixed_digital: FixedDigital::default(),
        }),
        ..Default::default()
    };
    Some(
        sonora::AudioProcessing::builder()
            .config(config)
            .capture_config(sonora::StreamConfig::new(SAMPLE_RATE, 1))
            .render_config(sonora::StreamConfig::new(SAMPLE_RATE, 1))
            .build(),
    )
}

/// One capture block through `apm`, or a copy without one.
fn run_capture(apm: Option<&mut sonora::AudioProcessing>, x: &[f32], out: &mut [f32]) {
    match apm {
        Some(apm) => {
            // Frame-size mismatches are impossible here (fixed 480-sample
            // mono blocks), so an error would be a bug in the caller.
            if apm.process_capture_f32(&[x], &mut [out]).is_err() {
                debug_assert!(false, "sonora rejected a capture block");
                out.copy_from_slice(x);
            }
        }
        None => out.copy_from_slice(x),
    }
}

/// The algorithmic delay of a noise-suppression-only sonora instance at
/// 48 kHz, in samples (7 ms): its band split and merge (46) plus the
/// suppressor's overlap (288). Measured (`the_step_down_lines_up_with_the_stage`).
pub(crate) const STEP_DOWN_NS_DELAY: usize = 334;

/// The step-down floor: sonora's noise suppression, run on every block on
/// the echo canceller's output and delayed to the stage's latency, used
/// while the stage is bypassed.
struct StepDown {
    ns: sonora::AudioProcessing,
    /// This block, suppressed and delayed.
    out: [f32; BLOCK_SAMPLES],
    /// Tops the suppressor's own delay up to the stage's latency.
    delay: Box<[f32]>,
    pos: usize,
    /// The suppressor's output was used for the last block.
    on: bool,
    /// The crossfade, 0 to 1 over a block (raised cosine).
    ramp: [f32; BLOCK_SAMPLES],
}

impl StepDown {
    fn new(strength: NoiseSuppressionStrength, stage_latency: usize) -> Option<StepDown> {
        let ns = build(
            &ApmSettings {
                echo_cancellation: false,
                noise_suppression: Some(strength),
                gain_control: false,
                high_pass: false,
                stage_fallback_ns: None,
            },
            AGC2_HEADROOM_DB,
        )?;
        let mut ramp = [0.0f32; BLOCK_SAMPLES];
        for (i, r) in ramp.iter_mut().enumerate() {
            let t = (i as f32 + 0.5) / BLOCK_SAMPLES as f32;
            *r = 0.5 - 0.5 * (std::f32::consts::PI * t).cos();
        }
        Some(StepDown {
            ns,
            out: [0.0; BLOCK_SAMPLES],
            delay: vec![0.0; stage_latency.saturating_sub(STEP_DOWN_NS_DELAY)].into_boxed_slice(),
            pos: 0,
            on: false,
            ramp,
        })
    }

    /// Suppress this block of the echo canceller's output into `self.out`,
    /// delayed to the stage's latency.
    fn feed(&mut self, aec: &[f32; BLOCK_SAMPLES]) {
        run_capture(Some(&mut self.ns), aec, &mut self.out);
        let l = self.delay.len();
        if l == 0 {
            return;
        }
        for v in self.out.iter_mut() {
            std::mem::swap(&mut self.delay[self.pos], v);
            self.pos += 1;
            if self.pos == l {
                self.pos = 0;
            }
        }
    }

    /// `block` holds the stage's output (or the delayed echo canceller
    /// output when bypassed); replace it with the suppressor's when
    /// `use_ns`, crossfading over this block when that changes.
    fn apply(&mut self, block: &mut [f32; BLOCK_SAMPLES], use_ns: bool) {
        if use_ns != self.on {
            for ((b, &n), &r) in block.iter_mut().zip(&self.out).zip(&self.ramp) {
                let (from, to) = if use_ns { (*b, n) } else { (n, *b) };
                *b = from + (to - from) * r;
            }
            self.on = use_ns;
        } else if use_ns {
            block.copy_from_slice(&self.out);
        }
    }

    fn reset(&mut self) {
        self.delay.fill(0.0);
        self.pos = 0;
    }
}

/// The sonora side of the capture path: everything but the caller's stage.
/// Built off the processing thread (it allocates) and swapped in whole
/// ([`Apm::replace_chain`]), so the phone backend can change what sonora
/// runs mid-call while the stage keeps its state.
pub(crate) struct Chain {
    /// What this chain runs.
    settings: ApmSettings,
    /// Without a stage, everything in one instance (as 0.1 ran it). With
    /// one: the high-pass filter, echo cancellation and noise suppression.
    inner: Option<sonora::AudioProcessing>,
    /// With a stage and gain control: AGC2 and its limiter, alone.
    post: Option<sonora::AudioProcessing>,
    /// With a stage, noise suppression off and the fallback on.
    step_down: Option<StepDown>,
}

impl Chain {
    /// The chain for `cfg`. `stage_latency` is the capture stage's latency
    /// in samples, or `None` without a stage.
    #[cfg_attr(
        not(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        )),
        allow(dead_code)
    )]
    pub(crate) fn new(cfg: ApmSettings, stage_latency: Option<usize>) -> Box<Chain> {
        Box::new(Self::build(cfg, stage_latency, AGC2_HEADROOM_DB))
    }

    fn build(cfg: ApmSettings, stage_latency: Option<usize>, headroom_db: f32) -> Chain {
        let Some(latency) = stage_latency else {
            return Chain {
                settings: cfg,
                inner: build(&cfg, headroom_db),
                post: None,
                step_down: None,
            };
        };
        let pre = ApmSettings {
            gain_control: false,
            stage_fallback_ns: None,
            ..cfg
        };
        let post = ApmSettings {
            echo_cancellation: false,
            noise_suppression: None,
            gain_control: cfg.gain_control,
            high_pass: false,
            stage_fallback_ns: None,
        };
        let step_down = match (cfg.noise_suppression, cfg.stage_fallback_ns) {
            (None, Some(strength)) => StepDown::new(strength, latency),
            _ => None,
        };
        Chain {
            settings: cfg,
            inner: build(&pre, headroom_db),
            post: build(&post, headroom_db),
            step_down,
        }
    }

    /// What this chain runs.
    #[cfg(test)]
    pub(crate) fn settings(&self) -> ApmSettings {
        self.settings
    }

    /// The sonora configs it runs: before the stage (everything, without
    /// one), after the stage, and the step-down suppressor's.
    #[cfg(test)]
    pub(crate) fn sonora_configs(&self) -> [Option<&sonora::Config>; 3] {
        [
            self.inner.as_ref().map(|a| a.config()),
            self.post.as_ref().map(|a| a.config()),
            self.step_down.as_ref().map(|s| s.ns.config()),
        ]
    }
}

impl std::fmt::Debug for Chain {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("Chain")
            .field("settings", &self.settings)
            .finish_non_exhaustive()
    }
}

pub(crate) struct Apm {
    chain: Chain,
    stage: Option<StageRunner>,
    scratch: [f32; BLOCK_SAMPLES],
    mid: [f32; BLOCK_SAMPLES],
}

impl Apm {
    pub(crate) fn new(cfg: impl Into<ApmSettings>) -> Self {
        Self::with_agc_headroom(cfg, AGC2_HEADROOM_DB)
    }

    pub(crate) fn with_agc_headroom(cfg: impl Into<ApmSettings>, headroom_db: f32) -> Self {
        Apm {
            chain: Chain::build(cfg.into(), None, headroom_db),
            stage: None,
            scratch: [0.0; BLOCK_SAMPLES],
            mid: [0.0; BLOCK_SAMPLES],
        }
    }

    /// With a capture stage: the high-pass filter, echo cancellation and
    /// noise suppression in one instance, then the stage, then gain control
    /// in a second instance; and the step-down suppressor if it applies.
    /// Build it on the thread that will run it (the stage is reset here).
    /// `grace` is the stage's grace window ([`ProcessingConfig::stage_grace`]).
    pub(crate) fn with_stage(
        cfg: impl Into<ApmSettings>,
        stage: Box<dyn CaptureStage>,
        grace: Duration,
    ) -> Result<Self, AudioError> {
        Self::with_runner(cfg.into(), StageRunner::new(stage, grace)?)
    }

    /// [`Apm::with_stage`] with the stage timed by `clock` and no grace
    /// window (tests: the budget applies from the first call).
    #[cfg(test)]
    pub(crate) fn with_stage_clock(
        cfg: impl Into<ApmSettings>,
        stage: Box<dyn CaptureStage>,
        clock: crate::stage::StageClock,
    ) -> Result<Self, AudioError> {
        Self::with_stage_clock_grace(cfg, stage, clock, Duration::ZERO)
    }

    /// [`Apm::with_stage`] with the stage timed by `clock` (tests).
    #[cfg(test)]
    pub(crate) fn with_stage_clock_grace(
        cfg: impl Into<ApmSettings>,
        stage: Box<dyn CaptureStage>,
        clock: crate::stage::StageClock,
        grace: Duration,
    ) -> Result<Self, AudioError> {
        Self::with_runner(cfg.into(), StageRunner::with_clock(stage, clock, grace)?)
    }

    fn with_runner(cfg: ApmSettings, stage: StageRunner) -> Result<Self, AudioError> {
        Ok(Apm {
            chain: Chain::build(cfg, Some(stage.latency()), AGC2_HEADROOM_DB),
            stage: Some(stage),
            scratch: [0.0; BLOCK_SAMPLES],
            mid: [0.0; BLOCK_SAMPLES],
        })
    }

    /// Swap in another chain (built off this thread for the same stage
    /// latency, see [`Chain::new`]) and hand back the old one, to be freed
    /// elsewhere. Allocates and frees nothing. The stage keeps its state;
    /// it is reset when the capture stream restarts, as usual.
    #[cfg_attr(
        not(any(
            test,
            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
        )),
        allow(dead_code)
    )]
    pub(crate) fn replace_chain(&mut self, mut chain: Box<Chain>) -> Box<Chain> {
        std::mem::swap(&mut self.chain, &mut *chain);
        chain
    }

    /// The chain running now.
    #[cfg(test)]
    pub(crate) fn chain(&self) -> &Chain {
        &self.chain
    }

    /// Analyse one 10 ms block of the playback mix (the echo reference).
    pub(crate) fn render(&mut self, x: &[f32]) {
        debug_assert_eq!(x.len(), BLOCK_SAMPLES);
        if let Some(apm) = self.chain.inner.as_mut() {
            // Frame-size mismatches are impossible here (fixed 480-sample
            // mono blocks), so an error would be a bug in the caller.
            if apm
                .process_render_f32(&[x], &mut [&mut self.scratch[..]])
                .is_err()
            {
                debug_assert!(false, "sonora rejected a render block");
            }
        }
    }

    /// Process one 10 ms capture block into `out`.
    pub(crate) fn capture(&mut self, x: &[f32], out: &mut [f32]) {
        debug_assert_eq!(x.len(), BLOCK_SAMPLES);
        debug_assert_eq!(out.len(), BLOCK_SAMPLES);
        let Some(stage) = self.stage.as_mut() else {
            run_capture(self.chain.inner.as_mut(), x, out);
            return;
        };
        run_capture(self.chain.inner.as_mut(), x, &mut self.mid);
        if let Some(sd) = self.chain.step_down.as_mut() {
            sd.feed(&self.mid);
        }
        stage.process(&mut self.mid);
        if let Some(sd) = self.chain.step_down.as_mut() {
            let use_ns = !stage.used_stage();
            sd.apply(&mut self.mid, use_ns);
            stage.set_fallback(use_ns);
        }
        run_capture(self.chain.post.as_mut(), &self.mid, out);
    }

    /// The capture stream restarted or had a gap: reset the capture stage.
    pub(crate) fn reset_stage(&mut self) {
        if let Some(s) = self.stage.as_mut() {
            s.reset();
        }
        if let Some(sd) = self.chain.step_down.as_mut() {
            sd.reset();
        }
    }

    /// Open (or extend) the capture stage's grace window; `event` is the
    /// host's reason. Without a stage, nothing.
    pub(crate) fn open_stage_grace(&mut self, event: Option<TransientEvent>) {
        if let Some(s) = self.stage.as_mut() {
            s.open_grace(event);
        }
    }

    /// The capture stage's counters, if there is a stage.
    pub(crate) fn stage_stats(&mut self) -> Option<CaptureStageStats> {
        self.stage.as_mut().map(|s| s.stats())
    }

    /// True once after the stage's state changed.
    pub(crate) fn take_stage_changed(&mut self) -> bool {
        self.stage.as_mut().is_some_and(|s| s.take_changed())
    }

    /// The echo canceller's delay estimate (ms).
    pub(crate) fn delay_ms(&self) -> Option<i32> {
        self.chain
            .inner
            .as_ref()
            .and_then(|a| a.statistics().delay_ms)
    }

    /// The echo canceller's ERLE estimate (dB).
    pub(crate) fn erle_db(&self) -> Option<f32> {
        self.chain
            .inner
            .as_ref()
            .and_then(|a| a.statistics().echo_return_loss_enhancement)
            .map(|v| v as f32)
    }
}