BlueGit

ict rusty-teams

Files

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

sound_capture.rs

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