weirdnet-audio-engine 0.4.1

Audio engine pieces for Weirdnet: the AudioSink trait, a manual sink for tests, a cpal device sink (feature `cpal`) and a waveform player.
Documentation
//! The cpal device sink. See [`CpalSink`].

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};

/// Plays through the default output device of a cpal host: ALSA on Linux (which a PipeWire or PulseAudio server serves through its ALSA
/// plugin), AAudio on Android, and the native host elsewhere.
///
/// 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
/// a scratch buffer that grows to the largest block seen, so it allocates on the first callbacks only.
///
/// A request the device cannot do exactly is [`SinkError::UnsupportedConfig`] with the device's default attached, never a silent change of rate.
pub struct CpalSink {
    host: Host,
    running: Arc<AtomicBool>,
}

impl Default for CpalSink {
    fn default() -> Self {
        CpalSink::new()
    }
}

struct StreamGuard {
    // Held for its Drop, which stops the stream.
    _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 {
    /// The platform's default host.
    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)) }
    }

    /// cpal's native PipeWire host (feature `pipewire`).
    #[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() };

        // Prefer f32, accept i16, and only those: the render function is f32 and conversion beyond i16 is not worth carrying yet.
        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();
            // For f32 the conversion is a copy; the extra pass is cheap next to a device buffer and keeps one code path.
            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(_))));
    }
}