Skip to main content

moq_audio/
aec.rs

1//! Acoustic echo cancellation: keep the speaker out of the microphone.
2//!
3//! Without this, anyone on a laptop without a headset sends the rest of the call
4//! back to itself. [`Processor`] accepts interleaved playback and microphone PCM
5//! from any audio stack. With both `capture` and `playback`, `Control` also wires
6//! a `playback::Engine` directly to `capture::Config`:
7//!
8//! ```no_run
9//! # async fn example() -> Result<(), moq_audio::Error> {
10//! use moq_audio::{aec, Layout};
11//!
12//! let mut processor = aec::Processor::new(
13//!     aec::Config::default(),
14//!     aec::Stream::new(48_000, Layout::Stereo),
15//!     aec::Stream::new(48_000, Layout::Mono),
16//! )?;
17//! processor.process_render(&[0.0; 960])?;
18//! let mut microphone = [0.0; 480];
19//! processor.process_capture(&mut microphone)?;
20//! # Ok(())
21//! # }
22//! ```
23//!
24//! One device control owns one adaptive filter and one playback reference. Its clones
25//! can toggle that filter, but only one live microphone can attach to it. A
26//! second capture fails explicitly until the first releases its attachment.
27//!
28//! With the built-in devices, the work happens in the microphone callback, on
29//! 10 ms frames, which adds up to 10 ms of latency to the capture path. Both the
30//! echo reference and the microphone are processed there, in that order, which
31//! is the ordering the echo model needs.
32
33#[cfg(all(feature = "capture", feature = "playback"))]
34use std::fmt;
35#[cfg(all(feature = "capture", feature = "playback"))]
36use std::sync::atomic::{AtomicBool, AtomicU64, Ordering};
37#[cfg(all(feature = "capture", feature = "playback"))]
38use std::sync::{Arc, Mutex, Weak};
39#[cfg(all(feature = "capture", feature = "playback"))]
40use std::time::Duration;
41
42#[cfg(all(feature = "capture", feature = "playback"))]
43use crate::Error;
44#[cfg(all(feature = "capture", feature = "playback"))]
45use crate::playback::{self, REFERENCE_CHANNELS};
46#[cfg(all(feature = "capture", feature = "playback"))]
47use crate::ring;
48use sonora::config::{EchoCanceller, GainController2, NoiseSuppression, NoiseSuppressionLevel};
49
50mod processor;
51pub use processor::{Processor, Stats, Stream};
52
53/// Sample rate the echo reference is resampled to on its way out of the mixer.
54///
55/// Fixed rather than the device's, so switching to a 44.1 kHz output doesn't
56/// invalidate an adaptive filter that spent seconds converging. Devices run at
57/// 48 kHz far more often than not, in which case this resamples nothing.
58#[cfg(all(feature = "capture", feature = "playback"))]
59const REFERENCE_RATE: u32 = 48_000;
60
61/// Slack between the output callback and the microphone callback, for the
62/// jitter between two independently scheduled threads.
63///
64/// Not a target depth. The microphone callback drains this queue every pass, so
65/// what it holds is only what the output callback has produced since, and the
66/// reference keeps the full head start the output hardware's own buffering
67/// gives it. A standing queue here would be subtracted from that head start,
68/// and a device that buffers less than the queue holds would see its echo
69/// arrive before the reference describing it, which is a reference the model
70/// cannot use at all.
71#[cfg(all(feature = "capture", feature = "playback"))]
72const REFERENCE_LATENCY: Duration = Duration::from_millis(10);
73
74/// Ceiling on that queue, bounding what a closed microphone can pin.
75#[cfg(all(feature = "capture", feature = "playback"))]
76const REFERENCE_CAPACITY: Duration = Duration::from_millis(200);
77
78/// Samples per channel in one 10 ms reference frame.
79#[cfg(all(feature = "capture", feature = "playback"))]
80const REFERENCE_FRAME: usize = REFERENCE_RATE as usize / 100;
81
82/// Echo cancellation settings.
83///
84/// `#[non_exhaustive]`: construct via [`Config::default`] and set fields, so new
85/// options can be added without breaking callers.
86#[derive(Clone, Debug)]
87#[non_exhaustive]
88pub struct Config {
89	/// Also suppress steady background noise: fans, hum, street noise.
90	///
91	/// On by default, matching what a browser gives a call. Turn it off to
92	/// capture music, or anything else where "steady" doesn't mean "unwanted".
93	pub noise_suppression: bool,
94
95	/// Also level the microphone toward a consistent loudness.
96	///
97	/// On by default, again matching the browser. Turn it off when the input
98	/// level is already managed, e.g. by an audio interface.
99	pub auto_gain: bool,
100
101	/// Also estimate the likelihood that echo remains after processing.
102	///
103	/// Off by default because it adds work and is only needed when
104	/// [`Stats::residual_echo_likelihood`] is observed.
105	pub residual_echo_detection: bool,
106}
107
108impl Default for Config {
109	fn default() -> Self {
110		Self {
111			noise_suppression: true,
112			auto_gain: true,
113			residual_echo_detection: false,
114		}
115	}
116}
117
118impl Config {
119	/// The settings sonora takes.
120	fn build(&self) -> sonora::Config {
121		sonora::Config {
122			echo_canceller: Some(EchoCanceller::default()),
123			noise_suppression: self.noise_suppression.then(|| NoiseSuppression {
124				level: NoiseSuppressionLevel::High,
125				..Default::default()
126			}),
127			gain_controller2: self.auto_gain.then(GainController2::default),
128			..Default::default()
129		}
130	}
131}
132
133/// Controls echo cancellation between one [`playback::Engine`] and microphone.
134///
135/// Built by [`Engine::canceller`](playback::Engine::canceller) and handed to
136/// [`capture::Config::aec`](crate::capture::Config::aec), which is the whole of
137/// the usual surface.
138///
139/// Cheap to clone. Every clone can toggle the same adaptive filter, but capture
140/// acquires an exclusive attachment before opening a microphone, so clones
141/// cannot run that state against two inputs. The playback reference goes away
142/// when the last control and attachment drop.
143#[cfg(all(feature = "capture", feature = "playback"))]
144#[derive(Clone)]
145pub struct Control {
146	inner: Arc<Inner>,
147}
148
149#[cfg(all(feature = "capture", feature = "playback"))]
150impl Control {
151	/// Register echo cancellation against a running engine.
152	///
153	/// `pub(crate)`: [`Engine::canceller`](playback::Engine::canceller) is the
154	/// entry point, so a control cannot exist without the reference it needs.
155	pub(crate) fn new(shared: Arc<playback::Shared>, config: Config) -> Result<Self, Error> {
156		static NEXT_ID: AtomicU64 = AtomicU64::new(0);
157
158		let inner = Arc::new(Inner {
159			id: NEXT_ID.fetch_add(1, Ordering::Relaxed),
160			enabled: AtomicBool::new(true),
161			attached: AtomicBool::new(false),
162			discontinuous: AtomicBool::new(false),
163			config,
164			state: Arc::new(Mutex::new(State::default())),
165			shared: shared.clone(),
166		});
167
168		shared.set_reference(Reference {
169			id: inner.id,
170			alive: Arc::downgrade(&inner),
171			state: inner.state.clone(),
172			pending: None,
173		})?;
174
175		Ok(Self { inner })
176	}
177
178	/// Turn cancellation on or off without reopening any device.
179	///
180	/// Off is a straight passthrough, so the 10 ms of latency goes with it. The
181	/// adaptive filter stops adapting while off and needs a moment to
182	/// re-converge once it comes back.
183	pub fn set_enabled(&self, enabled: bool) {
184		self.inner.enabled.store(enabled, Ordering::Relaxed);
185	}
186
187	/// Whether cancellation is running. Starts out `true`.
188	pub fn enabled(&self) -> bool {
189		self.inner.enabled.load(Ordering::Relaxed)
190	}
191
192	/// Attach the adaptive state to a microphone with this format.
193	///
194	/// Called when `capture` opens a device, so the allocation lands there
195	/// rather than in the first callback. This runs again every time capture
196	/// reopens after a stop or device failure: the adaptive filter survives that as long as the format hasn't
197	/// changed, since it is still the same room.
198	pub(crate) fn attach(&self, sample_rate: u32, channels: u32) -> Result<Attachment, Error> {
199		let capture = Stream::new(sample_rate, crate::Layout::from_channels(channels)?);
200		// Built outside the lock: this allocates, and the microphone callback
201		// takes the same lock. Processor construction also rejects unsupported
202		// formats while there is still a caller to hand an error to.
203		let processor = Processor::new(
204			self.inner.config.clone(),
205			Stream::new(REFERENCE_RATE, crate::Layout::Stereo),
206			capture,
207		)?;
208
209		if self
210			.inner
211			.attached
212			.compare_exchange(false, true, Ordering::Acquire, Ordering::Relaxed)
213			.is_err()
214		{
215			return Err(Error::Busy("echo canceller is attached to another microphone".into()));
216		}
217
218		let mut state = self.inner.state.lock().unwrap();
219		let same_capture = state
220			.processor
221			.as_ref()
222			.is_some_and(|processor| processor.capture() == capture);
223		if !same_capture {
224			state.processor = Some(processor);
225		} else {
226			state.reset();
227		}
228
229		// Nothing drained the tap while the microphone was closed, so it holds
230		// whatever was playing back then. Feeding that in as if it were current
231		// would put the echo model seconds out.
232		if let Some(reference) = &mut state.reference {
233			reference.discard(reference.available());
234		}
235
236		drop(state);
237		Ok(Attachment {
238			inner: self.inner.clone(),
239		})
240	}
241
242	/// Number of microphone samples waiting for a complete AEC frame.
243	#[cfg(test)]
244	pub(crate) fn pending_samples(&self) -> usize {
245		self.inner
246			.state
247			.lock()
248			.unwrap()
249			.processor
250			.as_ref()
251			.map_or(0, Processor::pending_samples)
252	}
253}
254
255#[cfg(all(feature = "capture", feature = "playback"))]
256impl fmt::Debug for Control {
257	fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
258		f.debug_struct("Control")
259			.field("enabled", &self.enabled())
260			.finish_non_exhaustive()
261	}
262}
263
264/// The exclusive microphone-side attachment to an echo canceller.
265///
266/// Capture owns this for exactly one live stream. Dropping it releases the
267/// adaptive state for a later microphone while cloned [`Control`] handles stay
268/// valid for UI toggles.
269#[cfg(all(feature = "capture", feature = "playback"))]
270pub(crate) struct Attachment {
271	inner: Arc<Inner>,
272}
273
274#[cfg(all(feature = "capture", feature = "playback"))]
275impl Attachment {
276	/// Replace the microphone samples in `buf` with the same span, minus the
277	/// echo.
278	///
279	/// Interleaved at the format passed to [`Control::attach`]. Runs on the
280	/// microphone callback thread, so it never waits for the playback driver.
281	/// Contention during a reference switch passes this buffer through; the
282	/// next callback resumes cancellation.
283	pub(crate) fn process(&self, buf: &mut [f32]) {
284		let enabled = self.inner.enabled.load(Ordering::Relaxed);
285		let Ok(mut state) = self.inner.state.try_lock() else {
286			self.mark_discontinuous();
287			return;
288		};
289		if self.inner.discontinuous.swap(false, Ordering::Relaxed) {
290			state.reset();
291		}
292		state.process(buf, enabled);
293	}
294
295	/// Discard partial frames before processing the next capture buffer.
296	pub(crate) fn mark_discontinuous(&self) {
297		self.inner.discontinuous.store(true, Ordering::Relaxed);
298	}
299}
300
301#[cfg(all(feature = "capture", feature = "playback"))]
302impl Drop for Attachment {
303	fn drop(&mut self) {
304		let mut state = self.inner.state.lock().unwrap();
305		state.reset();
306		if let Some(reference) = &mut state.reference {
307			reference.discard(reference.available());
308		}
309		drop(state);
310		self.inner.attached.store(false, Ordering::Release);
311	}
312}
313
314/// The shared half: what the microphone callback locks, and what the playback
315/// driver swaps a new reference into.
316#[cfg(all(feature = "capture", feature = "playback"))]
317struct Inner {
318	/// Distinguishes this canceller from a later one built on the same engine,
319	/// so dropping the first doesn't take the second's tap with it.
320	id: u64,
321	enabled: AtomicBool,
322	/// Whether a live capture stream owns the adaptive state.
323	attached: AtomicBool,
324	/// Whether capture continuity broke since the last processed callback.
325	discontinuous: AtomicBool,
326	config: Config,
327	/// Behind its own `Arc` so the playback driver can reach it without holding
328	/// a handle on this `Inner`. Dropping such a handle from inside the driver's
329	/// own lock would re-enter it through [`Inner::drop`] below.
330	state: Arc<Mutex<State>>,
331	/// The engine's registry, so dropping the last clone removes the tap.
332	shared: Arc<playback::Shared>,
333}
334
335#[cfg(all(feature = "capture", feature = "playback"))]
336impl Drop for Inner {
337	fn drop(&mut self) {
338		self.shared.clear_reference(self.id);
339	}
340}
341
342/// Everything the microphone callback accesses while it holds the lock.
343///
344/// Only the playback driver on a reference switch contends, and the callback
345/// passes that buffer through rather than waiting.
346#[cfg(all(feature = "capture", feature = "playback"))]
347struct State {
348	/// `None` until a microphone opens and reports its format.
349	processor: Option<Processor>,
350	/// Reference from the output mixer, replaced whenever the output stream is
351	/// rebuilt and `None` while none is running.
352	reference: Option<ring::Consumer>,
353
354	/// Whether the last callback cancelled, so a toggle can drop the buffers
355	/// that no longer line up.
356	running: bool,
357	/// One interleaved reference frame, read from [`State::reference`].
358	reference_frame: Vec<f32>,
359}
360
361#[cfg(all(feature = "capture", feature = "playback"))]
362impl Default for State {
363	fn default() -> Self {
364		Self {
365			processor: None,
366			reference: None,
367			running: false,
368			reference_frame: vec![0.0; REFERENCE_FRAME * REFERENCE_CHANNELS],
369		}
370	}
371}
372
373#[cfg(all(feature = "capture", feature = "playback"))]
374impl State {
375	/// Forget the samples in flight, because the stream they belong to is gone.
376	fn reset(&mut self) {
377		if let Some(processor) = &mut self.processor {
378			processor.clear_buffers();
379		}
380		self.running = false;
381	}
382
383	fn process(&mut self, buf: &mut [f32], enabled: bool) {
384		let Self {
385			processor,
386			reference,
387			running,
388			reference_frame,
389			..
390		} = self;
391
392		// No microphone has been opened against this canceller, so there is
393		// nothing to line the reference up against.
394		let Some(processor) = processor else { return };
395
396		if !enabled {
397			// Passthrough. Drop the partial frames that would otherwise
398			// resurface out of order when it is switched back on.
399			if *running {
400				processor.clear_buffers();
401				*running = false;
402			}
403			// Keep the tap empty anyway, so a toggle seconds from now starts on
404			// what is playing then rather than on what filled the queue while
405			// nobody was reading it.
406			if let Some(reference) = reference {
407				reference.discard(reference.available());
408			}
409			return;
410		}
411		*running = true;
412
413		// The reference first: the echo model has to be told what was played
414		// before it is asked to find it in the microphone.
415		//
416		// Everything the mixer has produced goes in, rather than one frame per
417		// microphone frame. Pacing it against capture would leave whatever the
418		// queue starts out holding in it forever, as a fixed delay on top of the
419		// hardware's, and a reference that trails its own echo is one the model
420		// cannot subtract. Draining instead means the reference is never older
421		// than the last output callback, so it leads the echo by however much
422		// the output device buffers, however little that is.
423		if let Some(reference) = reference {
424			// The mixer's writes are discarded until this side is marked read.
425			// Waiting for a whole frame to read first never ends on a resampled
426			// tap: the resampler's delay leaves the priming silence a few samples
427			// short of one, and nothing is ever written to make up the rest.
428			reference.start();
429			while reference.available() >= REFERENCE_FRAME {
430				reference.read(reference_frame);
431				// Preserve the reference timeline even when the mix contains an
432				// invalid sample, just as the microphone path does below.
433				for sample in &mut *reference_frame {
434					if !sample.is_finite() {
435						*sample = 0.0;
436					}
437				}
438				processor
439					.process_render(reference_frame)
440					.expect("the reference contains whole frames of finite PCM");
441			}
442		}
443
444		// Replace individual invalid samples rather than drop a callback and
445		// shift the microphone timeline against the echo reference.
446		for sample in &mut *buf {
447			if !sample.is_finite() {
448				*sample = 0.0;
449			}
450		}
451
452		processor
453			.process_capture(buf)
454			.expect("the device supplies channel-aligned finite PCM");
455	}
456}
457
458/// The echo reference as the playback driver sees it: enough to rebuild the tap
459/// when the output device changes underneath it.
460///
461/// The mirror image of a sink's registration, rebuilt at the same points. The
462/// producer goes to the mixer and the consumer to the canceller.
463#[cfg(all(feature = "capture", feature = "playback"))]
464pub(crate) struct Reference {
465	/// The canceller this belongs to, matched on removal.
466	id: u64,
467	/// Whether that canceller still exists. Never upgraded: this is held inside
468	/// the driver's lock, and the last handle to an `Inner` dropping there would
469	/// re-enter that lock.
470	alive: Weak<Inner>,
471	/// Where a rebuilt consumer is left for the microphone callback to pick up.
472	state: Arc<Mutex<State>>,
473	/// The producer waiting to be handed to a mixer, refilled by
474	/// [`rebuild`](Self::rebuild).
475	pending: Option<ring::Producer>,
476}
477
478#[cfg(all(feature = "capture", feature = "playback"))]
479impl Reference {
480	/// Whether this tap belongs to the canceller with this id.
481	pub(crate) fn owned_by(&self, id: u64) -> bool {
482		self.id == id
483	}
484
485	/// Whether the mixer has the producer, i.e. there is nothing left to retry.
486	pub(crate) fn attached(&self) -> bool {
487		self.pending.is_none()
488	}
489
490	/// The producer to hand to a running mixer, or `None` if one is already
491	/// there.
492	pub(crate) fn take(&mut self) -> Option<ring::Producer> {
493		self.pending.take()
494	}
495
496	/// Put back a producer the mixer refused, so the next attach retries.
497	pub(crate) fn restore(&mut self, prod: ring::Producer) {
498		self.pending = Some(prod);
499	}
500
501	/// Re-create the tap for an output stream now running at `rate`, handing the
502	/// canceller the new consumer.
503	///
504	/// Returns whether the canceller is still around; the driver drops the
505	/// registration when it isn't.
506	pub(crate) fn rebuild(&mut self, rate: u32) -> bool {
507		if self.alive.strong_count() == 0 {
508			return false;
509		}
510
511		let (prod, cons) = channel(rate);
512		self.state.lock().unwrap().reference = Some(cons);
513		self.pending = Some(prod);
514		true
515	}
516}
517
518/// The tap itself: the mixer pushes the device's mix in at `rate` and the
519/// canceller reads it back at [`REFERENCE_RATE`].
520#[cfg(all(feature = "capture", feature = "playback"))]
521fn channel(rate: u32) -> (ring::Producer, ring::Consumer) {
522	ring::channel(
523		REFERENCE_CHANNELS,
524		rate,
525		REFERENCE_RATE,
526		ring::Config {
527			latency: REFERENCE_LATENCY,
528			capacity: REFERENCE_CAPACITY,
529			// A near-empty queue is the normal state here, not an underflow to
530			// correct: the microphone callback drains it every pass. Padding it
531			// back up to the target depth with silence the speaker never played
532			// would be both a fabricated reference and the standing delay this
533			// is shaped to avoid.
534			correction: ring::Correction::Fixed { pad: false, trim: true },
535			comfort: false,
536		},
537	)
538}
539
540#[cfg(all(test, feature = "capture", feature = "playback"))]
541mod tests {
542	use std::collections::VecDeque;
543
544	use super::*;
545
546	/// Samples per channel in one 10 ms frame at `rate`.
547	const fn frame(rate: u32) -> usize {
548		rate as usize / 100
549	}
550
551	/// A canceller registered against an engine that never opened a device, so
552	/// the frame arithmetic can be tested without hardware.
553	fn detached() -> Control {
554		Control::new(Arc::new(playback::Shared::default()), Config::default()).unwrap()
555	}
556
557	fn opened(sample_rate: u32, channels: u32) -> Attachment {
558		detached().attach(sample_rate, channels).unwrap()
559	}
560
561	/// Give `canceller` a tap and hand back the end the mixer would push into,
562	/// built exactly as the driver builds it so the two can't drift.
563	fn tap(canceller: &Attachment) -> ring::Producer {
564		let (prod, cons) = channel(REFERENCE_RATE);
565		canceller.inner.state.lock().unwrap().reference = Some(cons);
566		prod
567	}
568
569	/// Push one 10 ms stereo frame of `value` into the tap.
570	fn play(prod: &mut ring::Producer, value: f32) {
571		prod.push(&vec![value; REFERENCE_FRAME * REFERENCE_CHANNELS]);
572	}
573
574	#[test]
575	fn rejects_formats_the_processor_cannot_take() {
576		let canceller = detached();
577		assert!(matches!(canceller.attach(4_000, 1), Err(Error::Unsupported(_))));
578		assert!(matches!(canceller.attach(48_000, 0), Err(Error::Unsupported(_))));
579		assert!(matches!(canceller.attach(48_000, 6), Err(Error::Unsupported(_))));
580		drop(canceller.attach(48_000, 1).unwrap());
581		drop(canceller.attach(16_000, 2).unwrap());
582	}
583
584	#[test]
585	fn returns_exactly_what_it_was_given() {
586		let canceller = opened(48_000, 2);
587		for frames in [64, 480, 512, 4096] {
588			let mut buf = vec![0.25f32; frames * 2];
589			canceller.process(&mut buf);
590			assert_eq!(buf.len(), frames * 2, "{frames} frames");
591		}
592	}
593
594	/// A device whose callback is a whole number of 10 ms frames pays no
595	/// latency: the frame is complete the moment it arrives.
596	#[test]
597	fn whole_frames_are_not_delayed() {
598		let canceller = opened(48_000, 1);
599		let frame = frame(48_000);
600
601		// Nothing is playing, so there is no echo to remove and a steady tone
602		// has to survive.
603		let mut loud = false;
604		for _ in 0..20 {
605			let mut buf = vec![0.5f32; frame];
606			canceller.process(&mut buf);
607			loud |= buf.iter().any(|s| s.abs() > 0.01);
608		}
609		assert!(loud, "the microphone came back silent");
610	}
611
612	/// A callback that straddles a frame boundary is short by the leftover, once,
613	/// which is where the latency comes from.
614	#[test]
615	fn partial_frames_cost_the_leftover_once() {
616		let canceller = opened(48_000, 1);
617		let frame = frame(48_000);
618
619		let mut first = vec![0.5f32; frame * 3 / 2];
620		canceller.process(&mut first);
621		let silent = first.iter().rev().take_while(|s| **s == 0.0).count();
622		assert_eq!(silent, frame / 2, "expected the leftover half-frame to be held back");
623
624		let mut second = vec![0.5f32; frame * 3 / 2];
625		canceller.process(&mut second);
626		assert_ne!(second.last(), Some(&0.0), "the leftover was never made up");
627	}
628
629	#[test]
630	fn device_path_sanitizes_non_finite_samples_without_resetting() {
631		let canceller = opened(48_000, 1);
632		let mut prod = tap(&canceller);
633		let frame = frame(48_000);
634
635		let mut first = vec![0.5f32; frame + 32];
636		canceller.process(&mut first);
637		play(&mut prod, f32::NAN);
638		let mut invalid = vec![f32::NAN; frame - 32];
639		canceller.process(&mut invalid);
640
641		assert!(invalid.iter().all(|sample| sample.is_finite()));
642		assert_eq!(
643			canceller
644				.inner
645				.state
646				.lock()
647				.unwrap()
648				.processor
649				.as_ref()
650				.unwrap()
651				.pending_samples(),
652			0,
653			"the invalid callback reset a partial frame instead of completing it"
654		);
655	}
656
657	/// Callback sizes that don't divide evenly into 10 ms must not lose samples:
658	/// the residual carries into the next call rather than being dropped.
659	#[test]
660	fn keeps_up_with_callbacks_that_straddle_frames() {
661		let canceller = opened(48_000, 1);
662		let chunk = frame(48_000) * 3 / 2;
663
664		let mut short = 0;
665		for round in 0..20 {
666			let mut buf = vec![0.5f32; chunk];
667			canceller.process(&mut buf);
668			// Past the first couple of rounds the pipeline is primed, so every
669			// callback has to come back full.
670			if round > 2 {
671				short += buf.iter().rev().take_while(|s| **s == 0.0).count();
672			}
673		}
674
675		assert_eq!(short, 0, "samples went missing after the pipeline filled");
676	}
677
678	#[test]
679	fn control_clones_toggle_one_attachment() {
680		let control = detached();
681		let ui = control.clone();
682		let canceller = control.attach(48_000, 2).unwrap();
683		ui.set_enabled(false);
684		assert!(!control.enabled());
685		assert!(matches!(ui.attach(48_000, 2), Err(Error::Busy(_))));
686
687		let mut buf = vec![0.5f32; 960 * 2];
688		canceller.process(&mut buf);
689		assert!(buf.iter().all(|s| *s == 0.5), "passthrough altered the samples");
690	}
691
692	/// Also the proof that the callback never waits on the reference lock:
693	/// `process` runs on the thread holding it, which would deadlock otherwise.
694	#[test]
695	fn reference_switch_contention_discards_partial_frames() {
696		let canceller = opened(48_000, 1);
697		let frame = frame(48_000);
698
699		let mut first = vec![0.5f32; frame + 32];
700		canceller.process(&mut first);
701		assert_eq!(
702			canceller
703				.inner
704				.state
705				.lock()
706				.unwrap()
707				.processor
708				.as_ref()
709				.unwrap()
710				.pending_samples(),
711			32
712		);
713
714		let locked = canceller.inner.state.lock().unwrap();
715		let mut bypassed = vec![0.25f32; frame + 32];
716		canceller.process(&mut bypassed);
717		drop(locked);
718		assert!(bypassed.iter().all(|sample| *sample == 0.25));
719
720		let mut resumed = vec![0.75f32; frame - 32];
721		canceller.process(&mut resumed);
722		assert_eq!(
723			canceller
724				.inner
725				.state
726				.lock()
727				.unwrap()
728				.processor
729				.as_ref()
730				.unwrap()
731				.pending_samples(),
732			frame - 32,
733			"samples buffered before contention leaked across the passthrough"
734		);
735	}
736
737	/// Turning it off must drop the partial frame that was in flight, which would
738	/// otherwise resurface seconds later in the middle of a live stream.
739	#[test]
740	fn toggling_off_drops_buffered_samples() {
741		let control = detached();
742		let canceller = control.attach(48_000, 1).unwrap();
743		let frame = frame(48_000);
744
745		let mut buf = vec![0.5f32; frame * 3 / 2];
746		canceller.process(&mut buf);
747		assert_ne!(
748			canceller
749				.inner
750				.state
751				.lock()
752				.unwrap()
753				.processor
754				.as_ref()
755				.unwrap()
756				.pending_samples(),
757			0
758		);
759
760		control.set_enabled(false);
761		let mut buf = vec![0.5f32; frame / 2];
762		canceller.process(&mut buf);
763		assert!(buf.iter().all(|s| *s == 0.5), "passthrough altered the samples");
764
765		let state = canceller.inner.state.lock().unwrap();
766		let processor = state.processor.as_ref().unwrap();
767		assert_eq!(processor.pending_samples(), 0, "a partial frame survived the toggle");
768		assert_eq!(
769			processor.processed_samples(),
770			0,
771			"processed samples survived the toggle"
772		);
773	}
774
775	#[test]
776	fn engine_refuses_a_second_reference_until_the_first_drops() {
777		let shared = Arc::new(playback::Shared::default());
778
779		let first = Control::new(shared.clone(), Config::default()).unwrap();
780		assert!(matches!(
781			Control::new(shared.clone(), Config::default()),
782			Err(Error::Busy(_))
783		));
784		assert!(shared.has_reference());
785
786		drop(first);
787		assert!(!shared.has_reference(), "the first reference outlived its controls");
788
789		let second = Control::new(shared.clone(), Config::default()).unwrap();
790		assert!(shared.has_reference(), "the released slot rejected a replacement");
791		drop(second);
792		assert!(!shared.has_reference(), "the second reference outlived its controls");
793	}
794
795	#[test]
796	fn one_control_attaches_to_one_microphone() {
797		let control = detached();
798		let first = control.attach(48_000, 1).unwrap();
799		assert!(matches!(control.attach(48_000, 1), Err(Error::Busy(_))));
800
801		drop(first);
802		let second = control.attach(16_000, 2).expect("drop releases the attachment");
803		drop(second);
804	}
805
806	/// Dropping capture resets its buffers before another microphone can claim
807	/// the state, even if teardown overlaps the callback's processing lock.
808	#[test]
809	fn teardown_while_processing_releases_after_the_callback() {
810		let control = detached();
811		let attachment = control.attach(48_000, 1).unwrap();
812		let mut partial = vec![0.5f32; 32];
813		attachment.process(&mut partial);
814		assert_eq!(control.pending_samples(), 32);
815
816		let inner = attachment.inner.clone();
817		let processing = inner.state.lock().unwrap();
818		let teardown = std::thread::spawn(move || drop(attachment));
819
820		assert!(matches!(control.attach(48_000, 1), Err(Error::Busy(_))));
821
822		drop(processing);
823		teardown.join().unwrap();
824		assert_eq!(control.pending_samples(), 0, "teardown skipped the reset");
825		drop(control.attach(48_000, 1).expect("teardown releases the state"));
826	}
827
828	/// Anything left queued in the tap is delay added on top of the hardware's,
829	/// and once it exceeds what the output device buffers, the echo reaches the
830	/// microphone before the reference describing it and cancellation is no
831	/// longer possible at all. So a pass has to take everything, not one frame
832	/// per microphone frame.
833	#[test]
834	fn a_pass_drains_the_whole_tap() {
835		let canceller = opened(48_000, 1);
836		let mut prod = tap(&canceller);
837		let frame = frame(48_000);
838
839		// The tap discards until the canceller has read once, so prime it.
840		canceller.process(&mut vec![0.0f32; frame]);
841		play(&mut prod, 0.5);
842		canceller.process(&mut vec![0.0f32; frame]);
843
844		// Ten frames of output against one frame of microphone, which is what a
845		// device with a long period against a short one looks like.
846		for _ in 0..10 {
847			play(&mut prod, 0.5);
848		}
849		canceller.process(&mut vec![0.0f32; frame]);
850
851		let queued = canceller
852			.inner
853			.state
854			.lock()
855			.unwrap()
856			.reference
857			.as_ref()
858			.map_or(0, |r| r.available());
859		assert!(
860			queued < REFERENCE_FRAME,
861			"{queued} reference frames were left queued as standing delay"
862		);
863	}
864
865	/// A 44.1 kHz output's tap resamples, which leaves its priming silence short
866	/// of one reference frame; the first pass must still open it to the mixer.
867	#[test]
868	fn a_resampled_tap_starts_flowing() {
869		let canceller = opened(48_000, 1);
870		let (mut prod, cons) = channel(44_100);
871		canceller.inner.state.lock().unwrap().reference = Some(cons);
872		let played = vec![0.5f32; frame(44_100) * REFERENCE_CHANNELS];
873
874		canceller.process(&mut vec![0.0f32; frame(48_000)]);
875		prod.push(&played);
876		canceller.process(&mut vec![0.0f32; frame(48_000)]);
877
878		assert_ne!(
879			prod.push(&played),
880			ring::Push::NotReady,
881			"the mixer's reference is still being discarded"
882		);
883	}
884
885	/// A canceller that never sees a reference still has to hand the microphone
886	/// back, since the output device may simply not be open yet.
887	#[test]
888	fn survives_a_missing_reference() {
889		let canceller = opened(48_000, 2);
890		assert!(canceller.inner.state.lock().unwrap().reference.is_none());
891
892		let mut buf = vec![0.5f32; frame(48_000) * 2 * 2];
893		canceller.process(&mut buf);
894		canceller.process(&mut buf);
895		assert!(buf.iter().any(|s| s.abs() > 0.01), "audio was dropped");
896	}
897
898	/// A synthetic speaker-to-microphone path, since a real one needs hardware:
899	/// the reference is noise and the microphone hears that same noise
900	/// attenuated and delayed, with nobody talking over it.
901	struct Room {
902		canceller: Attachment,
903		prod: ring::Producer,
904		noise: Noise,
905		/// Frames played, newest last, so the delay can move mid-run.
906		history: VecDeque<Vec<f32>>,
907		delay: usize,
908		frame: usize,
909	}
910
911	/// The most speaker-to-microphone delay [`Room`] can hold, in 10 ms frames.
912	const MAX_DELAY: usize = 12;
913
914	/// What a laptop lid does to its own speaker on the way to its own
915	/// microphone.
916	const ATTENUATION: f32 = 0.5;
917
918	impl Room {
919		/// The echo canceller on its own. Noise suppression would also attenuate
920		/// noise, and gain control would move the level under the measurement.
921		fn new(delay: usize) -> Self {
922			let control = Control::new(
923				Arc::new(playback::Shared::default()),
924				Config {
925					noise_suppression: false,
926					auto_gain: false,
927					..Default::default()
928				},
929			)
930			.unwrap();
931			let canceller = control.attach(48_000, 1).unwrap();
932
933			let prod = tap(&canceller);
934			Self {
935				canceller,
936				prod,
937				noise: Noise::default(),
938				history: VecDeque::with_capacity(MAX_DELAY + 1),
939				delay,
940				frame: frame(48_000),
941			}
942		}
943
944		/// Play 10 ms of noise, hear its echo, and report the energy the
945		/// microphone picked up against what came back out of the canceller.
946		fn round(&mut self) -> (f64, f64) {
947			let played: Vec<f32> = (0..self.frame).map(|_| self.noise.next()).collect();
948
949			let mut reference = vec![0.0f32; self.frame * REFERENCE_CHANNELS];
950			for (i, sample) in played.iter().enumerate() {
951				reference[i * REFERENCE_CHANNELS] = *sample;
952				reference[i * REFERENCE_CHANNELS + 1] = *sample;
953			}
954			self.prod.push(&reference);
955
956			self.history.push_back(played);
957			if self.history.len() > MAX_DELAY + 1 {
958				self.history.pop_front();
959			}
960
961			let echo = self.history.len().saturating_sub(1 + self.delay);
962			let mut heard: Vec<f32> = self.history[echo].iter().map(|s| s * ATTENUATION).collect();
963
964			let before = energy(&heard);
965			self.canceller.process(&mut heard);
966			(before, energy(&heard))
967		}
968	}
969
970	fn energy(samples: &[f32]) -> f64 {
971		samples.iter().map(|s| (*s as f64).powi(2)).sum()
972	}
973
974	/// The point of the whole module: audio played out the speaker and picked up
975	/// by the microphone has to come back quieter than it went in.
976	#[test]
977	fn cancels_the_echo_of_what_was_played() {
978		let mut room = Room::new(2);
979		let (mut heard, mut left, mut measured) = (0.0f64, 0.0f64, 0);
980
981		// Two seconds: the adaptive filter needs a moment before its output means
982		// anything, so only the last half second is measured.
983		for round in 0..200 {
984			let (before, after) = room.round();
985			if round >= 150 {
986				heard += before;
987				left += after;
988				measured += 1;
989			}
990		}
991
992		assert!(measured > 0);
993		let attenuation = 10.0 * (heard / left.max(f64::MIN_POSITIVE)).log10();
994		assert!(attenuation > 20.0, "echo was only attenuated by {attenuation:.1} dB");
995	}
996
997	/// A call where the echo path changes length, which is what a device switch,
998	/// an output stall, or somebody picking the laptop up looks like.
999	///
1000	/// Reaching the end *is* the assertion. The adaptive filter grows to cover a
1001	/// long delay and has to shrink again when it shortens, and until sonora
1002	/// 0.2.0 that shrink indexed a slice backwards and panicked
1003	/// (dignifiedquire/sonora#14, `slice index starts at 13 but ends at 12`).
1004	/// Here that surfaces as a test failure.
1005	#[test]
1006	fn survives_a_moving_echo_delay() {
1007		let mut room = Room::new(MAX_DELAY - 4);
1008
1009		// Long enough for the filter to grow past the size it starts at.
1010		for _ in 0..400 {
1011			room.round();
1012		}
1013
1014		// Then the path shortens, and keeps changing, so the estimate has to
1015		// keep moving rather than settling once.
1016		for delay in [1, MAX_DELAY - 4, 2, MAX_DELAY - 2, 1] {
1017			room.delay = delay;
1018			for _ in 0..200 {
1019				room.round();
1020			}
1021		}
1022
1023		// Still cancelling, so the filter recovered rather than merely surviving.
1024		let (mut heard, mut left) = (0.0f64, 0.0f64);
1025		for _ in 0..100 {
1026			let (before, after) = room.round();
1027			heard += before;
1028			left += after;
1029		}
1030		let attenuation = 10.0 * (heard / left.max(f64::MIN_POSITIVE)).log10();
1031		assert!(attenuation > 10.0, "the filter never re-converged: {attenuation:.1} dB");
1032	}
1033
1034	/// Deterministic white-ish noise, so the test above measures the same room
1035	/// every run. xorshift, because `rand` is not a dependency and this is not
1036	/// cryptography.
1037	#[derive(Default)]
1038	struct Noise(u32);
1039
1040	impl Noise {
1041		fn next(&mut self) -> f32 {
1042			if self.0 == 0 {
1043				self.0 = 0x1234_5678;
1044			}
1045			self.0 ^= self.0 << 13;
1046			self.0 ^= self.0 >> 17;
1047			self.0 ^= self.0 << 5;
1048			// Half scale, leaving headroom for the attenuated echo.
1049			self.0 as f32 / u32::MAX as f32 - 0.5
1050		}
1051	}
1052
1053	/// The half of this that only a real device can prove: what a
1054	/// [`playback::Engine`] plays reaches the tap.
1055	///
1056	/// Ignored by default, like the rest of the device round trips, which
1057	/// nightly runs against a null sink with `just rs audio-devices`. Whether the
1058	/// microphone then stops hearing the speaker is an acoustic question about
1059	/// the room, not something a test can assert. Real time, since the device
1060	/// drains the sink on its own clock.
1061	#[tokio::test]
1062	#[ignore = "needs an output device; run by just rs audio-devices"]
1063	async fn taps_a_real_output_device() {
1064		let engine = playback::Engine::open(playback::Config::default())
1065			.await
1066			.expect("an output device");
1067		let control = engine.canceller(Config::default()).expect("one echo reference");
1068		let canceller = control.attach(48_000, 1).expect("a mono microphone");
1069
1070		let mut sink = engine
1071			.sink(playback::Input {
1072				sample_rate: 48_000,
1073				layout: crate::Layout::Stereo,
1074				..Default::default()
1075			})
1076			.expect("a sink");
1077
1078		// A 440 Hz tone at half scale, as the interleaved `f32` bytes a decoder
1079		// would hand over.
1080		let frames = 48_000 / 10;
1081		let mut tone = Vec::with_capacity(frames * 2 * 4);
1082		for frame in 0..frames {
1083			let value = (std::f32::consts::TAU * 440.0 * frame as f32 / 48_000.0).sin() * 0.5;
1084			for _ in 0..REFERENCE_CHANNELS {
1085				tone.extend_from_slice(&value.to_le_bytes());
1086			}
1087		}
1088
1089		let mut energy = 0.0f64;
1090		let mut buf = vec![0.0f32; REFERENCE_FRAME * REFERENCE_CHANNELS];
1091
1092		// Until the tap hears it rather than for a fixed count: writes are dropped
1093		// until the device first reads, and a device can take seconds to start
1094		// (PulseAudio's idle null sink renders two seconds ahead).
1095		let deadline = kio::clock::Instant::now().saturating_add(std::time::Duration::from_secs(10));
1096		while energy <= 1.0 && kio::clock::Instant::now() < deadline {
1097			let _ = sink.write(&tone).expect("write");
1098			kio::clock::sleep(std::time::Duration::from_millis(100)).await;
1099
1100			// Drain the tap the way the microphone callback would, and add up
1101			// what the speaker was given.
1102			let mut state = canceller.inner.state.lock().unwrap();
1103			let Some(reference) = state.reference.as_mut() else {
1104				continue;
1105			};
1106			reference.start();
1107			while reference.available() >= REFERENCE_FRAME {
1108				reference.read(&mut buf);
1109				energy += buf.iter().map(|s| (*s as f64).powi(2)).sum::<f64>();
1110			}
1111		}
1112
1113		assert!(energy > 1.0, "the mix never reached the echo reference");
1114	}
1115}