1use 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#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
22pub enum NoiseSuppressionStrength {
23 Low,
25 Moderate,
27 High,
29 VeryHigh,
31}
32
33#[non_exhaustive]
38pub struct ProcessingConfig {
39 pub echo_cancellation: bool,
41 pub noise_suppression: Option<NoiseSuppressionStrength>,
46 pub gain_control: bool,
48 pub high_pass: bool,
51 pub capture_stage: Option<Box<dyn CaptureStage>>,
60 pub stage_fallback_noise_suppression: Option<NoiseSuppressionStrength>,
85 pub stage_grace: Duration,
96 pub stage_clock: StageClock,
103 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 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 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 pub fn with_capture_stage(mut self, stage: Box<dyn CaptureStage>) -> Self {
176 self.capture_stage = Some(stage);
177 self
178 }
179
180 pub fn with_noise_suppression(mut self, ns: Option<NoiseSuppressionStrength>) -> Self {
182 self.noise_suppression = ns;
183 self
184 }
185
186 pub fn with_echo_cancellation(mut self, on: bool) -> Self {
188 self.echo_cancellation = on;
189 self
190 }
191
192 pub fn with_gain_control(mut self, on: bool) -> Self {
194 self.gain_control = on;
195 self
196 }
197
198 pub fn with_high_pass(mut self, on: bool) -> Self {
200 self.high_pass = on;
201 self
202 }
203
204 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 pub fn with_stage_grace(mut self, grace: Duration) -> Self {
216 self.stage_grace = grace;
217 self
218 }
219
220 pub fn with_stage_clock(mut self, clock: StageClock) -> Self {
223 self.stage_clock = clock;
224 self
225 }
226
227 pub fn with_stage_starvation_cutoff(mut self, cutoff: Duration) -> Self {
229 self.stage_starvation_cutoff = cutoff;
230 self
231 }
232
233 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 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#[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 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
287pub const AGC2_HEADROOM_DB: f32 = 4.0;
298
299fn 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
341fn run_capture(apm: Option<&mut sonora::AudioProcessing>, x: &[f32], out: &mut [f32]) {
343 match apm {
344 Some(apm) => {
345 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
356pub(crate) const STEP_DOWN_NS_DELAY: usize = 334;
360
361struct StepDown {
365 ns: sonora::AudioProcessing,
366 out: [f32; BLOCK_SAMPLES],
368 delay: Box<[f32]>,
370 pos: usize,
371 on: bool,
373 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 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 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
442pub(crate) struct Chain {
447 settings: ApmSettings,
449 inner: Option<sonora::AudioProcessing>,
452 post: Option<sonora::AudioProcessing>,
454 step_down: Option<StepDown>,
456}
457
458impl Chain {
459 #[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 #[cfg(test)]
507 pub(crate) fn settings(&self) -> ApmSettings {
508 self.settings
509 }
510
511 #[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 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 #[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 #[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 #[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 #[cfg(test)]
619 pub(crate) fn chain(&self) -> &Chain {
620 &self.chain
621 }
622
623 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 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 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 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 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 pub(crate) fn stage_stats(&mut self) -> Option<CaptureStageStats> {
679 self.stage.as_mut().map(|s| s.stats())
680 }
681
682 pub(crate) fn take_stage_changed(&mut self) -> bool {
684 self.stage.as_mut().is_some_and(|s| s.take_changed())
685 }
686
687 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 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}