use crate::sink::validate;
use crate::{AudioSink, RenderFn, SinkConfig, SinkError, SinkHandle, SinkStats};
use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
use cpal::{BufferSize, Device, Error, ErrorKind, FromSample, Host, SampleFormat, SizedSample, StreamConfig, SupportedBufferSize};
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
pub struct CpalSink {
host: Host,
running: Arc<AtomicBool>,
}
impl Default for CpalSink {
fn default() -> Self {
CpalSink::new()
}
}
struct StreamGuard {
_stream: cpal::Stream,
running: Arc<AtomicBool>,
}
impl Drop for StreamGuard {
fn drop(&mut self) {
self.running.store(false, Ordering::Release);
}
}
pub(crate) fn map_error(e: &Error) -> SinkError {
match e.kind() {
ErrorKind::DeviceNotAvailable | ErrorKind::HostUnavailable => SinkError::NoDevice,
_ => SinkError::Backend(e.to_string()),
}
}
impl CpalSink {
pub fn new() -> Self {
CpalSink::with_host(cpal::default_host())
}
pub fn with_host(host: Host) -> Self {
CpalSink { host, running: Arc::new(AtomicBool::new(false)) }
}
#[cfg(all(feature = "pipewire", any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd")))]
pub fn pipewire() -> Result<Self, SinkError> {
cpal::host_from_id(cpal::HostId::PipeWire).map(CpalSink::with_host).map_err(|e| map_error(&e))
}
fn device(&self) -> Result<Device, SinkError> {
self.host.default_output_device().ok_or(SinkError::NoDevice)
}
}
fn config_of(rate: u32, channels: u16) -> SinkConfig {
SinkConfig::new(rate, channels)
}
impl AudioSink for CpalSink {
fn default_config(&self) -> Result<SinkConfig, SinkError> {
let c = self.device()?.default_output_config().map_err(|e| map_error(&e))?;
Ok(config_of(c.sample_rate(), c.channels()))
}
fn start(&mut self, config: SinkConfig, render: RenderFn) -> Result<SinkHandle, SinkError> {
validate(config)?;
if self.running.load(Ordering::Acquire) {
return Err(SinkError::AlreadyStarted);
}
let device = self.device()?;
let unsupported = || SinkError::UnsupportedConfig { requested: config, supported: self.default_config().ok() };
let mut chosen = None;
for range in device.supported_output_configs().map_err(|e| map_error(&e))? {
if range.channels() != config.channels || !range.contains_rate(config.sample_rate) {
continue;
}
match range.sample_format() {
SampleFormat::F32 => {
chosen = Some(range);
break;
}
SampleFormat::I16 if chosen.is_none() => chosen = Some(range),
_ => {}
}
}
let range = chosen.ok_or_else(unsupported)?;
let buffer_size = match (config.buffer_frames, range.buffer_size()) {
(Some(n), SupportedBufferSize::Range { min, max }) if (*min..=*max).contains(&n) => BufferSize::Fixed(n),
_ => BufferSize::Default,
};
let stream_config = StreamConfig { channels: config.channels, sample_rate: config.sample_rate, buffer_size };
let stats = SinkStats::new();
let stream = match range.sample_format() {
SampleFormat::F32 => build::<f32>(&device, stream_config, render, &stats),
_ => build::<i16>(&device, stream_config, render, &stats),
}
.map_err(|e| match e.kind() {
ErrorKind::UnsupportedConfig => unsupported(),
_ => map_error(&e),
})?;
stream.play().map_err(|e| map_error(&e))?;
self.running.store(true, Ordering::Release);
let actual = SinkConfig {
buffer_frames: match buffer_size {
BufferSize::Fixed(n) => Some(n),
BufferSize::Default => None,
},
..config
};
let name = device.description().map(|d| d.name().to_string()).unwrap_or_else(|_| "unnamed device".into());
let description = format!("cpal {:?}: {name} ({:?})", self.host.id(), range.sample_format());
Ok(SinkHandle::new(actual, description, stats, Box::new(StreamGuard { _stream: stream, running: self.running.clone() })))
}
}
fn build<T>(device: &Device, config: StreamConfig, mut render: RenderFn, stats: &SinkStats) -> Result<cpal::Stream, Error>
where
T: SizedSample + FromSample<f32> + Send + 'static,
{
let data_stats = stats.clone();
let error_stats = stats.clone();
let mut scratch: Vec<f32> = Vec::new();
device.build_output_stream(
config,
move |data: &mut [T], _: &cpal::OutputCallbackInfo| {
data_stats.record_callback();
scratch.resize(data.len(), 0.0);
render(&mut scratch);
for (d, s) in data.iter_mut().zip(&scratch) {
*d = T::from_sample(if s.is_nan() { 0.0 } else { s.clamp(-1.0, 1.0) });
}
},
move |e: Error| match e.kind() {
ErrorKind::Xrun => error_stats.record_xrun(),
_ => error_stats.record_error(),
},
None,
)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn cpal_errors_map_to_sink_errors() {
assert_eq!(map_error(&ErrorKind::DeviceNotAvailable.into()), SinkError::NoDevice);
assert_eq!(map_error(&ErrorKind::HostUnavailable.into()), SinkError::NoDevice);
assert!(matches!(map_error(&ErrorKind::BackendError.into()), SinkError::Backend(_)));
}
#[test]
fn invalid_configs_fail_before_touching_a_device() {
let mut sink = CpalSink::new();
let r: RenderFn = Box::new(|_| {});
assert!(matches!(sink.start(SinkConfig::new(0, 2), r), Err(SinkError::InvalidConfig(_))));
}
}