Skip to main content

koan_core/audio/
backend.rs

1use std::sync::Arc;
2use std::sync::atomic::AtomicU64;
3
4use thiserror::Error;
5
6#[derive(Debug, Error)]
7pub enum BackendError {
8    #[error("no output devices found")]
9    NoDevices,
10    #[error("device not found: {0}")]
11    DeviceNotFound(String),
12    #[error("unsupported sample rate: {0}")]
13    UnsupportedSampleRate(f64),
14    #[error("platform error: {0}")]
15    Platform(String),
16    #[error("stream creation failed: {0}")]
17    StreamCreation(String),
18}
19
20/// Platform-agnostic output device descriptor.
21#[derive(Debug, Clone)]
22pub struct DeviceInfo {
23    pub name: String,
24    pub sample_rates: Vec<f64>,
25    /// Opaque platform-specific ID. CoreAudio: AudioDeviceID, cpal: index.
26    pub platform_id: u64,
27}
28
29/// Trait abstracting platform audio output.
30///
31/// Implementations exist for CoreAudio (macOS) and cpal (Linux).
32/// The decode pipeline (rtrb ring buffer, Symphonia, `PlaybackTimeline`) is
33/// completely decoupled — backends are dumb consumers that drain the ring buffer.
34pub trait AudioBackend: Send + Sync {
35    /// List available output devices.
36    fn list_devices(&self) -> Result<Vec<DeviceInfo>, BackendError>;
37
38    /// Get the default output device.
39    fn default_device(&self) -> Result<DeviceInfo, BackendError>;
40
41    /// Query supported sample rates for a device.
42    fn supported_sample_rates(&self, device: &DeviceInfo) -> Result<Vec<f64>, BackendError>;
43
44    /// Get the current nominal sample rate of a device.
45    fn get_device_sample_rate(&self, device: &DeviceInfo) -> Result<f64, BackendError>;
46
47    /// Set the nominal sample rate of a device (for bit-perfect matching).
48    /// Returns the actual device rate after the switch (may differ if unsupported).
49    /// On Linux/cpal this is a no-op — the rate is set at stream creation.
50    fn set_device_sample_rate(&self, device: &DeviceInfo, rate: f64) -> Result<f64, BackendError>;
51
52    /// Create an audio engine targeting a device at a specific format.
53    /// Takes ownership of the rtrb consumer.
54    fn create_engine(
55        &self,
56        device: &DeviceInfo,
57        sample_rate: f64,
58        channels: u32,
59        consumer: rtrb::Consumer<f32>,
60        samples_played: Arc<AtomicU64>,
61    ) -> Result<Box<dyn AudioEngineHandle>, BackendError>;
62}
63
64/// Handle to a running audio engine. Start/stop control.
65pub trait AudioEngineHandle: Send {
66    fn start(&self) -> Result<(), BackendError>;
67    fn stop(&self) -> Result<(), BackendError>;
68    fn is_running(&self) -> bool;
69}
70
71#[cfg(test)]
72mod tests {
73    use super::*;
74
75    #[test]
76    fn device_info_construction() {
77        let info = DeviceInfo {
78            name: "Test DAC".into(),
79            sample_rates: vec![44100.0, 48000.0, 96000.0],
80            platform_id: 42,
81        };
82        assert_eq!(info.name, "Test DAC");
83        assert_eq!(info.sample_rates.len(), 3);
84        assert_eq!(info.platform_id, 42);
85    }
86
87    #[test]
88    fn backend_error_formatting() {
89        let err = BackendError::NoDevices;
90        assert_eq!(err.to_string(), "no output devices found");
91
92        let err = BackendError::DeviceNotFound("Missing".into());
93        assert!(err.to_string().contains("Missing"));
94
95        let err = BackendError::UnsupportedSampleRate(192000.0);
96        assert!(err.to_string().contains("192000"));
97    }
98
99    #[test]
100    fn platform_backend_constructs() {
101        // Verify the platform backend can be created without panicking.
102        let _backend = super::super::platform_backend();
103    }
104
105    #[test]
106    fn platform_backend_lists_devices() {
107        let backend = super::super::platform_backend();
108        // Should not panic. May return empty on CI (no audio hardware).
109        let result = backend.list_devices();
110        assert!(result.is_ok());
111    }
112
113    #[test]
114    fn platform_backend_has_default_device() {
115        let backend = super::super::platform_backend();
116        // On real hardware this should succeed. On CI it might fail (no device).
117        // We just verify it doesn't panic.
118        let _ = backend.default_device();
119    }
120
121    #[test]
122    fn engine_create_with_ring_buffer() {
123        let backend = super::super::platform_backend();
124        let device = match backend.default_device() {
125            Ok(d) => d,
126            Err(_) => return, // no audio device (CI) — skip
127        };
128
129        let (producer, consumer) = rtrb::RingBuffer::new(4096);
130        let samples_played = Arc::new(AtomicU64::new(0));
131
132        let rate = device.sample_rates.first().copied().unwrap_or(44100.0);
133
134        let engine = backend.create_engine(&device, rate, 2, consumer, samples_played);
135        // Should create without panicking on real hardware.
136        // May fail on CI — that's fine, we're testing the code path not the hardware.
137        if let Ok(engine) = engine {
138            assert!(!engine.is_running());
139            // Don't start — no point playing silence in a test.
140            drop(engine);
141        }
142        drop(producer); // keep producer alive until after engine
143    }
144}