1use crate::sink::validate;
10use crate::{SinkConfig, SinkError, SinkHandle, SinkStats};
11use std::sync::{Arc, Mutex};
12
13pub type CaptureFn = Box<dyn FnMut(&[f32]) + Send + 'static>;
15
16pub trait AudioSource {
18 fn default_config(&self) -> Result<SinkConfig, SinkError>;
20
21 fn start(&mut self, config: SinkConfig, capture: CaptureFn) -> Result<SinkHandle, SinkError>;
23}
24
25type Slot = Arc<Mutex<Option<(SinkConfig, CaptureFn)>>>;
26
27#[derive(Clone, Default)]
29pub struct ManualSource {
30 slot: Slot,
31 stats: SinkStats,
32}
33
34struct ManualGuard(Slot);
35
36impl Drop for ManualGuard {
37 fn drop(&mut self) {
38 if let Ok(mut s) = self.0.lock() {
39 *s = None;
40 }
41 }
42}
43
44impl ManualSource {
45 pub fn new() -> Self {
47 Self::default()
48 }
49
50 pub fn is_running(&self) -> bool {
52 self.slot.lock().map(|s| s.is_some()).unwrap_or(false)
53 }
54
55 pub fn push(&self, samples: &[f32]) -> bool {
57 let Ok(mut s) = self.slot.lock() else { return false };
58 match s.as_mut() {
59 Some((_, f)) => {
60 self.stats.record_callback();
61 f(samples);
62 true
63 }
64 None => false,
65 }
66 }
67}
68
69impl AudioSource for ManualSource {
70 fn default_config(&self) -> Result<SinkConfig, SinkError> {
71 Ok(SinkConfig::new(48_000, 1))
72 }
73
74 fn start(&mut self, config: SinkConfig, capture: CaptureFn) -> Result<SinkHandle, SinkError> {
75 validate(config)?;
76 let mut s = self.slot.lock().map_err(|_| SinkError::Backend("poisoned".into()))?;
77 if s.is_some() {
78 return Err(SinkError::AlreadyStarted);
79 }
80 *s = Some((config, capture));
81 Ok(SinkHandle::new(config, "manual source", self.stats.clone(), Box::new(ManualGuard(self.slot.clone()))))
82 }
83}
84
85#[cfg(feature = "cpal")]
86mod device {
87 use super::{AudioSource, CaptureFn};
88 use crate::cpal_sink::map_error;
89 use crate::sink::validate;
90 use crate::{SinkConfig, SinkError, SinkHandle, SinkStats};
91 use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
92 use cpal::{BufferSize, Device, Error, ErrorKind, Host, SampleFormat, SizedSample, StreamConfig, SupportedBufferSize};
93 use dasp_like::ToF32;
94
95 mod dasp_like {
96 pub trait ToF32: Copy {
98 fn to_f32(self) -> f32;
99 }
100 impl ToF32 for f32 {
101 fn to_f32(self) -> f32 {
102 self
103 }
104 }
105 impl ToF32 for i16 {
106 fn to_f32(self) -> f32 {
107 f32::from(self) / 32768.0
108 }
109 }
110 }
111
112 pub struct CpalSource {
117 host: Host,
118 }
119
120 impl Default for CpalSource {
121 fn default() -> Self {
122 CpalSource::new()
123 }
124 }
125
126 struct Guard(#[allow(dead_code)] cpal::Stream);
127
128 impl CpalSource {
129 pub fn new() -> Self {
131 CpalSource { host: cpal::default_host() }
132 }
133
134 pub fn with_host(host: Host) -> Self {
136 CpalSource { host }
137 }
138
139 #[cfg(all(feature = "pipewire", any(target_os = "linux", target_os = "freebsd", target_os = "dragonfly", target_os = "netbsd")))]
141 pub fn pipewire() -> Result<Self, SinkError> {
142 cpal::host_from_id(cpal::HostId::PipeWire).map(CpalSource::with_host).map_err(|e| map_error(&e))
143 }
144
145 fn device(&self) -> Result<Device, SinkError> {
146 self.host.default_input_device().ok_or(SinkError::NoDevice)
147 }
148 }
149
150 impl AudioSource for CpalSource {
151 fn default_config(&self) -> Result<SinkConfig, SinkError> {
152 let c = self.device()?.default_input_config().map_err(|e| map_error(&e))?;
153 Ok(SinkConfig::new(c.sample_rate(), c.channels()))
154 }
155
156 fn start(&mut self, config: SinkConfig, capture: CaptureFn) -> Result<SinkHandle, SinkError> {
157 validate(config)?;
158 let device = self.device()?;
159 let unsupported = || SinkError::UnsupportedConfig { requested: config, supported: self.default_config().ok() };
160 let mut chosen = None;
161 for range in device.supported_input_configs().map_err(|e| map_error(&e))? {
162 if range.channels() != config.channels || !range.contains_rate(config.sample_rate) {
163 continue;
164 }
165 match range.sample_format() {
166 SampleFormat::F32 => {
167 chosen = Some(range);
168 break;
169 }
170 SampleFormat::I16 if chosen.is_none() => chosen = Some(range),
171 _ => {}
172 }
173 }
174 let range = chosen.ok_or_else(unsupported)?;
175 let buffer_size = match (config.buffer_frames, range.buffer_size()) {
176 (Some(n), SupportedBufferSize::Range { min, max }) if (*min..=*max).contains(&n) => BufferSize::Fixed(n),
177 _ => BufferSize::Default,
178 };
179 let stream_config = StreamConfig { channels: config.channels, sample_rate: config.sample_rate, buffer_size };
180 let stats = SinkStats::new();
181 let stream = match range.sample_format() {
182 SampleFormat::F32 => build::<f32>(&device, stream_config, capture, &stats),
183 _ => build::<i16>(&device, stream_config, capture, &stats),
184 }
185 .map_err(|e| match e.kind() {
186 ErrorKind::UnsupportedConfig => unsupported(),
187 _ => map_error(&e),
188 })?;
189 stream.play().map_err(|e| map_error(&e))?;
190 let actual = SinkConfig {
191 buffer_frames: match buffer_size {
192 BufferSize::Fixed(n) => Some(n),
193 BufferSize::Default => None,
194 },
195 ..config
196 };
197 let name = device.description().map(|d| d.name().to_string()).unwrap_or_else(|_| "unnamed device".into());
198 let description = format!("cpal {:?} input: {name} ({:?})", self.host.id(), range.sample_format());
199 Ok(SinkHandle::new(actual, description, stats, Box::new(Guard(stream))))
200 }
201 }
202
203 fn build<T>(device: &Device, config: StreamConfig, mut capture: CaptureFn, stats: &SinkStats) -> Result<cpal::Stream, Error>
204 where
205 T: SizedSample + ToF32 + Send + 'static,
206 {
207 let data_stats = stats.clone();
208 let error_stats = stats.clone();
209 let mut scratch: Vec<f32> = Vec::new();
210 device.build_input_stream(
211 config,
212 move |data: &[T], _: &cpal::InputCallbackInfo| {
213 data_stats.record_callback();
214 scratch.clear();
215 scratch.extend(data.iter().map(|s| s.to_f32()));
216 capture(&scratch);
217 },
218 move |e: Error| match e.kind() {
219 ErrorKind::Xrun => error_stats.record_xrun(),
220 _ => error_stats.record_error(),
221 },
222 None,
223 )
224 }
225}
226
227#[cfg(feature = "cpal")]
228pub use device::CpalSource;
229
230#[cfg(test)]
231mod tests {
232 use super::*;
233 use std::sync::atomic::{AtomicUsize, Ordering};
234
235 #[test]
236 fn a_manual_source_hands_blocks_to_the_capture_function_until_dropped() {
237 let mut src = ManualSource::new();
238 let got = Arc::new(AtomicUsize::new(0));
239 let g = got.clone();
240 assert!(!src.push(&[0.0; 4]), "nothing runs yet");
241 let handle = src
242 .start(
243 SinkConfig::new(48_000, 1),
244 Box::new(move |b| {
245 g.fetch_add(b.len(), Ordering::Relaxed);
246 }),
247 )
248 .unwrap();
249 assert!(matches!(src.start(SinkConfig::new(48_000, 1), Box::new(|_| {})), Err(SinkError::AlreadyStarted)));
250 assert!(src.push(&[0.5; 480]));
251 assert_eq!(got.load(Ordering::Relaxed), 480);
252 assert_eq!(handle.stats().callbacks(), 1);
253 drop(handle);
254 assert!(!src.is_running() && !src.push(&[0.5; 480]));
255 }
256}