BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / sound_capture.rs

sound_capture.rs

sound_capture.rs 10.3 KiB Download Raw
1use std::sync::mpsc;
2
3use cpal::traits::{DeviceTrait, HostTrait, StreamTrait};
4use cpal::{Device, SampleFormat, Stream, StreamConfig};
5
6use crate::capture::Capture;
7use crate::devices::DeviceChoice;
8use crate::error::{Error, Result};
9use crate::pcm::{MonoResampler, SampleQueue};
10
11#[derive(Debug, Clone, Copy, PartialEq, Eq)]
12pub enum LoopbackKind {
13 ProcessExclude,
14 WholeEndpoint,
15 Monitor,
16 Synthetic,
17}
18
19impl LoopbackKind {
20 pub fn excludes_own_playback(self) -> bool {
21 matches!(self, LoopbackKind::ProcessExclude | LoopbackKind::Synthetic)
22 }
23}
24
25pub struct LoopbackStart {
26 pub capture: Capture,
27 pub kind: LoopbackKind,
28 pub warning: Option<String>,
29}
30
31fn audio_error(what: &str, error: impl std::fmt::Display) -> Error {
32 Error::Audio(format!("{what}: {error}"))
33}
34
35pub fn capture_name_matches(device_name: &str, target: &str) -> bool {
36 if target.is_empty() {
37 return false;
38 }
39 if device_name.eq_ignore_ascii_case(target) {
40 return true;
41 }
42 // cpal on Linux and macOS uses ALSA or CoreAudio names, which differ from
43 // the Pulse or CoreAudio descriptions in the device list.
44 #[cfg(not(windows))]
45 {
46 let device = device_name.to_ascii_lowercase();
47 let wanted = target.to_ascii_lowercase();
48 return device.contains(&wanted) || wanted.contains(&device);
49 }
50 #[cfg(windows)]
51 false
52}
53
54fn named_input(wanted: &str, label: Option<&str>) -> Option<Device> {
55 #[cfg(windows)]
56 let resolved = crate::mic_windows::friendly_name_for_id(wanted);
57 #[cfg(not(windows))]
58 let resolved: Option<String> = None;
59 let target = resolved.as_deref().or(label).unwrap_or(wanted);
60 let host = cpal::default_host();
61 let mut devices = host.input_devices().ok()?;
62 devices.find(|device| {
63 device
64 .description()
65 .is_ok_and(|description| capture_name_matches(&description.name(), target))
66 })
67}
68
69pub struct MicrophoneStart {
70 pub capture: Capture,
71 pub source: String,
72}
73
74#[cfg(windows)]
75pub fn start_microphone(
76 choice: &DeviceChoice,
77 label: Option<&str>,
78 queue: SampleQueue,
79) -> Result<MicrophoneStart> {
80 match crate::mic_windows::start_communications_microphone(choice, queue.clone()) {
81 Ok((capture, name, effects)) => {
82 let active: Vec<String> = effects
83 .iter()
84 .filter(|effect| effect.enabled)
85 .map(|effect| effect.name())
86 .collect();
87 Ok(MicrophoneStart {
88 capture,
89 source: format!(
90 "wasapi communications ({name}), windows effects: {}",
91 active.join(", ")
92 ),
93 })
94 }
95 Err(error) => {
96 let (capture, name) = start_cpal_microphone(choice, label, queue)?;
97 Ok(MicrophoneStart {
98 capture,
99 source: format!("cpal ({name}), wasapi communications failed: {error}"),
100 })
101 }
102 }
103}
104
105#[cfg(not(windows))]
106pub fn start_microphone(
107 choice: &DeviceChoice,
108 label: Option<&str>,
109 queue: SampleQueue,
110) -> Result<MicrophoneStart> {
111 let (capture, name) = start_cpal_microphone(choice, label, queue)?;
112 Ok(MicrophoneStart {
113 capture,
114 source: format!("cpal ({name})"),
115 })
116}
117
118fn start_cpal_microphone(
119 choice: &DeviceChoice,
120 label: Option<&str>,
121 queue: SampleQueue,
122) -> Result<(Capture, String)> {
123 let device = match choice {
124 DeviceChoice::SystemDefault => cpal::default_host()
125 .default_input_device()
126 .ok_or_else(|| Error::Audio("no microphone".into()))?,
127 DeviceChoice::Device(wanted) => named_input(wanted, label).ok_or_else(|| {
128 Error::Audio(format!(
129 "microphone `{wanted}` not found for capture; pick Default device or another mic"
130 ))
131 })?,
132 };
133 let name = device
134 .description()
135 .map(|description| description.name().to_owned())
136 .unwrap_or_else(|_| "unknown".into());
137 let config = device
138 .default_input_config()
139 .map_err(|error| audio_error("microphone format", error))?;
140 let capture = start_cpal_input(device, config.sample_format(), config.config(), queue)?;
141 Ok((capture, name))
142}
143
144#[cfg(windows)]
145pub fn start_loopback(queue: SampleQueue) -> Result<LoopbackStart> {
146 match crate::loopback_windows::start_process_loopback(queue.clone(), std::process::id()) {
147 Ok(capture) => Ok(LoopbackStart {
148 capture,
149 kind: LoopbackKind::ProcessExclude,
150 warning: None,
151 }),
152 Err(error) => {
153 let capture = start_endpoint_loopback(queue)?;
154 Ok(LoopbackStart {
155 capture,
156 kind: LoopbackKind::WholeEndpoint,
157 warning: Some(format!(
158 "process loopback unavailable ({error}); capturing the whole endpoint, call audio may echo"
159 )),
160 })
161 }
162 }
163}
164
165#[cfg(windows)]
166fn start_endpoint_loopback(queue: SampleQueue) -> Result<Capture> {
167 let device = cpal::default_host()
168 .default_output_device()
169 .ok_or_else(|| Error::Audio("no output device".into()))?;
170 let config = device
171 .default_output_config()
172 .map_err(|error| audio_error("output format", error))?;
173 start_cpal_input(device, config.sample_format(), config.config(), queue)
174}
175
176#[cfg(not(windows))]
177pub fn start_loopback(queue: SampleQueue) -> Result<LoopbackStart> {
178 Ok(LoopbackStart {
179 capture: start_monitor(queue)?,
180 kind: LoopbackKind::Monitor,
181 warning: None,
182 })
183}
184
185#[cfg(not(windows))]
186fn start_monitor(queue: SampleQueue) -> Result<Capture> {
187 use std::io::Read;
188 use std::process::{Command, Stdio};
189 use std::sync::{Arc, Mutex};
190
191 const READ_BYTES: usize = 960;
192 let mut child = Command::new("parec")
193 .args([
194 "--device=@DEFAULT_MONITOR@",
195 "--format=s16le",
196 "--rate=48000",
197 "--channels=1",
198 "--latency-msec=10",
199 ])
200 .stdout(Stdio::piped())
201 .stderr(Stdio::null())
202 .spawn()
203 .map_err(|error| audio_error("parec", error))?;
204 let mut output = child
205 .stdout
206 .take()
207 .ok_or_else(|| Error::Audio("parec without output".into()))?;
208 let child = Arc::new(Mutex::new(child));
209 let watched = child.clone();
210 Capture::spawn_thread("sound-monitor", move |stop| {
211 let watcher = std::thread::spawn({
212 let stop = stop.clone();
213 move || {
214 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
215 std::thread::sleep(std::time::Duration::from_millis(50));
216 }
217 let mut child = watched
218 .lock()
219 .unwrap_or_else(|poisoned| poisoned.into_inner());
220 let _ = child.kill();
221 let _ = child.wait();
222 }
223 });
224 let mut bytes = [0u8; READ_BYTES];
225 while output.read_exact(&mut bytes).is_ok() {
226 let samples: Vec<i16> = bytes
227 .as_chunks::<2>()
228 .0
229 .iter()
230 .map(|pair| i16::from_le_bytes(*pair))
231 .collect();
232 queue.push(&samples);
233 }
234 let _ = watcher.join();
235 })
236 .map_err(|error| audio_error("monitor thread", error))
237}
238
239fn start_cpal_input(
240 device: Device,
241 format: SampleFormat,
242 config: StreamConfig,
243 queue: SampleQueue,
244) -> Result<Capture> {
245 let (ready_sender, ready) = mpsc::channel::<Result<()>>();
246 let capture = Capture::spawn_thread("sound-input", move |stop| {
247 match build_stream(&device, format, &config, queue) {
248 Ok(stream) => {
249 let started = stream.play().map_err(|error| audio_error("start", error));
250 let _ = ready_sender.send(started);
251 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
252 std::thread::sleep(std::time::Duration::from_millis(50));
253 }
254 }
255 Err(error) => {
256 let _ = ready_sender.send(Err(error));
257 }
258 }
259 })
260 .map_err(|error| audio_error("input thread", error))?;
261 ready
262 .recv()
263 .map_err(|_| Error::Audio("input thread ended".into()))??;
264 Ok(capture)
265}
266
267fn build_stream(
268 device: &Device,
269 format: SampleFormat,
270 config: &StreamConfig,
271 queue: SampleQueue,
272) -> Result<Stream> {
273 let channels = usize::from(config.channels);
274 let mut resampler = MonoResampler::new(config.sample_rate);
275 let mut converted = Vec::new();
276 let failed = |_error| {};
277 match format {
278 SampleFormat::F32 => device.build_input_stream(
279 config,
280 move |data: &[f32], _| {
281 converted.clear();
282 resampler.convert(data, channels, &mut converted);
283 queue.push(&converted);
284 },
285 failed,
286 None,
287 ),
288 SampleFormat::I16 => device.build_input_stream(
289 config,
290 move |data: &[i16], _| {
291 converted.clear();
292 resampler.convert(&crate::pcm::i16_to_f32(data), channels, &mut converted);
293 queue.push(&converted);
294 },
295 failed,
296 None,
297 ),
298 other => return Err(Error::Audio(format!("unsupported sample format {other:?}"))),
299 }
300 .map_err(|error| audio_error("open input", error))
301}
302
303#[cfg(test)]
304mod tests {
305 use super::capture_name_matches;
306
307 #[test]
308 fn a_named_microphone_matches_the_listed_name() {
309 assert!(capture_name_matches(
310 "Headset Microphone",
311 "headset microphone"
312 ));
313 assert!(!capture_name_matches(
314 "Headset Microphone",
315 "{0.0.0.00000000}.{bbbb}"
316 ));
317 assert!(!capture_name_matches("Mic", ""));
318 #[cfg(windows)]
319 assert!(!capture_name_matches("Headset Microphone", "Microphone"));
320 #[cfg(not(windows))]
321 {
322 assert!(capture_name_matches("sysdefault:CARD=Jabra", "Jabra"));
323 assert!(capture_name_matches(
324 "Jabra Speak 750 Mono",
325 "Jabra Speak 750"
326 ));
327 assert!(capture_name_matches(
328 "Jabra Speak 750",
329 "Jabra Speak 750 Mono"
330 ));
331 }
332 }
333}