BlueGit

ict rusty-teams

Files

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

sound_capture.rs

sound_capture.rs 7.1 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
35fn named_input(choice: &DeviceChoice) -> Option<Device> {
36 let DeviceChoice::Device(wanted) = choice else { return None };
37 cpal::default_host()
38 .input_devices()
39 .ok()?
40 .find(|device| device.description().is_ok_and(|description| description.name() == wanted))
41}
42
43pub struct MicrophoneStart {
44 pub capture: Capture,
45 pub source: String,
46}
47
48#[cfg(windows)]
49pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
50 match crate::mic_windows::start_communications_microphone(choice, queue.clone()) {
51 Ok((capture, name)) => Ok(MicrophoneStart { capture, source: format!("wasapi communications ({name})") }),
52 Err(error) => {
53 let capture = start_cpal_microphone(choice, queue)?;
54 Ok(MicrophoneStart { capture, source: format!("cpal, wasapi communications failed: {error}") })
55 }
56 }
57}
58
59#[cfg(not(windows))]
60pub fn start_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<MicrophoneStart> {
61 let capture = start_cpal_microphone(choice, queue)?;
62 Ok(MicrophoneStart { capture, source: "cpal".into() })
63}
64
65fn start_cpal_microphone(choice: &DeviceChoice, queue: SampleQueue) -> Result<Capture> {
66 let device = named_input(choice)
67 .or_else(|| cpal::default_host().default_input_device())
68 .ok_or_else(|| Error::Audio("no microphone".into()))?;
69 let config = device.default_input_config().map_err(|error| audio_error("microphone format", error))?;
70 start_cpal_input(device, config.sample_format(), config.config(), queue)
71}
72
73#[cfg(windows)]
74pub fn start_loopback(queue: SampleQueue) -> Result<LoopbackStart> {
75 match crate::loopback_windows::start_process_loopback(queue.clone(), std::process::id()) {
76 Ok(capture) => Ok(LoopbackStart { capture, kind: LoopbackKind::ProcessExclude, warning: None }),
77 Err(error) => {
78 let capture = start_endpoint_loopback(queue)?;
79 Ok(LoopbackStart {
80 capture,
81 kind: LoopbackKind::WholeEndpoint,
82 warning: Some(format!("process loopback unavailable ({error}); capturing the whole endpoint, call audio may echo")),
83 })
84 }
85 }
86}
87
88#[cfg(windows)]
89fn start_endpoint_loopback(queue: SampleQueue) -> Result<Capture> {
90 let device = cpal::default_host()
91 .default_output_device()
92 .ok_or_else(|| Error::Audio("no output device".into()))?;
93 let config = device.default_output_config().map_err(|error| audio_error("output format", error))?;
94 start_cpal_input(device, config.sample_format(), config.config(), queue)
95}
96
97#[cfg(not(windows))]
98pub fn start_loopback(queue: SampleQueue) -> Result<LoopbackStart> {
99 Ok(LoopbackStart { capture: start_monitor(queue)?, kind: LoopbackKind::Monitor, warning: None })
100}
101
102#[cfg(not(windows))]
103fn start_monitor(queue: SampleQueue) -> Result<Capture> {
104 use std::io::Read;
105 use std::process::{Command, Stdio};
106 use std::sync::{Arc, Mutex};
107
108 const READ_BYTES: usize = 960;
109 let mut child = Command::new("parec")
110 .args(["--device=@DEFAULT_MONITOR@", "--format=s16le", "--rate=48000", "--channels=1", "--latency-msec=10"])
111 .stdout(Stdio::piped())
112 .stderr(Stdio::null())
113 .spawn()
114 .map_err(|error| audio_error("parec", error))?;
115 let mut output = child.stdout.take().ok_or_else(|| Error::Audio("parec without output".into()))?;
116 let child = Arc::new(Mutex::new(child));
117 let watched = child.clone();
118 Capture::spawn_thread("sound-monitor", move |stop| {
119 let watcher = std::thread::spawn({
120 let stop = stop.clone();
121 move || {
122 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
123 std::thread::sleep(std::time::Duration::from_millis(50));
124 }
125 let mut child = watched.lock().unwrap_or_else(|poisoned| poisoned.into_inner());
126 let _ = child.kill();
127 let _ = child.wait();
128 }
129 });
130 let mut bytes = [0u8; READ_BYTES];
131 while output.read_exact(&mut bytes).is_ok() {
132 let samples: Vec<i16> = bytes.as_chunks::<2>().0.iter().map(|pair| i16::from_le_bytes(*pair)).collect();
133 queue.push(&samples);
134 }
135 let _ = watcher.join();
136 })
137 .map_err(|error| audio_error("monitor thread", error))
138}
139
140fn start_cpal_input(device: Device, format: SampleFormat, config: StreamConfig, queue: SampleQueue) -> Result<Capture> {
141 let (ready_sender, ready) = mpsc::channel::<Result<()>>();
142 let capture = Capture::spawn_thread("sound-input", move |stop| {
143 match build_stream(&device, format, &config, queue) {
144 Ok(stream) => {
145 let started = stream.play().map_err(|error| audio_error("start", error));
146 let _ = ready_sender.send(started);
147 while !stop.load(std::sync::atomic::Ordering::SeqCst) {
148 std::thread::sleep(std::time::Duration::from_millis(50));
149 }
150 }
151 Err(error) => {
152 let _ = ready_sender.send(Err(error));
153 }
154 }
155 })
156 .map_err(|error| audio_error("input thread", error))?;
157 ready.recv().map_err(|_| Error::Audio("input thread ended".into()))??;
158 Ok(capture)
159}
160
161fn build_stream(device: &Device, format: SampleFormat, config: &StreamConfig, queue: SampleQueue) -> Result<Stream> {
162 let channels = usize::from(config.channels);
163 let mut resampler = MonoResampler::new(config.sample_rate);
164 let mut converted = Vec::new();
165 let failed = |_error| {};
166 match format {
167 SampleFormat::F32 => device.build_input_stream(
168 config,
169 move |data: &[f32], _| {
170 converted.clear();
171 resampler.convert(data, channels, &mut converted);
172 queue.push(&converted);
173 },
174 failed,
175 None,
176 ),
177 SampleFormat::I16 => device.build_input_stream(
178 config,
179 move |data: &[i16], _| {
180 converted.clear();
181 resampler.convert(&crate::pcm::i16_to_f32(data), channels, &mut converted);
182 queue.push(&converted);
183 },
184 failed,
185 None,
186 ),
187 other => return Err(Error::Audio(format!("unsupported sample format {other:?}"))),
188 }
189 .map_err(|error| audio_error("open input", error))
190}