use crate::error::AudioError;
use crate::frame::{BLOCK_SAMPLES, SAMPLE_RATE};
use crate::stage::{
CaptureStage, CaptureStageStats, StageClock, StageRunner, StageTiming, TransientEvent,
DEFAULT_STAGE_GRACE, DEFAULT_STAGE_STARVATION_CUTOFF,
};
use sonora::config::{
AdaptiveDigital, EchoCanceller, FixedDigital, GainController2, HighPassFilter,
MaxProcessingRate, NoiseSuppression, NoiseSuppressionLevel, Pipeline,
};
use std::time::Duration;
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
pub enum NoiseSuppressionStrength {
Low,
Moderate,
High,
VeryHigh,
}
#[non_exhaustive]
pub struct ProcessingConfig {
pub echo_cancellation: bool,
pub noise_suppression: Option<NoiseSuppressionStrength>,
pub gain_control: bool,
pub high_pass: bool,
pub capture_stage: Option<Box<dyn CaptureStage>>,
pub stage_fallback_noise_suppression: Option<NoiseSuppressionStrength>,
pub stage_grace: Duration,
pub stage_clock: StageClock,
pub stage_starvation_cutoff: 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)
.field("stage_clock", &self.stage_clock)
.field("stage_starvation_cutoff", &self.stage_starvation_cutoff)
.finish()
}
}
impl Default for ProcessingConfig {
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,
stage_clock: StageClock::default(),
stage_starvation_cutoff: DEFAULT_STAGE_STARVATION_CUTOFF,
}
}
}
impl ProcessingConfig {
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,
stage_clock: StageClock::default(),
stage_starvation_cutoff: DEFAULT_STAGE_STARVATION_CUTOFF,
}
}
pub fn with_capture_stage(mut self, stage: Box<dyn CaptureStage>) -> Self {
self.capture_stage = Some(stage);
self
}
pub fn with_noise_suppression(mut self, ns: Option<NoiseSuppressionStrength>) -> Self {
self.noise_suppression = ns;
self
}
pub fn with_echo_cancellation(mut self, on: bool) -> Self {
self.echo_cancellation = on;
self
}
pub fn with_gain_control(mut self, on: bool) -> Self {
self.gain_control = on;
self
}
pub fn with_high_pass(mut self, on: bool) -> Self {
self.high_pass = on;
self
}
pub fn with_stage_fallback_noise_suppression(
mut self,
ns: Option<NoiseSuppressionStrength>,
) -> Self {
self.stage_fallback_noise_suppression = ns;
self
}
pub fn with_stage_grace(mut self, grace: Duration) -> Self {
self.stage_grace = grace;
self
}
pub fn with_stage_clock(mut self, clock: StageClock) -> Self {
self.stage_clock = clock;
self
}
pub fn with_stage_starvation_cutoff(mut self, cutoff: Duration) -> Self {
self.stage_starvation_cutoff = cutoff;
self
}
pub(crate) fn stage_timing(&self) -> StageTiming {
StageTiming {
grace: self.stage_grace,
clock: self.stage_clock,
starvation_cutoff: self.stage_starvation_cutoff,
}
}
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,
}
}
}
#[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,
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()
}
}
pub const AGC2_HEADROOM_DB: f32 = 4.0;
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(),
)
}
fn run_capture(apm: Option<&mut sonora::AudioProcessing>, x: &[f32], out: &mut [f32]) {
match apm {
Some(apm) => {
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),
}
}
pub(crate) const STEP_DOWN_NS_DELAY: usize = 334;
struct StepDown {
ns: sonora::AudioProcessing,
out: [f32; BLOCK_SAMPLES],
delay: Box<[f32]>,
pos: usize,
on: bool,
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,
})
}
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;
}
}
}
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;
}
}
pub(crate) struct Chain {
settings: ApmSettings,
inner: Option<sonora::AudioProcessing>,
post: Option<sonora::AudioProcessing>,
step_down: Option<StepDown>,
}
impl Chain {
#[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,
}
}
#[cfg(test)]
pub(crate) fn settings(&self) -> ApmSettings {
self.settings
}
#[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],
}
}
pub(crate) fn with_stage(
cfg: impl Into<ApmSettings>,
stage: Box<dyn CaptureStage>,
timing: StageTiming,
) -> Result<Self, AudioError> {
Self::with_runner(cfg.into(), StageRunner::new(stage, timing)?)
}
#[cfg(test)]
pub(crate) fn with_stage_clock(
cfg: impl Into<ApmSettings>,
stage: Box<dyn CaptureStage>,
time: crate::stage::TimeSource,
) -> Result<Self, AudioError> {
let timing = StageTiming {
grace: Duration::ZERO,
..StageTiming::default()
};
Self::with_stage_timed(cfg, stage, time, timing)
}
#[cfg(test)]
pub(crate) fn with_stage_timed(
cfg: impl Into<ApmSettings>,
stage: Box<dyn CaptureStage>,
time: crate::stage::TimeSource,
timing: StageTiming,
) -> Result<Self, AudioError> {
Self::with_runner(cfg.into(), StageRunner::with_source(stage, time, timing)?)
}
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],
})
}
#[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
}
#[cfg(test)]
pub(crate) fn chain(&self) -> &Chain {
&self.chain
}
pub(crate) fn render(&mut self, x: &[f32]) {
debug_assert_eq!(x.len(), BLOCK_SAMPLES);
if let Some(apm) = self.chain.inner.as_mut() {
if apm
.process_render_f32(&[x], &mut [&mut self.scratch[..]])
.is_err()
{
debug_assert!(false, "sonora rejected a render block");
}
}
}
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);
}
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();
}
}
pub(crate) fn open_stage_grace(&mut self, event: Option<TransientEvent>) {
if let Some(s) = self.stage.as_mut() {
s.open_grace(event);
}
}
pub(crate) fn stage_stats(&mut self) -> Option<CaptureStageStats> {
self.stage.as_mut().map(|s| s.stats())
}
pub(crate) fn take_stage_changed(&mut self) -> bool {
self.stage.as_mut().is_some_and(|s| s.take_changed())
}
pub(crate) fn delay_ms(&self) -> Option<i32> {
self.chain
.inner
.as_ref()
.and_then(|a| a.statistics().delay_ms)
}
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)
}
}