weirdnet-audio-engine 0.3.0

Audio engine pieces for Weirdnet: the AudioSink trait, a manual sink for tests, a cpal device sink (feature `cpal`) and a waveform player.
Documentation
use std::any::Any;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};

/// What a sink is asked for, and what a running one reports.
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SinkConfig {
    pub sample_rate: u32,
    pub channels: u16,
    /// A preferred buffer size in frames. `None` lets the backend choose. The running stream may differ.
    pub buffer_frames: Option<u32>,
}

impl SinkConfig {
    pub const fn new(sample_rate: u32, channels: u16) -> Self {
        SinkConfig { sample_rate, channels, buffer_frames: None }
    }

    pub const fn with_buffer_frames(mut self, frames: u32) -> Self {
        self.buffer_frames = Some(frames);
        self
    }
}

/// Fills one buffer of interleaved `f32` samples (`frames * channels` long) for the device. Called on the audio thread.
pub type RenderFn = Box<dyn FnMut(&mut [f32]) + Send>;

/// Why a sink could not start.
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SinkError {
    /// There is no output device (or the audio server is not running).
    NoDevice,
    /// The device cannot do the requested format. `supported` is what [`AudioSink::default_config`] reports, to retry with.
    UnsupportedConfig { requested: SinkConfig, supported: Option<SinkConfig> },
    /// The request is not valid (zero rate or channels).
    InvalidConfig(&'static str),
    /// The sink is already running; stop it (drop its handle) first.
    AlreadyStarted,
    /// The backend failed. The text is its own message.
    Backend(String),
}

impl std::fmt::Display for SinkError {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        match self {
            SinkError::NoDevice => write!(f, "no audio output device"),
            SinkError::UnsupportedConfig { requested, supported } => {
                write!(f, "the device does not support {} Hz, {} channels", requested.sample_rate, requested.channels)?;
                if let Some(s) = supported {
                    write!(f, " (it offers {} Hz, {} channels)", s.sample_rate, s.channels)?;
                }
                Ok(())
            }
            SinkError::InvalidConfig(why) => write!(f, "invalid sink config: {why}"),
            SinkError::AlreadyStarted => write!(f, "the sink is already running"),
            SinkError::Backend(why) => write!(f, "audio backend: {why}"),
        }
    }
}

impl std::error::Error for SinkError {}

/// Counters the backend updates from its threads. Cloning shares them.
#[derive(Debug, Clone, Default)]
pub struct SinkStats {
    xruns: Arc<AtomicU64>,
    errors: Arc<AtomicU64>,
    callbacks: Arc<AtomicU64>,
}

impl SinkStats {
    pub fn new() -> Self {
        SinkStats::default()
    }

    /// Buffer underruns the backend reported.
    pub fn xruns(&self) -> u64 {
        self.xruns.load(Ordering::Relaxed)
    }

    /// Errors other than xruns the backend reported while running.
    pub fn errors(&self) -> u64 {
        self.errors.load(Ordering::Relaxed)
    }

    /// How many times the render function has been called.
    pub fn callbacks(&self) -> u64 {
        self.callbacks.load(Ordering::Relaxed)
    }

    /// For backends: counts an xrun. Lock-free, safe on the audio thread.
    pub fn record_xrun(&self) {
        self.xruns.fetch_add(1, Ordering::Relaxed);
    }

    /// For backends: counts another error.
    pub fn record_error(&self) {
        self.errors.fetch_add(1, Ordering::Relaxed);
    }

    /// For backends: counts a render call.
    pub fn record_callback(&self) {
        self.callbacks.fetch_add(1, Ordering::Relaxed);
    }
}

/// A running stream. Dropping it stops the stream. It is not `Send`, because some platform streams are not.
pub struct SinkHandle {
    config: SinkConfig,
    description: String,
    stats: SinkStats,
    // Held for its Drop. Type-erased so a backend can keep whatever stops its stream.
    _guard: Box<dyn Any>,
}

impl SinkHandle {
    /// For backends: wraps a running stream. `guard` stops the stream when dropped.
    pub fn new(config: SinkConfig, description: impl Into<String>, stats: SinkStats, guard: Box<dyn Any>) -> Self {
        SinkHandle { config, description: description.into(), stats, _guard: guard }
    }

    /// The format the stream actually runs at.
    pub fn config(&self) -> SinkConfig {
        self.config
    }

    /// Which device and backend this is, for logs and a settings screen.
    pub fn description(&self) -> &str {
        &self.description
    }

    pub fn stats(&self) -> &SinkStats {
        &self.stats
    }
}

impl std::fmt::Debug for SinkHandle {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.debug_struct("SinkHandle").field("config", &self.config).field("description", &self.description).finish()
    }
}

/// An audio output. Platform code lives behind this trait and nowhere else.
pub trait AudioSink {
    /// The format the device prefers, to ask for when a request is [`SinkError::UnsupportedConfig`].
    fn default_config(&self) -> Result<SinkConfig, SinkError>;

    /// Starts the stream. `render` is called on the audio thread with a buffer to fill. The stream stops when the handle is dropped.
    /// A sink that cannot run the exact `config` returns [`SinkError::UnsupportedConfig`] instead of running at another rate, so the render
    /// function never has to guess its format.
    fn start(&mut self, config: SinkConfig, render: RenderFn) -> Result<SinkHandle, SinkError>;
}

pub(crate) fn validate(config: SinkConfig) -> Result<(), SinkError> {
    if config.sample_rate == 0 {
        return Err(SinkError::InvalidConfig("the sample rate is zero"));
    }
    if config.channels == 0 {
        return Err(SinkError::InvalidConfig("the channel count is zero"));
    }
    if config.buffer_frames == Some(0) {
        return Err(SinkError::InvalidConfig("the buffer size is zero"));
    }
    Ok(())
}