nadir_platform/audio.rs
1// Copyright 2026 Joseph Anthony Abbott III
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15//! Audio output: a stream to the default device, which an audio thread of
16//! its own fills through a callback.
17
18use std::time::Duration;
19
20use crate::PlatformError;
21#[cfg(target_os = "linux")]
22use crate::linux::alsa as backend;
23#[cfg(not(target_os = "linux"))]
24use crate::no_audio as backend;
25
26/// What audio output to open, as [`open_audio`] takes it.
27#[derive(Clone, Copy, Debug, PartialEq, Eq)]
28pub struct AudioOutputConfig {
29 /// The frames a second, from 8,000 to 384,000: 48,000 by default.
30 pub sample_rate: u32,
31 /// The samples of a frame, from 1 to 8: 2 by default, left then right.
32 pub channels: u16,
33 /// About how long a sample waits in the device's buffer before it is
34 /// heard, in milliseconds, from 5 to 500: 30 by default. A longer one
35 /// rides out a busy moment of the audio thread; a shorter one makes a
36 /// sound start sooner.
37 pub latency_ms: u32,
38}
39
40impl Default for AudioOutputConfig {
41 /// 48 kHz stereo, with 30 ms of latency.
42 fn default() -> Self {
43 Self {
44 sample_rate: 48_000,
45 channels: 2,
46 latency_ms: 30,
47 }
48 }
49}
50
51impl AudioOutputConfig {
52 /// Checks each field against its range.
53 fn validate(&self) -> Result<(), PlatformError> {
54 let check = |ok: bool, field, expected| {
55 if ok {
56 Ok(())
57 } else {
58 Err(PlatformError::InvalidAudioConfig { field, expected })
59 }
60 };
61 check((1..=8).contains(&self.channels), "channels", "1 to 8")?;
62 check(
63 (8_000..=384_000).contains(&self.sample_rate),
64 "sample_rate",
65 "8,000 to 384,000",
66 )?;
67 check(
68 (5..=500).contains(&self.latency_ms),
69 "latency_ms",
70 "5 to 500",
71 )
72 }
73}
74
75/// What makes the sound: the audio thread calls it, as [`open_audio`]
76/// describes.
77///
78/// It runs on the audio thread, which the device waits on: it must not
79/// block, allocate, free or log. A mixer that the main thread talks to
80/// through a queue it never waits on, as `nadir-audio`'s, fits. A render
81/// that panics ends the stream: the device is closed, nothing more plays,
82/// and the panic hook reports it.
83pub trait AudioRender: Send + 'static {
84 /// Overwrites every sample of `out` with `out.len() / channels`
85 /// interleaved frames of `channels` samples, from −1 to 1, at
86 /// `sample_rate` frames a second, which follow those of the call
87 /// before. The length can change from one call to the next; on Linux
88 /// it is one period of the device, until the device is opened again.
89 fn render(&mut self, out: &mut [f32], channels: u16, sample_rate: u32);
90
91 /// The device ran out of samples (an underrun), so that a gap was
92 /// heard. Called on the audio thread, once for each the system reports,
93 /// before the next [`render`](AudioRender::render).
94 fn underrun(&mut self);
95}
96
97/// Audio output that is playing: an audio thread, and the device it fills.
98///
99/// Dropping it stops the thread and closes the device; what the device had
100/// not played yet is dropped. The drop waits for the thread up to 2 s,
101/// which it takes only when the system holds the device, as while it
102/// resumes from a suspend; past that, the thread is left to end with the
103/// process.
104///
105/// It is `Send` and `Sync` on every system.
106pub struct AudioStream {
107 inner: backend::Stream,
108}
109
110// The same on every system (AGENTS.md, rule 4).
111const _: fn() = || {
112 fn send_and_sync<T: Send + Sync>() {}
113 send_and_sync::<AudioStream>();
114};
115
116impl AudioStream {
117 /// How long a sample waits in the device's buffer before it is heard,
118 /// as the device took it the last time it opened, besides what a sound
119 /// server adds. `None` while there is no device: before the first one
120 /// opens, and from the loss of one until it opens again.
121 pub fn latency(&self) -> Option<Duration> {
122 self.inner.latency()
123 }
124}
125
126/// Opens the default audio output device, and starts an audio thread that
127/// keeps it fed from `render`.
128///
129/// It returns once the thread has opened the device, or found that there
130/// is none, or after 2 s, when the device is slow to open, as a sound
131/// server that does not answer makes it: the stream then starts without
132/// it. Until the stream is dropped, the thread calls
133/// [`AudioRender::render`] for a period of the device at a time, and
134/// writes it as room comes, so that what plays keeps time with the device;
135/// a device with no clock of its own, which takes samples as fast as they
136/// come, as ALSA's `null`, is held to the system's clock. Each underrun is
137/// [`AudioRender::underrun`], and the device is recovered.
138///
139/// If there is no device, or it stops working, as when it is unplugged, or
140/// takes no samples for 2 s, the thread logs a warning, and goes on
141/// calling `render` in time while it tries to open the device again once a
142/// second. It logs again when it has, or when a device opens but refuses
143/// the format. It logs nothing else.
144///
145/// # Platforms
146///
147/// - **Linux:** ALSA's `default` device, which a sound server, PipeWire or
148/// PulseAudio, usually provides, or the ALSA device that
149/// `NADIR_ALSA_DEVICE` names, such as `plughw:CARD=Device`, when it is set
150/// and not empty. `libasound.so.2` is loaded when audio is first opened,
151/// not linked. The device takes the rate and channels asked for, as ALSA
152/// converts and resamples where it must, or the call fails.
153/// - **Windows and macOS:** not built yet (roadmap tasks M6.4 and M6.5):
154/// this returns [`PlatformError::Unsupported`].
155///
156/// # Errors
157///
158/// - [`PlatformError::InvalidAudioConfig`] for a field of `config` out of
159/// its range, on every system.
160/// - [`PlatformError::LibraryNotFound`] or [`PlatformError::MissingSymbols`]
161/// if the system's audio library is missing or too old.
162/// - [`PlatformError::AudioCallFailed`] if the device opens but does not
163/// take `config`, within the 2 s, or the thread cannot be started. A
164/// device that does not open is no error: the stream starts without one,
165/// as above.
166///
167/// # Examples
168///
169/// A second of a quiet 440 Hz tone:
170///
171/// ```no_run
172/// use std::f32::consts::TAU;
173/// use std::thread;
174/// use std::time::Duration;
175///
176/// use nadir_platform::{AudioOutputConfig, AudioRender, open_audio};
177///
178/// struct Tone {
179/// phase: f32,
180/// }
181///
182/// impl AudioRender for Tone {
183/// fn render(&mut self, out: &mut [f32], channels: u16, sample_rate: u32) {
184/// let step = 440.0 / sample_rate as f32;
185/// for frame in out.chunks_exact_mut(usize::from(channels)) {
186/// frame.fill((self.phase * TAU).sin() * 0.1);
187/// self.phase = (self.phase + step).fract();
188/// }
189/// }
190///
191/// fn underrun(&mut self) {}
192/// }
193///
194/// let config = AudioOutputConfig::default();
195/// let stream = open_audio(&config, Box::new(Tone { phase: 0.0 }))?;
196/// thread::sleep(Duration::from_secs(1));
197/// drop(stream);
198/// # Ok::<(), nadir_platform::PlatformError>(())
199/// ```
200pub fn open_audio(
201 config: &AudioOutputConfig,
202 render: Box<dyn AudioRender>,
203) -> Result<AudioStream, PlatformError> {
204 config.validate()?;
205 let inner = backend::open(config, render)?;
206 Ok(AudioStream { inner })
207}
208
209#[cfg(test)]
210mod tests {
211 use super::*;
212
213 /// A render that is never called.
214 struct Never;
215
216 impl AudioRender for Never {
217 fn render(&mut self, _out: &mut [f32], _channels: u16, _sample_rate: u32) {
218 unreachable!("the stream does not start");
219 }
220
221 fn underrun(&mut self) {
222 unreachable!("the stream does not start");
223 }
224 }
225
226 fn refused(config: AudioOutputConfig) -> (&'static str, &'static str) {
227 match open_audio(&config, Box::new(Never)) {
228 Err(PlatformError::InvalidAudioConfig { field, expected }) => (field, expected),
229 Err(error) => panic!("{error}"),
230 Ok(_) => panic!("the stream started"),
231 }
232 }
233
234 #[test]
235 fn each_field_out_of_its_range_is_refused_on_every_system() {
236 let config = AudioOutputConfig::default();
237 for channels in [0, 9, u16::MAX] {
238 let field = refused(AudioOutputConfig { channels, ..config });
239 assert_eq!(field, ("channels", "1 to 8"), "{channels} channels");
240 }
241 for sample_rate in [0, 7_999, 384_001, u32::MAX] {
242 let field = refused(AudioOutputConfig {
243 sample_rate,
244 ..config
245 });
246 assert_eq!(
247 field,
248 ("sample_rate", "8,000 to 384,000"),
249 "{sample_rate} Hz"
250 );
251 }
252 for latency_ms in [0, 4, 501, u32::MAX] {
253 let field = refused(AudioOutputConfig {
254 latency_ms,
255 ..config
256 });
257 assert_eq!(field, ("latency_ms", "5 to 500"), "{latency_ms} ms");
258 }
259 }
260
261 #[test]
262 fn each_range_includes_its_ends() {
263 for config in [
264 AudioOutputConfig {
265 sample_rate: 8_000,
266 channels: 1,
267 latency_ms: 5,
268 },
269 AudioOutputConfig {
270 sample_rate: 384_000,
271 channels: 8,
272 latency_ms: 500,
273 },
274 ] {
275 assert_eq!(config.validate(), Ok(()), "{config:?}");
276 }
277 assert_eq!(AudioOutputConfig::default().validate(), Ok(()));
278 }
279}