Skip to main content

weirdnet_audio_engine/
cpal_sink.rs

1//! The cpal device sink. See [`CpalSink`].
2
3use crate::sink::validate;
4use crate::{AudioSink, RenderFn, SinkConfig, SinkError, SinkHandle, SinkStats};
5use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
6use cpal::{BufferSize, Device, Error, ErrorKind, FromSample, Host, SampleFormat, SizedSample, StreamConfig, SupportedBufferSize};
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, Ordering};
9
10/// Plays through the default output device of a cpal host: ALSA on Linux (which a PipeWire or PulseAudio server serves through its ALSA
11/// plugin), AAudio on Android, and the native host elsewhere.
12///
13/// The stream is built as `f32`, or as `i16` when the device offers nothing else; the render function always sees `f32`. The `i16` path keeps
14/// a scratch buffer that grows to the largest block seen, so it allocates on the first callbacks only.
15///
16/// A request the device cannot do exactly is [`SinkError::UnsupportedConfig`] with the device's default attached, never a silent change of rate.
17pub struct CpalSink {
18    host: Host,
19    running: Arc<AtomicBool>,
20}
21
22impl Default for CpalSink {
23    fn default() -> Self {
24        CpalSink::new()
25    }
26}
27
28struct StreamGuard {
29    // Held for its Drop, which stops the stream.
30    _stream: cpal::Stream,
31    running: Arc<AtomicBool>,
32}
33
34impl Drop for StreamGuard {
35    fn drop(&mut self) {
36        self.running.store(false, Ordering::Release);
37    }
38}
39
40pub(crate) fn map_error(e: &Error) -> SinkError {
41    match e.kind() {
42        ErrorKind::DeviceNotAvailable | ErrorKind::HostUnavailable => SinkError::NoDevice,
43        _ => SinkError::Backend(e.to_string()),
44    }
45}
46
47impl CpalSink {
48    /// The platform's default host.
49    pub fn new() -> Self {
50        CpalSink::with_host(cpal::default_host())
51    }
52
53    pub fn with_host(host: Host) -> Self {
54        CpalSink { host, running: Arc::new(AtomicBool::new(false)) }
55    }
56
57    /// cpal's native PipeWire host (feature `pipewire`).
58    #[cfg(all(feature = "pipewire", any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd")))]
59    pub fn pipewire() -> Result<Self, SinkError> {
60        cpal::host_from_id(cpal::HostId::PipeWire).map(CpalSink::with_host).map_err(|e| map_error(&e))
61    }
62
63    fn device(&self) -> Result<Device, SinkError> {
64        self.host.default_output_device().ok_or(SinkError::NoDevice)
65    }
66}
67
68fn config_of(rate: u32, channels: u16) -> SinkConfig {
69    SinkConfig::new(rate, channels)
70}
71
72impl AudioSink for CpalSink {
73    fn default_config(&self) -> Result<SinkConfig, SinkError> {
74        let c = self.device()?.default_output_config().map_err(|e| map_error(&e))?;
75        Ok(config_of(c.sample_rate(), c.channels()))
76    }
77
78    fn start(&mut self, config: SinkConfig, render: RenderFn) -> Result<SinkHandle, SinkError> {
79        validate(config)?;
80        if self.running.load(Ordering::Acquire) {
81            return Err(SinkError::AlreadyStarted);
82        }
83        let device = self.device()?;
84        let unsupported = || SinkError::UnsupportedConfig { requested: config, supported: self.default_config().ok() };
85
86        // Prefer f32, accept i16, and only those: the render function is f32 and conversion beyond i16 is not worth carrying yet.
87        let mut chosen = None;
88        for range in device.supported_output_configs().map_err(|e| map_error(&e))? {
89            if range.channels() != config.channels || !range.contains_rate(config.sample_rate) {
90                continue;
91            }
92            match range.sample_format() {
93                SampleFormat::F32 => {
94                    chosen = Some(range);
95                    break;
96                }
97                SampleFormat::I16 if chosen.is_none() => chosen = Some(range),
98                _ => {}
99            }
100        }
101        let range = chosen.ok_or_else(unsupported)?;
102        let buffer_size = match (config.buffer_frames, range.buffer_size()) {
103            (Some(n), SupportedBufferSize::Range { min, max }) if (*min..=*max).contains(&n) => BufferSize::Fixed(n),
104            _ => BufferSize::Default,
105        };
106        let stream_config = StreamConfig { channels: config.channels, sample_rate: config.sample_rate, buffer_size };
107        let stats = SinkStats::new();
108        let stream = match range.sample_format() {
109            SampleFormat::F32 => build::<f32>(&device, stream_config, render, &stats),
110            _ => build::<i16>(&device, stream_config, render, &stats),
111        }
112        .map_err(|e| match e.kind() {
113            ErrorKind::UnsupportedConfig => unsupported(),
114            _ => map_error(&e),
115        })?;
116        stream.play().map_err(|e| map_error(&e))?;
117        self.running.store(true, Ordering::Release);
118        let actual = SinkConfig {
119            buffer_frames: match buffer_size {
120                BufferSize::Fixed(n) => Some(n),
121                BufferSize::Default => None,
122            },
123            ..config
124        };
125        let name = device.description().map(|d| d.name().to_string()).unwrap_or_else(|_| "unnamed device".into());
126        let description = format!("cpal {:?}: {name} ({:?})", self.host.id(), range.sample_format());
127        Ok(SinkHandle::new(actual, description, stats, Box::new(StreamGuard { _stream: stream, running: self.running.clone() })))
128    }
129}
130
131fn build<T>(device: &Device, config: StreamConfig, mut render: RenderFn, stats: &SinkStats) -> Result<cpal::Stream, Error>
132where
133    T: SizedSample + FromSample<f32> + Send + 'static,
134{
135    let data_stats = stats.clone();
136    let error_stats = stats.clone();
137    let mut scratch: Vec<f32> = Vec::new();
138    device.build_output_stream(
139        config,
140        move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
141            data_stats.record_callback();
142            // For f32 the conversion is a copy; the extra pass is cheap next to a device buffer and keeps one code path.
143            scratch.resize(data.len(), 0.0);
144            render(&mut scratch);
145            for (d, s) in data.iter_mut().zip(&scratch) {
146                *d = T::from_sample(if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) });
147            }
148        },
149        move |e: Error| match e.kind() {
150            ErrorKind::Xrun => error_stats.record_xrun(),
151            _ => error_stats.record_error(),
152        },
153        None,
154    )
155}
156
157#[cfg(test)]
158mod tests {
159    use super::*;
160
161    #[test]
162    fn cpal_errors_map_to_sink_errors() {
163        assert_eq!(map_error(&ErrorKind::DeviceNotAvailable.into()), SinkError::NoDevice);
164        assert_eq!(map_error(&ErrorKind::HostUnavailable.into()), SinkError::NoDevice);
165        assert!(matches!(map_error(&ErrorKind::BackendError.into()), SinkError::Backend(_)));
166    }
167
168    #[test]
169    fn invalid_configs_fail_before_touching_a_device() {
170        let mut sink = CpalSink::new();
171        let r: RenderFn = Box::new(|_| {});
172        assert!(matches!(sink.start(SinkConfig::new(0, 2), r), Err(SinkError::InvalidConfig(_))));
173    }
174}