Skip to main content

moq_audio/aec/
processor.rs

1use std::time::Duration;
2
3use sonora::{AudioProcessing, StreamConfig};
4
5use super::Config;
6use crate::{Error, Layout};
7
8/// Callback headroom retained from the built-in device path.
9const MAX_CALLBACK_FRAMES: usize = 4096;
10
11/// Format of one interleaved PCM stream processed by echo cancellation.
12#[derive(Clone, Copy, Debug, PartialEq, Eq)]
13#[non_exhaustive]
14pub struct Stream {
15	/// Samples per channel per second: a multiple of 100 Hz from 8 to 384 kHz,
16	/// so every 10 ms processing frame is a whole number of samples.
17	pub sample_rate: u32,
18	/// Mono or stereo channel layout.
19	pub layout: Layout,
20}
21
22impl Stream {
23	/// Describe an interleaved PCM stream.
24	pub fn new(sample_rate: u32, layout: Layout) -> Self {
25		Self { sample_rate, layout }
26	}
27
28	fn validate(self, role: &str) -> Result<StreamConfig, Error> {
29		if !(8_000..=384_000).contains(&self.sample_rate) {
30			return Err(Error::Unsupported(format!(
31				"echo cancellation needs a {role} sample rate between 8 and 384 kHz (got {})",
32				self.sample_rate
33			)));
34		}
35		// Sonora consumes `rate / 100` samples as each 10 ms frame. At a rate such as
36		// 22,050 Hz that frame is short, so the stream would drift against the other.
37		if !self.sample_rate.is_multiple_of(100) {
38			return Err(Error::Unsupported(format!(
39				"echo cancellation needs a {role} sample rate that is a multiple of 100 Hz (got {})",
40				self.sample_rate
41			)));
42		}
43
44		let channels = self.layout.channels();
45		if channels == 0 || channels > 2 {
46			return Err(Error::Unsupported(format!(
47				"echo cancellation accepts mono or stereo {role} PCM (got {channels} channels)"
48			)));
49		}
50
51		Ok(StreamConfig::new(self.sample_rate, channels as u16))
52	}
53}
54
55/// Echo-cancellation measurements, with `None` for unavailable estimates.
56#[derive(Clone, Debug, Default, PartialEq)]
57#[non_exhaustive]
58pub struct Stats {
59	/// Echo return loss in decibels.
60	pub echo_return_loss: Option<f64>,
61	/// Additional echo return loss from processing, in decibels.
62	pub echo_return_loss_enhancement: Option<f64>,
63	/// Fraction of the latest aggregation window with a divergent filter.
64	pub divergent_filter_fraction: Option<f64>,
65	/// Median estimated echo-path delay.
66	pub delay_median: Option<Duration>,
67	/// Standard deviation of the estimated echo-path delay.
68	pub delay_standard_deviation: Option<Duration>,
69	/// Current estimated echo-path delay.
70	pub delay: Option<Duration>,
71	/// Current residual echo likelihood from zero to one.
72	pub residual_echo_likelihood: Option<f64>,
73	/// Maximum recent residual echo likelihood from zero to one.
74	pub residual_echo_likelihood_recent_max: Option<f64>,
75}
76
77impl Stats {
78	fn from_sonora(stats: &sonora::AudioProcessingStats) -> Self {
79		Self {
80			echo_return_loss: stats.echo_return_loss,
81			echo_return_loss_enhancement: stats.echo_return_loss_enhancement,
82			divergent_filter_fraction: stats.divergent_filter_fraction,
83			delay_median: duration(stats.delay_median_ms),
84			delay_standard_deviation: duration(stats.delay_standard_deviation_ms),
85			delay: duration(stats.delay_ms),
86			residual_echo_likelihood: stats.residual_echo_likelihood,
87			residual_echo_likelihood_recent_max: stats.residual_echo_likelihood_recent_max,
88		}
89	}
90}
91
92/// Device-independent acoustic echo processor for interleaved `f32` PCM.
93///
94/// Give one owner every playback buffer through [`Processor::process_render`]
95/// before the microphone buffer that can contain its echo. Buffers may be any
96/// channel-aligned size. Samples outside `[-1.0, 1.0]` are clipped and
97/// non-finite samples are rejected.
98pub struct Processor {
99	config: Config,
100	render: Stream,
101	capture: Stream,
102	inner: AudioProcessing,
103	stream_delay: Duration,
104	render_pending: Vec<f32>,
105	capture_pending: Vec<f32>,
106	capture_processed: Vec<f32>,
107	render_in: Vec<f32>,
108	render_out: Vec<f32>,
109	capture_in: Vec<f32>,
110	capture_out: Vec<f32>,
111}
112
113impl Processor {
114	/// Build a processor for fixed playback and microphone formats.
115	pub fn new(config: Config, render: Stream, capture: Stream) -> Result<Self, Error> {
116		let render_config = render.validate("playback")?;
117		let capture_config = capture.validate("microphone")?;
118		let inner = build(&config, render_config, capture_config);
119
120		let render_samples = render_config.num_samples();
121		let capture_samples = capture_config.num_samples();
122		Ok(Self {
123			config,
124			render,
125			capture,
126			inner,
127			stream_delay: Duration::ZERO,
128			render_pending: Vec::with_capacity(render_samples),
129			capture_pending: Vec::with_capacity(
130				capture_samples + MAX_CALLBACK_FRAMES * capture.layout.channels() as usize,
131			),
132			capture_processed: Vec::with_capacity(
133				capture_samples + MAX_CALLBACK_FRAMES * capture.layout.channels() as usize,
134			),
135			render_in: vec![0.0; render_samples],
136			render_out: vec![0.0; render_samples],
137			capture_in: vec![0.0; capture_samples],
138			capture_out: vec![0.0; capture_samples],
139		})
140	}
141
142	/// Feed chronological playback PCM into the echo model before capture.
143	pub fn process_render(&mut self, samples: &[f32]) -> Result<(), Error> {
144		validate_samples(samples, self.render.layout.channels() as usize)?;
145
146		let Self {
147			inner,
148			render,
149			render_pending,
150			render_in,
151			render_out,
152			..
153		} = self;
154		let config = stream_config(*render);
155		let stride = config.num_samples();
156		let mut remaining = samples;
157
158		if !render_pending.is_empty() {
159			let needed = stride - render_pending.len();
160			let take = needed.min(remaining.len());
161			render_pending.extend_from_slice(&remaining[..take]);
162			remaining = &remaining[take..];
163			if render_pending.len() == stride {
164				process_frame(inner, &config, render_pending, render_in, render_out, true);
165				render_pending.clear();
166			}
167		}
168
169		let mut frames = remaining.chunks_exact(stride);
170		for frame in &mut frames {
171			process_frame(inner, &config, frame, render_in, render_out, true);
172		}
173		render_pending.extend_from_slice(frames.remainder());
174		Ok(())
175	}
176
177	/// Replace microphone PCM with the same span after echo processing.
178	///
179	/// Buffers may contain any whole number of interleaved samples. A partial
180	/// 10 ms processing frame is retained, so the first irregular buffer can end
181	/// with silence and later calls recover the same number of samples.
182	pub fn process_capture(&mut self, samples: &mut [f32]) -> Result<(), Error> {
183		validate_samples(samples, self.capture.layout.channels() as usize)?;
184
185		let Self {
186			inner,
187			capture,
188			capture_pending,
189			capture_processed,
190			capture_in,
191			capture_out,
192			..
193		} = self;
194		let config = stream_config(*capture);
195		let stride = config.num_samples();
196		capture_pending.extend_from_slice(samples);
197		let complete = capture_pending.len() / stride * stride;
198
199		for frame in capture_pending[..complete].chunks_exact(stride) {
200			process_frame(inner, &config, frame, capture_in, capture_out, false);
201			interleave(capture_out, config.num_channels() as usize, capture_processed);
202		}
203		capture_pending.drain(..complete);
204
205		let ready = capture_processed.len().min(samples.len());
206		samples[..ready].copy_from_slice(&capture_processed[..ready]);
207		samples[ready..].fill(0.0);
208		capture_processed.drain(..ready);
209		Ok(())
210	}
211
212	/// Set the render-to-capture delay with millisecond precision.
213	pub fn set_stream_delay(&mut self, delay: Duration) -> Result<(), Error> {
214		if delay > Duration::from_millis(500) || !delay.as_nanos().is_multiple_of(1_000_000) {
215			return Err(Error::Unsupported(format!(
216				"echo cancellation delay must be a whole number of milliseconds from 0 through 500 (got {delay:?})"
217			)));
218		}
219
220		self.inner
221			.set_stream_delay_ms(delay.as_millis() as i32)
222			.expect("the delay is within the supported range");
223		self.stream_delay = delay;
224		Ok(())
225	}
226
227	/// Return the configured render-to-capture delay.
228	pub fn stream_delay(&self) -> Duration {
229		self.stream_delay
230	}
231
232	#[cfg(all(feature = "capture", feature = "playback"))]
233	pub(super) fn capture(&self) -> Stream {
234		self.capture
235	}
236
237	/// Return the latest echo-cancellation measurements.
238	pub fn statistics(&self) -> Stats {
239		Stats::from_sonora(self.inner.statistics())
240	}
241
242	/// Forget adaptive and partial-frame state after a stream discontinuity.
243	pub fn reset(&mut self) {
244		let render = stream_config(self.render);
245		let capture = stream_config(self.capture);
246		self.inner = build(&self.config, render, capture);
247		self.inner
248			.set_stream_delay_ms(self.stream_delay.as_millis() as i32)
249			.expect("a previously accepted delay remains valid");
250		self.clear_buffers();
251	}
252
253	pub(super) fn clear_buffers(&mut self) {
254		self.render_pending.clear();
255		self.capture_pending.clear();
256		self.capture_processed.clear();
257	}
258
259	#[cfg(all(test, feature = "capture", feature = "playback"))]
260	pub(super) fn pending_samples(&self) -> usize {
261		self.capture_pending.len()
262	}
263
264	#[cfg(all(test, feature = "capture", feature = "playback"))]
265	pub(super) fn processed_samples(&self) -> usize {
266		self.capture_processed.len()
267	}
268}
269
270impl std::fmt::Debug for Processor {
271	fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
272		f.debug_struct("Processor")
273			.field("render", &self.render)
274			.field("capture", &self.capture)
275			.field("stream_delay", &self.stream_delay)
276			.finish_non_exhaustive()
277	}
278}
279
280fn build(config: &Config, render: StreamConfig, capture: StreamConfig) -> AudioProcessing {
281	AudioProcessing::builder()
282		.capture_config(capture)
283		.render_config(render)
284		.config(config.build())
285		.echo_detector(config.residual_echo_detection)
286		.build()
287}
288
289fn stream_config(stream: Stream) -> StreamConfig {
290	StreamConfig::new(stream.sample_rate, stream.layout.channels() as u16)
291}
292
293fn validate_samples(samples: &[f32], channels: usize) -> Result<(), Error> {
294	if !samples.len().is_multiple_of(channels) {
295		return Err(Error::Misaligned {
296			got: samples.len(),
297			expected: samples.len().next_multiple_of(channels),
298		});
299	}
300	if samples.iter().any(|sample| !sample.is_finite()) {
301		return Err(Error::Unsupported(
302			"echo cancellation PCM samples must be finite".into(),
303		));
304	}
305	Ok(())
306}
307
308fn process_frame(
309	processor: &mut AudioProcessing,
310	config: &StreamConfig,
311	input: &[f32],
312	planar_in: &mut [f32],
313	planar_out: &mut [f32],
314	render: bool,
315) {
316	let channels = config.num_channels() as usize;
317	deinterleave(input, planar_in, channels);
318	let result = match channels {
319		1 if render => processor.process_render_f32_with_config(&[planar_in], config, config, &mut [planar_out]),
320		1 => processor.process_capture_f32_with_config(&[planar_in], config, config, &mut [planar_out]),
321		_ => {
322			let frame = config.num_frames();
323			let (left, right) = planar_in.split_at(frame);
324			let (left_out, right_out) = planar_out.split_at_mut(frame);
325			if render {
326				processor.process_render_f32_with_config(&[left, right], config, config, &mut [left_out, right_out])
327			} else {
328				processor.process_capture_f32_with_config(&[left, right], config, config, &mut [left_out, right_out])
329			}
330		}
331	};
332	result.expect("stream formats were validated at construction");
333}
334
335fn duration(milliseconds: Option<i32>) -> Option<Duration> {
336	milliseconds.and_then(|value| u64::try_from(value).ok().map(Duration::from_millis))
337}
338
339fn deinterleave(src: &[f32], dest: &mut [f32], channels: usize) {
340	let frames = src.len() / channels;
341	for (channel, samples) in dest.chunks_exact_mut(frames).enumerate() {
342		for (frame, sample) in samples.iter_mut().enumerate() {
343			*sample = src[frame * channels + channel].clamp(-1.0, 1.0);
344		}
345	}
346}
347
348fn interleave(src: &[f32], channels: usize, dest: &mut Vec<f32>) {
349	let frames = src.len() / channels;
350	for frame in 0..frames {
351		for channel in 0..channels {
352			dest.push(src[channel * frames + frame]);
353		}
354	}
355}
356
357#[cfg(test)]
358mod tests {
359	use std::collections::VecDeque;
360
361	use super::*;
362
363	fn processor() -> Processor {
364		Processor::new(
365			Config {
366				noise_suppression: false,
367				auto_gain: false,
368				..Default::default()
369			},
370			Stream::new(48_000, Layout::Stereo),
371			Stream::new(48_000, Layout::Mono),
372		)
373		.unwrap()
374	}
375
376	#[test]
377	fn accepts_irregular_pcm_buffers() {
378		let mut processor = processor();
379		for frames in [64, 480, 511, 4096] {
380			processor.process_render(&vec![0.0; frames * 2]).unwrap();
381			let mut capture = vec![0.25; frames];
382			processor.process_capture(&mut capture).unwrap();
383			assert_eq!(capture.len(), frames);
384		}
385	}
386
387	#[test]
388	fn rejects_invalid_formats_and_samples() {
389		assert!(
390			Processor::new(
391				Config::default(),
392				Stream::new(4_000, Layout::Mono),
393				Stream::new(48_000, Layout::Mono),
394			)
395			.is_err()
396		);
397		assert!(
398			Processor::new(
399				Config::default(),
400				Stream::new(48_000, Layout::FivePointOne),
401				Stream::new(48_000, Layout::Mono),
402			)
403			.is_err()
404		);
405		assert!(
406			Processor::new(
407				Config::default(),
408				Stream::new(22_050, Layout::Mono),
409				Stream::new(48_000, Layout::Mono),
410			)
411			.is_err()
412		);
413		assert!(
414			Processor::new(
415				Config::default(),
416				Stream::new(48_000, Layout::Stereo),
417				Stream::new(22_050, Layout::Mono),
418			)
419			.is_err()
420		);
421
422		let mut processor = processor();
423		assert!(processor.process_render(&[0.0, 0.0, 0.0]).is_err());
424		assert!(processor.process_render(&[f32::NAN, 0.0]).is_err());
425		let mut capture = [f32::INFINITY];
426		assert!(processor.process_capture(&mut capture).is_err());
427		let mut clipped = [1.5; 480];
428		processor.process_capture(&mut clipped).unwrap();
429		assert!(clipped.iter().all(|sample| *sample <= 1.0));
430	}
431
432	#[test]
433	fn delay_is_typed_and_bounded() {
434		let mut processor = processor();
435		processor.set_stream_delay(Duration::from_millis(140)).unwrap();
436		assert_eq!(processor.stream_delay(), Duration::from_millis(140));
437		assert!(processor.set_stream_delay(Duration::from_micros(1)).is_err());
438		assert!(processor.set_stream_delay(Duration::from_millis(501)).is_err());
439		processor.reset();
440		assert_eq!(processor.stream_delay(), Duration::from_millis(140));
441	}
442
443	#[test]
444	fn cancels_caller_supplied_echo() {
445		const DELAY: usize = 2;
446		const ATTENUATION: f32 = 0.5;
447		let mut processor = processor();
448		let mut noise = Noise::default();
449		let mut history = VecDeque::new();
450		let mut heard = 0.0;
451		let mut left = 0.0;
452
453		for round in 0..200 {
454			let played: Vec<f32> = (0..480).map(|_| noise.next()).collect();
455			let render: Vec<f32> = played.iter().flat_map(|sample| [*sample, *sample]).collect();
456			processor.process_render(&render).unwrap();
457			history.push_back(played);
458			if history.len() <= DELAY {
459				continue;
460			}
461
462			let mut echo: Vec<f32> = history
463				.pop_front()
464				.unwrap()
465				.into_iter()
466				.map(|sample| sample * ATTENUATION)
467				.collect();
468			let before = energy(&echo);
469			processor.process_capture(&mut echo).unwrap();
470			if round >= 150 {
471				heard += before;
472				left += energy(&echo);
473			}
474		}
475
476		let attenuation = 10.0 * (heard / left.max(f64::MIN_POSITIVE)).log10();
477		assert!(attenuation > 20.0, "echo was only attenuated by {attenuation:.1} dB");
478	}
479
480	fn energy(samples: &[f32]) -> f64 {
481		samples.iter().map(|sample| (*sample as f64).powi(2)).sum()
482	}
483
484	#[derive(Default)]
485	struct Noise(u32);
486
487	impl Noise {
488		fn next(&mut self) -> f32 {
489			if self.0 == 0 {
490				self.0 = 0x1234_5678;
491			}
492			self.0 ^= self.0 << 13;
493			self.0 ^= self.0 >> 17;
494			self.0 ^= self.0 << 5;
495			self.0 as f32 / u32::MAX as f32 - 0.5
496		}
497	}
498}