BlueGit

ict rusty-teams

Files

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

sound_capture.rs

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