Skip to main content

weirdnet_audio_engine/
sink.rs

1use std::any::Any;
2use std::sync::Arc;
3use std::sync::atomic::{AtomicU64, Ordering};
4
5/// What a sink is asked for, and what a running one reports.
6#[derive(Debug, Clone, Copy, PartialEq, Eq)]
7pub struct SinkConfig {
8    pub sample_rate: u32,
9    pub channels: u16,
10    /// A preferred buffer size in frames. `None` lets the backend choose. The running stream may differ.
11    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
25/// Fills one buffer of interleaved `f32` samples (`frames * channels` long) for the device. Called on the audio thread.
26pub type RenderFn = Box<dyn FnMut(&mut [f32]) + Send>;
27
28/// Why a sink could not start.
29#[derive(Debug, Clone, PartialEq, Eq)]
30pub enum SinkError {
31    /// There is no output device (or the audio server is not running).
32    NoDevice,
33    /// The device cannot do the requested format. `supported` is what [`AudioSink::default_config`] reports, to retry with.
34    UnsupportedConfig { requested: SinkConfig, supported: Option<SinkConfig> },
35    /// The request is not valid (zero rate or channels).
36    InvalidConfig(&'static str),
37    /// The sink is already running; stop it (drop its handle) first.
38    AlreadyStarted,
39    /// The backend failed. The text is its own message.
40    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/// Counters the backend updates from its threads. Cloning shares them.
64#[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    /// Buffer underruns the backend reported.
77    pub fn xruns(&self) -> u64 {
78        self.xruns.load(Ordering::Relaxed)
79    }
80
81    /// Errors other than xruns the backend reported while running.
82    pub fn errors(&self) -> u64 {
83        self.errors.load(Ordering::Relaxed)
84    }
85
86    /// How many times the render function has been called.
87    pub fn callbacks(&self) -> u64 {
88        self.callbacks.load(Ordering::Relaxed)
89    }
90
91    /// For backends: counts an xrun. Lock-free, safe on the audio thread.
92    pub fn record_xrun(&self) {
93        self.xruns.fetch_add(1, Ordering::Relaxed);
94    }
95
96    /// For backends: counts another error.
97    pub fn record_error(&self) {
98        self.errors.fetch_add(1, Ordering::Relaxed);
99    }
100
101    /// For backends: counts a render call.
102    pub fn record_callback(&self) {
103        self.callbacks.fetch_add(1, Ordering::Relaxed);
104    }
105}
106
107/// A running stream. Dropping it stops the stream. It is not `Send`, because some platform streams are not.
108pub struct SinkHandle {
109    config: SinkConfig,
110    description: String,
111    stats: SinkStats,
112    // Held for its Drop. Type-erased so a backend can keep whatever stops its stream.
113    _guard: Box<dyn Any>,
114}
115
116impl SinkHandle {
117    /// For backends: wraps a running stream. `guard` stops the stream when dropped.
118    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    /// The format the stream actually runs at.
123    pub fn config(&self) -> SinkConfig {
124        self.config
125    }
126
127    /// Which device and backend this is, for logs and a settings screen.
128    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
143/// An audio output. Platform code lives behind this trait and nowhere else.
144pub trait AudioSink {
145    /// The format the device prefers, to ask for when a request is [`SinkError::UnsupportedConfig`].
146    fn default_config(&self) -> Result<SinkConfig, SinkError>;
147
148    /// Starts the stream. `render` is called on the audio thread with a buffer to fill. The stream stops when the handle is dropped.
149    /// A sink that cannot run the exact `config` returns [`SinkError::UnsupportedConfig`] instead of running at another rate, so the render
150    /// function never has to guess its format.
151    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}