use std::any::Any;
use std::sync::Arc;
use std::sync::atomic::{AtomicU64, Ordering};
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub struct SinkConfig {
pub sample_rate: u32,
pub channels: u16,
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
}
}
pub type RenderFn = Box<dyn FnMut(&mut [f32]) + Send>;
#[derive(Debug, Clone, PartialEq, Eq)]
pub enum SinkError {
NoDevice,
UnsupportedConfig { requested: SinkConfig, supported: Option<SinkConfig> },
InvalidConfig(&'static str),
AlreadyStarted,
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 {}
#[derive(Debug, Clone, Default)]
pub struct SinkStats {
xruns: Arc<AtomicU64>,
errors: Arc<AtomicU64>,
callbacks: Arc<AtomicU64>,
}
impl SinkStats {
pub fn new() -> Self {
SinkStats::default()
}
pub fn xruns(&self) -> u64 {
self.xruns.load(Ordering::Relaxed)
}
pub fn errors(&self) -> u64 {
self.errors.load(Ordering::Relaxed)
}
pub fn callbacks(&self) -> u64 {
self.callbacks.load(Ordering::Relaxed)
}
pub fn record_xrun(&self) {
self.xruns.fetch_add(1, Ordering::Relaxed);
}
pub fn record_error(&self) {
self.errors.fetch_add(1, Ordering::Relaxed);
}
pub fn record_callback(&self) {
self.callbacks.fetch_add(1, Ordering::Relaxed);
}
}
pub struct SinkHandle {
config: SinkConfig,
description: String,
stats: SinkStats,
_guard: Box<dyn Any>,
}
impl SinkHandle {
pub fn new(config: SinkConfig, description: impl Into<String>, stats: SinkStats, guard: Box<dyn Any>) -> Self {
SinkHandle { config, description: description.into(), stats, _guard: guard }
}
pub fn config(&self) -> SinkConfig {
self.config
}
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()
}
}
pub trait AudioSink {
fn default_config(&self) -> Result<SinkConfig, SinkError>;
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(())
}