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    /// On Linux/cpal this is a no-op — the rate is set at stream creation.
49    fn set_device_sample_rate(&self, device: &DeviceInfo, rate: f64) -> Result<(), BackendError>;
50
51    /// Create an audio engine targeting a device at a specific format.
52    /// Takes ownership of the rtrb consumer.
53    fn create_engine(
54        &self,
55        device: &DeviceInfo,
56        sample_rate: f64,
57        channels: u32,
58        consumer: rtrb::Consumer<f32>,
59        samples_played: Arc<AtomicU64>,
60    ) -> Result<Box<dyn AudioEngineHandle>, BackendError>;
61}
62
63/// Handle to a running audio engine. Start/stop control.
64pub trait AudioEngineHandle: Send {
65    fn start(&self) -> Result<(), BackendError>;
66    fn stop(&self) -> Result<(), BackendError>;
67    fn is_running(&self) -> bool;
68}
69
70#[cfg(test)]
71mod tests {
72    use super::*;
73
74    #[test]
75    fn device_info_construction() {
76        let info = DeviceInfo {
77            name: "Test DAC".into(),
78            sample_rates: vec![44100.0, 48000.0, 96000.0],
79            platform_id: 42,
80        };
81        assert_eq!(info.name, "Test DAC");
82        assert_eq!(info.sample_rates.len(), 3);
83        assert_eq!(info.platform_id, 42);
84    }
85
86    #[test]
87    fn backend_error_formatting() {
88        let err = BackendError::NoDevices;
89        assert_eq!(err.to_string(), "no output devices found");
90
91        let err = BackendError::DeviceNotFound("Missing".into());
92        assert!(err.to_string().contains("Missing"));
93
94        let err = BackendError::UnsupportedSampleRate(192000.0);
95        assert!(err.to_string().contains("192000"));
96    }
97
98    #[test]
99    fn platform_backend_constructs() {
100        // Verify the platform backend can be created without panicking.
101        let _backend = super::super::platform_backend();
102    }
103
104    #[test]
105    fn platform_backend_lists_devices() {
106        let backend = super::super::platform_backend();
107        // Should not panic. May return empty on CI (no audio hardware).
108        let result = backend.list_devices();
109        assert!(result.is_ok());
110    }
111
112    #[test]
113    fn platform_backend_has_default_device() {
114        let backend = super::super::platform_backend();
115        // On real hardware this should succeed. On CI it might fail (no device).
116        // We just verify it doesn't panic.
117        let _ = backend.default_device();
118    }
119
120    #[test]
121    fn engine_create_with_ring_buffer() {
122        let backend = super::super::platform_backend();
123        let device = match backend.default_device() {
124            Ok(d) => d,
125            Err(_) => return, // no audio device (CI) — skip
126        };
127
128        let (producer, consumer) = rtrb::RingBuffer::new(4096);
129        let samples_played = Arc::new(AtomicU64::new(0));
130
131        let rate = device.sample_rates.first().copied().unwrap_or(44100.0);
132
133        let engine = backend.create_engine(&device, rate, 2, consumer, samples_played);
134        // Should create without panicking on real hardware.
135        // May fail on CI — that's fine, we're testing the code path not the hardware.
136        if let Ok(engine) = engine {
137            assert!(!engine.is_running());
138            // Don't start — no point playing silence in a test.
139            drop(engine);
140        }
141        drop(producer); // keep producer alive until after engine
142    }
143}