sim_logic/audio/output.rs
1use std::{
2 error::Error,
3 fmt,
4 iter::FusedIterator,
5 num::{NonZeroU16, NonZeroU32},
6 sync::{
7 Arc,
8 atomic::{AtomicBool, AtomicU64, Ordering},
9 },
10 time::Duration,
11};
12
13use rodio::{
14 DeviceSinkBuilder, DeviceSinkError, MixerDeviceSink, Source,
15 cpal::{
16 self, BufferSize, Sample as _,
17 traits::{DeviceTrait, HostTrait},
18 },
19};
20
21const MAX_BUFFER_FRAMES: u32 = 16_384;
22
23/// Setup policy for one default-device output stream.
24///
25/// Defaults request 512 sample frames with fallback disabled. A frame contains
26/// one sample per output channel; 512 frames at 48 kHz represent about 10.7 ms
27/// of samples, not a measurement of end-to-end audible latency.
28#[derive(Debug, Clone, Copy, PartialEq, Eq)]
29pub struct AudioOutputConfig {
30 buffer_frames: u32,
31 device_buffer_fallback: bool,
32}
33
34impl AudioOutputConfig {
35 /// Requests a buffer of 1 through 16,384 sample frames without opening audio.
36 ///
37 /// Zero and larger values return a typed error. Devices may reject a valid
38 /// request; device-default fallback remains disabled until explicitly set.
39 pub const fn new(buffer_frames: u32) -> Result<Self, AudioOutputError> {
40 if buffer_frames == 0 || buffer_frames > MAX_BUFFER_FRAMES {
41 return Err(AudioOutputError::InvalidBufferFrames {
42 requested: buffer_frames,
43 maximum: MAX_BUFFER_FRAMES,
44 });
45 }
46 Ok(Self {
47 buffer_frames,
48 device_buffer_fallback: false,
49 })
50 }
51
52 /// Returns the requested buffer length in sample frames, not scalar samples.
53 pub const fn buffer_frames(self) -> u32 {
54 self.buffer_frames
55 }
56
57 /// Permits a failed fixed-buffer attempt to retry with the device default.
58 ///
59 /// This retries only the selected default device, with the same sample rate,
60 /// channels, and sample format. It never selects another output device.
61 /// The device-default buffer is not bounded by the requested frame count;
62 /// [`AudioOutputInfo`] reports when this explicit fallback was used.
63 pub const fn with_device_buffer_fallback(mut self, enabled: bool) -> Self {
64 self.device_buffer_fallback = enabled;
65 self
66 }
67
68 /// Returns whether the same-device default-buffer retry is enabled.
69 pub const fn device_buffer_fallback(self) -> bool {
70 self.device_buffer_fallback
71 }
72}
73
74impl Default for AudioOutputConfig {
75 fn default() -> Self {
76 Self {
77 buffer_frames: 512,
78 device_buffer_fallback: false,
79 }
80 }
81}
82
83/// The successfully opened stream's configuration, not measured device latency.
84///
85/// Sample rate and channel count come from the opened backend. A fixed buffer
86/// size is a backend request, not a guarantee about callback lengths or the
87/// additional buffering performed by the operating system and physical device.
88#[derive(Debug, Clone, Copy, PartialEq, Eq)]
89pub struct AudioOutputInfo {
90 sample_rate: NonZeroU32,
91 channels: NonZeroU16,
92 requested_buffer_frames: u32,
93 configured_buffer_frames: Option<u32>,
94 used_device_buffer_fallback: bool,
95}
96
97impl AudioOutputInfo {
98 /// Returns frames per second for the output and its mono source.
99 pub const fn sample_rate(self) -> NonZeroU32 {
100 self.sample_rate
101 }
102
103 /// Returns the output's channel count; the application source remains mono.
104 pub const fn channels(self) -> NonZeroU16 {
105 self.channels
106 }
107
108 /// Returns the original bounded request, even when fallback was used.
109 pub const fn requested_buffer_frames(self) -> u32 {
110 self.requested_buffer_frames
111 }
112
113 /// Returns the configured fixed request, or None for device-default sizing.
114 ///
115 /// This is not the actual callback length or measured physical latency.
116 pub const fn configured_buffer_frames(self) -> Option<u32> {
117 self.configured_buffer_frames
118 }
119
120 /// Reports a successful retry using the same device's default buffer size.
121 pub const fn used_device_buffer_fallback(self) -> bool {
122 self.used_device_buffer_fallback
123 }
124}
125
126#[derive(Debug, Default)]
127struct OutputState {
128 stream_errors: AtomicU64,
129 generated_samples: AtomicU64,
130 invalid_samples: AtomicU64,
131 finished: AtomicBool,
132 closed: AtomicBool,
133}
134
135/// Cloneable, read-only diagnostics that do not keep the output device alive.
136///
137/// Fields are independent atomic observations, not one transactional snapshot.
138/// Counters saturate at u64::MAX. Generated samples can be buffered ahead of
139/// audible output; they are not a physical playback clock.
140#[derive(Debug, Clone)]
141pub struct AudioOutputStatus {
142 state: Arc<OutputState>,
143}
144
145impl AudioOutputStatus {
146 fn new() -> Self {
147 Self {
148 state: Arc::new(OutputState::default()),
149 }
150 }
151
152 /// Reports whether any backend stream error has occurred, including underrun.
153 ///
154 /// Errors are sticky diagnostics; this adapter neither reconnects nor replays
155 /// the source. The application decides whether to stop or reopen output.
156 pub fn is_faulted(&self) -> bool {
157 self.stream_error_count() != 0
158 }
159
160 /// Returns the number of asynchronous backend error callbacks observed.
161 ///
162 /// Callbacks only update this counter; they do not print or retain allocating
163 /// backend error messages. Setup failures remain detailed typed errors.
164 pub fn stream_error_count(&self) -> u64 {
165 self.state.stream_errors.load(Ordering::Relaxed)
166 }
167
168 /// Returns mono samples pulled from the source, including sanitized samples.
169 ///
170 /// Each sample represents one source/output frame, independently of output
171 /// channel count. Silence yielded while stopped also advances this counter;
172 /// an application transport must maintain its own musical position.
173 pub fn generated_sample_count(&self) -> u64 {
174 self.state.generated_samples.load(Ordering::Relaxed)
175 }
176
177 /// Returns samples replaced or clamped because they were invalid PCM.
178 ///
179 /// Non-finite values become silence; finite values outside -1.0 through 1.0
180 /// are clamped. Exact endpoints and signed zero are valid samples.
181 pub fn invalid_sample_count(&self) -> u64 {
182 self.state.invalid_samples.load(Ordering::Relaxed)
183 }
184
185 /// Reports that the source returned None, which permanently ends that source.
186 ///
187 /// This does not mean buffered samples have reached the speakers. Dropping
188 /// playback before source exhaustion closes output without marking finished.
189 pub fn is_finished(&self) -> bool {
190 self.state.finished.load(Ordering::Acquire)
191 }
192
193 /// Reports that the owning output guard has been dropped.
194 ///
195 /// Status clones cannot prevent closure. Already submitted device samples
196 /// cannot be recalled, so closure does not promise instantaneous silence.
197 pub fn is_closed(&self) -> bool {
198 self.state.closed.load(Ordering::Acquire)
199 }
200
201 fn record_stream_error(&self) {
202 increment(&self.state.stream_errors);
203 }
204}
205
206fn increment(counter: &AtomicU64) {
207 let _ = counter.fetch_update(Ordering::Relaxed, Ordering::Relaxed, |value| {
208 Some(value.saturating_add(1))
209 });
210}
211
212#[derive(Debug)]
213struct OutputLifetime {
214 status: AudioOutputStatus,
215}
216
217impl Drop for OutputLifetime {
218 fn drop(&mut self) {
219 self.status.state.closed.store(true, Ordering::Release);
220 }
221}
222
223/// An opened output device that may accept exactly one application source.
224///
225/// Opening immediately starts a silent backend stream. Keep this guard, or the
226/// [`AudioPlayback`] returned from it, outside World preparation and renderer
227/// ownership. Dropping the guard closes output. No application/window/GPU is
228/// required, but the optional `audio` feature and a working device are required.
229#[derive(Debug)]
230#[must_use = "dropping the output guard closes its audio device"]
231pub struct AudioOutput {
232 // Field order ensures the backend is dropped before lifetime reports closed.
233 device: MixerDeviceSink,
234 info: AudioOutputInfo,
235 lifetime: OutputLifetime,
236}
237
238impl AudioOutput {
239 /// Opens the default device with explicit buffer policy and atomic diagnostics.
240 ///
241 /// Failure returns an error, never an implicitly successful silent backend.
242 /// Applications may choose and display their own silent-mode fallback.
243 /// Backend setup can allocate; this API does not claim recovery from every
244 /// backend allocation failure. No automatic device recovery is installed.
245 pub fn open(config: AudioOutputConfig) -> Result<Self, AudioOutputError> {
246 let selected_device = cpal::default_host().default_output_device().ok_or(
247 AudioOutputError::DeviceConfiguration(DeviceSinkError::NoDevice),
248 )?;
249 let format = selected_device.default_output_config().map_err(|error| {
250 AudioOutputError::DeviceConfiguration(DeviceSinkError::DefaultSinkConfigError(error))
251 })?;
252 let ((mut device, status), used_fallback) = open_with_policy(config, |buffer_size| {
253 // The backend's fallback helper may try other configurations. Make
254 // only our documented same-device buffer retry instead.
255 // Failed attempts have separate diagnostics, so they cannot mark a
256 // successfully opened fallback stream as asynchronously faulted.
257 let status = AudioOutputStatus::new();
258 let callback_status = status.clone();
259 let device = DeviceSinkBuilder::default()
260 .with_device(selected_device.clone())
261 .with_supported_config(&format)
262 .with_buffer_size(buffer_size)
263 .with_error_callback(move |_| callback_status.record_stream_error())
264 .open_stream()?;
265 Ok((device, status))
266 })?;
267 device.log_on_drop(false);
268 let backend = device.config();
269 let info = AudioOutputInfo {
270 sample_rate: backend.sample_rate(),
271 channels: backend.channel_count(),
272 requested_buffer_frames: config.buffer_frames,
273 configured_buffer_frames: match backend.buffer_size() {
274 BufferSize::Fixed(frames) => Some(*frames),
275 BufferSize::Default => None,
276 },
277 used_device_buffer_fallback: used_fallback,
278 };
279 Ok(Self {
280 device,
281 info,
282 lifetime: OutputLifetime { status },
283 })
284 }
285
286 /// Returns the opened output format and requested/default buffer policy.
287 pub const fn info(&self) -> AudioOutputInfo {
288 self.info
289 }
290
291 /// Returns independently shareable diagnostics without sharing device ownership.
292 pub fn status(&self) -> AudioOutputStatus {
293 self.lifetime.status.clone()
294 }
295
296 /// Transfers one mono PCM iterator to the output and returns its lifetime guard.
297 ///
298 /// Construct the source for [`AudioOutputInfo::sample_rate`]; output uses that
299 /// same rate without resampling. Rodio duplicates mono into stereo; output
300 /// channels beyond the first two receive silence.
301 /// Each sample is sanitized to finite -1.0 through 1.0 PCM before conversion.
302 /// The source executes on the audio thread: it must return promptly, avoid
303 /// blocking, allocation, file/device calls and panics, and bound its own work.
304 ///
305 /// None ends the source permanently. Interactive stopped/paused sources must
306 /// keep yielding zero if they need to resume. Controls and musical timing
307 /// belong to the application; no pause, time-scale or World policy is implied.
308 /// This consumes the output, so callers cannot enqueue unbounded sources.
309 /// Backend attachment may allocate; it is setup, not a real-time operation.
310 pub fn play_mono(self, source: impl Iterator<Item = f32> + Send + 'static) -> AudioPlayback {
311 let source = MonoSource {
312 source,
313 sample_rate: self.info.sample_rate,
314 status: self.status(),
315 ended: false,
316 };
317 self.device.mixer().add(source);
318 AudioPlayback { output: self }
319 }
320}
321
322/// Keeps the sole attached source's output device alive until dropped.
323///
324/// There is no detach or second-source API. Application-specific controls belong
325/// to the source; dropping this guard closes output even when status is cloned.
326#[derive(Debug)]
327#[must_use = "dropping playback closes its audio output"]
328pub struct AudioPlayback {
329 output: AudioOutput,
330}
331
332impl AudioPlayback {
333 /// Returns the configured output format and buffer selection.
334 pub const fn info(&self) -> AudioOutputInfo {
335 self.output.info()
336 }
337
338 /// Returns shared diagnostics without extending the output lifetime.
339 pub fn status(&self) -> AudioOutputStatus {
340 self.output.status()
341 }
342}
343
344/// A rejected output configuration or failed device-opening attempt.
345#[derive(Debug)]
346#[non_exhaustive]
347pub enum AudioOutputError {
348 /// The requested buffer is zero or exceeds the adapter's setup bound.
349 InvalidBufferFrames {
350 /// Rejected number of sample frames.
351 requested: u32,
352 /// Maximum permitted request, in sample frames.
353 maximum: u32,
354 },
355 /// No default device or usable default format could be obtained.
356 DeviceConfiguration(DeviceSinkError),
357 /// The requested buffer failed, and any explicitly enabled retry also failed.
358 Open {
359 /// Original fixed-buffer opening failure.
360 requested: DeviceSinkError,
361 /// Same-device default-buffer failure, if that retry was enabled.
362 fallback: Option<DeviceSinkError>,
363 },
364}
365
366impl fmt::Display for AudioOutputError {
367 fn fmt(&self, formatter: &mut fmt::Formatter<'_>) -> fmt::Result {
368 match self {
369 Self::InvalidBufferFrames { requested, maximum } => write!(
370 formatter,
371 "audio buffer request {requested} must be between 1 and {maximum} frames"
372 ),
373 Self::DeviceConfiguration(error) => {
374 write!(
375 formatter,
376 "default audio device configuration failed: {error}"
377 )
378 }
379 Self::Open {
380 requested,
381 fallback,
382 } => {
383 write!(
384 formatter,
385 "requested audio buffer could not open: {requested}"
386 )?;
387 if let Some(fallback) = fallback {
388 write!(
389 formatter,
390 "; device-default buffer retry also failed: {fallback}"
391 )?;
392 }
393 Ok(())
394 }
395 }
396 }
397}
398
399impl Error for AudioOutputError {
400 fn source(&self) -> Option<&(dyn Error + 'static)> {
401 match self {
402 Self::InvalidBufferFrames { .. } => None,
403 Self::DeviceConfiguration(error) => Some(error),
404 Self::Open {
405 requested,
406 fallback,
407 } => Some(fallback.as_ref().unwrap_or(requested)),
408 }
409 }
410}
411
412fn open_with_policy<T>(
413 config: AudioOutputConfig,
414 mut open: impl FnMut(BufferSize) -> Result<T, DeviceSinkError>,
415) -> Result<(T, bool), AudioOutputError> {
416 match open(BufferSize::Fixed(config.buffer_frames)) {
417 Ok(output) => Ok((output, false)),
418 Err(requested) => {
419 if !config.device_buffer_fallback {
420 return Err(AudioOutputError::Open {
421 requested,
422 fallback: None,
423 });
424 }
425 match open(BufferSize::Default) {
426 Ok(output) => Ok((output, true)),
427 Err(fallback) => Err(AudioOutputError::Open {
428 requested,
429 fallback: Some(fallback),
430 }),
431 }
432 }
433 }
434}
435
436struct MonoSource<I> {
437 source: I,
438 sample_rate: NonZeroU32,
439 status: AudioOutputStatus,
440 ended: bool,
441}
442
443impl<I: Iterator<Item = f32>> Iterator for MonoSource<I> {
444 type Item = rodio::Sample;
445
446 fn next(&mut self) -> Option<Self::Item> {
447 if self.ended {
448 return None;
449 }
450 let Some(sample) = self.source.next() else {
451 self.ended = true;
452 self.status.state.finished.store(true, Ordering::Release);
453 return None;
454 };
455 increment(&self.status.state.generated_samples);
456 let sanitized = if !sample.is_finite() {
457 increment(&self.status.state.invalid_samples);
458 0.0
459 } else if !(-1.0..=1.0).contains(&sample) {
460 increment(&self.status.state.invalid_samples);
461 sample.clamp(-1.0, 1.0)
462 } else {
463 sample
464 };
465 // Rodio's additive `64bit` feature may be enabled by another dependency.
466 // Keep the public mono input f32 while honoring the backend sample type.
467 Some(rodio::Sample::from_sample(sanitized))
468 }
469}
470
471impl<I: Iterator<Item = f32>> FusedIterator for MonoSource<I> {}
472
473impl<I: Iterator<Item = f32>> Source for MonoSource<I> {
474 fn current_span_len(&self) -> Option<usize> {
475 self.ended.then_some(0)
476 }
477
478 fn channels(&self) -> NonZeroU16 {
479 NonZeroU16::MIN
480 }
481
482 fn sample_rate(&self) -> NonZeroU32 {
483 self.sample_rate
484 }
485
486 fn total_duration(&self) -> Option<Duration> {
487 None
488 }
489}
490
491#[cfg(test)]
492#[path = "output_tests.rs"]
493mod tests;