weirdnet-audio-engine 0.5.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
//! The audio input boundary: a microphone or any other capture device.
//!
//! * [`AudioSource`]: starts capture and calls a function from the device's thread with each block of interleaved `f32` samples.
//! * [`ManualSource`]: no device; the caller pushes blocks. It makes capture code deterministic to test.
//! * `CpalSource` (feature `cpal`): the default input device.
//!
//! Like a render function, the capture function runs on the audio thread: it must not block, lock, or allocate.

use crate::sink::validate;
use crate::{SinkConfig, SinkError, SinkHandle, SinkStats};
use std::sync::{Arc, Mutex};

/// Called with each captured block of interleaved samples.
pub type CaptureFn = Box<dyn FnMut(&[f32]) + Send + 'static>;

/// A capture device.
pub trait AudioSource {
    /// The device's preferred configuration.
    fn default_config(&self) -> Result<SinkConfig, SinkError>;

    /// Start capturing with exactly `config`, calling `capture` with each block. Capture stops when the handle is dropped.
    fn start(&mut self, config: SinkConfig, capture: CaptureFn) -> Result<SinkHandle, SinkError>;
}

type Slot = Arc<Mutex<Option<(SinkConfig, CaptureFn)>>>;

/// A source with no device: [`ManualSource::push`] hands a block to the running capture function.
#[derive(Clone, Default)]
pub struct ManualSource {
    slot: Slot,
    stats: SinkStats,
}

struct ManualGuard(Slot);

impl Drop for ManualGuard {
    fn drop(&mut self) {
        if let Ok(mut s) = self.0.lock() {
            *s = None;
        }
    }
}

impl ManualSource {
    /// A source with nothing running yet.
    pub fn new() -> Self {
        Self::default()
    }

    /// Whether capture is running.
    pub fn is_running(&self) -> bool {
        self.slot.lock().map(|s| s.is_some()).unwrap_or(false)
    }

    /// Hand `samples` (interleaved) to the capture function. Returns false when nothing is running.
    pub fn push(&self, samples: &[f32]) -> bool {
        let Ok(mut s) = self.slot.lock() else { return false };
        match s.as_mut() {
            Some((_, f)) => {
                self.stats.record_callback();
                f(samples);
                true
            }
            None => false,
        }
    }
}

impl AudioSource for ManualSource {
    fn default_config(&self) -> Result<SinkConfig, SinkError> {
        Ok(SinkConfig::new(48_000, 1))
    }

    fn start(&mut self, config: SinkConfig, capture: CaptureFn) -> Result<SinkHandle, SinkError> {
        validate(config)?;
        let mut s = self.slot.lock().map_err(|_| SinkError::Backend("poisoned".into()))?;
        if s.is_some() {
            return Err(SinkError::AlreadyStarted);
        }
        *s = Some((config, capture));
        Ok(SinkHandle::new(config, "manual source", self.stats.clone(), Box::new(ManualGuard(self.slot.clone()))))
    }
}

#[cfg(feature = "cpal")]
mod device {
    use super::{AudioSource, CaptureFn};
    use crate::cpal_sink::map_error;
    use crate::sink::validate;
    use crate::{SinkConfig, SinkError, SinkHandle, SinkStats};
    use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
    use cpal::{BufferSize, Device, Error, ErrorKind, Host, SampleFormat, SizedSample, StreamConfig, SupportedBufferSize};
    use dasp_like::ToF32;

    mod dasp_like {
        /// Sample conversion to f32 for the formats the source accepts.
        pub trait ToF32: Copy {
            fn to_f32(self) -> f32;
        }
        impl ToF32 for f32 {
            fn to_f32(self) -> f32 {
                self
            }
        }
        impl ToF32 for i16 {
            fn to_f32(self) -> f32 {
                f32::from(self) / 32768.0
            }
        }
    }

    /// Captures from the default input device of a cpal host (ALSA on Linux, which PipeWire and PulseAudio serve; AAudio on Android).
    ///
    /// The stream is built as `f32`, or as `i16` when the device offers nothing else; the capture 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.
    pub struct CpalSource {
        host: Host,
    }

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

    struct Guard(#[allow(dead_code)] cpal::Stream);

    impl CpalSource {
        /// The platform's default host.
        pub fn new() -> Self {
            CpalSource { host: cpal::default_host() }
        }

        /// A given host.
        pub fn with_host(host: Host) -> Self {
            CpalSource { host }
        }

        /// 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(CpalSource::with_host).map_err(|e| map_error(&e))
        }

        fn device(&self) -> Result<Device, SinkError> {
            self.host.default_input_device().ok_or(SinkError::NoDevice)
        }
    }

    impl AudioSource for CpalSource {
        fn default_config(&self) -> Result<SinkConfig, SinkError> {
            let c = self.device()?.default_input_config().map_err(|e| map_error(&e))?;
            Ok(SinkConfig::new(c.sample_rate(), c.channels()))
        }

        fn start(&mut self, config: SinkConfig, capture: CaptureFn) -> Result<SinkHandle, SinkError> {
            validate(config)?;
            let device = self.device()?;
            let unsupported = || SinkError::UnsupportedConfig { requested: config, supported: self.default_config().ok() };
            let mut chosen = None;
            for range in device.supported_input_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, capture, &stats),
                _ => build::<i16>(&device, stream_config, capture, &stats),
            }
            .map_err(|e| match e.kind() {
                ErrorKind::UnsupportedConfig => unsupported(),
                _ => map_error(&e),
            })?;
            stream.play().map_err(|e| map_error(&e))?;
            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 {:?} input: {name} ({:?})", self.host.id(), range.sample_format());
            Ok(SinkHandle::new(actual, description, stats, Box::new(Guard(stream))))
        }
    }

    fn build<T>(device: &Device, config: StreamConfig, mut capture: CaptureFn, stats: &SinkStats) -> Result<cpal::Stream, Error>
    where
        T: SizedSample + ToF32 + Send + 'static,
    {
        let data_stats = stats.clone();
        let error_stats = stats.clone();
        let mut scratch: Vec<f32> = Vec::new();
        device.build_input_stream(
            config,
            move |data: &[T], _: &cpal::InputCallbackInfo| {
                data_stats.record_callback();
                scratch.clear();
                scratch.extend(data.iter().map(|s| s.to_f32()));
                capture(&scratch);
            },
            move |e: Error| match e.kind() {
                ErrorKind::Xrun => error_stats.record_xrun(),
                _ => error_stats.record_error(),
            },
            None,
        )
    }
}

#[cfg(feature = "cpal")]
pub use device::CpalSource;

#[cfg(test)]
mod tests {
    use super::*;
    use std::sync::atomic::{AtomicUsize, Ordering};

    #[test]
    fn a_manual_source_hands_blocks_to_the_capture_function_until_dropped() {
        let mut src = ManualSource::new();
        let got = Arc::new(AtomicUsize::new(0));
        let g = got.clone();
        assert!(!src.push(&[0.0; 4]), "nothing runs yet");
        let handle = src
            .start(
                SinkConfig::new(48_000, 1),
                Box::new(move |b| {
                    g.fetch_add(b.len(), Ordering::Relaxed);
                }),
            )
            .unwrap();
        assert!(matches!(src.start(SinkConfig::new(48_000, 1), Box::new(|_| {})), Err(SinkError::AlreadyStarted)));
        assert!(src.push(&[0.5; 480]));
        assert_eq!(got.load(Ordering::Relaxed), 480);
        assert_eq!(handle.stats().callbacks(), 1);
        drop(handle);
        assert!(!src.is_running() && !src.push(&[0.5; 480]));
    }
}