| 1 | use super::*; |
| 2 | |
| 3 | #[derive(Default)] |
| 4 | pub(super) struct Recording { |
| 5 | pub(super) samples: Vec<i16>, |
| 6 | pub(super) current_second: Vec<i16>, |
| 7 | pub(super) per_second: Vec<(f32, f32)>, |
| 8 | } |
| 9 | |
| 10 | pub(super) fn withhold_media( |
| 11 | muted: &mut bool, |
| 12 | audio: &AudioSetup, |
| 13 | software_audio: Option<&SoftwareAudio>, |
| 14 | remote: &RemoteCall, |
| 15 | local_video: &mut LocalVideo, |
| 16 | control: &CallControl, |
| 17 | ) { |
| 18 | *muted = apply_mute( |
| 19 | MuteCommand::Mute, |
| 20 | *muted, |
| 21 | audio, |
| 22 | software_audio, |
| 23 | remote, |
| 24 | control, |
| 25 | ); |
| 26 | if local_video.camera_on() { |
| 27 | local_video.stop_camera(); |
| 28 | control.send(CallUpdate::Camera(false)); |
| 29 | } |
| 30 | } |
| 31 | |
| 32 | pub(super) fn record_audio_devices( |
| 33 | timeline: &Timeline, |
| 34 | lists: &devices::DeviceLists, |
| 35 | input: Option<&AppliedDevice>, |
| 36 | output: Option<&AppliedDevice>, |
| 37 | ) { |
| 38 | let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| { |
| 39 | applied |
| 40 | .and_then(|applied| devices.iter().find(|device| device.index == applied.index)) |
| 41 | .map_or("none", |device| device.name.as_str()) |
| 42 | .to_owned() |
| 43 | }; |
| 44 | timeline.record( |
| 45 | "audio devices", |
| 46 | format!( |
| 47 | "input={} output={}", |
| 48 | name(&lists.inputs, input), |
| 49 | name(&lists.outputs, output) |
| 50 | ), |
| 51 | ); |
| 52 | } |
| 53 | |
| 54 | #[allow(clippy::too_many_arguments)] |
| 55 | pub(super) fn follow_device_change( |
| 56 | flow: Flow, |
| 57 | (previous, current): (&[AudioDevice], &[AudioDevice]), |
| 58 | choice: &DeviceChoice, |
| 59 | applied: &mut Option<AppliedDevice>, |
| 60 | touched_ids: &[String], |
| 61 | select: impl Fn(u16) -> bool, |
| 62 | timeline: &Timeline, |
| 63 | control: &CallControl, |
| 64 | ) -> bool { |
| 65 | let system_default = devices::system_default_id(flow); |
| 66 | let (index, fell_back, recovery) = |
| 67 | match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) { |
| 68 | Reselect::Keep => { |
| 69 | // On Windows, a Bluetooth headset profile switch or brief disconnect+reconnect |
| 70 | // within the debounce window can leave the same endpoint index while the legacy |
| 71 | // WASAPI render/capture thread has already died on timeout/invalidation. |
| 72 | let Some(active) = applied.as_ref() else { |
| 73 | return false; |
| 74 | }; |
| 75 | let active_touched = touched_ids |
| 76 | .iter() |
| 77 | .any(|id| id.eq_ignore_ascii_case(&active.key)); |
| 78 | if !active_touched { |
| 79 | return false; |
| 80 | } |
| 81 | let Some(still_present) = current |
| 82 | .iter() |
| 83 | .find(|device| device.key().eq_ignore_ascii_case(&active.key)) |
| 84 | else { |
| 85 | return false; |
| 86 | }; |
| 87 | (still_present.index, false, true) |
| 88 | } |
| 89 | Reselect::Select(index) => (index, false, false), |
| 90 | Reselect::FallBack(index) => (index, true, false), |
| 91 | }; |
| 92 | let selected = select(index); |
| 93 | timeline.record( |
| 94 | if recovery { |
| 95 | "device recovery" |
| 96 | } else { |
| 97 | "device change" |
| 98 | }, |
| 99 | format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"), |
| 100 | ); |
| 101 | if selected { |
| 102 | *applied = current |
| 103 | .iter() |
| 104 | .find(|device| device.index == index) |
| 105 | .map(|device| AppliedDevice { |
| 106 | index, |
| 107 | key: device.key(), |
| 108 | }); |
| 109 | } |
| 110 | if fell_back { |
| 111 | let fallback = current.iter().find(|device| device.index == index); |
| 112 | control.send(CallUpdate::Notice(devices::disconnect_notice( |
| 113 | previous, choice, fallback, |
| 114 | ))); |
| 115 | } |
| 116 | selected |
| 117 | } |
| 118 | |
| 119 | pub(super) fn apply_mute( |
| 120 | command: MuteCommand, |
| 121 | currently_muted: bool, |
| 122 | audio: &AudioSetup, |
| 123 | software_audio: Option<&SoftwareAudio>, |
| 124 | remote: &RemoteCall, |
| 125 | control: &CallControl, |
| 126 | ) -> bool { |
| 127 | let effect = MuteEffect::for_muted(command.target(currently_muted)); |
| 128 | audio.set_device_tracks_enabled(effect.track_enabled); |
| 129 | if let Some(software_audio) = software_audio { |
| 130 | software_audio.set_microphone_muted(effect.muted); |
| 131 | } |
| 132 | control.send(CallUpdate::Muted(effect.muted)); |
| 133 | let remote = remote.clone(); |
| 134 | tokio::spawn(async move { |
| 135 | let _ = remote |
| 136 | .signaling |
| 137 | .update_endpoint_state( |
| 138 | &remote.conversation, |
| 139 | &remote.participant, |
| 140 | effect.endpoint_is_muted, |
| 141 | ) |
| 142 | .await; |
| 143 | }); |
| 144 | effect.muted |
| 145 | } |
| 146 | |
| 147 | pub(super) fn silence_for_server_mute( |
| 148 | audio: &AudioSetup, |
| 149 | software_audio: Option<&SoftwareAudio>, |
| 150 | control: &CallControl, |
| 151 | ) { |
| 152 | let effect = MuteEffect::for_muted(true); |
| 153 | audio.set_device_tracks_enabled(effect.track_enabled); |
| 154 | if let Some(software_audio) = software_audio { |
| 155 | software_audio.set_microphone_muted(true); |
| 156 | } |
| 157 | control.send(CallUpdate::Muted(true)); |
| 158 | } |
| 159 | |
| 160 | pub(super) fn silence_for_hold( |
| 161 | on_hold: bool, |
| 162 | muted: bool, |
| 163 | audio: Option<&AudioSetup>, |
| 164 | software_audio: Option<&SoftwareAudio>, |
| 165 | ) { |
| 166 | let silent = on_hold || muted; |
| 167 | if let Some(audio) = audio { |
| 168 | audio.set_device_tracks_enabled(MuteEffect::for_muted(silent).track_enabled); |
| 169 | } |
| 170 | if let Some(software_audio) = software_audio { |
| 171 | software_audio.set_microphone_muted(silent); |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | pub(super) fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> { |
| 176 | let sender = peer |
| 177 | .senders() |
| 178 | .into_iter() |
| 179 | .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_)))) |
| 180 | .ok_or_else(|| Error::Webrtc("no audio sender".into()))?; |
| 181 | sender |
| 182 | .set_track(Some(MediaStreamTrack::Audio(track.clone()))) |
| 183 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 184 | } |
| 185 | |
| 186 | pub(super) fn outgoing_track<'a>( |
| 187 | software_audio: Option<&'a SoftwareAudio>, |
| 188 | device_track: &'a RtcAudioTrack, |
| 189 | ) -> &'a RtcAudioTrack { |
| 190 | pick_track(software_audio.map(|audio| &audio.track), device_track) |
| 191 | } |
| 192 | |
| 193 | pub(super) fn pick_track<'a, T>(software: Option<&'a T>, device: &'a T) -> &'a T { |
| 194 | software.unwrap_or(device) |
| 195 | } |
| 196 | |
| 197 | pub(super) fn software_wanted( |
| 198 | mic_settings: MicSettings, |
| 199 | share_sound_wanted: bool, |
| 200 | local_video: &LocalVideo, |
| 201 | audio: Option<&AudioSetup>, |
| 202 | ) -> Option<SoftwareAudioPlan> { |
| 203 | let sharing_sound = share_sound_wanted && local_video.sharing(); |
| 204 | SoftwareAudioPlan::wanted( |
| 205 | mic_settings, |
| 206 | sharing_sound, |
| 207 | audio.is_some_and(AudioSetup::uses_devices), |
| 208 | ) |
| 209 | } |
| 210 | |
| 211 | pub(super) fn restore_device_track( |
| 212 | factory: &PeerConnectionFactory, |
| 213 | input: &DeviceChoice, |
| 214 | peer: &PeerConnection, |
| 215 | device_track: &RtcAudioTrack, |
| 216 | timeline: &Timeline, |
| 217 | ) { |
| 218 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 219 | if !factory.adm_recording_enabled() { |
| 220 | factory.set_adm_recording_enabled(true); |
| 221 | devices::select_input(factory, input); |
| 222 | } |
| 223 | if let Err(error) = swap_audio_track(peer, device_track) { |
| 224 | timeline.record("microphone track not restored", error.to_string()); |
| 225 | } |
| 226 | } |
| 227 | |
| 228 | #[allow(clippy::too_many_arguments)] |
| 229 | pub(super) fn sync_software_audio( |
| 230 | factory: &PeerConnectionFactory, |
| 231 | options: &CallOptions, |
| 232 | input: &DeviceChoice, |
| 233 | muted: bool, |
| 234 | remote_audio: Option<RtcAudioTrack>, |
| 235 | peer: &PeerConnection, |
| 236 | device_track: &RtcAudioTrack, |
| 237 | wanted: Option<SoftwareAudioPlan>, |
| 238 | restart: bool, |
| 239 | software_audio: &mut Option<SoftwareAudio>, |
| 240 | mic_settings: MicSettings, |
| 241 | control: &CallControl, |
| 242 | timeline: &Timeline, |
| 243 | ) { |
| 244 | let running = software_audio.as_ref().map(|audio| audio.plan); |
| 245 | if running == wanted && !restart { |
| 246 | crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none()); |
| 247 | return; |
| 248 | } |
| 249 | if running.is_some() { |
| 250 | timeline.record("software audio", "stopping"); |
| 251 | } |
| 252 | *software_audio = None; |
| 253 | let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound); |
| 254 | let Some(plan) = wanted else { |
| 255 | restore_device_track(factory, input, peer, device_track, timeline); |
| 256 | control.send(CallUpdate::ShareSound(false)); |
| 257 | crate::noise_stage::apply_for_outgoing(mic_settings, true); |
| 258 | return; |
| 259 | }; |
| 260 | let started = SoftwareAudio::start( |
| 261 | factory, |
| 262 | options.audio, |
| 263 | options.tone_hz, |
| 264 | input, |
| 265 | plan, |
| 266 | muted, |
| 267 | remote_audio, |
| 268 | ) |
| 269 | .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio)); |
| 270 | match started { |
| 271 | Ok(audio) => { |
| 272 | timeline.record( |
| 273 | "software audio", |
| 274 | format!("{:?}, computer sound {:?}", plan.processing, audio.loopback), |
| 275 | ); |
| 276 | if let Some(source) = &audio.microphone_source { |
| 277 | timeline.record("mic capture", source.clone()); |
| 278 | } |
| 279 | if audio.microphone_source.is_some() { |
| 280 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 281 | factory.set_adm_recording_enabled(false); |
| 282 | } |
| 283 | if let Some(warning) = &audio.warning { |
| 284 | timeline.record("computer sound warning", warning.clone()); |
| 285 | } |
| 286 | control.send(CallUpdate::ShareSound(plan.computer_sound)); |
| 287 | if let Some(notice) = audio.microphone_notice { |
| 288 | control.send(CallUpdate::Notice(notice.into())); |
| 289 | } |
| 290 | *software_audio = Some(audio); |
| 291 | } |
| 292 | Err(error) => { |
| 293 | timeline.record("software audio failed", error.to_string()); |
| 294 | restore_device_track(factory, input, peer, device_track, timeline); |
| 295 | if was_sharing_sound || plan.computer_sound { |
| 296 | control.send(CallUpdate::ShareSound(false)); |
| 297 | } |
| 298 | let notice = if plan.computer_sound { |
| 299 | "Computer sound could not start, sharing without it" |
| 300 | } else { |
| 301 | "Microphone processing could not start, using the standard microphone" |
| 302 | }; |
| 303 | control.send(CallUpdate::Notice(notice.into())); |
| 304 | } |
| 305 | } |
| 306 | crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none()); |
| 307 | } |
| 308 | |
| 309 | pub(super) async fn record_track( |
| 310 | track: RtcAudioTrack, |
| 311 | recording: Arc<Mutex<Recording>>, |
| 312 | tone_hz: f32, |
| 313 | ) { |
| 314 | let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1); |
| 315 | while let Some(frame) = stream.next().await { |
| 316 | let mut recording = recording.lock().await; |
| 317 | recording.samples.extend_from_slice(&frame.data); |
| 318 | recording.current_second.extend_from_slice(&frame.data); |
| 319 | if recording.current_second.len() >= SAMPLE_RATE as usize { |
| 320 | let second: Vec<i16> = std::mem::take(&mut recording.current_second); |
| 321 | let summary = (rms(&second), tone_ratio(&second, tone_hz)); |
| 322 | recording.per_second.push(summary); |
| 323 | } |
| 324 | } |
| 325 | } |