use crate::sink::validate;
use crate::{SinkConfig, SinkError, SinkHandle, SinkStats};
use std::sync::{Arc, Mutex};
pub type CaptureFn = Box<dyn FnMut(&[f32]) + Send + 'static>;
pub trait AudioSource {
fn default_config(&self) -> Result<SinkConfig, SinkError>;
fn start(&mut self, config: SinkConfig, capture: CaptureFn) -> Result<SinkHandle, SinkError>;
}
type Slot = Arc<Mutex<Option<(SinkConfig, CaptureFn)>>>;
#[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 {
pub fn new() -> Self {
Self::default()
}
pub fn is_running(&self) -> bool {
self.slot.lock().map(|s| s.is_some()).unwrap_or(false)
}
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 {
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
}
}
}
pub struct CpalSource {
host: Host,
}
impl Default for CpalSource {
fn default() -> Self {
CpalSource::new()
}
}
struct Guard(#[allow(dead_code)] cpal::Stream);
impl CpalSource {
pub fn new() -> Self {
CpalSource { host: cpal::default_host() }
}
pub fn with_host(host: Host) -> Self {
CpalSource { host }
}
#[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]));
}
}