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