weirdnet_audio_engine/
sink.rs1use std::any::Any;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU64, Ordering};
4
5#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct SinkConfig {
8 pub sample_rate: u32,
9 pub channels: u16,
10 pub buffer_frames: Option<u32>,
12}
13
14impl SinkConfig {
15 pub const fn new(sample_rate: u32, channels: u16) -> Self {
16 SinkConfig { sample_rate, channels, buffer_frames: None }
17 }
18
19 pub const fn with_buffer_frames(mut self, frames: u32) -> Self {
20 self.buffer_frames = Some(frames);
21 self
22 }
23}
24
25pub type RenderFn = Box<dyn FnMut(&mut [f32]) + Send>;
27
28#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum SinkError {
31 NoDevice,
33 UnsupportedConfig { requested: SinkConfig, supported: Option<SinkConfig> },
35 InvalidConfig(&'static str),
37 AlreadyStarted,
39 Backend(String),
41}
42
43impl std::fmt::Display for SinkError {
44 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
45 match self {
46 SinkError::NoDevice => write!(f, "no audio output device"),
47 SinkError::UnsupportedConfig { requested, supported } => {
48 write!(f, "the device does not support {} Hz, {} channels", requested.sample_rate, requested.channels)?;
49 if let Some(s) = supported {
50 write!(f, " (it offers {} Hz, {} channels)", s.sample_rate, s.channels)?;
51 }
52 Ok(())
53 }
54 SinkError::InvalidConfig(why) => write!(f, "invalid sink config: {why}"),
55 SinkError::AlreadyStarted => write!(f, "the sink is already running"),
56 SinkError::Backend(why) => write!(f, "audio backend: {why}"),
57 }
58 }
59}
60
61impl std::error::Error for SinkError {}
62
63#[derive(Debug, Clone, Default)]
65pub struct SinkStats {
66 xruns: Arc<AtomicU64>,
67 errors: Arc<AtomicU64>,
68 callbacks: Arc<AtomicU64>,
69}
70
71impl SinkStats {
72 pub fn new() -> Self {
73 SinkStats::default()
74 }
75
76 pub fn xruns(&self) -> u64 {
78 self.xruns.load(Ordering::Relaxed)
79 }
80
81 pub fn errors(&self) -> u64 {
83 self.errors.load(Ordering::Relaxed)
84 }
85
86 pub fn callbacks(&self) -> u64 {
88 self.callbacks.load(Ordering::Relaxed)
89 }
90
91 pub fn record_xrun(&self) {
93 self.xruns.fetch_add(1, Ordering::Relaxed);
94 }
95
96 pub fn record_error(&self) {
98 self.errors.fetch_add(1, Ordering::Relaxed);
99 }
100
101 pub fn record_callback(&self) {
103 self.callbacks.fetch_add(1, Ordering::Relaxed);
104 }
105}
106
107pub struct SinkHandle {
109 config: SinkConfig,
110 description: String,
111 stats: SinkStats,
112 _guard: Box<dyn Any>,
114}
115
116impl SinkHandle {
117 pub fn new(config: SinkConfig, description: impl Into<String>, stats: SinkStats, guard: Box<dyn Any>) -> Self {
119 SinkHandle { config, description: description.into(), stats, _guard: guard }
120 }
121
122 pub fn config(&self) -> SinkConfig {
124 self.config
125 }
126
127 pub fn description(&self) -> &str {
129 &self.description
130 }
131
132 pub fn stats(&self) -> &SinkStats {
133 &self.stats
134 }
135}
136
137impl std::fmt::Debug for SinkHandle {
138 fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
139 f.debug_struct("SinkHandle").field("config", &self.config).field("description", &self.description).finish()
140 }
141}
142
143pub trait AudioSink {
145 fn default_config(&self) -> Result<SinkConfig, SinkError>;
147
148 fn start(&mut self, config: SinkConfig, render: RenderFn) -> Result<SinkHandle, SinkError>;
152}
153
154pub(crate) fn validate(config: SinkConfig) -> Result<(), SinkError> {
155 if config.sample_rate == 0 {
156 return Err(SinkError::InvalidConfig("the sample rate is zero"));
157 }
158 if config.channels == 0 {
159 return Err(SinkError::InvalidConfig("the channel count is zero"));
160 }
161 if config.buffer_frames == Some(0) {
162 return Err(SinkError::InvalidConfig("the buffer size is zero"));
163 }
164 Ok(())
165}