use std::time::Duration;
use crate::PlatformError;
#[cfg(target_os = "linux")]
use crate::linux::alsa as backend;
#[cfg(not(target_os = "linux"))]
use crate::no_audio as backend;
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct AudioOutputConfig {
pub sample_rate: u32,
pub channels: u16,
pub latency_ms: u32,
}
impl Default for AudioOutputConfig {
fn default() -> Self {
Self {
sample_rate: 48_000,
channels: 2,
latency_ms: 30,
}
}
}
impl AudioOutputConfig {
fn validate(&self) -> Result<(), PlatformError> {
let check = |ok: bool, field, expected| {
if ok {
Ok(())
} else {
Err(PlatformError::InvalidAudioConfig { field, expected })
}
};
check((1..=8).contains(&self.channels), "channels", "1 to 8")?;
check(
(8_000..=384_000).contains(&self.sample_rate),
"sample_rate",
"8,000 to 384,000",
)?;
check(
(5..=500).contains(&self.latency_ms),
"latency_ms",
"5 to 500",
)
}
}
pub trait AudioRender: Send + 'static {
fn render(&mut self, out: &mut [f32], channels: u16, sample_rate: u32);
fn underrun(&mut self);
}
pub struct AudioStream {
inner: backend::Stream,
}
const _: fn() = || {
fn send_and_sync<T: Send + Sync>() {}
send_and_sync::<AudioStream>();
};
impl AudioStream {
pub fn latency(&self) -> Option<Duration> {
self.inner.latency()
}
}
pub fn open_audio(
config: &AudioOutputConfig,
render: Box<dyn AudioRender>,
) -> Result<AudioStream, PlatformError> {
config.validate()?;
let inner = backend::open(config, render)?;
Ok(AudioStream { inner })
}
#[cfg(test)]
mod tests {
use super::*;
struct Never;
impl AudioRender for Never {
fn render(&mut self, _out: &mut [f32], _channels: u16, _sample_rate: u32) {
unreachable!("the stream does not start");
}
fn underrun(&mut self) {
unreachable!("the stream does not start");
}
}
fn refused(config: AudioOutputConfig) -> (&'static str, &'static str) {
match open_audio(&config, Box::new(Never)) {
Err(PlatformError::InvalidAudioConfig { field, expected }) => (field, expected),
Err(error) => panic!("{error}"),
Ok(_) => panic!("the stream started"),
}
}
#[test]
fn each_field_out_of_its_range_is_refused_on_every_system() {
let config = AudioOutputConfig::default();
for channels in [0, 9, u16::MAX] {
let field = refused(AudioOutputConfig { channels, ..config });
assert_eq!(field, ("channels", "1 to 8"), "{channels} channels");
}
for sample_rate in [0, 7_999, 384_001, u32::MAX] {
let field = refused(AudioOutputConfig {
sample_rate,
..config
});
assert_eq!(
field,
("sample_rate", "8,000 to 384,000"),
"{sample_rate} Hz"
);
}
for latency_ms in [0, 4, 501, u32::MAX] {
let field = refused(AudioOutputConfig {
latency_ms,
..config
});
assert_eq!(field, ("latency_ms", "5 to 500"), "{latency_ms} ms");
}
}
#[test]
fn each_range_includes_its_ends() {
for config in [
AudioOutputConfig {
sample_rate: 8_000,
channels: 1,
latency_ms: 5,
},
AudioOutputConfig {
sample_rate: 384_000,
channels: 8,
latency_ms: 500,
},
] {
assert_eq!(config.validate(), Ok(()), "{config:?}");
}
assert_eq!(AudioOutputConfig::default().validate(), Ok(()));
}
}