Skip to main content

kessel_audio/
apm.rs

1//! Echo cancellation, noise suppression and gain control (sonora, a pure
2//! Rust port of WebRTC's audio processing module), and the caller's
3//! capture stage between them.
4//!
5//! The playback mix is the echo reference: every 10 ms block the engine
6//! plays is passed to [`Apm::render`] before it reaches the device.
7
8use crate::error::AudioError;
9use crate::frame::{BLOCK_SAMPLES, SAMPLE_RATE};
10use crate::stage::{
11    CaptureStage, CaptureStageStats, StageClock, StageRunner, StageTiming, TransientEvent,
12    DEFAULT_STAGE_GRACE, DEFAULT_STAGE_STARVATION_CUTOFF,
13};
14use sonora::config::{
15    AdaptiveDigital, EchoCanceller, FixedDigital, GainController2, HighPassFilter,
16    MaxProcessingRate, NoiseSuppression, NoiseSuppressionLevel, Pipeline,
17};
18use std::time::Duration;
19
20/// Noise-suppression strength.
21#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
22pub enum NoiseSuppressionStrength {
23    /// About 6 dB.
24    Low,
25    /// About 12 dB (the default).
26    Moderate,
27    /// About 18 dB.
28    High,
29    /// About 21 dB.
30    VeryHigh,
31}
32
33/// Which processing runs on the capture path.
34///
35/// `#[non_exhaustive]`: start from [`ProcessingConfig::default`] or
36/// [`ProcessingConfig::off`], then set fields or use the `with_` methods.
37#[non_exhaustive]
38pub struct ProcessingConfig {
39    /// Acoustic echo cancellation (AEC3) against the playback mix.
40    pub echo_cancellation: bool,
41    /// Noise suppression, or `None` for off. Turn it off when a
42    /// [`capture_stage`](Self::capture_stage) removes noise: two
43    /// suppressors in a row add artefacts for no gain. The engine doesn't
44    /// decide that for you.
45    pub noise_suppression: Option<NoiseSuppressionStrength>,
46    /// Automatic gain control (AGC2 adaptive digital, plus its limiter).
47    pub gain_control: bool,
48    /// The high-pass filter (removes DC and rumble below about 100 Hz).
49    /// Echo cancellation turns it on regardless.
50    pub high_pass: bool,
51    /// The caller's own processing, after the high-pass filter, echo
52    /// cancellation and noise suppression (if set) and before gain control.
53    /// See [`CaptureStage`] for the rules, the time budget and the bypass.
54    /// Levels, VAD and DTX read the signal after the stage and gain control.
55    ///
56    /// `None` (the default) runs exactly what 0.1 ran. With a stage, echo
57    /// cancellation and gain control run in two sonora instances with the
58    /// stage between them.
59    pub capture_stage: Option<Box<dyn CaptureStage>>,
60    /// The step-down floor: sonora's noise suppression at this strength
61    /// stands in while the capture stage is bypassed (over budget or a
62    /// fault), and stops again when a retry brings the stage back. The
63    /// switch crossfades over one 10 ms block and keeps the stage's timing.
64    /// Default `Some(Moderate)`, as 0.1 runs it.
65    ///
66    /// It only applies with a stage set and
67    /// [`noise_suppression`](Self::noise_suppression) `None` (otherwise
68    /// noise suppression already runs before the stage). The suppressor
69    /// runs on every block in its own sonora instance, so it is converged
70    /// the moment it is needed; it allocates nothing per block, and costs
71    /// its band split and merge on top of the suppression 0.1 ran: about
72    /// 0.5% of a core (50–54 µs per 10 ms block, measured on x86-64). Its own delay (334 samples,
73    /// 7 ms) is taken out of the stage's latency, so the timing holds for a
74    /// stage with at least that much latency (a shorter one: the suppressed
75    /// signal is that much later). `None` turns the floor off: a bypassed
76    /// stage leaves no suppression.
77    ///
78    /// Known behaviour: the phone backend's raw mode
79    /// (`PhoneMode::Raw`, iOS and Android) never runs this floor, whatever
80    /// it is set to, as it runs no noise suppression at all. A capture stage
81    /// on raw capture that is bypassed leaves the signal unsuppressed until
82    /// its retry. That only matters for a stage that removes noise on raw
83    /// capture.
84    pub stage_fallback_noise_suppression: Option<NoiseSuppressionStrength>,
85    /// The capture stage's grace window: for this long (in capture, rounded
86    /// up to 10 ms blocks) after a
87    /// [`TransientEvent`] ([`crate::AudioEngine::transient_event`]), the
88    /// stage's start or a capture stream (re)start, slow calls don't count
89    /// toward a strike; they are still timed and reported (see
90    /// [`CaptureStage`]). Default [`DEFAULT_STAGE_GRACE`] (1.5 s); at most
91    /// [`crate::MAX_STAGE_GRACE`] (10 s), or [`crate::AudioEngine::start`]
92    /// refuses the config. `Duration::ZERO` turns the grace off: the budget
93    /// applies from the first call, as in 0.2.1. Only applies with a stage
94    /// set.
95    pub stage_grace: Duration,
96    /// What times the capture stage's calls for its time budget (see
97    /// [`StageClock`]). Default [`StageClock::default`]: the processing
98    /// thread's CPU time ([`StageClock::ThreadCpu`]) where the platform
99    /// supports it (macOS, iOS, Linux and Android), else the wall clock.
100    /// [`StageClock::Wall`] times as 0.2.2 and earlier did. Only applies
101    /// with a stage set.
102    pub stage_clock: StageClock,
103    /// With [`StageClock::ThreadCpu`]: a call that takes this long or longer
104    /// on the wall clock counts as slow toward the 2-in-a-row rule whatever
105    /// its CPU time, so a thread that really is starved is still caught
106    /// (counted in [`CaptureStageStats::starved`]). Default
107    /// [`DEFAULT_STAGE_STARVATION_CUTOFF`] (20 ms); at least 9 ms (the hard
108    /// budget), or [`crate::AudioEngine::start`] refuses the config.
109    /// `Duration::MAX` leaves CPU time alone to decide. Ignored with
110    /// [`StageClock::Wall`] (every call counts its wall time there). Only
111    /// applies with a stage set.
112    pub stage_starvation_cutoff: Duration,
113}
114
115impl std::fmt::Debug for ProcessingConfig {
116    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
117        f.debug_struct("ProcessingConfig")
118            .field("echo_cancellation", &self.echo_cancellation)
119            .field("noise_suppression", &self.noise_suppression)
120            .field("gain_control", &self.gain_control)
121            .field("high_pass", &self.high_pass)
122            .field(
123                "capture_stage_latency",
124                &self.capture_stage.as_ref().map(|s| s.latency_samples()),
125            )
126            .field(
127                "stage_fallback_noise_suppression",
128                &self.stage_fallback_noise_suppression,
129            )
130            .field("stage_grace", &self.stage_grace)
131            .field("stage_clock", &self.stage_clock)
132            .field("stage_starvation_cutoff", &self.stage_starvation_cutoff)
133            .finish()
134    }
135}
136
137impl Default for ProcessingConfig {
138    /// Everything on: AEC3, moderate noise suppression, AGC2 and the
139    /// high-pass filter. No capture stage.
140    fn default() -> Self {
141        ProcessingConfig {
142            echo_cancellation: true,
143            noise_suppression: Some(NoiseSuppressionStrength::Moderate),
144            gain_control: true,
145            high_pass: true,
146            capture_stage: None,
147            stage_fallback_noise_suppression: Some(NoiseSuppressionStrength::Moderate),
148            stage_grace: DEFAULT_STAGE_GRACE,
149            stage_clock: StageClock::default(),
150            stage_starvation_cutoff: DEFAULT_STAGE_STARVATION_CUTOFF,
151        }
152    }
153}
154
155impl ProcessingConfig {
156    /// No processing at all: capture passes through unchanged.
157    pub fn off() -> Self {
158        ProcessingConfig {
159            echo_cancellation: false,
160            noise_suppression: None,
161            gain_control: false,
162            high_pass: false,
163            capture_stage: None,
164            stage_fallback_noise_suppression: Some(NoiseSuppressionStrength::Moderate),
165            stage_grace: DEFAULT_STAGE_GRACE,
166            stage_clock: StageClock::default(),
167            stage_starvation_cutoff: DEFAULT_STAGE_STARVATION_CUTOFF,
168        }
169    }
170
171    /// Set the [`capture_stage`](Self::capture_stage). Noise suppression
172    /// stays as it is: turn it off with
173    /// [`with_noise_suppression(None)`](Self::with_noise_suppression) if the
174    /// stage removes noise.
175    pub fn with_capture_stage(mut self, stage: Box<dyn CaptureStage>) -> Self {
176        self.capture_stage = Some(stage);
177        self
178    }
179
180    /// Set [`noise_suppression`](Self::noise_suppression).
181    pub fn with_noise_suppression(mut self, ns: Option<NoiseSuppressionStrength>) -> Self {
182        self.noise_suppression = ns;
183        self
184    }
185
186    /// Set [`echo_cancellation`](Self::echo_cancellation).
187    pub fn with_echo_cancellation(mut self, on: bool) -> Self {
188        self.echo_cancellation = on;
189        self
190    }
191
192    /// Set [`gain_control`](Self::gain_control).
193    pub fn with_gain_control(mut self, on: bool) -> Self {
194        self.gain_control = on;
195        self
196    }
197
198    /// Set [`high_pass`](Self::high_pass).
199    pub fn with_high_pass(mut self, on: bool) -> Self {
200        self.high_pass = on;
201        self
202    }
203
204    /// Set
205    /// [`stage_fallback_noise_suppression`](Self::stage_fallback_noise_suppression).
206    pub fn with_stage_fallback_noise_suppression(
207        mut self,
208        ns: Option<NoiseSuppressionStrength>,
209    ) -> Self {
210        self.stage_fallback_noise_suppression = ns;
211        self
212    }
213
214    /// Set [`stage_grace`](Self::stage_grace).
215    pub fn with_stage_grace(mut self, grace: Duration) -> Self {
216        self.stage_grace = grace;
217        self
218    }
219
220    /// Set [`stage_clock`](Self::stage_clock).
221    /// `with_stage_clock(StageClock::Wall)` times the stage as 0.2.2 did.
222    pub fn with_stage_clock(mut self, clock: StageClock) -> Self {
223        self.stage_clock = clock;
224        self
225    }
226
227    /// Set [`stage_starvation_cutoff`](Self::stage_starvation_cutoff).
228    pub fn with_stage_starvation_cutoff(mut self, cutoff: Duration) -> Self {
229        self.stage_starvation_cutoff = cutoff;
230        self
231    }
232
233    /// How the capture stage is timed.
234    pub(crate) fn stage_timing(&self) -> StageTiming {
235        StageTiming {
236            grace: self.stage_grace,
237            clock: self.stage_clock,
238            starvation_cutoff: self.stage_starvation_cutoff,
239        }
240    }
241
242    /// What sonora runs: everything but the stage.
243    pub(crate) fn settings(&self) -> ApmSettings {
244        ApmSettings {
245            echo_cancellation: self.echo_cancellation,
246            noise_suppression: self.noise_suppression,
247            gain_control: self.gain_control,
248            high_pass: self.high_pass,
249            stage_fallback_ns: self.stage_fallback_noise_suppression,
250        }
251    }
252}
253
254/// [`ProcessingConfig`] without the stage: what sonora runs.
255#[derive(Clone, Copy, Debug, PartialEq, Eq)]
256pub(crate) struct ApmSettings {
257    pub(crate) echo_cancellation: bool,
258    pub(crate) noise_suppression: Option<NoiseSuppressionStrength>,
259    pub(crate) gain_control: bool,
260    pub(crate) high_pass: bool,
261    /// Only used with a stage (see
262    /// [`ProcessingConfig::stage_fallback_noise_suppression`]).
263    pub(crate) stage_fallback_ns: Option<NoiseSuppressionStrength>,
264}
265
266impl ApmSettings {
267    fn any(&self) -> bool {
268        self.echo_cancellation
269            || self.noise_suppression.is_some()
270            || self.gain_control
271            || self.high_pass
272    }
273}
274
275impl From<&ProcessingConfig> for ApmSettings {
276    fn from(c: &ProcessingConfig) -> Self {
277        c.settings()
278    }
279}
280
281impl From<ProcessingConfig> for ApmSettings {
282    fn from(c: ProcessingConfig) -> Self {
283        c.settings()
284    }
285}
286
287/// AGC2 adaptive-digital headroom, in dB.
288///
289/// With WebRTC's default of 5 dB, sonora 0.2.0 settles 0.7 to 1.6 dB
290/// quieter than the C++ WebRTC library. Measured on LibriSpeech speech
291/// against the C++ library (5.0 / 4.0 / 3.4 / 3.0 dB swept), 4 dB matches
292/// it best: AGC2 alone at -40 and -30 dBFS input lands at -22.8 and
293/// -23.0 dBFS (C++: -23.1, -23.1); the full chain on near-end speech at
294/// -23.5 dBFS (C++: -22.9) and in double talk at -25.5 dBFS (C++: -25.4).
295/// Every level is within 0.6 dB of the C++ library, against up to 1.6 dB
296/// with 5 dB. Quiet (-50 dBFS) and loud (-20 dBFS) input are unaffected.
297pub const AGC2_HEADROOM_DB: f32 = 4.0;
298
299/// One sonora instance for `cfg`, or `None` if it would do nothing.
300fn build(cfg: &ApmSettings, headroom_db: f32) -> Option<sonora::AudioProcessing> {
301    if !cfg.any() {
302        return None;
303    }
304    let config = sonora::Config {
305        pipeline: Pipeline {
306            maximum_internal_processing_rate: MaxProcessingRate::Rate48kHz,
307            multi_channel_render: false,
308            multi_channel_capture: false,
309            ..Pipeline::default()
310        },
311        high_pass_filter: (cfg.high_pass || cfg.echo_cancellation).then(HighPassFilter::default),
312        echo_canceller: cfg.echo_cancellation.then(EchoCanceller::default),
313        noise_suppression: cfg.noise_suppression.map(|s| NoiseSuppression {
314            level: match s {
315                NoiseSuppressionStrength::Low => NoiseSuppressionLevel::Low,
316                NoiseSuppressionStrength::Moderate => NoiseSuppressionLevel::Moderate,
317                NoiseSuppressionStrength::High => NoiseSuppressionLevel::High,
318                NoiseSuppressionStrength::VeryHigh => NoiseSuppressionLevel::VeryHigh,
319            },
320            analyze_linear_aec_output_when_available: false,
321        }),
322        gain_controller2: cfg.gain_control.then(|| GainController2 {
323            input_volume_controller: false,
324            adaptive_digital: Some(AdaptiveDigital {
325                headroom_db,
326                ..AdaptiveDigital::default()
327            }),
328            fixed_digital: FixedDigital::default(),
329        }),
330        ..Default::default()
331    };
332    Some(
333        sonora::AudioProcessing::builder()
334            .config(config)
335            .capture_config(sonora::StreamConfig::new(SAMPLE_RATE, 1))
336            .render_config(sonora::StreamConfig::new(SAMPLE_RATE, 1))
337            .build(),
338    )
339}
340
341/// One capture block through `apm`, or a copy without one.
342fn run_capture(apm: Option<&mut sonora::AudioProcessing>, x: &[f32], out: &mut [f32]) {
343    match apm {
344        Some(apm) => {
345            // Frame-size mismatches are impossible here (fixed 480-sample
346            // mono blocks), so an error would be a bug in the caller.
347            if apm.process_capture_f32(&[x], &mut [out]).is_err() {
348                debug_assert!(false, "sonora rejected a capture block");
349                out.copy_from_slice(x);
350            }
351        }
352        None => out.copy_from_slice(x),
353    }
354}
355
356/// The algorithmic delay of a noise-suppression-only sonora instance at
357/// 48 kHz, in samples (7 ms): its band split and merge (46) plus the
358/// suppressor's overlap (288). Measured (`the_step_down_lines_up_with_the_stage`).
359pub(crate) const STEP_DOWN_NS_DELAY: usize = 334;
360
361/// The step-down floor: sonora's noise suppression, run on every block on
362/// the echo canceller's output and delayed to the stage's latency, used
363/// while the stage is bypassed.
364struct StepDown {
365    ns: sonora::AudioProcessing,
366    /// This block, suppressed and delayed.
367    out: [f32; BLOCK_SAMPLES],
368    /// Tops the suppressor's own delay up to the stage's latency.
369    delay: Box<[f32]>,
370    pos: usize,
371    /// The suppressor's output was used for the last block.
372    on: bool,
373    /// The crossfade, 0 to 1 over a block (raised cosine).
374    ramp: [f32; BLOCK_SAMPLES],
375}
376
377impl StepDown {
378    fn new(strength: NoiseSuppressionStrength, stage_latency: usize) -> Option<StepDown> {
379        let ns = build(
380            &ApmSettings {
381                echo_cancellation: false,
382                noise_suppression: Some(strength),
383                gain_control: false,
384                high_pass: false,
385                stage_fallback_ns: None,
386            },
387            AGC2_HEADROOM_DB,
388        )?;
389        let mut ramp = [0.0f32; BLOCK_SAMPLES];
390        for (i, r) in ramp.iter_mut().enumerate() {
391            let t = (i as f32 + 0.5) / BLOCK_SAMPLES as f32;
392            *r = 0.5 - 0.5 * (std::f32::consts::PI * t).cos();
393        }
394        Some(StepDown {
395            ns,
396            out: [0.0; BLOCK_SAMPLES],
397            delay: vec![0.0; stage_latency.saturating_sub(STEP_DOWN_NS_DELAY)].into_boxed_slice(),
398            pos: 0,
399            on: false,
400            ramp,
401        })
402    }
403
404    /// Suppress this block of the echo canceller's output into `self.out`,
405    /// delayed to the stage's latency.
406    fn feed(&mut self, aec: &[f32; BLOCK_SAMPLES]) {
407        run_capture(Some(&mut self.ns), aec, &mut self.out);
408        let l = self.delay.len();
409        if l == 0 {
410            return;
411        }
412        for v in self.out.iter_mut() {
413            std::mem::swap(&mut self.delay[self.pos], v);
414            self.pos += 1;
415            if self.pos == l {
416                self.pos = 0;
417            }
418        }
419    }
420
421    /// `block` holds the stage's output (or the delayed echo canceller
422    /// output when bypassed); replace it with the suppressor's when
423    /// `use_ns`, crossfading over this block when that changes.
424    fn apply(&mut self, block: &mut [f32; BLOCK_SAMPLES], use_ns: bool) {
425        if use_ns != self.on {
426            for ((b, &n), &r) in block.iter_mut().zip(&self.out).zip(&self.ramp) {
427                let (from, to) = if use_ns { (*b, n) } else { (n, *b) };
428                *b = from + (to - from) * r;
429            }
430            self.on = use_ns;
431        } else if use_ns {
432            block.copy_from_slice(&self.out);
433        }
434    }
435
436    fn reset(&mut self) {
437        self.delay.fill(0.0);
438        self.pos = 0;
439    }
440}
441
442/// The sonora side of the capture path: everything but the caller's stage.
443/// Built off the processing thread (it allocates) and swapped in whole
444/// ([`Apm::replace_chain`]), so the phone backend can change what sonora
445/// runs mid-call while the stage keeps its state.
446pub(crate) struct Chain {
447    /// What this chain runs.
448    settings: ApmSettings,
449    /// Without a stage, everything in one instance (as 0.1 ran it). With
450    /// one: the high-pass filter, echo cancellation and noise suppression.
451    inner: Option<sonora::AudioProcessing>,
452    /// With a stage and gain control: AGC2 and its limiter, alone.
453    post: Option<sonora::AudioProcessing>,
454    /// With a stage, noise suppression off and the fallback on.
455    step_down: Option<StepDown>,
456}
457
458impl Chain {
459    /// The chain for `cfg`. `stage_latency` is the capture stage's latency
460    /// in samples, or `None` without a stage.
461    #[cfg_attr(
462        not(any(
463            test,
464            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
465        )),
466        allow(dead_code)
467    )]
468    pub(crate) fn new(cfg: ApmSettings, stage_latency: Option<usize>) -> Box<Chain> {
469        Box::new(Self::build(cfg, stage_latency, AGC2_HEADROOM_DB))
470    }
471
472    fn build(cfg: ApmSettings, stage_latency: Option<usize>, headroom_db: f32) -> Chain {
473        let Some(latency) = stage_latency else {
474            return Chain {
475                settings: cfg,
476                inner: build(&cfg, headroom_db),
477                post: None,
478                step_down: None,
479            };
480        };
481        let pre = ApmSettings {
482            gain_control: false,
483            stage_fallback_ns: None,
484            ..cfg
485        };
486        let post = ApmSettings {
487            echo_cancellation: false,
488            noise_suppression: None,
489            gain_control: cfg.gain_control,
490            high_pass: false,
491            stage_fallback_ns: None,
492        };
493        let step_down = match (cfg.noise_suppression, cfg.stage_fallback_ns) {
494            (None, Some(strength)) => StepDown::new(strength, latency),
495            _ => None,
496        };
497        Chain {
498            settings: cfg,
499            inner: build(&pre, headroom_db),
500            post: build(&post, headroom_db),
501            step_down,
502        }
503    }
504
505    /// What this chain runs.
506    #[cfg(test)]
507    pub(crate) fn settings(&self) -> ApmSettings {
508        self.settings
509    }
510
511    /// The sonora configs it runs: before the stage (everything, without
512    /// one), after the stage, and the step-down suppressor's.
513    #[cfg(test)]
514    pub(crate) fn sonora_configs(&self) -> [Option<&sonora::Config>; 3] {
515        [
516            self.inner.as_ref().map(|a| a.config()),
517            self.post.as_ref().map(|a| a.config()),
518            self.step_down.as_ref().map(|s| s.ns.config()),
519        ]
520    }
521}
522
523impl std::fmt::Debug for Chain {
524    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
525        f.debug_struct("Chain")
526            .field("settings", &self.settings)
527            .finish_non_exhaustive()
528    }
529}
530
531pub(crate) struct Apm {
532    chain: Chain,
533    stage: Option<StageRunner>,
534    scratch: [f32; BLOCK_SAMPLES],
535    mid: [f32; BLOCK_SAMPLES],
536}
537
538impl Apm {
539    pub(crate) fn new(cfg: impl Into<ApmSettings>) -> Self {
540        Self::with_agc_headroom(cfg, AGC2_HEADROOM_DB)
541    }
542
543    pub(crate) fn with_agc_headroom(cfg: impl Into<ApmSettings>, headroom_db: f32) -> Self {
544        Apm {
545            chain: Chain::build(cfg.into(), None, headroom_db),
546            stage: None,
547            scratch: [0.0; BLOCK_SAMPLES],
548            mid: [0.0; BLOCK_SAMPLES],
549        }
550    }
551
552    /// With a capture stage: the high-pass filter, echo cancellation and
553    /// noise suppression in one instance, then the stage, then gain control
554    /// in a second instance; and the step-down suppressor if it applies.
555    /// Build it on the thread that will run it (the stage is reset here).
556    /// `timing` is how the stage is timed (the grace window, the clock and
557    /// the starvation cutoff, from [`ProcessingConfig`]).
558    pub(crate) fn with_stage(
559        cfg: impl Into<ApmSettings>,
560        stage: Box<dyn CaptureStage>,
561        timing: StageTiming,
562    ) -> Result<Self, AudioError> {
563        Self::with_runner(cfg.into(), StageRunner::new(stage, timing)?)
564    }
565
566    /// [`Apm::with_stage`] with call times from `time`, the default clock
567    /// and no grace window (tests: the budget applies from the first call).
568    #[cfg(test)]
569    pub(crate) fn with_stage_clock(
570        cfg: impl Into<ApmSettings>,
571        stage: Box<dyn CaptureStage>,
572        time: crate::stage::TimeSource,
573    ) -> Result<Self, AudioError> {
574        let timing = StageTiming {
575            grace: Duration::ZERO,
576            ..StageTiming::default()
577        };
578        Self::with_stage_timed(cfg, stage, time, timing)
579    }
580
581    /// [`Apm::with_stage`] with call times from `time` (tests).
582    #[cfg(test)]
583    pub(crate) fn with_stage_timed(
584        cfg: impl Into<ApmSettings>,
585        stage: Box<dyn CaptureStage>,
586        time: crate::stage::TimeSource,
587        timing: StageTiming,
588    ) -> Result<Self, AudioError> {
589        Self::with_runner(cfg.into(), StageRunner::with_source(stage, time, timing)?)
590    }
591
592    fn with_runner(cfg: ApmSettings, stage: StageRunner) -> Result<Self, AudioError> {
593        Ok(Apm {
594            chain: Chain::build(cfg, Some(stage.latency()), AGC2_HEADROOM_DB),
595            stage: Some(stage),
596            scratch: [0.0; BLOCK_SAMPLES],
597            mid: [0.0; BLOCK_SAMPLES],
598        })
599    }
600
601    /// Swap in another chain (built off this thread for the same stage
602    /// latency, see [`Chain::new`]) and hand back the old one, to be freed
603    /// elsewhere. Allocates and frees nothing. The stage keeps its state;
604    /// it is reset when the capture stream restarts, as usual.
605    #[cfg_attr(
606        not(any(
607            test,
608            all(feature = "os-voice", any(target_os = "ios", target_os = "android"))
609        )),
610        allow(dead_code)
611    )]
612    pub(crate) fn replace_chain(&mut self, mut chain: Box<Chain>) -> Box<Chain> {
613        std::mem::swap(&mut self.chain, &mut *chain);
614        chain
615    }
616
617    /// The chain running now.
618    #[cfg(test)]
619    pub(crate) fn chain(&self) -> &Chain {
620        &self.chain
621    }
622
623    /// Analyse one 10 ms block of the playback mix (the echo reference).
624    pub(crate) fn render(&mut self, x: &[f32]) {
625        debug_assert_eq!(x.len(), BLOCK_SAMPLES);
626        if let Some(apm) = self.chain.inner.as_mut() {
627            // Frame-size mismatches are impossible here (fixed 480-sample
628            // mono blocks), so an error would be a bug in the caller.
629            if apm
630                .process_render_f32(&[x], &mut [&mut self.scratch[..]])
631                .is_err()
632            {
633                debug_assert!(false, "sonora rejected a render block");
634            }
635        }
636    }
637
638    /// Process one 10 ms capture block into `out`.
639    pub(crate) fn capture(&mut self, x: &[f32], out: &mut [f32]) {
640        debug_assert_eq!(x.len(), BLOCK_SAMPLES);
641        debug_assert_eq!(out.len(), BLOCK_SAMPLES);
642        let Some(stage) = self.stage.as_mut() else {
643            run_capture(self.chain.inner.as_mut(), x, out);
644            return;
645        };
646        run_capture(self.chain.inner.as_mut(), x, &mut self.mid);
647        if let Some(sd) = self.chain.step_down.as_mut() {
648            sd.feed(&self.mid);
649        }
650        stage.process(&mut self.mid);
651        if let Some(sd) = self.chain.step_down.as_mut() {
652            let use_ns = !stage.used_stage();
653            sd.apply(&mut self.mid, use_ns);
654            stage.set_fallback(use_ns);
655        }
656        run_capture(self.chain.post.as_mut(), &self.mid, out);
657    }
658
659    /// The capture stream restarted or had a gap: reset the capture stage.
660    pub(crate) fn reset_stage(&mut self) {
661        if let Some(s) = self.stage.as_mut() {
662            s.reset();
663        }
664        if let Some(sd) = self.chain.step_down.as_mut() {
665            sd.reset();
666        }
667    }
668
669    /// Open (or extend) the capture stage's grace window; `event` is the
670    /// host's reason. Without a stage, nothing.
671    pub(crate) fn open_stage_grace(&mut self, event: Option<TransientEvent>) {
672        if let Some(s) = self.stage.as_mut() {
673            s.open_grace(event);
674        }
675    }
676
677    /// The capture stage's counters, if there is a stage.
678    pub(crate) fn stage_stats(&mut self) -> Option<CaptureStageStats> {
679        self.stage.as_mut().map(|s| s.stats())
680    }
681
682    /// True once after the stage's state changed.
683    pub(crate) fn take_stage_changed(&mut self) -> bool {
684        self.stage.as_mut().is_some_and(|s| s.take_changed())
685    }
686
687    /// The echo canceller's delay estimate (ms).
688    pub(crate) fn delay_ms(&self) -> Option<i32> {
689        self.chain
690            .inner
691            .as_ref()
692            .and_then(|a| a.statistics().delay_ms)
693    }
694
695    /// The echo canceller's ERLE estimate (dB).
696    pub(crate) fn erle_db(&self) -> Option<f32> {
697        self.chain
698            .inner
699            .as_ref()
700            .and_then(|a| a.statistics().echo_return_loss_enhancement)
701            .map(|v| v as f32)
702    }
703}