1use 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#[derive(Clone, Debug, PartialEq, Eq)]
42#[non_exhaustive]
43pub enum Source {
44 Microphone(Option<String>),
47
48 System,
52}
53
54impl Default for Source {
56 fn default() -> Self {
57 Self::Microphone(None)
58 }
59}
60
61const FIRST_BUFFER_TIMEOUT: Duration = Duration::from_secs(5);
66
67#[derive(Clone, Debug, Default)]
78#[non_exhaustive]
79pub struct Config {
80 pub source: Source,
82 pub sample_rate: Option<u32>,
84 pub channels: Option<u32>,
86 #[cfg(all(feature = "capture", feature = "playback"))]
97 pub aec: Option<crate::aec::Control>,
98}
99
100pub(crate) struct Samples {
102 pub data: Vec<f32>,
104
105 pub gap: bool,
111
112 pub captured: Option<Instant>,
115
116 recycle: Option<ringbuf::HeapProd<Vec<f32>>>,
119}
120
121impl Samples {
122 #[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 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 }
153 }
154}
155
156impl Drop for Samples {
157 fn drop(&mut self) {
158 self.recycle();
159 }
160}
161
162#[derive(Clone, Copy, Debug, PartialEq, Eq)]
164pub(crate) struct Layout {
165 pub sample_rate: u32,
166 pub channels: u32,
167}
168
169fn 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#[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 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 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 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
240pub(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
255pub struct Producer {
261 stream: Stream,
262 shared: fanout::Producer,
263}
264
265impl Producer {
266 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 pub fn consume(&self) -> Consumer {
282 self.shared.consume()
283 }
284
285 pub async fn run(mut self) -> Result<(), Error> {
290 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 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#[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
327fn 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
335pub(crate) struct Microphone {
340 _stream: cpal::Stream,
342 reader: MicrophoneReader,
343 pending: Option<Samples>,
346 layout: Layout,
348 device: Device,
350}
351
352struct MicrophoneReader {
356 rx: buffer::Reader,
357 errors: kio::Consumer<Option<cpal::Error>>,
358}
359
360impl MicrophoneReader {
361 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 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
384async 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 async fn open(selector: Option<&str>, config: &Config) -> Result<Self, Error> {
403 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 #[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 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 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 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#[derive(Clone, Debug, PartialEq, Eq)]
516#[non_exhaustive]
517pub struct Device {
518 pub id: String,
523 pub name: String,
525 pub default: bool,
530 pub host: String,
535}
536
537impl Device {
538 pub fn source(&self) -> Source {
540 Source::Microphone(Some(self.id.clone()))
541 }
542}
543
544pub async fn devices() -> Result<Vec<Device>, Error> {
546 blocking(list).await
547}
548
549fn list() -> Result<Vec<Device>, Error> {
551 let preferred = cpal::default_host().id();
556 let mut devices = Vec::new();
557 let mut seen = std::collections::HashSet::new();
560
561 for id in cpal::available_hosts() {
562 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 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
606async 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
617fn 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 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 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 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
667fn negotiate(
671 device: &str,
672 default: cpal::SupportedStreamConfig,
673 ranges: impl IntoIterator<Item = cpal::SupportedStreamConfigRange>,
674 config: &Config,
675) -> Result<cpal::SupportedStreamConfig, Error> {
676 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 .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
725fn writable(format: cpal::SampleFormat) -> bool {
727 matches!(
728 format,
729 cpal::SampleFormat::F32 | cpal::SampleFormat::I16 | cpal::SampleFormat::U16
730 )
731}
732
733fn 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
743const MAX_CAPTURE_DELAY: Duration = Duration::from_secs(1);
747
748const MAX_DRIFT: u32 = 1_000;
752
753#[derive(Default)]
761struct StreamClock {
762 anchor: Option<(Instant, cpal::StreamInstant)>,
764}
765
766impl StreamClock {
767 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
791fn 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
810fn 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 #[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 #[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 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 #[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 #[test]
1033 fn a_slow_stream_clock_is_followed() {
1034 let start = Instant::now();
1035 let mut clock = StreamClock::default();
1036 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 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 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 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}