Skip to main content

moq_audio/
capture.rs

1//! Audio capture: a microphone via [`cpal`] (pure-Rust: CoreAudio / WASAPI /
2//! ALSA), or macOS system audio via ScreenCaptureKit.
3//!
4//! [`Producer::open`] opens one source, and [`Producer::consume`] creates
5//! independent readers for bus channels and encoded tracks. Drive [`Producer::run`]
6//! alongside them. Every reader shares the layout, samples, capture timestamps,
7//! and source gaps. A slow reader skips expired buffers without delaying others.
8//!
9//! Device callbacks keep their bounded, preallocated handoff. The producer
10//! copies each buffer out once before sharing it, so a reader never holds a
11//! realtime allocation. Stopping or failing capture ends every reader with the
12//! same error; dropping a reader only releases that reader.
13//!
14//! A microphone that can hear the speaker takes an
15//! `aec::Control` through `Config::aec`, which runs
16//! in that same callback so the buffers leaving here are already clean.
17
18use std::task::Poll;
19use std::time::Duration;
20
21use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
22use moq_net::time::Instant;
23use ringbuf::traits::Producer as _;
24
25use crate::Error;
26
27mod buffer;
28mod fanout;
29pub use fanout::{Buffer, Consumer};
30#[cfg(target_os = "macos")]
31mod channel;
32mod permission;
33
34#[cfg(target_os = "macos")]
35mod screencapture;
36
37/// Where the audio comes from.
38///
39/// The identifiers come from [`devices`]; each listed device's
40/// [`source`](Device::source) builds the matching variant.
41#[derive(Clone, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum Source {
44	/// An audio input device, by the id [`devices`] reports. `None` opens the
45	/// system default input.
46	Microphone(Option<String>),
47
48	/// System (desktop) audio: everything the machine is playing, minus this
49	/// process. macOS only, and it needs the Screen Recording permission, since
50	/// that's the API Apple exposes it through.
51	System,
52}
53
54/// The default microphone, matching the historical `Config::default()`.
55impl Default for Source {
56	fn default() -> Self {
57		Self::Microphone(None)
58	}
59}
60
61/// How long `open` waits for the first buffer before assuming the mic never
62/// started (e.g. permission denied), mirroring the camera path's first-frame
63/// timeout. Without this the capture loop hangs silently forever when macOS TCC
64/// denies microphone access.
65const FIRST_BUFFER_TIMEOUT: Duration = Duration::from_secs(5);
66
67/// Audio capture configuration.
68///
69/// `sample_rate` and `channels` are requirements, not hints: a device that
70/// cannot capture the requested format fails with [`Error::Unsupported`] instead
71/// of opening at another one. Leave them `None` to take the device's default;
72/// the [`encode::Producer`](crate::encode::Producer) resamples and remixes to the
73/// codec format either way.
74///
75/// `#[non_exhaustive]`: construct via [`Config::default`] and set fields, so
76/// new options can be added without breaking callers.
77#[derive(Clone, Debug, Default)]
78#[non_exhaustive]
79pub struct Config {
80	/// What to capture.
81	pub source: Source,
82	/// Samples per second the device must capture at. `None` takes its default.
83	pub sample_rate: Option<u32>,
84	/// Channels the device must capture. `None` takes its default.
85	pub channels: Option<u32>,
86	/// Cancel the echo of what a speaker is playing, controlled by
87	/// [`Engine::canceller`](crate::playback::Engine::canceller).
88	///
89	/// Applies to [`Source::Microphone`] only: system audio is already the
90	/// output, so there is nothing to subtract from it. Costs up to 10 ms of
91	/// capture latency while enabled. Clones may toggle the same adaptive state,
92	/// but only one live microphone can attach to it; another open returns
93	/// [`Error::Busy`].
94	///
95	/// Requires the `playback` feature.
96	#[cfg(all(feature = "capture", feature = "playback"))]
97	pub aec: Option<crate::aec::Control>,
98}
99
100/// One buffer read from a capture source.
101pub(crate) struct Samples {
102	/// Interleaved `f32` PCM.
103	pub data: Vec<f32>,
104
105	/// Set when buffers were dropped before this one, because the reader fell
106	/// behind. The samples are not contiguous with the previous read, so the
107	/// caller must re-anchor its timeline rather than encode straight across:
108	/// PTS advances by sample count, so a swallowed gap becomes permanent drift
109	/// behind wall clock.
110	pub gap: bool,
111
112	/// When the first sample was captured, or `None` when the host did not report
113	/// a usable capture time and the buffer should be stamped at arrival.
114	pub captured: Option<Instant>,
115
116	/// Returns the allocation to the microphone callback after every downstream
117	/// borrower is done with it. `None` for non-cpal capture sources.
118	recycle: Option<ringbuf::HeapProd<Vec<f32>>>,
119}
120
121impl Samples {
122	/// Samples whose allocation belongs to the ordinary async path.
123	#[cfg(any(test, target_os = "macos"))]
124	pub(crate) fn plain(data: Vec<f32>, gap: bool) -> Self {
125		Self {
126			data,
127			gap,
128			captured: None,
129			recycle: None,
130		}
131	}
132
133	/// Samples borrowed from the microphone callback's fixed buffer pool.
134	fn pooled(data: Vec<f32>, gap: bool, captured: Option<Instant>, recycle: ringbuf::HeapProd<Vec<f32>>) -> Self {
135		Self {
136			data,
137			gap,
138			captured,
139			recycle: Some(recycle),
140		}
141	}
142
143	fn recycle(&mut self) {
144		let Some(mut recycle) = self.recycle.take() else {
145			return;
146		};
147
148		let mut data = std::mem::take(&mut self.data);
149		data.clear();
150		if recycle.try_push(data).is_err() {
151			// This is the async consumer, so freeing a buffer here is safe.
152		}
153	}
154}
155
156impl Drop for Samples {
157	fn drop(&mut self) {
158		self.recycle();
159	}
160}
161
162/// The PCM layout delivered by one capture stream.
163#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164pub(crate) struct Layout {
165	pub sample_rate: u32,
166	pub channels: u32,
167}
168
169/// Name the device and requested format when the host refuses to open it.
170fn opening_error(error: cpal::Error, device: &str, layout: Layout) -> Error {
171	let Layout { sample_rate, channels } = layout;
172	let message = format!("microphone {device} at {sample_rate} Hz with {channels} channels: {error}");
173	match error.kind() {
174		cpal::ErrorKind::UnsupportedConfig | cpal::ErrorKind::InvalidInput => Error::Unsupported(message),
175		_ => Error::Capture(message),
176	}
177}
178
179/// An open capture source, read buffer-by-buffer via [`read`](Self::read).
180///
181/// Backends stay private behind the shared capture producer.
182#[cfg_attr(
183	all(test, not(target_os = "macos")),
184	expect(
185		clippy::large_enum_variant,
186		reason = "a synthetic stream has no device allocation; one enum per capture"
187	)
188)]
189pub(crate) enum Stream {
190	Microphone(Microphone),
191	#[cfg(target_os = "macos")]
192	System(screencapture::SystemAudio),
193	#[cfg(test)]
194	Test {
195		layout: Layout,
196		samples: kio::Queue<Result<Samples, Error>>,
197	},
198}
199
200impl Stream {
201	/// The concrete microphone currently in use, if this is a microphone stream.
202	pub(crate) fn device(&self) -> Option<&Device> {
203		match self {
204			Self::Microphone(mic) => Some(&mic.device),
205			#[cfg(test)]
206			Self::Test { .. } => None,
207			#[cfg(target_os = "macos")]
208			Self::System(_) => None,
209		}
210	}
211
212	/// The PCM layout this opened stream actually delivers.
213	pub(crate) fn layout(&self) -> Layout {
214		match self {
215			Self::Microphone(mic) => mic.layout,
216			#[cfg(test)]
217			Self::Test { layout, .. } => *layout,
218			#[cfg(target_os = "macos")]
219			Self::System(system) => system.layout(),
220		}
221	}
222
223	/// Await the next buffer, or `None` once the source stops. A microphone stream
224	/// error is returned immediately even if the device delivers no more samples.
225	/// Cancel-safe: drop the future to release the device.
226	pub(crate) async fn read(&mut self) -> Result<Option<Samples>, Error> {
227		match self {
228			Self::Microphone(mic) => mic.read().await,
229			#[cfg(test)]
230			Self::Test { samples, .. } => match samples.pop().await {
231				Ok(samples) => samples.map(Some),
232				Err(_) => Ok(None),
233			},
234			#[cfg(target_os = "macos")]
235			Self::System(system) => Ok(system.read().await),
236		}
237	}
238}
239
240/// Open the capture source described by `config`.
241pub(crate) async fn open(config: &Config) -> Result<Stream, Error> {
242	match &config.source {
243		Source::Microphone(device) => Ok(Stream::Microphone(Microphone::open(device.as_deref(), config).await?)),
244		#[cfg(target_os = "macos")]
245		Source::System => Ok(Stream::System(
246			screencapture::SystemAudio::open(config.sample_rate, config.channels).await?,
247		)),
248		#[cfg(not(target_os = "macos"))]
249		Source::System => Err(Error::Unsupported(
250			"system audio capture is only supported on macOS".into(),
251		)),
252	}
253}
254
255/// One open device feeding independent capture consumers.
256///
257/// Call [`consume`](Self::consume) for each bus channel or encoded track, then
258/// drive [`run`](Self::run) alongside them. Dropping the producer releases the
259/// device and ends every consumer; consumers cannot keep it open.
260pub struct Producer {
261	stream: Stream,
262	shared: fanout::Producer,
263}
264
265impl Producer {
266	/// Open the selected device once and fix the layout for all consumers.
267	pub async fn open(config: Config) -> Result<Self, Error> {
268		let stream = open(&config).await?;
269		Self::from_stream(stream, config.source)
270	}
271
272	fn from_stream(stream: Stream, source: Source) -> Result<Self, Error> {
273		let layout = stream.layout();
274		let mut input = crate::encode::Input::new(layout.sample_rate, device_layout(layout.channels)?);
275		input.format = crate::Format::F32;
276		let shared = fanout::Producer::new(input, source, stream.device().cloned());
277		Ok(Self { stream, shared })
278	}
279
280	/// Start an independent reader at the next captured buffer.
281	pub fn consume(&self) -> Consumer {
282		self.shared.consume()
283	}
284
285	/// Deliver capture until the device stops or fails, reporting the same error to every reader.
286	///
287	/// Dropping this future releases the device. On macOS, run it on a local
288	/// task because ScreenCaptureKit owns Objective-C handles across awaits.
289	pub async fn run(mut self) -> Result<(), Error> {
290		// A gap reported by an empty buffer still belongs before the next samples.
291		let mut gap = false;
292		let error = loop {
293			match self.stream.read().await {
294				Ok(Some(samples)) => {
295					gap |= samples.gap;
296					if samples.data.is_empty() {
297						continue;
298					}
299					// Return the callback pool allocation before publishing. A retained reader
300					// can own an Arc indefinitely without starving the realtime buffer pool.
301					let buffer = Buffer {
302						data: samples.data.as_slice().into(),
303						captured: samples.captured.unwrap_or_else(Instant::now),
304						gap: std::mem::take(&mut gap),
305					};
306					drop(samples);
307					self.shared.write(buffer);
308				}
309				Ok(None) => break Error::Capture("audio capture stream stopped".into()),
310				Err(failure) => break failure,
311			}
312		};
313		self.shared.abort(error.clone());
314		Err(error)
315	}
316}
317
318/// Native device futures must remain spawnable wherever the backend permits it.
319#[cfg(not(target_os = "macos"))]
320#[allow(dead_code, reason = "compile-time Send assertions, never called")]
321fn assert_capture_send(config: Config, producer: Producer) {
322	fn is_send<T: Send>(_: &T) {}
323	is_send(&Producer::open(config));
324	is_send(&producer.run());
325}
326
327/// A channel count alone cannot identify the speakers of a microphone array.
328fn device_layout(channels: u32) -> Result<crate::Layout, Error> {
329	match std::num::NonZeroU32::new(channels) {
330		Some(count) if channels > 2 => Ok(crate::Layout::Discrete(count)),
331		_ => crate::Layout::from_channels(channels),
332	}
333}
334
335/// An open microphone.
336///
337/// Holds the live `cpal` stream, which keeps capturing until it is dropped.
338/// Buffers arrive from the realtime callback over an async channel.
339pub(crate) struct Microphone {
340	// Kept alive to keep capturing; dropping it stops the stream.
341	_stream: cpal::Stream,
342	reader: MicrophoneReader,
343	/// The first buffer, captured during `open` to surface a permission failure
344	/// as an error rather than a silent hang.
345	pending: Option<Samples>,
346	/// The format cpal negotiated for this stream generation.
347	layout: Layout,
348	/// The concrete device selected for this stream generation.
349	device: Device,
350}
351
352/// The async half of a microphone stream, separate from the cpal handle so its
353/// failure wakeup and stream-generation isolation can be tested without audio
354/// hardware.
355struct MicrophoneReader {
356	rx: buffer::Reader,
357	errors: kio::Consumer<Option<cpal::Error>>,
358}
359
360impl MicrophoneReader {
361	/// Return the buffer consumed during open unless a stream error arrived in
362	/// the meantime.
363	async fn pending(&mut self, samples: Samples) -> Result<Option<Samples>, Error> {
364		tokio::select! {
365			biased;
366			Some(err) = failure(&self.errors) => Err(err),
367			_ = std::future::ready(()) => Ok(Some(samples)),
368		}
369	}
370
371	/// Race samples against cpal's error callback. Errors win if both are ready so
372	/// a dead device is never kept alive just to drain already-buffered audio.
373	async fn read(&mut self) -> Result<Option<Samples>, Error> {
374		let data = tokio::select! {
375			biased;
376			Some(err) = failure(&self.errors) => return Err(err),
377			data = self.rx.recv() => data,
378		};
379
380		Ok(data)
381	}
382}
383
384/// Await the first terminal cpal error for this stream generation.
385async fn failure(errors: &kio::Consumer<Option<cpal::Error>>) -> Option<Error> {
386	errors
387		.wait(|error| match error.as_ref() {
388			Some(error) => Poll::Ready(error.clone()),
389			None => Poll::Pending,
390		})
391		.await
392		.ok()
393		.map(capture_err)
394}
395
396impl Microphone {
397	/// Open (and start) the requested microphone.
398	///
399	/// The cpal calls run inline rather than going through [`blocking`]: they
400	/// return as soon as the device starts, so the only real wait is the
401	/// first-buffer await below.
402	async fn open(selector: Option<&str>, config: &Config) -> Result<Self, Error> {
403		// Fail fast on a denied/restricted mic (macOS TCC) instead of opening a
404		// stream that silently delivers nothing. A no-op on other platforms.
405		permission::ensure_microphone_access().await?;
406
407		let (device, current, sample_format, stream_config) = resolve(selector, config)?;
408		let sample_rate = stream_config.sample_rate;
409		let channels = u32::from(stream_config.channels);
410		let layout = Layout { sample_rate, channels };
411		let opening = |err| opening_error(err, &device.to_string(), layout);
412
413		// Claim the adaptive state and tell it what it is listening to before the
414		// first callback arrives, so the buffers it needs are allocated off the
415		// audio thread. The attachment moves into the callback writer and releases
416		// automatically when this stream tears down.
417		#[cfg(all(feature = "capture", feature = "playback"))]
418		let aec = config
419			.aec
420			.as_ref()
421			.map(|control| control.attach(sample_rate, channels))
422			.transpose()?;
423
424		let (mut writer, rx) = buffer::channel(
425			channels as usize,
426			sample_rate,
427			#[cfg(all(feature = "capture", feature = "playback"))]
428			aec,
429		);
430		let error_tx = kio::Producer::new(None);
431		let errors = error_tx.consume();
432		let mut reader = MicrophoneReader { rx, errors };
433
434		// The callback runs on cpal's realtime audio thread. Every format writes
435		// into the same preallocated bounded pool.
436		let mut clock = StreamClock::default();
437		let stream = match sample_format {
438			cpal::SampleFormat::F32 => {
439				let (errors, gap) = (error_tx.clone(), writer.gap());
440				device.build_input_stream(
441					stream_config,
442					move |data: &[f32], info| writer.write_f32(data, clock.capture(info, Instant::now())),
443					move |err| stream_err(&errors, &gap, err),
444					None,
445				)
446			}
447			cpal::SampleFormat::I16 => {
448				let (errors, gap) = (error_tx.clone(), writer.gap());
449				device.build_input_stream(
450					stream_config,
451					move |data: &[i16], info| writer.write_i16(data, clock.capture(info, Instant::now())),
452					move |err| stream_err(&errors, &gap, err),
453					None,
454				)
455			}
456			cpal::SampleFormat::U16 => {
457				let (errors, gap) = (error_tx.clone(), writer.gap());
458				device.build_input_stream(
459					stream_config,
460					move |data: &[u16], info| writer.write_u16(data, clock.capture(info, Instant::now())),
461					move |err| stream_err(&errors, &gap, err),
462					None,
463				)
464			}
465			other => {
466				return Err(Error::Unsupported(format!(
467					"microphone {device} captures {other}, which is not a supported sample format"
468				)));
469			}
470		}
471		.map_err(opening)?;
472
473		stream.play().map_err(opening)?;
474
475		// Await the first buffer to surface a permission failure (or dead device)
476		// as an error rather than a silent hang in the capture loop.
477		let pending = match kio::clock::timeout(FIRST_BUFFER_TIMEOUT, reader.read()).await {
478			Ok(Ok(Some(samples))) => samples,
479			Ok(Ok(None)) => {
480				return Err(Error::Capture(format!(
481					"microphone {device} stopped before any samples"
482				)));
483			}
484			Ok(Err(err)) => return Err(err),
485			Err(_) => {
486				return Err(Error::Capture(format!(
487					"no samples from microphone {device} within {FIRST_BUFFER_TIMEOUT:?} (permission denied?)"
488				)));
489			}
490		};
491
492		tracing::info!(device = %device, sample_rate, channels, "opened microphone");
493
494		Ok(Self {
495			_stream: stream,
496			reader,
497			pending: Some(pending),
498			layout,
499			device: current,
500		})
501	}
502
503	/// Await the next buffer or stream error. Cancel-safe: drop the future to stop
504	/// reading.
505	async fn read(&mut self) -> Result<Option<Samples>, Error> {
506		if let Some(samples) = self.pending.take() {
507			return self.reader.pending(samples).await;
508		}
509
510		self.reader.read().await
511	}
512}
513
514/// An audio input reported by [`devices`].
515#[derive(Clone, Debug, PartialEq, Eq)]
516#[non_exhaustive]
517pub struct Device {
518	/// Opaque identifier: pass to [`Source::Microphone`].
519	///
520	/// This is cpal's `host:device` id, so it is stable across restarts and
521	/// unique even when two inputs share a [`name`](Self::name).
522	pub id: String,
523	/// Human-readable name, e.g. "MacBook Pro Microphone".
524	pub name: String,
525	/// Whether this is the system default input.
526	///
527	/// True for at most one device: the preferred host's default. Another host's
528	/// default is that host's, not the system's.
529	pub default: bool,
530	/// The host API this device is reached through, e.g. "PipeWire" or "ALSA".
531	///
532	/// The same hardware is usually reachable through several, so a caller that
533	/// offers a choice groups by this.
534	pub host: String,
535}
536
537impl Device {
538	/// The [`Source`] that captures this device.
539	pub fn source(&self) -> Source {
540		Source::Microphone(Some(self.id.clone()))
541	}
542}
543
544/// List the audio inputs.
545pub async fn devices() -> Result<Vec<Device>, Error> {
546	blocking(list).await
547}
548
549/// The blocking half of [`devices`].
550fn list() -> Result<Vec<Device>, Error> {
551	// Every host, not just the preferred one, matching the output side. The same
552	// hardware appears under each, and which one a caller wants is its decision:
553	// PipeWire and PulseAudio carry the server's own names and routing, ALSA
554	// reaches a device directly. `Device::host` is what lets a caller group them.
555	let preferred = cpal::default_host().id();
556	let mut devices = Vec::new();
557	// A sound server reports one id per stream, not per device, so a client with
558	// several open would otherwise appear once per stream.
559	let mut seen = std::collections::HashSet::new();
560
561	for id in cpal::available_hosts() {
562		// A host that will not open takes every device on it with it, so say so:
563		// the symptom is a device missing from the listing with no other trace.
564		let host = match cpal::host_from_id(id) {
565			Ok(host) => host,
566			Err(err) => {
567				tracing::debug!(host = id.name(), error = %err, "skipping an audio host that would not open");
568				continue;
569			}
570		};
571		let default = host.default_input_device().and_then(|device| device.id().ok());
572
573		let inputs = match host.input_devices() {
574			Ok(inputs) => inputs,
575			Err(err) => {
576				tracing::debug!(host = id.name(), error = %err, "skipping a host that would not list its inputs");
577				continue;
578			}
579		};
580		for device in inputs {
581			let device_id = match device.id() {
582				Ok(device_id) => device_id,
583				Err(err) => {
584					tracing::debug!(host = id.name(), error = %err, "skipping an input device with no id");
585					continue;
586				}
587			};
588			if !seen.insert(device_id.to_string()) {
589				continue;
590			}
591			// Only the preferred host's default is the system default; the others
592			// are that host's idea of one.
593			let is_default = id == preferred && Some(&device_id) == default.as_ref();
594			match describe(&device, &device_id, is_default) {
595				Ok(device) => devices.push(device),
596				Err(err) => {
597					tracing::debug!(error = %err, "skipping an input device that could not be described");
598				}
599			}
600		}
601	}
602
603	Ok(devices)
604}
605
606/// Run blocking cpal host I/O off the runtime's worker threads.
607async fn blocking<T, F>(f: F) -> Result<T, Error>
608where
609	F: FnOnce() -> Result<T, Error> + Send + 'static,
610	T: Send + 'static,
611{
612	tokio::task::spawn_blocking(f)
613		.await
614		.map_err(|err| Error::Capture(format!("audio host thread failed: {err}")))?
615}
616
617/// Resolve the input device and its negotiated stream config from `config`.
618fn resolve(
619	selector: Option<&str>,
620	config: &Config,
621) -> Result<(cpal::Device, Device, cpal::SampleFormat, cpal::StreamConfig), Error> {
622	let host = cpal::default_host();
623	let default = host.default_input_device().and_then(|device| device.id().ok());
624	let (device, id) = match selector {
625		// `Host::device_by_id` searches outputs too, so match against the inputs
626		// ourselves: an output id must not resolve as a microphone.
627		Some(selector) => {
628			let wanted: cpal::DeviceId = selector.parse().map_err(|err| {
629				Error::Device(format!(
630					"{selector:?} is not an input device id; run `devices` to list them: {err}"
631				))
632			})?;
633			// Ids are host-qualified, so route to the host that issued this one
634			// rather than searching the preferred host alone: `devices` lists
635			// every host, and a device it named has to be openable.
636			let host =
637				cpal::host_from_id(wanted.host()).map_err(|err| Error::Device(format!("{selector:?}: {err}")))?;
638			let device = host
639				.input_devices()
640				.map_err(capture_err)?
641				.find(|device| device.id().ok().as_ref() == Some(&wanted))
642				.ok_or_else(|| Error::Device(format!("input device {selector:?} not found")))?;
643			(device, wanted)
644		}
645		None => {
646			let device = host
647				.default_input_device()
648				.ok_or_else(|| Error::Device("no default input device".into()))?;
649			let id = device.id().map_err(capture_err)?;
650			(device, id)
651		}
652	};
653	let current = describe(&device, &id, Some(&id) == default.as_ref()).map_err(capture_err)?;
654
655	let supported = device.default_input_config().map_err(capture_err)?;
656	// Enumerate only for an override: the default needs no range check, and a
657	// host that cannot list its ranges can still open its default.
658	let supported = if config.sample_rate.is_none() && config.channels.is_none() {
659		supported
660	} else {
661		let ranges = device.supported_input_configs().map_err(capture_err)?;
662		negotiate(&device.to_string(), supported, ranges, config)?
663	};
664	Ok((device, current, supported.sample_format(), supported.config()))
665}
666
667/// Pick the device format matching `config`'s overrides from the `ranges` the
668/// device reports, refusing a format it cannot capture rather than substituting
669/// the nearest one.
670fn negotiate(
671	device: &str,
672	default: cpal::SupportedStreamConfig,
673	ranges: impl IntoIterator<Item = cpal::SupportedStreamConfigRange>,
674	config: &Config,
675) -> Result<cpal::SupportedStreamConfig, Error> {
676	// Compare in u32 so an out-of-range channel count matches nothing instead of
677	// wrapping when narrowed to cpal's u16.
678	let sample_rate = config.sample_rate.unwrap_or(default.sample_rate());
679	let channels = config.channels.unwrap_or(u32::from(default.channels()));
680	if sample_rate == default.sample_rate() && channels == u32::from(default.channels()) {
681		return Ok(default);
682	}
683
684	let mut usable: Vec<_> = ranges
685		.into_iter()
686		.filter(|range| writable(range.sample_format()))
687		.collect();
688	let preferred = |range: &cpal::SupportedStreamConfigRange| range.sample_format() == default.sample_format();
689	let best = usable
690		.iter()
691		.filter(|range| u32::from(range.channels()) == channels && range.contains_rate(sample_rate))
692		// Keep the default's sample format when it can, then take cpal's preference.
693		.max_by(|a, b| {
694			preferred(a)
695				.cmp(&preferred(b))
696				.then_with(|| a.cmp_default_heuristics(b))
697		});
698	if let Some(best) = best {
699		return Ok(best.with_sample_rate(sample_rate));
700	}
701
702	usable.sort_by_key(|range| (range.channels(), range.min_sample_rate(), range.max_sample_rate()));
703	let supported: Vec<_> = usable
704		.iter()
705		.map(|range| {
706			format!(
707				"{} channels at {}-{} Hz ({})",
708				range.channels(),
709				range.min_sample_rate(),
710				range.max_sample_rate(),
711				range.sample_format()
712			)
713		})
714		.collect();
715	let supported = if supported.is_empty() {
716		"no usable format".to_string()
717	} else {
718		supported.join(", ")
719	};
720	Err(Error::Unsupported(format!(
721		"microphone {device} cannot capture {sample_rate} Hz with {channels} channels; it supports {supported}"
722	)))
723}
724
725/// Sample formats the capture callback converts to `f32`.
726fn writable(format: cpal::SampleFormat) -> bool {
727	matches!(
728		format,
729		cpal::SampleFormat::F32 | cpal::SampleFormat::I16 | cpal::SampleFormat::U16
730	)
731}
732
733/// Build the listing entry for `device`, whose id the caller has already read.
734fn describe(device: &cpal::Device, id: &cpal::DeviceId, default: bool) -> Result<Device, cpal::Error> {
735	Ok(Device {
736		default,
737		name: device.description()?.name().into(),
738		host: id.host().name().to_string(),
739		id: id.to_string(),
740	})
741}
742
743/// Longer than a live device buffer. A host that leaves `capture` at zero against
744/// an absolute callback clock reports a delay of the whole uptime, which is not
745/// a sample time this process can place.
746const MAX_CAPTURE_DELAY: Duration = Duration::from_secs(1);
747
748/// How much slower than `Instant` a stream clock may run and still be followed: one part in
749/// this many (1000 ppm), far above the gap between a host's hardware or raw monotonic clock
750/// and `Instant`.
751const MAX_DRIFT: u32 = 1_000;
752
753/// Places one open's cpal timestamps on the monotonic clock.
754///
755/// The host stamps a callback before the closure runs, so `Instant::now()` there overstates the
756/// callback's instant by its delivery delay. The estimate is the earliest arrival the stream
757/// clock predicts: a late callback cannot move it later, and it creeps by up to [`MAX_DRIFT`] so
758/// a slow stream clock is still followed. Only an open's first callback, with nothing earlier to
759/// predict it, carries its own delivery delay.
760#[derive(Default)]
761struct StreamClock {
762	/// The estimated instant of the last usable callback, and its stream timestamp.
763	anchor: Option<(Instant, cpal::StreamInstant)>,
764}
765
766impl StreamClock {
767	/// The instant the callback's first sample was captured, for a callback running at `now`.
768	///
769	/// `None` when the host timestamp cannot name one: the capture mark is after the
770	/// callback, or the delay is not a device buffer. The caller then stamps arrival.
771	fn capture(&mut self, info: &cpal::InputCallbackInfo, now: Instant) -> Option<Instant> {
772		let timestamp = info.timestamp();
773		self.place(timestamp.callback, timestamp.capture, now)
774	}
775
776	fn place(&mut self, callback: cpal::StreamInstant, capture: cpal::StreamInstant, now: Instant) -> Option<Instant> {
777		let delay = callback.checked_duration_since(capture)?;
778		if delay > MAX_CAPTURE_DELAY {
779			return None;
780		}
781		let predicted = self.anchor.and_then(|(at, stream)| {
782			let elapsed = callback.checked_duration_since(stream)?;
783			at.checked_add(elapsed + elapsed / MAX_DRIFT)
784		});
785		let at = predicted.map_or(now, |predicted| predicted.min(now));
786		self.anchor = Some((at, callback));
787		at.checked_sub(delay)
788	}
789}
790
791/// End capture on a fatal stream error. One the stream survives, such as an overrun, may still
792/// have lost audio, so the next buffer carries a gap rather than closing over the loss: encoding
793/// straight across it would shift every later sample earlier by what was lost.
794fn stream_err(errors: &kio::Producer<Option<cpal::Error>>, gap: &buffer::Gap, err: cpal::Error) {
795	if survivable(err.kind()) {
796		tracing::warn!(error = %err, "microphone stream error does not require a restart");
797		gap.mark();
798		return;
799	}
800
801	tracing::error!(error = %err, "microphone stream error");
802	let Ok(mut failure) = errors.write() else { return };
803	if failure.is_some() {
804		return;
805	}
806	*failure = Some(err);
807	failure.close();
808}
809
810/// Errors for which cpal documents that the live stream remains usable.
811fn survivable(kind: cpal::ErrorKind) -> bool {
812	matches!(
813		kind,
814		cpal::ErrorKind::DeviceChanged | cpal::ErrorKind::RealtimeDenied | cpal::ErrorKind::Xrun
815	)
816}
817
818fn capture_err(err: impl std::fmt::Display) -> Error {
819	Error::Capture(err.to_string())
820}
821
822#[cfg(test)]
823pub(crate) fn test_source() -> (Producer, kio::Queue<Result<Samples, Error>>) {
824	test_source_with(48_000, 2)
825}
826
827#[cfg(test)]
828pub(crate) fn test_source_with(sample_rate: u32, channels: u32) -> (Producer, kio::Queue<Result<Samples, Error>>) {
829	let samples = kio::Queue::new();
830	let producer = Producer::from_stream(
831		Stream::Test {
832			layout: Layout { sample_rate, channels },
833			samples: samples.clone(),
834		},
835		Source::default(),
836	)
837	.unwrap();
838	(producer, samples)
839}
840
841#[cfg(test)]
842mod tests {
843	use super::*;
844
845	#[tokio::test(start_paused = true)]
846	async fn a_stopped_source_ends_every_consumer_with_its_error() {
847		let (producer, samples) = test_source();
848		let mut first = producer.consume();
849		let mut second = producer.consume();
850		samples.close();
851		let error = producer.run().await.unwrap_err().to_string();
852		assert!(error.contains("stream stopped"));
853		assert_eq!(first.read().await.unwrap_err().to_string(), error);
854		assert_eq!(second.read().await.unwrap_err().to_string(), error);
855	}
856
857	#[tokio::test(start_paused = true)]
858	async fn an_empty_gap_buffer_marks_the_next_samples() {
859		let (producer, samples) = test_source();
860		let mut reader = producer.consume();
861		samples.try_push(Ok(Samples::plain(Vec::new(), true))).unwrap();
862		samples.try_push(Ok(Samples::plain(vec![0.25; 960], false))).unwrap();
863		samples.try_push(Ok(Samples::plain(vec![0.5; 960], false))).unwrap();
864		tokio::select! {
865			result = producer.run() => panic!("capture stopped: {result:?}"),
866			_ = async {
867				assert!(reader.read().await.unwrap().gap);
868				assert!(!reader.read().await.unwrap().gap);
869			} => {},
870		}
871	}
872
873	fn reader() -> (buffer::Writer, kio::Producer<Option<cpal::Error>>, MicrophoneReader) {
874		let (tx, rx) = buffer::channel(
875			1,
876			48_000,
877			#[cfg(all(feature = "capture", feature = "playback"))]
878			None,
879		);
880		let failures = kio::Producer::new(None);
881		let errors = failures.consume();
882		(tx, failures, MicrophoneReader { rx, errors })
883	}
884
885	fn fail(errors: &kio::Producer<Option<cpal::Error>>, message: &'static str) {
886		stream_err(
887			errors,
888			&buffer::Gap::default(),
889			cpal::Error::with_message(cpal::ErrorKind::DeviceNotAvailable, message),
890		);
891	}
892
893	#[tokio::test]
894	async fn stream_error_wakes_a_reader_without_samples() {
895		let (_samples, errors, mut reader) = reader();
896		fail(&errors, "device lost");
897
898		let err = match reader.read().await {
899			Err(err) => err,
900			Ok(_) => panic!("the reader ignored its stream error"),
901		};
902		assert!(matches!(err, Error::Capture(message) if message == "device lost"));
903	}
904
905	#[tokio::test]
906	async fn replaced_stream_cannot_fail_its_replacement() {
907		let (_old_samples, old_errors, old_reader) = reader();
908		let (mut new_samples, _new_errors, mut new_reader) = reader();
909		drop(old_reader);
910
911		fail(&old_errors, "stale");
912		new_samples.write_f32(&[1.0], None);
913		let samples = new_reader.read().await.unwrap().unwrap();
914		assert_eq!(samples.data, vec![1.0]);
915	}
916
917	#[tokio::test]
918	async fn stream_error_wins_over_the_buffer_saved_during_open() {
919		let (_samples, errors, mut reader) = reader();
920		fail(&errors, "device lost");
921
922		let result = reader.pending(Samples::plain(vec![1.0], false)).await;
923		let err = match result {
924			Err(err) => err,
925			Ok(_) => panic!("the pending sample hid a stream error"),
926		};
927		assert!(matches!(err, Error::Capture(message) if message == "device lost"));
928	}
929
930	#[test]
931	fn survivable_errors_do_not_end_the_stream() {
932		let (_samples, errors, _reader) = reader();
933		stream_err(
934			&errors,
935			&buffer::Gap::default(),
936			cpal::Error::new(cpal::ErrorKind::DeviceChanged),
937		);
938
939		assert!(errors.read().is_none());
940	}
941
942	/// An overrun the host recovered from lost audio between callbacks, so the next buffer says so
943	/// and the encode re-anchors rather than closing over the loss.
944	#[tokio::test]
945	async fn a_survived_overrun_marks_the_next_buffer_as_a_gap() {
946		let (mut samples, errors, mut reader) = reader();
947		samples.write_f32(&[1.0], None);
948		stream_err(&errors, &samples.gap(), cpal::Error::new(cpal::ErrorKind::Xrun));
949		samples.write_f32(&[2.0], None);
950		samples.write_f32(&[3.0], None);
951
952		let gaps: Vec<bool> = [
953			reader.read().await.unwrap().unwrap(),
954			reader.read().await.unwrap().unwrap(),
955			reader.read().await.unwrap().unwrap(),
956		]
957		.iter()
958		.map(|samples| samples.gap)
959		.collect();
960		assert_eq!(gaps, [false, true, false]);
961		assert!(errors.read().is_none());
962	}
963
964	fn stream(millis: u64) -> cpal::StreamInstant {
965		cpal::StreamInstant::from_millis(millis)
966	}
967
968	#[test]
969	fn a_capture_timestamp_is_the_first_sample_not_the_callback() {
970		let now = Instant::now();
971		let placed = StreamClock::default().place(stream(1_000), stream(980), now).unwrap();
972		assert_eq!(now - placed, Duration::from_millis(20));
973	}
974
975	#[test]
976	fn a_capture_mark_after_the_callback_is_unusable() {
977		let now = Instant::now();
978		assert!(StreamClock::default().place(stream(10), stream(11), now).is_none());
979	}
980
981	#[test]
982	fn an_uptime_sized_capture_delay_is_unusable() {
983		let now = Instant::now();
984		let placed = StreamClock::default().place(stream(60_000), cpal::StreamInstant::ZERO, now);
985		assert!(placed.is_none());
986	}
987
988	#[test]
989	fn a_zero_capture_delay_stamps_the_callback() {
990		let now = Instant::now();
991		assert_eq!(StreamClock::default().place(stream(5), stream(5), now), Some(now));
992	}
993
994	/// A callback the scheduler runs late is placed where the stream clock says its samples
995	/// were captured, not where the closure ran.
996	#[test]
997	fn a_late_callback_keeps_its_stream_capture_time() {
998		let start = Instant::now();
999		let mut clock = StreamClock::default();
1000		for millis in [0, 10, 20] {
1001			let at = start.saturating_add(Duration::from_millis(millis));
1002			assert_eq!(clock.place(stream(millis), stream(millis), at), Some(at));
1003		}
1004
1005		// Captured at 25 ms, stamped by the host at 30 ms, run at 55 ms.
1006		let placed = clock.place(stream(30), stream(25), start.saturating_add(Duration::from_millis(55)));
1007		let creep = Duration::from_millis(10) / MAX_DRIFT;
1008		assert_eq!(
1009			placed,
1010			Some(start.saturating_add(Duration::from_millis(25)).saturating_add(creep))
1011		);
1012
1013		let on_time = start.saturating_add(Duration::from_millis(40));
1014		assert_eq!(clock.place(stream(40), stream(40), on_time), Some(on_time));
1015	}
1016
1017	/// An open's first callback has nothing to predict it, so a late one is placed at its run
1018	/// time. The next callback that runs on time corrects the estimate.
1019	#[test]
1020	fn an_on_time_callback_corrects_a_late_first_one() {
1021		let start = Instant::now();
1022		let mut clock = StreamClock::default();
1023		let late = start.saturating_add(Duration::from_millis(30));
1024		assert_eq!(clock.place(stream(0), stream(0), late), Some(late));
1025
1026		let on_time = start.saturating_add(Duration::from_millis(40));
1027		assert_eq!(clock.place(stream(40), stream(40), on_time), Some(on_time));
1028	}
1029
1030	/// A stream clock running slower than `Instant`, within the drift bound, is followed instead
1031	/// of leaving every later capture early.
1032	#[test]
1033	fn a_slow_stream_clock_is_followed() {
1034		let start = Instant::now();
1035		let mut clock = StreamClock::default();
1036		// 500 ppm slow: 10 ms on the stream clock is 10.005 ms of `Instant`.
1037		for index in 0..10_000u64 {
1038			let at = start.saturating_add(Duration::from_micros(10_005 * index));
1039			assert_eq!(clock.place(stream(10 * index), stream(10 * index), at), Some(at));
1040		}
1041	}
1042
1043	const MIC: &str = "Test Mic";
1044
1045	fn default_config() -> cpal::SupportedStreamConfig {
1046		cpal::SupportedStreamConfig::new(2, 48_000, cpal::SupportedBufferSize::Unknown, cpal::SampleFormat::F32)
1047	}
1048
1049	fn range(channels: u16, min: u32, max: u32, format: cpal::SampleFormat) -> cpal::SupportedStreamConfigRange {
1050		cpal::SupportedStreamConfigRange::new(channels, min, max, cpal::SupportedBufferSize::Unknown, format)
1051	}
1052
1053	/// A device offering mono and stereo from 8 to 48 kHz as I16, and stereo at
1054	/// 44.1 to 48 kHz as F32.
1055	fn ranges() -> Vec<cpal::SupportedStreamConfigRange> {
1056		vec![
1057			range(1, 8_000, 48_000, cpal::SampleFormat::I16),
1058			range(2, 8_000, 48_000, cpal::SampleFormat::I16),
1059			range(2, 44_100, 48_000, cpal::SampleFormat::F32),
1060			// Unwritable formats are never picked, even when they match.
1061			range(1, 96_000, 96_000, cpal::SampleFormat::I32),
1062		]
1063	}
1064
1065	fn request(sample_rate: Option<u32>, channels: Option<u32>) -> Config {
1066		Config {
1067			sample_rate,
1068			channels,
1069			..Default::default()
1070		}
1071	}
1072
1073	fn unsupported(result: Result<cpal::SupportedStreamConfig, Error>) -> String {
1074		match result {
1075			Err(Error::Unsupported(message)) => message,
1076			other => panic!("expected an unsupported format, got {other:?}"),
1077		}
1078	}
1079
1080	#[test]
1081	fn requesting_the_default_keeps_it() {
1082		let config = negotiate(MIC, default_config(), [], &request(Some(48_000), Some(2))).unwrap();
1083		assert_eq!(config, default_config());
1084	}
1085
1086	#[test]
1087	fn an_override_keeps_the_default_sample_format_when_it_can() {
1088		let config = negotiate(MIC, default_config(), ranges(), &request(Some(44_100), None)).unwrap();
1089		assert_eq!(config.sample_rate(), 44_100);
1090		assert_eq!(config.channels(), 2);
1091		assert_eq!(config.sample_format(), cpal::SampleFormat::F32);
1092	}
1093
1094	#[test]
1095	fn an_override_takes_another_sample_format_from_the_device_ranges() {
1096		let config = negotiate(MIC, default_config(), ranges(), &request(None, Some(1))).unwrap();
1097		assert_eq!(config.sample_rate(), 48_000);
1098		assert_eq!(config.channels(), 1);
1099		assert_eq!(config.sample_format(), cpal::SampleFormat::I16);
1100
1101		let config = negotiate(MIC, default_config(), ranges(), &request(Some(16_000), None)).unwrap();
1102		assert_eq!(config.sample_rate(), 16_000);
1103		assert_eq!(config.channels(), 2);
1104		assert_eq!(config.sample_format(), cpal::SampleFormat::I16);
1105	}
1106
1107	#[test]
1108	fn an_unsupported_sample_rate_is_refused_with_context() {
1109		let message = unsupported(negotiate(MIC, default_config(), ranges(), &request(Some(96_000), None)));
1110		assert!(message.contains(MIC), "{message}");
1111		assert!(message.contains("96000 Hz with 2 channels"), "{message}");
1112		assert!(message.contains("1 channels at 8000-48000 Hz (i16)"), "{message}");
1113		assert!(!message.contains("i32"), "{message}");
1114	}
1115
1116	#[test]
1117	fn a_channel_count_beyond_u16_does_not_wrap() {
1118		// 65537 narrowed to u16 is 1, which the device supports.
1119		let message = unsupported(negotiate(MIC, default_config(), ranges(), &request(None, Some(65_537))));
1120		assert!(message.contains("48000 Hz with 65537 channels"), "{message}");
1121	}
1122
1123	#[test]
1124	fn a_device_with_no_usable_ranges_is_refused() {
1125		let ranges = [range(1, 8_000, 48_000, cpal::SampleFormat::I32)];
1126		let message = unsupported(negotiate(MIC, default_config(), ranges, &request(None, Some(1))));
1127		assert!(message.contains("no usable format"), "{message}");
1128	}
1129
1130	#[test]
1131	fn a_refused_open_names_the_device_and_format() {
1132		let layout = Layout {
1133			sample_rate: 44_100,
1134			channels: 1,
1135		};
1136
1137		let failure = opening_error(cpal::Error::new(cpal::ErrorKind::UnsupportedConfig), MIC, layout);
1138		match failure {
1139			Error::Unsupported(message) => {
1140				assert!(message.contains("Test Mic at 44100 Hz with 1 channels"), "{message}")
1141			}
1142			other => panic!("expected an unsupported format, got {other:?}"),
1143		}
1144
1145		let failure = opening_error(cpal::Error::new(cpal::ErrorKind::DeviceBusy), MIC, layout);
1146		match failure {
1147			Error::Capture(message) => assert!(message.contains("Test Mic at 44100 Hz with 1 channels"), "{message}"),
1148			other => panic!("expected a capture failure, got {other:?}"),
1149		}
1150	}
1151}