BlueGit

ict rusty-teams

Files

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

sound_capture.rs

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