1use crate::config::AudioConfig;
4use crate::error::IoResult;
5use std::fmt::Debug;
6use std::time::Duration;
7
8#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)]
10#[cfg_attr(feature = "serde-config", derive(serde::Serialize, serde::Deserialize))]
11pub enum BackendType {
12 Cpal,
14 Alsa,
16 PipeWire,
18 Jack,
20 Null,
22}
23
24impl BackendType {
25 pub fn name(&self) -> &'static str {
27 match self {
28 BackendType::Cpal => "CPAL",
29 BackendType::Alsa => "ALSA",
30 BackendType::PipeWire => "PipeWire",
31 BackendType::Jack => "JACK",
32 BackendType::Null => "Null",
33 }
34 }
35
36 pub fn is_available(&self) -> bool {
38 match self {
39 BackendType::Cpal => true,
40 BackendType::Alsa => cfg!(target_os = "linux"),
41 BackendType::PipeWire => cfg!(target_os = "linux"),
42 BackendType::Jack => cfg!(any(target_os = "linux", target_os = "macos")),
43 BackendType::Null => true,
44 }
45 }
46}
47
48pub trait AudioBackend: Send + Sync + Debug {
50 fn backend_type(&self) -> BackendType;
52
53 fn config(&self) -> &AudioConfig;
55
56 fn config_mut(&mut self) -> &mut AudioConfig;
58
59 fn init(&mut self) -> IoResult<()>;
61
62 fn start(&mut self) -> IoResult<()>;
64
65 fn stop(&mut self) -> IoResult<()>;
67
68 fn read(&mut self, buffer: &mut [f32]) -> IoResult<usize>;
70
71 fn write(&mut self, buffer: &[f32]) -> IoResult<usize>;
73
74 fn xruns(&self) -> u32;
76
77 fn latency(&self) -> Duration;
79
80 fn list_input_devices(&self) -> Vec<String>;
82
83 fn list_output_devices(&self) -> Vec<String>;
85}
86
87impl<T: AudioBackend + ?Sized> AudioBackend for Box<T> {
89 fn backend_type(&self) -> BackendType {
90 (**self).backend_type()
91 }
92
93 fn config(&self) -> &AudioConfig {
94 (**self).config()
95 }
96
97 fn config_mut(&mut self) -> &mut AudioConfig {
98 (**self).config_mut()
99 }
100
101 fn init(&mut self) -> IoResult<()> {
102 (**self).init()
103 }
104
105 fn start(&mut self) -> IoResult<()> {
106 (**self).start()
107 }
108
109 fn stop(&mut self) -> IoResult<()> {
110 (**self).stop()
111 }
112
113 fn read(&mut self, buffer: &mut [f32]) -> IoResult<usize> {
114 (**self).read(buffer)
115 }
116
117 fn write(&mut self, buffer: &[f32]) -> IoResult<usize> {
118 (**self).write(buffer)
119 }
120
121 fn xruns(&self) -> u32 {
122 (**self).xruns()
123 }
124
125 fn latency(&self) -> Duration {
126 (**self).latency()
127 }
128
129 fn list_input_devices(&self) -> Vec<String> {
130 (**self).list_input_devices()
131 }
132
133 fn list_output_devices(&self) -> Vec<String> {
134 (**self).list_output_devices()
135 }
136}
137
138#[derive(Debug, Clone)]
140pub struct DeviceInfo {
141 pub name: String,
143 pub backend: BackendType,
145 pub is_default: bool,
147 pub max_input_channels: u32,
149 pub max_output_channels: u32,
151 pub supported_sample_rates: Vec<u32>,
153 pub supported_buffer_sizes: Vec<u32>,
155}