Skip to main content

handy_cpal/
lib.rs

1//! Low-level library for audio input and output, written in Rust.
2//!
3//! For higher-level audio playback and capture, consider
4//! [Rodio](https://github.com/RustAudio/rodio) or similar libraries.
5//!
6//! # How to use cpal
7//!
8//! Here are some concepts cpal exposes:
9//!
10//! - A [`Host`] provides access to the available audio devices on the system.
11//!   Some platforms have more than one host available, but every platform supported by CPAL has at
12//!   least one [default_host] that is guaranteed to be available.
13//! - A [`Device`] is an audio device that may have any number of input and
14//!   output streams.
15//! - A [`Stream`] is an open flow of audio data. Input streams allow you to
16//!   receive audio data, output streams allow you to play audio data. You must choose which
17//!   [Device] will run your stream before you can create one. Often, a default device can be
18//!   retrieved via the [Host].
19//!
20//! The first step is to initialise the [`Host`]:
21//!
22//! ```
23//! use cpal::traits::HostTrait;
24//! let host = cpal::default_host();
25//! ```
26//!
27//! Then choose an available [`Device`]. The easiest way is to use the default input or output
28//! `Device` via the [`default_input_device()`] or [`default_output_device()`] methods on `host`.
29//!
30//! Alternatively, you can enumerate all the available devices with the [`devices()`] method.
31//! Beware that the `default_*_device()` functions return an `Option<Device>` in case no device
32//! is available for that stream type on the system.
33//!
34//! ```no_run
35//! # use cpal::traits::HostTrait;
36//! # let host = cpal::default_host();
37//! let device = host.default_output_device().expect("no output device available");
38//! ```
39//!
40//! Before we can create a stream, we must decide what the configuration of the audio stream is
41//! going to be.
42//! You can query all the supported configurations with the
43//! [`supported_input_configs()`] and [`supported_output_configs()`] methods.
44//! These produce a list of [`SupportedStreamConfigRange`] structs which can later be turned into
45//! actual [`SupportedStreamConfig`] structs.
46//!
47//! If you don't want to query the list of configs,
48//! you can also build your own [`StreamConfig`] manually, but doing so could lead to an error when
49//! building the stream if the config is not supported by the device.
50//!
51//! > **Note**: the `supported_input/output_configs()` methods
52//! > could return an error for example if the device has been disconnected.
53//!
54//! ```no_run
55//! use cpal::traits::{DeviceTrait, HostTrait};
56//! # let host = cpal::default_host();
57//! # let device = host.default_output_device().unwrap();
58//! let mut supported_configs_range = device.supported_output_configs()
59//!     .expect("error while querying configs");
60//! let supported_config = supported_configs_range.next()
61//!     .expect("no supported config?!")
62//!     .with_max_sample_rate();
63//! ```
64//!
65//! Now that we have everything for the stream, we are ready to create it from our selected device:
66//!
67//! ```no_run
68//! use cpal::Data;
69//! use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
70//! # let host = cpal::default_host();
71//! # let device = host.default_output_device().unwrap();
72//! # let config = device.default_output_config().unwrap().into();
73//! let stream = device.build_output_stream(
74//!     config,
75//!     move |data: &mut [f32], _: &cpal::OutputCallbackInfo| {
76//!         // react to stream events and read or write stream data here.
77//!     },
78//!     move |err| {
79//!         // react to errors here.
80//!     },
81//!     None // Timeout for stream initialization: None = wait indefinitely,
82//!          // Some(Duration) = time to wait for the backend to initialize the stream.
83//! );
84//! ```
85//!
86//! Streams are returned in a paused state. Once the stream has been started with
87//! [`Stream::play`](traits::StreamTrait::play), the selected audio device will periodically call
88//! the data callback that was passed to the function. For input streams, the callback receives
89//! `&`[`Data`] containing captured audio samples. For output streams, the callback receives
90//! `&mut`[`Data`] to be filled with audio samples for playback.
91//!
92//! > **Note**: Creating and running a stream will *not* block the thread. On modern platforms, the
93//! > given callback is called by a dedicated, high-priority thread responsible for delivering
94//! > audio data to the system's audio device in a timely manner. On older platforms that only
95//! > provide a blocking API (e.g. ALSA), CPAL will create a thread in order to consistently
96//! > provide non-blocking behaviour (currently this is a thread per stream, but this may change to
97//! > use a single thread for all streams). *If this is an issue for your platform or design,
98//! > please share your issue and use-case with the CPAL team on the GitHub issue tracker for
99//! > consideration.*
100//!
101//! In this example, we simply fill the given output buffer with silence.
102//!
103//! ```no_run
104//! use cpal::{Data, Sample, SampleFormat, FromSample};
105//! use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
106//! # let host = cpal::default_host();
107//! # let device = host.default_output_device().unwrap();
108//! # let supported_config = device.default_output_config().unwrap();
109//! let err_fn = |err| eprintln!("an error occurred on the output audio stream: {}", err);
110//! let sample_format = supported_config.sample_format();
111//! let config = supported_config.into();
112//! let stream = match sample_format {
113//!     SampleFormat::F32 => device.build_output_stream(config, write_silence::<f32>, err_fn, None),
114//!     SampleFormat::I16 => device.build_output_stream(config, write_silence::<i16>, err_fn, None),
115//!     SampleFormat::U16 => device.build_output_stream(config, write_silence::<u16>, err_fn, None),
116//!     sample_format => panic!("Unsupported sample format '{sample_format}'")
117//! }.unwrap();
118//!
119//! fn write_silence<T: Sample>(data: &mut [T], _: &cpal::OutputCallbackInfo) {
120//!     for sample in data.iter_mut() {
121//!         *sample = Sample::EQUILIBRIUM;
122//!     }
123//! }
124//! ```
125//!
126//! Streams are always returned in a paused state, so we must call
127//! [`Stream::play`](traits::StreamTrait::play) to start running the data callback.
128//!
129//! ```no_run
130//! # use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
131//! # let host = cpal::default_host();
132//! # let device = host.default_output_device().unwrap();
133//! # let supported_config = device.default_output_config().unwrap();
134//! # let sample_format = supported_config.sample_format();
135//! # let config = supported_config.into();
136//! # let data_fn = move |_data: &mut cpal::Data, _: &cpal::OutputCallbackInfo| {};
137//! # let err_fn = move |_err| {};
138//! # let stream = device.build_output_stream_raw(config, sample_format, data_fn, err_fn, None).unwrap();
139//! stream.play().unwrap();
140//! ```
141//!
142//! Some devices support pausing the audio stream. This can be useful for saving energy in moments
143//! of silence.
144//!
145//! ```no_run
146//! # use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
147//! # let host = cpal::default_host();
148//! # let device = host.default_output_device().unwrap();
149//! # let supported_config = device.default_output_config().unwrap();
150//! # let sample_format = supported_config.sample_format();
151//! # let config = supported_config.into();
152//! # let data_fn = move |_data: &mut cpal::Data, _: &cpal::OutputCallbackInfo| {};
153//! # let err_fn = move |_err| {};
154//! # let stream = device.build_output_stream_raw(config, sample_format, data_fn, err_fn, None).unwrap();
155//! stream.pause().unwrap();
156//! ```
157//!
158//! [`default_input_device()`]: traits::HostTrait::default_input_device
159//! [`default_output_device()`]: traits::HostTrait::default_output_device
160//! [`devices()`]: traits::HostTrait::devices
161//! [`supported_input_configs()`]: traits::DeviceTrait::supported_input_configs
162//! [`supported_output_configs()`]: traits::DeviceTrait::supported_output_configs
163
164#![cfg_attr(docsrs, feature(doc_cfg))]
165
166// Extern crate declarations with `#[macro_use]` must unfortunately be at crate root.
167#[cfg(all(
168    target_arch = "wasm32",
169    target_os = "unknown",
170    feature = "wasm-bindgen"
171))]
172extern crate js_sys;
173#[cfg(all(
174    target_arch = "wasm32",
175    target_os = "unknown",
176    feature = "wasm-bindgen"
177))]
178extern crate wasm_bindgen;
179#[cfg(all(
180    target_arch = "wasm32",
181    target_os = "unknown",
182    feature = "wasm-bindgen"
183))]
184extern crate web_sys;
185
186pub use device_description::{
187    DeviceDescription, DeviceDescriptionBuilder, DeviceDirection, DeviceType, InterfaceType,
188};
189pub use error::*;
190pub use platform::{
191    available_hosts, default_host, host_from_id, Device, Devices, Host, HostId, Stream,
192    SupportedInputConfigs, SupportedOutputConfigs, ALL_HOSTS,
193};
194pub use sample_format::{FromSample, Sample, SampleFormat, SizedSample, I24, U24};
195#[cfg(all(
196    target_arch = "wasm32",
197    target_os = "unknown",
198    feature = "wasm-bindgen"
199))]
200use wasm_bindgen::prelude::*;
201
202pub mod device_description;
203mod error;
204mod host;
205pub mod platform;
206mod sample_format;
207mod timestamp;
208pub mod traits;
209
210/// Iterator of devices wrapped in a filter to only include certain device types
211pub type DevicesFiltered<I> = std::iter::Filter<I, fn(&<I as Iterator>::Item) -> bool>;
212
213/// A host's device iterator yielding only *input* devices.
214pub type InputDevices<I> = DevicesFiltered<I>;
215
216/// A host's device iterator yielding only *output* devices.
217pub type OutputDevices<I> = DevicesFiltered<I>;
218
219/// Number of channels.
220pub type ChannelCount = u16;
221
222/// The number of samples processed per second for a single channel of audio.
223pub type SampleRate = u32;
224
225/// 44.1 kHz: the CD standard, widely used in music production and consumer audio.
226pub const SAMPLE_RATE_CD: SampleRate = 44_100;
227
228/// 48 kHz: the EBU/SMPTE broadcast standard, default on most modern hardware.
229pub const SAMPLE_RATE_48K: SampleRate = 48_000;
230
231/// A frame represents one sample for each channel. For example, with stereo audio,
232/// one frame contains two samples (left and right channels).
233pub type FrameCount = u32;
234
235/// A stable identifier for an audio device across all supported platforms.
236///
237/// Device IDs should remain stable across application restarts and can be serialized using `Display`/`FromStr`.
238///
239/// A device ID consists of a [`HostId`] identifying the audio backend and a device-specific identifier string.
240///
241/// # Example
242///
243/// ```no_run
244/// use cpal::traits::{HostTrait, DeviceTrait};
245/// use cpal::DeviceId;
246/// use std::str::FromStr;
247///
248/// let host = cpal::default_host();
249/// let device = host.default_output_device().unwrap();
250/// let device_id = device.id().unwrap();
251///
252/// // Serialize to string (e.g., for storage in config file)
253/// let id_string = device_id.to_string();
254/// println!("Device ID: {}", id_string); // e.g., "wasapi:device_identifier"
255///
256/// // Deserialize from string
257/// match DeviceId::from_str(&id_string) {
258///     Ok(parsed_id) => {
259///         // Retrieve the device by its ID
260///         if let Some(device) = host.device_by_id(&parsed_id) {
261///             println!("Found device: {:?}", device.id());
262///         }
263///     }
264///     Err(e) => eprintln!("Failed to parse device ID: {}", e),
265/// }
266/// ```
267#[derive(Clone, Debug, PartialEq, Eq, Hash)]
268pub struct DeviceId(crate::platform::HostId, Box<str>);
269
270impl DeviceId {
271    /// Creates a `DeviceId` from a host identifier and a device-specific identifier string.
272    ///
273    /// This constructor is used by backend implementations. Application code should obtain
274    /// `DeviceId` values through [`DeviceTrait::id`] and persist them via [`Display`]/[`FromStr`].
275    ///
276    /// [`DeviceTrait::id`]: crate::traits::DeviceTrait::id
277    /// [`Display`]: std::fmt::Display
278    /// [`FromStr`]: std::str::FromStr
279    pub fn new(host: crate::platform::HostId, id: impl AsRef<str>) -> Self {
280        Self(host, Box::from(id.as_ref()))
281    }
282
283    /// Returns the host this device belongs to.
284    pub fn host(&self) -> crate::platform::HostId {
285        self.0
286    }
287
288    /// Returns the backend-specific device identifier string.
289    pub fn id(&self) -> &str {
290        &self.1
291    }
292}
293
294impl std::fmt::Display for DeviceId {
295    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
296        write!(f, "{}:{}", self.host(), self.id())
297    }
298}
299
300impl std::str::FromStr for DeviceId {
301    type Err = Error;
302
303    /// Parse a device identifier from its string representation (e.g. `"alsa:hw:0,0"`).
304    ///
305    /// The format is `"<host>:<device>"` where `<host>` is the lowercase host name (see
306    /// [`HostId`]) and `<device>` is the device-specific identifier string.
307    ///
308    /// # Errors
309    ///
310    /// - [`ErrorKind::InvalidInput`] if the string is not in `"host:device"` format.
311    /// - [`ErrorKind::UnsupportedOperation`] if the host portion names a host not available on this
312    ///   platform.
313    ///
314    /// [`ErrorKind::InvalidInput`]: ErrorKind::InvalidInput
315    /// [`ErrorKind::UnsupportedOperation`]: ErrorKind::UnsupportedOperation
316    fn from_str(s: &str) -> Result<Self, Self::Err> {
317        let (host_str, device_str) = s.split_once(':').ok_or_else(|| {
318            Error::with_message(
319                ErrorKind::InvalidInput,
320                format!("failed to parse device ID \"{s}\": expected \"host:device_id\" format"),
321            )
322        })?;
323
324        let host_id = crate::platform::HostId::from_str(host_str)?;
325
326        Ok(Self::new(host_id, device_str))
327    }
328}
329
330/// The buffer size requests the callback size for audio streams.
331///
332/// This controls the approximate size of the audio buffer passed to your callback.
333/// The actual callback size depends on the host/platform implementation and hardware
334/// constraints, and may differ from or vary around the requested size.
335///
336/// ## Callback Size Expectations
337///
338/// When you specify [`BufferSize::Fixed(x)`], you are **requesting** that callbacks
339/// receive approximately `x` frames of audio data. However, **no guarantees can be
340/// made** about the actual callback size:
341///
342/// - The host may round to hardware-supported values
343/// - Different devices have different constraints
344/// - The callback size may vary between calls (especially on mobile platforms)
345/// - The actual size might be larger or smaller than requested
346///
347/// ## Latency Considerations
348///
349/// [`BufferSize::Default`] uses the host's default buffer size, which may be
350/// surprisingly large, leading to higher latency. If low latency is desired,
351/// [`BufferSize::Fixed`] should be used with a small value in accordance with
352/// the [`SupportedBufferSize`] range from [`SupportedStreamConfig`].
353///
354/// Smaller buffer sizes reduce latency but may increase CPU usage and risk audio
355/// dropouts if the callback cannot process audio quickly enough.
356///
357/// # Example
358///
359/// ```no_run
360/// use cpal::traits::{DeviceTrait, HostTrait};
361/// use cpal::{BufferSize, SupportedBufferSize};
362///
363/// let host = cpal::default_host();
364/// let device = host.default_output_device().unwrap();
365/// let config = device.default_output_config().unwrap();
366///
367/// // Check supported buffer size range
368/// match config.buffer_size() {
369///     SupportedBufferSize::Range { min, max } => {
370///         println!("Buffer size range: {} - {}", min, max);
371///         // Request a small buffer for low latency
372///         let mut stream_config = config.config();
373///         stream_config.buffer_size = BufferSize::Fixed(256);
374///     }
375///     SupportedBufferSize::Unknown => {
376///         // Platform doesn't expose buffer size control
377///         println!("Buffer size cannot be queried on this platform");
378///     }
379/// }
380/// ```
381///
382/// [`BufferSize::Default`]: BufferSize::Default
383/// [`BufferSize::Fixed`]: BufferSize::Fixed
384/// [`BufferSize::Fixed(x)`]: BufferSize::Fixed
385/// [`SupportedBufferSize`]: SupportedStreamConfig::buffer_size
386/// [`SupportedStreamConfig`]: SupportedStreamConfig
387#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
388pub enum BufferSize {
389    #[default]
390    Default,
391    Fixed(FrameCount),
392}
393
394#[cfg(all(
395    target_arch = "wasm32",
396    target_os = "unknown",
397    feature = "wasm-bindgen"
398))]
399impl wasm_bindgen::describe::WasmDescribe for BufferSize {
400    fn describe() {
401        <Option<FrameCount> as wasm_bindgen::describe::WasmDescribe>::describe();
402    }
403}
404
405#[cfg(all(
406    target_arch = "wasm32",
407    target_os = "unknown",
408    feature = "wasm-bindgen"
409))]
410impl wasm_bindgen::convert::IntoWasmAbi for BufferSize {
411    type Abi = <Option<FrameCount> as wasm_bindgen::convert::IntoWasmAbi>::Abi;
412
413    fn into_abi(self) -> Self::Abi {
414        match self {
415            Self::Default => None,
416            Self::Fixed(fc) => Some(fc),
417        }
418        .into_abi()
419    }
420}
421
422#[cfg(all(
423    target_arch = "wasm32",
424    target_os = "unknown",
425    feature = "wasm-bindgen"
426))]
427impl wasm_bindgen::convert::FromWasmAbi for BufferSize {
428    type Abi = <Option<FrameCount> as wasm_bindgen::convert::FromWasmAbi>::Abi;
429
430    unsafe fn from_abi(js: Self::Abi) -> Self {
431        match Option::<FrameCount>::from_abi(js) {
432            None => Self::Default,
433            Some(fc) => Self::Fixed(fc),
434        }
435    }
436}
437
438/// The set of parameters used to describe how to open a stream.
439///
440/// The sample format is omitted in favour of using a sample type.
441///
442/// See also [`BufferSize`] for details on buffer size behavior and latency considerations.
443#[cfg_attr(
444    all(
445        target_arch = "wasm32",
446        target_os = "unknown",
447        feature = "wasm-bindgen"
448    ),
449    wasm_bindgen
450)]
451#[derive(Clone, Debug, Eq, PartialEq, Copy)]
452pub struct StreamConfig {
453    pub channels: ChannelCount,
454    pub sample_rate: SampleRate,
455    pub buffer_size: BufferSize,
456}
457
458/// Describes the minimum and maximum supported buffer size for the device
459#[derive(Clone, Copy, Debug, Default, Eq, PartialEq)]
460pub enum SupportedBufferSize {
461    Range {
462        min: FrameCount,
463        max: FrameCount,
464    },
465    /// In the case that the platform provides no way of getting the default
466    /// buffer size before starting a stream.
467    #[default]
468    Unknown,
469}
470
471/// Describes a range of supported stream configurations, retrieved via the
472/// [`Device::supported_input/output_configs`](traits::DeviceTrait#required-methods) method.
473#[derive(Debug, Clone, Copy, PartialEq, Eq)]
474pub struct SupportedStreamConfigRange {
475    pub(crate) channels: ChannelCount,
476    /// Minimum value for the sample rate of the supported formats.
477    pub(crate) min_sample_rate: SampleRate,
478    /// Maximum value for the sample rate of the supported formats.
479    pub(crate) max_sample_rate: SampleRate,
480    /// Buffer size ranges supported by the device
481    pub(crate) buffer_size: SupportedBufferSize,
482    /// Type of data expected by the device.
483    pub(crate) sample_format: SampleFormat,
484}
485
486/// Common iterator types used by backend implementations.
487///
488/// All backends use these same concrete iterator types for supported stream configurations.
489#[allow(dead_code)]
490pub(crate) mod iter {
491    use super::SupportedStreamConfigRange;
492
493    /// Iterator type for supported input stream configurations.
494    ///
495    /// This is the iterator type returned by all backend implementations of
496    /// [`DeviceTrait::supported_input_configs`](crate::traits::DeviceTrait::supported_input_configs).
497    pub type SupportedInputConfigs = std::vec::IntoIter<SupportedStreamConfigRange>;
498
499    /// Iterator type for supported output stream configurations.
500    ///
501    /// This is the iterator type returned by all backend implementations of
502    /// [`DeviceTrait::supported_output_configs`](crate::traits::DeviceTrait::supported_output_configs).
503    pub type SupportedOutputConfigs = std::vec::IntoIter<SupportedStreamConfigRange>;
504}
505
506/// Describes a single supported stream configuration, retrieved via either a
507/// [`SupportedStreamConfigRange`] instance or one of the
508/// [`Device::default_input/output_config`](traits::DeviceTrait#required-methods) methods.
509#[derive(Debug, Clone, Copy, PartialEq, Eq)]
510pub struct SupportedStreamConfig {
511    channels: ChannelCount,
512    sample_rate: SampleRate,
513    buffer_size: SupportedBufferSize,
514    sample_format: SampleFormat,
515}
516
517/// A buffer of dynamically typed audio data, passed to raw stream callbacks.
518///
519/// Raw input stream callbacks receive `&Data`, while raw output stream callbacks expect `&mut Data`.
520#[derive(Debug)]
521pub struct Data {
522    data: *mut (),
523    len: usize,
524    sample_format: SampleFormat,
525}
526
527pub use timestamp::{
528    InputCallbackInfo, InputStreamTimestamp, OutputCallbackInfo, OutputStreamTimestamp,
529    StreamInstant,
530};
531
532impl SupportedStreamConfig {
533    pub fn new(
534        channels: ChannelCount,
535        sample_rate: SampleRate,
536        buffer_size: SupportedBufferSize,
537        sample_format: SampleFormat,
538    ) -> Self {
539        Self {
540            channels,
541            sample_rate,
542            buffer_size,
543            sample_format,
544        }
545    }
546
547    pub fn channels(&self) -> ChannelCount {
548        self.channels
549    }
550
551    pub fn sample_rate(&self) -> SampleRate {
552        self.sample_rate
553    }
554
555    pub fn buffer_size(&self) -> &SupportedBufferSize {
556        &self.buffer_size
557    }
558
559    pub fn sample_format(&self) -> SampleFormat {
560        self.sample_format
561    }
562
563    pub fn config(&self) -> StreamConfig {
564        StreamConfig {
565            channels: self.channels,
566            sample_rate: self.sample_rate,
567            buffer_size: BufferSize::Default,
568        }
569    }
570}
571
572// Note: Data does not implement `is_empty()` because it always contains a valid audio buffer
573// by design. The buffer may contain silence, but it is never structurally empty.
574#[allow(clippy::len_without_is_empty)]
575impl Data {
576    /// Constructor for host implementations to use.
577    ///
578    /// # Safety
579    /// The following requirements must be met in order for the safety of `Data`'s API.
580    /// - The `data` pointer must point to the first sample in the slice containing all samples.
581    /// - The `len` must describe the length of the buffer as a number of samples in the expected
582    ///   format specified via the `sample_format` argument.
583    /// - The `sample_format` must correctly represent the underlying sample data delivered/expected
584    ///   by the stream.
585    pub unsafe fn from_parts(data: *mut (), len: usize, sample_format: SampleFormat) -> Self {
586        Self {
587            data,
588            len,
589            sample_format,
590        }
591    }
592
593    /// The sample format of the internal audio data.
594    pub fn sample_format(&self) -> SampleFormat {
595        self.sample_format
596    }
597
598    /// The full length of the buffer in samples.
599    ///
600    /// The returned length is the same length as the slice of type `T` that would be returned via
601    /// [`as_slice`](Self::as_slice) given a sample type that matches the inner sample format.
602    pub fn len(&self) -> usize {
603        self.len
604    }
605
606    /// The raw slice of memory representing the underlying audio data as a slice of bytes.
607    ///
608    /// It is up to the user to interpret the slice of memory based on [`Data::sample_format`].
609    pub fn bytes(&self) -> &[u8] {
610        let len = self.len * self.sample_format.sample_size();
611        // The safety of this block relies on correct construction of the `Data` instance.
612        // See the unsafe `from_parts` constructor for these requirements.
613        unsafe { std::slice::from_raw_parts(self.data as *const u8, len) }
614    }
615
616    /// The raw slice of memory representing the underlying audio data as a slice of bytes.
617    ///
618    /// It is up to the user to interpret the slice of memory based on [`Data::sample_format`].
619    pub fn bytes_mut(&mut self) -> &mut [u8] {
620        let len = self.len * self.sample_format.sample_size();
621        // The safety of this block relies on correct construction of the `Data` instance. See
622        // the unsafe `from_parts` constructor for these requirements.
623        unsafe { std::slice::from_raw_parts_mut(self.data as *mut u8, len) }
624    }
625
626    /// Access the data as a slice of sample type `T`.
627    ///
628    /// Returns `None` if the sample type does not match the expected sample format.
629    pub fn as_slice<T>(&self) -> Option<&[T]>
630    where
631        T: SizedSample,
632    {
633        if T::FORMAT == self.sample_format {
634            // The safety of this block relies on correct construction of the `Data` instance. See
635            // the unsafe `from_parts` constructor for these requirements.
636            unsafe { Some(std::slice::from_raw_parts(self.data as *const T, self.len)) }
637        } else {
638            None
639        }
640    }
641
642    /// Access the data as a slice of sample type `T`.
643    ///
644    /// Returns `None` if the sample type does not match the expected sample format.
645    pub fn as_slice_mut<T>(&mut self) -> Option<&mut [T]>
646    where
647        T: SizedSample,
648    {
649        if T::FORMAT == self.sample_format {
650            // The safety of this block relies on correct construction of the `Data` instance. See
651            // the unsafe `from_parts` constructor for these requirements.
652            unsafe {
653                Some(std::slice::from_raw_parts_mut(
654                    self.data as *mut T,
655                    self.len,
656                ))
657            }
658        } else {
659            None
660        }
661    }
662}
663
664impl SupportedStreamConfigRange {
665    pub fn new(
666        channels: ChannelCount,
667        min_sample_rate: SampleRate,
668        max_sample_rate: SampleRate,
669        buffer_size: SupportedBufferSize,
670        sample_format: SampleFormat,
671    ) -> Self {
672        Self {
673            channels,
674            min_sample_rate,
675            max_sample_rate,
676            buffer_size,
677            sample_format,
678        }
679    }
680
681    pub fn channels(&self) -> ChannelCount {
682        self.channels
683    }
684
685    pub fn min_sample_rate(&self) -> SampleRate {
686        self.min_sample_rate
687    }
688
689    pub fn max_sample_rate(&self) -> SampleRate {
690        self.max_sample_rate
691    }
692
693    pub fn buffer_size(&self) -> &SupportedBufferSize {
694        &self.buffer_size
695    }
696
697    pub fn sample_format(&self) -> SampleFormat {
698        self.sample_format
699    }
700
701    /// Retrieve a [`SupportedStreamConfig`] with the given sample rate.
702    ///
703    /// # Panics
704    ///
705    /// Panics if the given `sample_rate` is outside the range specified within
706    /// this [`SupportedStreamConfigRange`] instance. For a non-panicking
707    /// variant, use [`try_with_sample_rate`](#method.try_with_sample_rate).
708    pub fn with_sample_rate(self, sample_rate: SampleRate) -> SupportedStreamConfig {
709        self.try_with_sample_rate(sample_rate)
710            .expect("sample rate out of range")
711    }
712
713    /// Retrieve a [`SupportedStreamConfig`] with the given sample rate.
714    ///
715    /// Returns `None` if the given sample rate is outside the range specified
716    /// within this [`SupportedStreamConfigRange`] instance.
717    pub fn try_with_sample_rate(self, sample_rate: SampleRate) -> Option<SupportedStreamConfig> {
718        if self.min_sample_rate <= sample_rate && sample_rate <= self.max_sample_rate {
719            Some(SupportedStreamConfig {
720                channels: self.channels,
721                sample_rate,
722                sample_format: self.sample_format,
723                buffer_size: self.buffer_size,
724            })
725        } else {
726            None
727        }
728    }
729
730    /// Turns this [`SupportedStreamConfigRange`] into a [`SupportedStreamConfig`] corresponding to the maximum sample rate.
731    #[inline]
732    pub fn with_max_sample_rate(self) -> SupportedStreamConfig {
733        SupportedStreamConfig {
734            channels: self.channels,
735            sample_rate: self.max_sample_rate,
736            sample_format: self.sample_format,
737            buffer_size: self.buffer_size,
738        }
739    }
740
741    /// Returns `true` if `rate` falls within `[min_sample_rate, max_sample_rate]`.
742    pub fn contains_rate(&self, rate: SampleRate) -> bool {
743        self.min_sample_rate <= rate && rate <= self.max_sample_rate
744    }
745
746    /// Retrieve a [`SupportedStreamConfig`] with a standard sample rate.
747    ///
748    /// The preferred rate is selected in order:
749    /// 1. 48 kHz as the dominant native rate on modern hardware.
750    /// 2. 44.1 kHz as the standard CD/consumer rate.
751    ///
752    /// Returns `None` if neither standard rate falls within the range specified within this
753    /// [`SupportedStreamConfigRange`] instance.
754    pub fn try_with_standard_sample_rate(self) -> Option<SupportedStreamConfig> {
755        for rate in [SAMPLE_RATE_48K, SAMPLE_RATE_CD] {
756            if self.contains_rate(rate) {
757                return Some(self.with_sample_rate(rate));
758            }
759        }
760        None
761    }
762
763    /// Retrieve a [`SupportedStreamConfig`] with a standard sample rate.
764    ///
765    /// The preferred rate is selected in order:
766    /// 1. 48 kHz as the dominant native rate on modern hardware.
767    /// 2. 44.1 kHz as the standard CD/consumer rate.
768    ///
769    /// # Panics
770    ///
771    /// Panics if neither standard rate falls within the range specified within this
772    /// [`SupportedStreamConfigRange`] instance. For a non-panicking variant, use
773    /// [`try_with_standard_sample_rate`](Self::try_with_standard_sample_rate).
774    pub fn with_standard_sample_rate(self) -> SupportedStreamConfig {
775        self.try_with_standard_sample_rate()
776            .expect("no standard sample rate (48000 or 44100 Hz) in supported range")
777    }
778
779    /// A comparison function which compares two [`SupportedStreamConfigRange`]s in terms of their
780    /// priority of use as a default stream format.
781    ///
782    /// Some backends do not provide a default stream format for their audio devices. In these
783    /// cases, CPAL attempts to decide on a reasonable default format for the user. To do this we
784    /// use the "greatest" of all supported stream formats when compared with this method.
785    ///
786    /// [`SupportedStreamConfig`]s are prioritised by the following heuristics, applied in order:
787    ///
788    /// **Channels**:
789    ///
790    /// 1. Stereo
791    /// 2. Mono
792    /// 3. Highest available channel count
793    ///
794    /// **Sample format** (most preferred first):
795    ///
796    /// F32 is ranked highest as the universal realtime audio format, followed by F64. Standard
797    /// integer widths descend by bit depth (I32 > I24 > I16); 64-bit integers are deprioritised
798    /// below I16 as accumulator types rather than native stream formats. Signed beats unsigned
799    /// at the same width. DSD ranks last as non-PCM.
800    ///
801    /// **Sample rate**:
802    ///
803    /// 1. 48 kHz (EBU/SMPTE broadcast standard)
804    /// 2. 44.1 kHz (CD standard)
805    /// 3. Highest supported sample rate
806    pub fn cmp_default_heuristics(&self, other: &Self) -> std::cmp::Ordering {
807        use std::cmp::Ordering::Equal;
808
809        let cmp_stereo = (self.channels == 2).cmp(&(other.channels == 2));
810        if cmp_stereo != Equal {
811            return cmp_stereo;
812        }
813
814        let cmp_mono = (self.channels == 1).cmp(&(other.channels == 1));
815        if cmp_mono != Equal {
816            return cmp_mono;
817        }
818
819        let cmp_channels = self.channels.cmp(&other.channels);
820        if cmp_channels != Equal {
821            return cmp_channels;
822        }
823
824        fn format_rank(fmt: SampleFormat) -> u8 {
825            match fmt {
826                SampleFormat::DsdU8 => 0,
827                SampleFormat::DsdU16 => 1,
828                SampleFormat::DsdU32 => 2,
829                SampleFormat::U8 => 3,
830                SampleFormat::I8 => 4,
831                // 64-bit integers: deprioritised below standard audio widths.
832                SampleFormat::U64 => 5,
833                SampleFormat::I64 => 6,
834                SampleFormat::U16 => 7,
835                SampleFormat::I16 => 8,
836                SampleFormat::U24 => 9,
837                SampleFormat::I24 => 10,
838                SampleFormat::U32 => 11,
839                SampleFormat::I32 => 12,
840                SampleFormat::F64 => 13,
841                SampleFormat::F32 => 14,
842            }
843        }
844
845        let cmp_format = format_rank(self.sample_format).cmp(&format_rank(other.sample_format));
846        if cmp_format != Equal {
847            return cmp_format;
848        }
849
850        let cmp_broadcast = self
851            .contains_rate(SAMPLE_RATE_48K)
852            .cmp(&other.contains_rate(SAMPLE_RATE_48K));
853        if cmp_broadcast != Equal {
854            return cmp_broadcast;
855        }
856
857        let cmp_cd = self
858            .contains_rate(SAMPLE_RATE_CD)
859            .cmp(&other.contains_rate(SAMPLE_RATE_CD));
860        if cmp_cd != Equal {
861            return cmp_cd;
862        }
863
864        self.max_sample_rate.cmp(&other.max_sample_rate)
865    }
866}
867
868impl From<SupportedStreamConfig> for StreamConfig {
869    fn from(conf: SupportedStreamConfig) -> Self {
870        conf.config()
871    }
872}
873
874#[allow(dead_code)]
875pub(crate) fn validate_stream_config(config: &StreamConfig) -> Result<(), Error> {
876    if config.channels == 0 {
877        return Err(Error::with_message(
878            ErrorKind::InvalidInput,
879            "channel count must be at least 1",
880        ));
881    }
882    if config.sample_rate == 0 {
883        return Err(Error::with_message(
884            ErrorKind::InvalidInput,
885            "sample rate must be at least 1 Hz",
886        ));
887    }
888    if config.buffer_size == BufferSize::Fixed(0) {
889        return Err(Error::with_message(
890            ErrorKind::InvalidInput,
891            "buffer size must be greater than 0",
892        ));
893    }
894    Ok(())
895}
896
897// If a backend does not provide an API for retrieving supported formats, we query it with a bunch
898// of commonly used rates. This is always the case for WASAPI and is sometimes the case for ALSA.
899#[allow(dead_code)]
900pub(crate) const COMMON_SAMPLE_RATES: &[SampleRate] = &[
901    // Standard PCM rates and DSD sample rates through DSD512
902    5512, 8000, 11025, 12000, 16000, 22050, 24000, 32000, 44100, 48000, 64000, 88200, 96000, 176400,
903    192000, 352800, 384000, 705600, 768000, 1411200, 1536000, 2822400, 3072000, 5644800, 6144000,
904    11289600, 12288000, 22579200, 24576000,
905];
906
907#[cfg(test)]
908mod tests {
909    use super::*;
910
911    fn make_range(
912        channels: ChannelCount,
913        format: SampleFormat,
914        min: SampleRate,
915        max: SampleRate,
916    ) -> SupportedStreamConfigRange {
917        SupportedStreamConfigRange {
918            buffer_size: SupportedBufferSize::Range { min: 256, max: 512 },
919            channels,
920            min_sample_rate: min,
921            max_sample_rate: max,
922            sample_format: format,
923        }
924    }
925
926    #[test]
927    fn with_standard_sample_rate() {
928        let r = |min, max| make_range(2, SampleFormat::F32, min, max);
929
930        assert_eq!(
931            r(1, 96_000).with_standard_sample_rate().sample_rate(),
932            SAMPLE_RATE_48K
933        );
934        assert_eq!(
935            r(1, 44_100).with_standard_sample_rate().sample_rate(),
936            SAMPLE_RATE_CD
937        );
938    }
939
940    #[test]
941    #[should_panic(expected = "no standard sample rate")]
942    fn with_standard_sample_rate_panics_when_no_standard_rate() {
943        make_range(2, SampleFormat::F32, 8_000, 32_000).with_standard_sample_rate();
944    }
945
946    #[test]
947    fn try_with_standard_sample_rate() {
948        let r = |min, max| make_range(2, SampleFormat::F32, min, max);
949
950        // 48 kHz available; first choice
951        assert_eq!(
952            r(1, 96_000)
953                .try_with_standard_sample_rate()
954                .map(|c| c.sample_rate()),
955            Some(SAMPLE_RATE_48K)
956        );
957
958        // 48 kHz not available but 44.1 kHz is; second choice
959        assert_eq!(
960            r(1, 44_100)
961                .try_with_standard_sample_rate()
962                .map(|c| c.sample_rate()),
963            Some(SAMPLE_RATE_CD)
964        );
965
966        // Neither preferred rate available
967        assert_eq!(r(8_000, 32_000).try_with_standard_sample_rate(), None);
968    }
969
970    #[test]
971    fn cmp_default_heuristics_format_order() {
972        use SampleFormat::*;
973
974        // Input is deliberately not sorted to prove the sort works.
975        let unsorted = [
976            F32, I16, DsdU32, U64, I32, DsdU8, F64, U8, I24, U16, I64, U24, U32, I8, DsdU16,
977        ];
978
979        let mut ranges: Vec<_> = unsorted
980            .iter()
981            .map(|&fmt| make_range(2, fmt, 1, 96_000))
982            .collect();
983        ranges.sort_by(|a, b| a.cmp_default_heuristics(b));
984
985        let sorted_formats: Vec<SampleFormat> = ranges.iter().map(|r| r.sample_format()).collect();
986
987        // Expected order from lowest to highest priority:
988        assert_eq!(
989            sorted_formats,
990            vec![DsdU8, DsdU16, DsdU32, U8, I8, U64, I64, U16, I16, U24, I24, U32, I32, F64, F32,]
991        );
992    }
993
994    #[test]
995    fn cmp_default_heuristics() {
996        let mut configs = [
997            make_range(1, SampleFormat::F64, 1, 96_000), // mono; loses to all stereo
998            make_range(2, SampleFormat::DsdU8, 1, 96_000), // DSD; lowest format priority
999            make_range(2, SampleFormat::U8, 1, 96_000),
1000            make_range(2, SampleFormat::I8, 1, 96_000),
1001            make_range(2, SampleFormat::U16, 1, 96_000),
1002            make_range(2, SampleFormat::I16, 1, 96_000),
1003            make_range(2, SampleFormat::F32, 1, 22_050), // neither standard rate
1004            make_range(2, SampleFormat::F32, 1, 44_100), // 44.1 kHz only
1005            make_range(2, SampleFormat::F32, 48_000, 96_000), // 48 kHz only
1006            make_range(2, SampleFormat::F32, 1, 96_000), // both standard rates
1007            make_range(2, SampleFormat::F64, 1, 96_000),
1008        ];
1009
1010        configs.sort_by(|a, b| a.cmp_default_heuristics(b));
1011
1012        // Results in ascending priority order (lowest first):
1013
1014        // [0] Mono loses to every stereo entry regardless of format or rate.
1015        assert_eq!(configs[0].channels(), 1);
1016        assert_eq!(configs[0].sample_format(), SampleFormat::F64);
1017
1018        // [1]–[5] Stereo entries ranked by format (DSD < 8-bit < 16-bit).
1019        assert_eq!(configs[1].sample_format(), SampleFormat::DsdU8);
1020        assert_eq!(configs[2].sample_format(), SampleFormat::U8);
1021        assert_eq!(configs[3].sample_format(), SampleFormat::I8);
1022        assert_eq!(configs[4].sample_format(), SampleFormat::U16);
1023        assert_eq!(configs[5].sample_format(), SampleFormat::I16);
1024
1025        // [6] F64 is outranked by F32.
1026        assert_eq!(configs[6].sample_format(), SampleFormat::F64);
1027        assert_eq!(configs[6].channels(), 2);
1028
1029        // [7]–[10] Stereo F32 entries ranked by rate coverage.
1030        assert_eq!(configs[7].sample_format(), SampleFormat::F32);
1031        assert_eq!(configs[7].max_sample_rate(), 22_050); // neither standard rate
1032
1033        assert_eq!(configs[8].sample_format(), SampleFormat::F32);
1034        assert_eq!(configs[8].max_sample_rate(), 44_100); // 44.1 kHz only
1035
1036        assert_eq!(configs[9].sample_format(), SampleFormat::F32);
1037        assert_eq!(configs[9].min_sample_rate(), 48_000); // 48 kHz only (no 44.1 kHz)
1038        assert_eq!(configs[9].max_sample_rate(), 96_000);
1039
1040        assert_eq!(configs[10].sample_format(), SampleFormat::F32);
1041        assert_eq!(configs[10].min_sample_rate(), 1);
1042        assert_eq!(configs[10].max_sample_rate(), 96_000); // both standard rates
1043    }
1044
1045    #[test]
1046    fn validate_stream_config_rejects_zero_channels() {
1047        let err = validate_stream_config(&StreamConfig {
1048            channels: 0,
1049            sample_rate: 44100,
1050            buffer_size: BufferSize::Default,
1051        })
1052        .unwrap_err();
1053        assert_eq!(err.kind(), ErrorKind::InvalidInput);
1054        assert!(err.message().unwrap().contains("channel"));
1055    }
1056
1057    #[test]
1058    fn validate_stream_config_rejects_zero_sample_rate() {
1059        let err = validate_stream_config(&StreamConfig {
1060            channels: 2,
1061            sample_rate: 0,
1062            buffer_size: BufferSize::Default,
1063        })
1064        .unwrap_err();
1065        assert_eq!(err.kind(), ErrorKind::InvalidInput);
1066        assert!(err.message().unwrap().contains("sample rate"));
1067    }
1068
1069    #[test]
1070    fn validate_stream_config_rejects_fixed_buffer_zero() {
1071        let err = validate_stream_config(&StreamConfig {
1072            channels: 2,
1073            sample_rate: 44100,
1074            buffer_size: BufferSize::Fixed(0),
1075        })
1076        .unwrap_err();
1077        assert_eq!(err.kind(), ErrorKind::InvalidInput);
1078        assert!(err.message().unwrap().contains("buffer size"));
1079    }
1080
1081    #[test]
1082    fn validate_stream_config_accepts_valid_configs() {
1083        assert!(validate_stream_config(&StreamConfig {
1084            channels: 2,
1085            sample_rate: 44100,
1086            buffer_size: BufferSize::Default,
1087        })
1088        .is_ok());
1089        assert!(validate_stream_config(&StreamConfig {
1090            channels: 1,
1091            sample_rate: 1,
1092            buffer_size: BufferSize::Fixed(1),
1093        })
1094        .is_ok());
1095    }
1096}