| 1 | use std::collections::BTreeMap; |
| 2 | use std::path::PathBuf; |
| 3 | use std::sync::Arc; |
| 4 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | use chatsvc::TrouterCallback; |
| 8 | use futures_util::StreamExt; |
| 9 | use libwebrtc::audio_stream::native::NativeAudioStream; |
| 10 | use libwebrtc::data_channel::{DataChannel, DataChannelInit}; |
| 11 | use libwebrtc::prelude::*; |
| 12 | use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit}; |
| 13 | use libwebrtc::session_description::{SdpType, SessionDescription}; |
| 14 | use libwebrtc::stats::RtcStats; |
| 15 | use session::Session; |
| 16 | use tokio::sync::{Mutex, mpsc}; |
| 17 | use tokio::task::JoinHandle; |
| 18 | use tokio::time::{Instant, interval, sleep_until, timeout}; |
| 19 | |
| 20 | use crate::active_speakers; |
| 21 | use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav}; |
| 22 | use crate::audio_io::{AudioMode, AudioSetup}; |
| 23 | use crate::background::{BackgroundChoice, BackgroundPicture}; |
| 24 | use crate::breakout::{self, RoomWatcher}; |
| 25 | use crate::callee_gate::{CalleeGate, EchoWatch, roster_has_callee}; |
| 26 | use crate::camera::{CameraDevice, list_cameras}; |
| 27 | use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates}; |
| 28 | use crate::captions::{ |
| 29 | BotAction, CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep, |
| 30 | parse_caption_message, |
| 31 | }; |
| 32 | use crate::control::{CallCommand, CallControl, CallUpdate, Progress}; |
| 33 | use crate::data_channel::Depacketizer; |
| 34 | use crate::device_watch::{self, Debounce}; |
| 35 | use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect}; |
| 36 | use crate::diagnostics::{CallDiagnostics, StatsSample}; |
| 37 | use crate::end::EndKind; |
| 38 | use crate::engine::{CallEngine, EngineConfig, Inner}; |
| 39 | use crate::error::{Error, Result}; |
| 40 | use crate::health::{ |
| 41 | CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats, |
| 42 | }; |
| 43 | use crate::hold::{ |
| 44 | HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, is_hold, keep_media_running, |
| 45 | offer_modalities, offer_sends_video, rewrite_directions, stop_sending_on, |
| 46 | }; |
| 47 | use crate::meeting_options::{self, OptionWrite}; |
| 48 | use crate::mic_processing::MicSettings; |
| 49 | use crate::mute::{MuteCommand, MuteEffect}; |
| 50 | use crate::notices::{ |
| 51 | ADMIT_ALL_FAILED_NOTICE, ADMIT_FAILED_NOTICE, ATTENDEE_SETTINGS_FAILED_NOTICE, |
| 52 | BACKGROUND_IMAGE_FAILED_NOTICE, CALL_TRANSFERRED_NOTICE, CAMERA_RESTART_NOTICE, |
| 53 | CAMERA_SETTING_FAILED_NOTICE, CAMERA_START_NOTICE, CAPTION_LANGUAGE_FAILED_NOTICE, |
| 54 | CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE, CHANGE_ROLE_FAILED_NOTICE, |
| 55 | CHANGE_RUNNING_NOTICE, CONFIRM_RECORDING_FAILED_NOTICE, CONSENT_FIRST_NOTICE, |
| 56 | DENY_FAILED_NOTICE, HOLD_CHANGE_FAILED_NOTICE, HOLD_FAILED_NOTICE, INVITE_PERSON_FAILED_NOTICE, |
| 57 | LOWER_ALL_HANDS_FAILED_NOTICE, LOWER_HAND_FAILED_NOTICE, LOWER_THAT_HAND_FAILED_NOTICE, |
| 58 | MEETING_LOCK_FAILED_NOTICE, MIC_SETTING_FAILED_NOTICE, MUTE_ALL_FAILED_NOTICE, |
| 59 | MUTE_PARTICIPANT_FAILED_NOTICE, NOT_CONNECTED_FOR_VIDEO, ON_HOLD_NOTICE, |
| 60 | RAISE_HAND_FAILED_NOTICE, REACTION_FAILED_NOTICE, RECORDING_JOIN_FAILED_NOTICE, |
| 61 | RECORDING_NOT_STARTED_NOTICE, RECORDING_START_FAILED_NOTICE, RECORDING_STOP_FAILED_NOTICE, |
| 62 | REMOVE_PARTICIPANT_FAILED_NOTICE, RESUME_FAILED_NOTICE, SHARE_QUEUED_NOTICE, |
| 63 | SHARE_REFUSED_NOTICE, SHARING_START_NOTICE, SPOTLIGHT_FAILED_NOTICE, |
| 64 | STOP_SPOTLIGHT_FAILED_NOTICE, TRANSFER_CALL_FAILED_NOTICE, TRANSFER_FAILED_NOTICE, |
| 65 | TRANSFER_NOT_ALLOWED_NOTICE, TRANSFERRING_NOTICE, VIDEO_FAILED_NOTICE, |
| 66 | WHITEBOARD_OPEN_FAILED_NOTICE, WHITEBOARDS_MEETINGS_ONLY_NOTICE, notice_with_detail, |
| 67 | }; |
| 68 | use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps}; |
| 69 | use crate::outcome::{embedded_end, failed_participant_count, outcome_summary}; |
| 70 | use crate::push::CallNotification; |
| 71 | use crate::recording::{Consent, RecordingPlan, RecordingStatus}; |
| 72 | use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant}; |
| 73 | use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer}; |
| 74 | use crate::roster::{Roster, direct_roster}; |
| 75 | use crate::screen::{ |
| 76 | ShareKind, SharePicker, ShareSource, current_share_picker, list_share_sources, |
| 77 | share_sources_for_menu, share_thumbnail, |
| 78 | }; |
| 79 | use crate::sdp::{ |
| 80 | LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, |
| 81 | to_browser_answer, to_teams_answer, to_teams_offer, |
| 82 | }; |
| 83 | use crate::send_control::{RequestFilter, parse_request}; |
| 84 | use crate::signaling::{ |
| 85 | Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, |
| 86 | NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id, |
| 87 | escalation_answer_body, find_echo_bot_thread, one_to_one_thread, renegotiation_body, |
| 88 | }; |
| 89 | use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan}; |
| 90 | use crate::state::{CallSignal, CallState}; |
| 91 | use crate::timeline::{Timeline, TimelineEntry}; |
| 92 | use crate::transfer::{Replacement, TransferEvent, TransferTarget}; |
| 93 | use crate::trouter_events::{ |
| 94 | CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body, |
| 95 | }; |
| 96 | use crate::video_frame::{VideoKey, VideoPicture}; |
| 97 | use crate::video_layout::{ |
| 98 | CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter, |
| 99 | SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines, |
| 100 | offer_plan, one_to_one_plan, |
| 101 | }; |
| 102 | use crate::video_receive::{ |
| 103 | ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump, |
| 104 | }; |
| 105 | use crate::video_send::{LocalVideo, SendSource, VideoMode}; |
| 106 | use crate::whiteboard; |
| 107 | |
| 108 | const END_CALLBACK_WAIT: Duration = Duration::from_secs(4); |
| 109 | const STATS_PERIOD: Duration = Duration::from_millis(200); |
| 110 | const TICKS_PER_SECOND: u32 = 5; |
| 111 | const RECONNECT_WINDOW: Duration = Duration::from_secs(30); |
| 112 | const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90); |
| 113 | const SETUP_STEP_TIMEOUT: Duration = Duration::from_secs(30); |
| 114 | const DIRECT_OUTGOING_TIMEOUT: Duration = Duration::from_secs(185); |
| 115 | const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365); |
| 116 | const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700; |
| 117 | const MIN_KEEP_ALIVE_SECONDS: u64 = 60; |
| 118 | const KEEP_ALIVE_FRACTION: f64 = 0.9; |
| 119 | const MIC_STREAM: &str = "microphone"; |
| 120 | const DATA_CHANNEL_LABEL: &str = "main-channel"; |
| 121 | pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL"; |
| 122 | const CAPTION_START_LIMIT: Duration = Duration::from_secs(40); |
| 123 | const SEND_CAPABILITIES_LABEL: &str = "POST applyChannelParameters"; |
| 124 | const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2; |
| 125 | const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2; |
| 126 | const BOT_PREFIX: &str = "28:"; |
| 127 | const RECORDING_START_LIMIT: Duration = Duration::from_secs(40); |
| 128 | const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40); |
| 129 | /// Teams sometimes answers a few seconds after the soft limit; keep the local offer until this grace ends. |
| 130 | const SAME_PEER_LATE_GRACE: Duration = Duration::from_secs(15); |
| 131 | const GATHERING_LIMIT: Duration = Duration::from_secs(5); |
| 132 | const RELAY_SETTLE: Duration = Duration::from_millis(200); |
| 133 | const GATHERING_POLL: Duration = Duration::from_millis(50); |
| 134 | const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40); |
| 135 | const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3); |
| 136 | const GLARE_CODE: i64 = 491; |
| 137 | const RETARGET_WAIT: Duration = Duration::from_secs(20); |
| 138 | const CAMERA_STREAM: &str = "camera"; |
| 139 | |
| 140 | #[derive(Debug, Clone)] |
| 141 | pub struct CallOptions { |
| 142 | pub hold_after_connected: Option<Duration>, |
| 143 | pub hard_limit: Option<Duration>, |
| 144 | pub reconnect_window: Duration, |
| 145 | pub audio: AudioMode, |
| 146 | pub video: VideoMode, |
| 147 | pub camera: DeviceChoice, |
| 148 | pub tone_hz: f32, |
| 149 | pub input: DeviceChoice, |
| 150 | pub output: DeviceChoice, |
| 151 | pub relay_host: String, |
| 152 | pub routing: TenantRouting, |
| 153 | pub record_remote: bool, |
| 154 | pub wav_path: Option<PathBuf>, |
| 155 | pub sdp_dump_dir: Option<PathBuf>, |
| 156 | pub trace: bool, |
| 157 | pub data_channel: bool, |
| 158 | pub concurrent: bool, |
| 159 | pub start_camera: bool, |
| 160 | } |
| 161 | |
| 162 | impl Default for CallOptions { |
| 163 | fn default() -> Self { |
| 164 | CallOptions { |
| 165 | hold_after_connected: None, |
| 166 | hard_limit: None, |
| 167 | reconnect_window: RECONNECT_WINDOW, |
| 168 | audio: AudioMode::from_env(), |
| 169 | video: VideoMode::from_env(), |
| 170 | camera: DeviceChoice::SystemDefault, |
| 171 | tone_hz: 440.0, |
| 172 | input: DeviceChoice::SystemDefault, |
| 173 | output: DeviceChoice::SystemDefault, |
| 174 | relay_host: DEFAULT_RELAY_HOST.to_owned(), |
| 175 | routing: TenantRouting::default(), |
| 176 | record_remote: false, |
| 177 | wav_path: None, |
| 178 | sdp_dump_dir: None, |
| 179 | trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(), |
| 180 | data_channel: data_channel_from_env(), |
| 181 | concurrent: false, |
| 182 | start_camera: false, |
| 183 | } |
| 184 | } |
| 185 | } |
| 186 | |
| 187 | #[derive(Debug, Clone, Default)] |
| 188 | pub struct AudioSecond { |
| 189 | pub second: u32, |
| 190 | pub packets: u64, |
| 191 | pub bytes: u64, |
| 192 | pub audio_level: f64, |
| 193 | pub decoded_rms: f32, |
| 194 | pub tone_ratio: f32, |
| 195 | } |
| 196 | |
| 197 | #[derive(Debug, Clone, Default, PartialEq)] |
| 198 | pub struct VideoReport { |
| 199 | pub inbound_packets: u64, |
| 200 | pub inbound_frames_decoded: u64, |
| 201 | pub inbound_width: u32, |
| 202 | pub inbound_height: u32, |
| 203 | pub frames_received: u64, |
| 204 | pub frames_published: u64, |
| 205 | pub outbound_packets: u64, |
| 206 | pub outbound_frames_encoded: u64, |
| 207 | pub outbound_width: u32, |
| 208 | pub outbound_height: u32, |
| 209 | pub remote_reports: u64, |
| 210 | pub remote_round_trip_ms: f64, |
| 211 | } |
| 212 | |
| 213 | #[derive(Debug, Clone, Default)] |
| 214 | pub struct CallReport { |
| 215 | pub timeline: Vec<TimelineEntry>, |
| 216 | pub ice_connected_ms: Option<u128>, |
| 217 | pub peer_connected_ms: Option<u128>, |
| 218 | pub selected_pair: Option<String>, |
| 219 | pub tls_version: String, |
| 220 | pub dtls_cipher: String, |
| 221 | pub srtp_cipher: String, |
| 222 | pub inbound_packets: u64, |
| 223 | pub inbound_bytes: u64, |
| 224 | pub outbound_packets: u64, |
| 225 | pub video: VideoReport, |
| 226 | pub own_streams: Vec<String>, |
| 227 | pub seconds_with_inbound_audio: u32, |
| 228 | pub seconds: Vec<AudioSecond>, |
| 229 | pub end: Option<CallEnd>, |
| 230 | pub left_cleanly: bool, |
| 231 | pub recorded_samples: usize, |
| 232 | } |
| 233 | |
| 234 | #[derive(Debug, Clone)] |
| 235 | pub enum CallSpec { |
| 236 | Echo, |
| 237 | People { |
| 238 | callees: Vec<Callee>, |
| 239 | thread_id: String, |
| 240 | }, |
| 241 | Meeting(MeetingTarget), |
| 242 | } |
| 243 | |
| 244 | impl CallSpec { |
| 245 | fn target(&self) -> InviteTarget { |
| 246 | match self { |
| 247 | CallSpec::Echo => InviteTarget::Echo, |
| 248 | CallSpec::People { callees, thread_id } => InviteTarget::People { |
| 249 | callees: callees.clone(), |
| 250 | thread_id: thread_id.clone(), |
| 251 | }, |
| 252 | CallSpec::Meeting(meeting) => InviteTarget::Meeting(meeting.clone()), |
| 253 | } |
| 254 | } |
| 255 | |
| 256 | fn is_meeting(&self) -> bool { |
| 257 | matches!(self, CallSpec::Meeting(_)) |
| 258 | } |
| 259 | |
| 260 | fn is_people(&self) -> bool { |
| 261 | matches!(self, CallSpec::People { .. }) |
| 262 | } |
| 263 | |
| 264 | fn callee_count(&self) -> usize { |
| 265 | match self { |
| 266 | CallSpec::People { callees, .. } => callees.len(), |
| 267 | CallSpec::Echo => 1, |
| 268 | CallSpec::Meeting(_) => 0, |
| 269 | } |
| 270 | } |
| 271 | } |
| 272 | |
| 273 | pub(crate) struct IncomingCall { |
| 274 | pub accept: AcceptMode, |
| 275 | pub notification: CallNotification, |
| 276 | pub attached: Attached, |
| 277 | pub links: CallbackLinks, |
| 278 | pub participant: Participant, |
| 279 | pub callbacks: mpsc::UnboundedReceiver<TrouterCallback>, |
| 280 | } |
| 281 | |
| 282 | pub(crate) enum Plan { |
| 283 | Outgoing(CallSpec), |
| 284 | Incoming(Box<IncomingCall>), |
| 285 | } |
| 286 | |
| 287 | fn data_channel_from_env() -> bool { |
| 288 | !matches!( |
| 289 | std::env::var(DATA_CHANNEL_ENV).ok().as_deref(), |
| 290 | Some("0" | "off") |
| 291 | ) |
| 292 | } |
| 293 | |
| 294 | pub fn keep_alive_period(seconds: Option<u64>) -> Duration { |
| 295 | let seconds = seconds |
| 296 | .unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS) |
| 297 | .max(MIN_KEEP_ALIVE_SECONDS); |
| 298 | Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION) |
| 299 | } |
| 300 | |
| 301 | fn random_u32() -> u32 { |
| 302 | let bytes = uuid::Uuid::new_v4().into_bytes(); |
| 303 | u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff |
| 304 | } |
| 305 | |
| 306 | #[derive(Default)] |
| 307 | struct Recording { |
| 308 | samples: Vec<i16>, |
| 309 | current_second: Vec<i16>, |
| 310 | per_second: Vec<(f32, f32)>, |
| 311 | } |
| 312 | |
| 313 | enum PeerEvent { |
| 314 | Ice(IceConnectionState), |
| 315 | Connection(PeerConnectionState), |
| 316 | Track(RtcAudioTrack), |
| 317 | VideoTrack { mid: String, track: RtcVideoTrack }, |
| 318 | Data(Vec<u8>), |
| 319 | } |
| 320 | |
| 321 | struct PeerSession { |
| 322 | peer: PeerConnection, |
| 323 | events: mpsc::UnboundedReceiver<PeerEvent>, |
| 324 | _data_channel: Option<DataChannel>, |
| 325 | gathered: Gathered, |
| 326 | } |
| 327 | |
| 328 | #[derive(Clone, Default)] |
| 329 | struct Gathered { |
| 330 | candidates: Arc<std::sync::Mutex<Vec<String>>>, |
| 331 | complete: Arc<AtomicBool>, |
| 332 | relay_seen_at: Arc<std::sync::Mutex<Option<Instant>>>, |
| 333 | waited_ms: Arc<AtomicU64>, |
| 334 | } |
| 335 | |
| 336 | /// libwebrtc gathers continually here, and TCP/TLS relays trickle in late, so a UDP relay plus a short settle is enough. |
| 337 | fn gathering_settled(complete: bool, since_udp_relay: Option<Duration>) -> bool { |
| 338 | complete || since_udp_relay.is_some_and(|since| since >= RELAY_SETTLE) |
| 339 | } |
| 340 | |
| 341 | impl Gathered { |
| 342 | fn settled(&self) -> bool { |
| 343 | let since_udp_relay = self |
| 344 | .relay_seen_at |
| 345 | .lock() |
| 346 | .expect("relay time lock") |
| 347 | .map(|at| at.elapsed()); |
| 348 | gathering_settled(self.complete.load(Ordering::SeqCst), since_udp_relay) |
| 349 | } |
| 350 | |
| 351 | async fn candidates(&self) -> Vec<String> { |
| 352 | let waited = Instant::now(); |
| 353 | while !self.settled() && waited.elapsed() < GATHERING_LIMIT { |
| 354 | tokio::time::sleep(GATHERING_POLL).await; |
| 355 | } |
| 356 | self.complete.store(true, Ordering::SeqCst); |
| 357 | self.waited_ms |
| 358 | .store(waited.elapsed().as_millis() as u64, Ordering::SeqCst); |
| 359 | self.candidates.lock().expect("candidates lock").clone() |
| 360 | } |
| 361 | |
| 362 | fn summary(&self) -> String { |
| 363 | let count = self.candidates.lock().expect("candidates lock").len(); |
| 364 | format!( |
| 365 | "{count} candidate(s) after {} ms", |
| 366 | self.waited_ms.load(Ordering::SeqCst) |
| 367 | ) |
| 368 | } |
| 369 | } |
| 370 | |
| 371 | async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> { |
| 372 | match gathered { |
| 373 | Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind), |
| 374 | None => Ok(teams_sdp.to_owned()), |
| 375 | } |
| 376 | } |
| 377 | |
| 378 | struct OfferedMedia { |
| 379 | browser_offer: String, |
| 380 | signaled: SignaledOffer, |
| 381 | video: VideoLines, |
| 382 | plan: OfferPlan, |
| 383 | modalities: Vec<String>, |
| 384 | } |
| 385 | |
| 386 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 387 | enum Layout { |
| 388 | Conference, |
| 389 | OneToOne, |
| 390 | } |
| 391 | |
| 392 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 393 | pub enum AcceptMode { |
| 394 | Audio, |
| 395 | Video, |
| 396 | } |
| 397 | |
| 398 | #[derive(Clone, Copy)] |
| 399 | enum AnswerVideo<'a> { |
| 400 | Reject, |
| 401 | Receive, |
| 402 | Send(&'a RtcVideoTrack), |
| 403 | } |
| 404 | |
| 405 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 406 | enum Change { |
| 407 | Hold(bool), |
| 408 | Camera(bool), |
| 409 | Share(bool), |
| 410 | } |
| 411 | |
| 412 | struct SamePeerOffer { |
| 413 | browser_offer: String, |
| 414 | signaled: SignaledOffer, |
| 415 | change: Change, |
| 416 | reply_tags: Vec<String>, |
| 417 | } |
| 418 | |
| 419 | struct GlareResend { |
| 420 | change: Change, |
| 421 | reply_tags: Vec<String>, |
| 422 | at: Instant, |
| 423 | } |
| 424 | |
| 425 | struct NextPeer { |
| 426 | session: PeerSession, |
| 427 | offered: Option<OfferedMedia>, |
| 428 | reply_tags: Vec<String>, |
| 429 | deadline: Option<Instant>, |
| 430 | connected: bool, |
| 431 | retargeted: bool, |
| 432 | } |
| 433 | |
| 434 | fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool { |
| 435 | match callback_tag(callback_path) { |
| 436 | Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag), |
| 437 | _ => true, |
| 438 | } |
| 439 | } |
| 440 | |
| 441 | #[derive(Clone)] |
| 442 | struct RemoteCall { |
| 443 | signaling: Arc<Signaling>, |
| 444 | conversation: Conversation, |
| 445 | participant: Participant, |
| 446 | threadless: bool, |
| 447 | } |
| 448 | |
| 449 | #[derive(Default)] |
| 450 | struct Live { |
| 451 | peers: Vec<PeerConnection>, |
| 452 | audio: Option<AudioSetup>, |
| 453 | remote: Option<RemoteCall>, |
| 454 | broker: Option<JoinHandle<()>>, |
| 455 | broker_running: Arc<AtomicBool>, |
| 456 | callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>, |
| 457 | route_id: Option<String>, |
| 458 | skip_leave: bool, |
| 459 | cancel_leave: bool, |
| 460 | video_tasks: Vec<JoinHandle<()>>, |
| 461 | video_counters: Arc<VideoCounters>, |
| 462 | } |
| 463 | |
| 464 | fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool { |
| 465 | let next = state.next(signal, std::time::Instant::now()); |
| 466 | if next == *state { |
| 467 | return false; |
| 468 | } |
| 469 | *state = next.clone(); |
| 470 | control.send(CallUpdate::State(next)); |
| 471 | true |
| 472 | } |
| 473 | |
| 474 | /// Places the Echo test call on its own non-ringable Trouter instance; the app uses a shared engine instead. |
| 475 | pub async fn run_test_call( |
| 476 | session: &Session, |
| 477 | poll_session: &Session, |
| 478 | options: CallOptions, |
| 479 | control: CallControl, |
| 480 | ) -> Result<CallReport> { |
| 481 | let config = EngineConfig { |
| 482 | ringable: false, |
| 483 | routing: options.routing.clone(), |
| 484 | relay_host: options.relay_host.clone(), |
| 485 | trace: options.trace, |
| 486 | dump_dir: None, |
| 487 | instance: chatsvc::InstanceNames { |
| 488 | global: "__testCallTrouter".into(), |
| 489 | binding: "__testCallRealtime".into(), |
| 490 | endpoint_storage_key: "__testCallEpid".into(), |
| 491 | }, |
| 492 | }; |
| 493 | let (engine, _events) = |
| 494 | CallEngine::start(session.clone(), poll_session.clone(), config).await?; |
| 495 | let report = engine |
| 496 | .run(Plan::Outgoing(CallSpec::Echo), options, control) |
| 497 | .await; |
| 498 | engine.stop().await; |
| 499 | report |
| 500 | } |
| 501 | |
| 502 | impl CallEngine { |
| 503 | pub(crate) async fn run( |
| 504 | &self, |
| 505 | plan: Plan, |
| 506 | options: CallOptions, |
| 507 | mut control: CallControl, |
| 508 | ) -> Result<CallReport> { |
| 509 | let inner = self.inner.as_ref(); |
| 510 | let _one_call_at_a_time = if options.concurrent { |
| 511 | None |
| 512 | } else { |
| 513 | match control.until_hangup(inner.gate.lock()).await { |
| 514 | Ok(guard) => Some(guard), |
| 515 | Err(_) => { |
| 516 | let mut state = CallState::Idle; |
| 517 | advance(&mut state, CallSignal::Dial, &control); |
| 518 | advance(&mut state, CallSignal::LocalLeave, &control); |
| 519 | return Ok(CallReport::default()); |
| 520 | } |
| 521 | } |
| 522 | }; |
| 523 | let timeline = Timeline::new(options.trace); |
| 524 | let stay_awake = crate::awake::StayAwake::new(); |
| 525 | timeline.record( |
| 526 | "stay awake", |
| 527 | if stay_awake.holding() { |
| 528 | "system and display kept awake" |
| 529 | } else { |
| 530 | "not available" |
| 531 | }, |
| 532 | ); |
| 533 | let mut report = CallReport::default(); |
| 534 | let mut state = CallState::Idle; |
| 535 | advance(&mut state, CallSignal::Dial, &control); |
| 536 | let mut live = Live::default(); |
| 537 | let recording = Arc::new(Mutex::new(Recording::default())); |
| 538 | let outcome = drive( |
| 539 | inner, |
| 540 | &options, |
| 541 | &timeline, |
| 542 | &recording, |
| 543 | plan, |
| 544 | &mut live, |
| 545 | &mut control, |
| 546 | &mut state, |
| 547 | &mut report, |
| 548 | ) |
| 549 | .await; |
| 550 | let failure = match outcome { |
| 551 | Ok(()) => None, |
| 552 | Err(Error::Cancelled) => { |
| 553 | advance(&mut state, CallSignal::LocalLeave, &control); |
| 554 | None |
| 555 | } |
| 556 | Err(error) => { |
| 557 | advance(&mut state, CallSignal::Error(error.to_string()), &control); |
| 558 | Some(error) |
| 559 | } |
| 560 | }; |
| 561 | dump_timeline(&options, &timeline, failure.as_ref()); |
| 562 | let cancelled = live.cancel_leave |
| 563 | || matches!( |
| 564 | &state, |
| 565 | CallState::Ended { |
| 566 | reason: crate::state::EndReason::Cancelled |
| 567 | } |
| 568 | ); |
| 569 | tear_down(live, inner, &timeline, &mut report, cancelled).await; |
| 570 | let recording = recording.lock().await; |
| 571 | report.recorded_samples = recording.samples.len(); |
| 572 | report.timeline = timeline.entries(); |
| 573 | control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new( |
| 574 | &report, |
| 575 | timeline.sdp_summaries(), |
| 576 | )))); |
| 577 | if let Some(path) = &options.wav_path { |
| 578 | write_wav(path, &recording.samples) |
| 579 | .map_err(|error| Error::Webrtc(format!("wav: {error}")))?; |
| 580 | } |
| 581 | match failure { |
| 582 | Some(error) => Err(error), |
| 583 | None => Ok(report), |
| 584 | } |
| 585 | } |
| 586 | } |
| 587 | |
| 588 | fn open_peer( |
| 589 | factory: &PeerConnectionFactory, |
| 590 | grant: &RelayGrant, |
| 591 | relay_host: &str, |
| 592 | with_data_channel: bool, |
| 593 | ) -> Result<PeerSession> { |
| 594 | let mut configuration = RtcConfiguration::default(); |
| 595 | configuration.ice_servers = vec![grant.ice_server(relay_host)]; |
| 596 | let peer = factory |
| 597 | .create_peer_connection(configuration) |
| 598 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 599 | let (sender, events) = mpsc::unbounded_channel(); |
| 600 | let data_channel = with_data_channel |
| 601 | .then(|| open_data_channel(&peer, sender.clone())) |
| 602 | .transpose()?; |
| 603 | let gathered = Gathered::default(); |
| 604 | let candidate_sink = gathered.candidates.clone(); |
| 605 | let relay_seen_at = gathered.relay_seen_at.clone(); |
| 606 | peer.on_ice_candidate(Some(Box::new(move |candidate| { |
| 607 | if candidate.sdp_mline_index() == 0 { |
| 608 | let text = candidate.candidate(); |
| 609 | if is_udp_relay(&text) { |
| 610 | relay_seen_at |
| 611 | .lock() |
| 612 | .expect("relay time lock") |
| 613 | .get_or_insert_with(Instant::now); |
| 614 | } |
| 615 | candidate_sink.lock().expect("candidates lock").push(text); |
| 616 | } |
| 617 | }))); |
| 618 | let gathering_done = gathered.complete.clone(); |
| 619 | peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state { |
| 620 | IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst), |
| 621 | IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst), |
| 622 | IceGatheringState::New => {} |
| 623 | }))); |
| 624 | let ice_sender = sender.clone(); |
| 625 | peer.on_ice_connection_state_change(Some(Box::new(move |state| { |
| 626 | let _ = ice_sender.send(PeerEvent::Ice(state)); |
| 627 | }))); |
| 628 | let connection_sender = sender.clone(); |
| 629 | peer.on_connection_state_change(Some(Box::new(move |state| { |
| 630 | let _ = connection_sender.send(PeerEvent::Connection(state)); |
| 631 | }))); |
| 632 | peer.on_track(Some(Box::new(move |event| match event.track { |
| 633 | MediaStreamTrack::Audio(track) => { |
| 634 | let _ = sender.send(PeerEvent::Track(track)); |
| 635 | } |
| 636 | MediaStreamTrack::Video(track) => { |
| 637 | let mid = event.transceiver.mid().unwrap_or_default(); |
| 638 | let _ = sender.send(PeerEvent::VideoTrack { mid, track }); |
| 639 | } |
| 640 | }))); |
| 641 | Ok(PeerSession { |
| 642 | peer, |
| 643 | events, |
| 644 | _data_channel: data_channel, |
| 645 | gathered, |
| 646 | }) |
| 647 | } |
| 648 | |
| 649 | fn open_data_channel( |
| 650 | peer: &PeerConnection, |
| 651 | sender: mpsc::UnboundedSender<PeerEvent>, |
| 652 | ) -> Result<DataChannel> { |
| 653 | let channel = peer |
| 654 | .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default()) |
| 655 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 656 | channel.on_message(Some(Box::new(move |buffer| { |
| 657 | let _ = sender.send(PeerEvent::Data(buffer.data.to_vec())); |
| 658 | }))); |
| 659 | Ok(channel) |
| 660 | } |
| 661 | |
| 662 | fn one_to_one_directions<'a>( |
| 663 | camera: bool, |
| 664 | share: bool, |
| 665 | camera_mid: &'a str, |
| 666 | share_mid: Option<&'a str>, |
| 667 | remote_shares: bool, |
| 668 | ) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a { |
| 669 | move |line| match line.kind { |
| 670 | "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }), |
| 671 | "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) { |
| 672 | (true, true) => "sendrecv", |
| 673 | (true, false) => "sendonly", |
| 674 | (false, true) => "recvonly", |
| 675 | (false, false) => INACTIVE, |
| 676 | }), |
| 677 | _ => None, |
| 678 | } |
| 679 | } |
| 680 | |
| 681 | fn share_mid_in(offer_text: &str) -> Option<String> { |
| 682 | let mut mid = None; |
| 683 | for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) { |
| 684 | if line.starts_with("m=") { |
| 685 | mid = None; |
| 686 | } else if let Some(value) = line.strip_prefix("a=mid:") { |
| 687 | mid = Some(value.to_owned()); |
| 688 | } else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() { |
| 689 | return mid; |
| 690 | } |
| 691 | } |
| 692 | None |
| 693 | } |
| 694 | |
| 695 | #[allow(clippy::too_many_arguments)] |
| 696 | fn directions_for( |
| 697 | layout: Layout, |
| 698 | hold: bool, |
| 699 | camera: bool, |
| 700 | share: bool, |
| 701 | camera_mid: &str, |
| 702 | share_mid: Option<&str>, |
| 703 | remote_shares: bool, |
| 704 | text: &str, |
| 705 | ) -> String { |
| 706 | match (hold, layout) { |
| 707 | (true, _) => rewrite_directions(text, |_| Some(INACTIVE)), |
| 708 | (false, Layout::OneToOne) => rewrite_directions( |
| 709 | text, |
| 710 | one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares), |
| 711 | ), |
| 712 | (false, Layout::Conference) => text.to_owned(), |
| 713 | } |
| 714 | } |
| 715 | |
| 716 | async fn create_offer( |
| 717 | peer: &PeerConnection, |
| 718 | factory: &PeerConnectionFactory, |
| 719 | track: &RtcAudioTrack, |
| 720 | layout: Layout, |
| 721 | gathered: Option<&Gathered>, |
| 722 | ) -> Result<OfferedMedia> { |
| 723 | let transceiver_init = RtpTransceiverInit { |
| 724 | direction: RtpTransceiverDirection::SendRecv, |
| 725 | stream_ids: vec![MIC_STREAM.into()], |
| 726 | send_encodings: Vec::new(), |
| 727 | }; |
| 728 | peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init) |
| 729 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 730 | let (video, plan) = match layout { |
| 731 | Layout::Conference => (add_video_lines(peer, factory)?, offer_plan()), |
| 732 | Layout::OneToOne => (add_one_to_one_lines(peer, factory)?, one_to_one_plan()), |
| 733 | }; |
| 734 | let offer = peer |
| 735 | .create_offer(OfferOptions { |
| 736 | offer_to_receive_audio: true, |
| 737 | offer_to_receive_video: true, |
| 738 | ..OfferOptions::default() |
| 739 | }) |
| 740 | .await |
| 741 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 742 | let browser_offer = directions_for( |
| 743 | layout, |
| 744 | false, |
| 745 | false, |
| 746 | false, |
| 747 | CAMERA_MID, |
| 748 | Some(ONE_TO_ONE_SHARE_MID), |
| 749 | false, |
| 750 | &offer.to_string(), |
| 751 | ); |
| 752 | let description = parse_sdp(&browser_offer, SdpType::Offer)?; |
| 753 | peer.set_local_description(description) |
| 754 | .await |
| 755 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 756 | let mut numbers = random_u32; |
| 757 | let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?; |
| 758 | signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?; |
| 759 | Ok(OfferedMedia { |
| 760 | browser_offer, |
| 761 | signaled, |
| 762 | video, |
| 763 | plan, |
| 764 | modalities: accepted_modalities(false), |
| 765 | }) |
| 766 | } |
| 767 | |
| 768 | struct AnsweredMedia { |
| 769 | remote: RemoteOffer, |
| 770 | answer_sdp: String, |
| 771 | camera_mid: Option<String>, |
| 772 | receiving_share_mid: Option<String>, |
| 773 | } |
| 774 | |
| 775 | fn main_video_mid(remote: &RemoteOffer) -> Option<String> { |
| 776 | remote |
| 777 | .lines |
| 778 | .iter() |
| 779 | .find(|line| line.role == LineRole::MainVideo) |
| 780 | .and_then(|line| line.browser_mids.first().cloned()) |
| 781 | } |
| 782 | |
| 783 | fn share_mids(remote: &RemoteOffer) -> Vec<String> { |
| 784 | remote |
| 785 | .lines |
| 786 | .iter() |
| 787 | .filter(|line| line.role == LineRole::ScreenShare) |
| 788 | .filter_map(|line| line.browser_mids.first().cloned()) |
| 789 | .collect() |
| 790 | } |
| 791 | |
| 792 | async fn answer_offer( |
| 793 | peer: &PeerConnection, |
| 794 | track: Option<&RtcAudioTrack>, |
| 795 | teams_offer: &str, |
| 796 | video: AnswerVideo<'_>, |
| 797 | sending_share_mid: Option<String>, |
| 798 | camera_on: bool, |
| 799 | gathered: Option<&Gathered>, |
| 800 | ) -> Result<AnsweredMedia> { |
| 801 | let remote = from_teams_offer(teams_offer)?; |
| 802 | let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?; |
| 803 | peer.set_remote_description(description) |
| 804 | .await |
| 805 | .map_err(|error| { |
| 806 | let lines: Vec<String> = remote |
| 807 | .lines |
| 808 | .iter() |
| 809 | .map(|line| format!("{:?}{:?}", line.role, line.browser_mids)) |
| 810 | .collect(); |
| 811 | Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" "))) |
| 812 | })?; |
| 813 | let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject)); |
| 814 | let kept_share_mids = if matches!(video, AnswerVideo::Reject) { |
| 815 | Vec::new() |
| 816 | } else { |
| 817 | share_mids(&remote) |
| 818 | }; |
| 819 | for transceiver in peer.transceivers() { |
| 820 | let is_video = matches!( |
| 821 | transceiver.receiver().track(), |
| 822 | Some(MediaStreamTrack::Video(_)) |
| 823 | ); |
| 824 | let unused = transceiver.mid().is_some_and(|mid| { |
| 825 | Some(&mid) != camera_mid.as_ref() |
| 826 | && !kept_share_mids.contains(&mid) |
| 827 | && Some(&mid) != sending_share_mid.as_ref() |
| 828 | }); |
| 829 | if is_video && unused { |
| 830 | let _ = transceiver.stop(); |
| 831 | } |
| 832 | } |
| 833 | if let Some(track) = track { |
| 834 | peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM]) |
| 835 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 836 | } |
| 837 | if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) { |
| 838 | peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM]) |
| 839 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 840 | } |
| 841 | let answer = peer |
| 842 | .create_answer(AnswerOptions::default()) |
| 843 | .await |
| 844 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 845 | let mut answer_text = answer.to_string(); |
| 846 | for mid in kept_share_mids |
| 847 | .iter() |
| 848 | .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) |
| 849 | { |
| 850 | answer_text = stop_sending_on(&answer_text, mid); |
| 851 | } |
| 852 | let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_)); |
| 853 | if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) { |
| 854 | answer_text = stop_sending_on(&answer_text, mid); |
| 855 | } |
| 856 | peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?) |
| 857 | .await |
| 858 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 859 | let receiving_share_mid = kept_share_mids |
| 860 | .into_iter() |
| 861 | .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) |
| 862 | .find(|mid| { |
| 863 | matches!( |
| 864 | direction_of(&answer_text, mid).as_deref(), |
| 865 | Some("recvonly" | "sendrecv") |
| 866 | ) |
| 867 | }); |
| 868 | let mut numbers = random_u32; |
| 869 | let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?; |
| 870 | Ok(AnsweredMedia { |
| 871 | remote, |
| 872 | answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?, |
| 873 | camera_mid, |
| 874 | receiving_share_mid, |
| 875 | }) |
| 876 | } |
| 877 | |
| 878 | fn new_media_leg_id() -> String { |
| 879 | uuid::Uuid::new_v4().simple().to_string().to_uppercase() |
| 880 | } |
| 881 | |
| 882 | async fn setup_step<T, E>( |
| 883 | control: &mut CallControl, |
| 884 | step: impl std::future::Future<Output = std::result::Result<T, E>>, |
| 885 | ) -> Result<T> |
| 886 | where |
| 887 | Error: From<E>, |
| 888 | { |
| 889 | setup_step_within(control, SETUP_STEP_TIMEOUT, step).await |
| 890 | } |
| 891 | |
| 892 | async fn setup_step_within<T, E>( |
| 893 | control: &mut CallControl, |
| 894 | limit: Duration, |
| 895 | step: impl std::future::Future<Output = std::result::Result<T, E>>, |
| 896 | ) -> Result<T> |
| 897 | where |
| 898 | Error: From<E>, |
| 899 | { |
| 900 | match control.until_hangup(timeout(limit, step)).await? { |
| 901 | Ok(result) => Ok(result?), |
| 902 | Err(_) => Err(Error::Signaling("Teams did not answer in time".into())), |
| 903 | } |
| 904 | } |
| 905 | |
| 906 | async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> { |
| 907 | match next { |
| 908 | Some(next) => next.session.events.recv().await, |
| 909 | None => std::future::pending().await, |
| 910 | } |
| 911 | } |
| 912 | |
| 913 | fn video_possible(remote_set: bool, layout: Layout, path: MediaPath) -> bool { |
| 914 | remote_set && !(layout == Layout::OneToOne && path == MediaPath::Mixer) |
| 915 | } |
| 916 | |
| 917 | #[allow(clippy::too_many_arguments)] |
| 918 | async fn drive( |
| 919 | inner: &Inner, |
| 920 | options: &CallOptions, |
| 921 | timeline: &Timeline, |
| 922 | recording: &Arc<Mutex<Recording>>, |
| 923 | plan: Plan, |
| 924 | live: &mut Live, |
| 925 | control: &mut CallControl, |
| 926 | state: &mut CallState, |
| 927 | report: &mut CallReport, |
| 928 | ) -> Result<()> { |
| 929 | let own_mri = format!("8:orgid:{}", inner.identity.object_id); |
| 930 | control.send(CallUpdate::OwnIdentity { |
| 931 | mri: own_mri.clone(), |
| 932 | }); |
| 933 | let (spec, incoming) = match plan { |
| 934 | Plan::Outgoing(spec) => (Some(spec), None), |
| 935 | Plan::Incoming(incoming) => (None, Some(*incoming)), |
| 936 | }; |
| 937 | let accept_mode = incoming |
| 938 | .as_ref() |
| 939 | .map_or(AcceptMode::Audio, |incoming| incoming.accept); |
| 940 | let (links, participant, mut callbacks, incoming_media) = match incoming { |
| 941 | Some(IncomingCall { |
| 942 | accept: _, |
| 943 | notification, |
| 944 | attached, |
| 945 | links, |
| 946 | participant, |
| 947 | callbacks, |
| 948 | }) => ( |
| 949 | links, |
| 950 | participant, |
| 951 | callbacks, |
| 952 | Some((notification, attached)), |
| 953 | ), |
| 954 | None => { |
| 955 | let links = inner.callback_links(); |
| 956 | let participant = inner.participant(&uuid::Uuid::new_v4().to_string()); |
| 957 | let callbacks = inner.register_route(&links); |
| 958 | (links, participant, callbacks, None) |
| 959 | } |
| 960 | }; |
| 961 | live.route_id = Some(links.call_id().to_owned()); |
| 962 | timeline.record("Trouter connected", "callback socket ready"); |
| 963 | |
| 964 | let thread_id = if matches!(spec, Some(CallSpec::Echo)) { |
| 965 | let thread_id = control |
| 966 | .until_hangup(find_echo_bot_thread( |
| 967 | &inner.session, |
| 968 | &inner.identity.object_id, |
| 969 | )) |
| 970 | .await??; |
| 971 | timeline.record( |
| 972 | "echo bot chat", |
| 973 | if thread_id.is_some() { "found" } else { "none" }, |
| 974 | ); |
| 975 | thread_id |
| 976 | } else { |
| 977 | None |
| 978 | }; |
| 979 | let grant = control |
| 980 | .until_hangup(inner.relay.grant(&inner.session)) |
| 981 | .await??; |
| 982 | timeline.record( |
| 983 | "GET trap/tokens", |
| 984 | format!("relay grant, expires in {} s", grant.expires_in_seconds), |
| 985 | ); |
| 986 | |
| 987 | let factory = devices::shared_factory(); |
| 988 | let mut input = options.input.clone(); |
| 989 | let mut output = options.output.clone(); |
| 990 | let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output); |
| 991 | control.send(CallUpdate::ListenOnly(audio.listen_only)); |
| 992 | let mut device_lists = devices::list_devices(&factory); |
| 993 | let mut applied_input = devices::applied_device( |
| 994 | &device_lists.inputs, |
| 995 | &input, |
| 996 | devices::system_default_id(Flow::Capture).as_deref(), |
| 997 | ); |
| 998 | let mut applied_output = devices::applied_device( |
| 999 | &device_lists.outputs, |
| 1000 | &output, |
| 1001 | devices::system_default_id(Flow::Render).as_deref(), |
| 1002 | ); |
| 1003 | let (_device_watcher, mut device_changes) = device_watch::watch(); |
| 1004 | let mut device_debounce = Debounce::default(); |
| 1005 | timeline.record( |
| 1006 | "audio setup", |
| 1007 | format!( |
| 1008 | "listen only {}, {} input(s), {} output(s); {}", |
| 1009 | audio.listen_only, |
| 1010 | device_lists.inputs.len(), |
| 1011 | device_lists.outputs.len(), |
| 1012 | audio.adm_state |
| 1013 | ), |
| 1014 | ); |
| 1015 | record_audio_devices( |
| 1016 | timeline, |
| 1017 | &device_lists, |
| 1018 | applied_input.as_ref(), |
| 1019 | applied_output.as_ref(), |
| 1020 | ); |
| 1021 | control.send(CallUpdate::Devices(device_lists.clone())); |
| 1022 | control.send(CallUpdate::Selected { |
| 1023 | input: input.clone(), |
| 1024 | output: output.clone(), |
| 1025 | }); |
| 1026 | let track = audio.track.clone(); |
| 1027 | live.audio = Some(audio); |
| 1028 | let mut local_video = LocalVideo::new( |
| 1029 | &factory, |
| 1030 | options.video, |
| 1031 | control.video.clone(), |
| 1032 | control.updates(), |
| 1033 | ); |
| 1034 | local_video.attach_timeline(timeline.clone()); |
| 1035 | let mut camera_choice = options.camera.clone(); |
| 1036 | if options.start_camera { |
| 1037 | match local_video.preview_camera(&camera_choice) { |
| 1038 | Ok(()) => control.send(CallUpdate::Camera(true)), |
| 1039 | Err(error) => timeline.record("camera preview failed", error.to_string()), |
| 1040 | } |
| 1041 | } |
| 1042 | let mut media_description_request = 1u32; |
| 1043 | refresh_cameras(control.updates(), options.video, timeline.clone()); |
| 1044 | control.send(CallUpdate::SharePicker(current_share_picker())); |
| 1045 | refresh_share_sources(control.updates(), options.video, false); |
| 1046 | |
| 1047 | let wants_data_channel = |
| 1048 | options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting); |
| 1049 | let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?; |
| 1050 | live.peers.push(current.peer.clone()); |
| 1051 | |
| 1052 | let signaling = Arc::new(inner.signaling(timeline.clone())); |
| 1053 | let media_leg_id = new_media_leg_id(); |
| 1054 | let call_started = Instant::now(); |
| 1055 | let mut offered: Option<OfferedMedia> = None; |
| 1056 | let mut negotiator = MediaNegotiator::default(); |
| 1057 | let mut remote_set = false; |
| 1058 | let mut keep_alive_link: Option<String> = None; |
| 1059 | let mut keep_alive_seconds: Option<u64> = None; |
| 1060 | let mut keep_alive_at: Option<Instant> = None; |
| 1061 | let mut outgoing_deadline: Option<Instant> = None; |
| 1062 | let mut outgoing_limit = OUTGOING_TIMEOUT; |
| 1063 | let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting); |
| 1064 | let is_echo = matches!(spec, Some(CallSpec::Echo)); |
| 1065 | let mut echo_watch = EchoWatch::default(); |
| 1066 | let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count)); |
| 1067 | let meeting_target = match &spec { |
| 1068 | Some(CallSpec::Meeting(target)) => Some(target.clone()), |
| 1069 | _ => None, |
| 1070 | }; |
| 1071 | let people_thread = match &spec { |
| 1072 | Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => { |
| 1073 | Some(thread_id.clone()) |
| 1074 | } |
| 1075 | _ => incoming_media |
| 1076 | .as_ref() |
| 1077 | .filter(|(notification, _)| !notification.is_multi_party) |
| 1078 | .and_then(|(notification, _)| { |
| 1079 | notification |
| 1080 | .thread_id |
| 1081 | .clone() |
| 1082 | .filter(|thread| *thread != notification.caller.mri) |
| 1083 | .or_else(|| { |
| 1084 | one_to_one_thread(&inner.identity.object_id, ¬ification.caller.mri) |
| 1085 | }) |
| 1086 | }), |
| 1087 | }; |
| 1088 | let mut layout = match &spec { |
| 1089 | Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne, |
| 1090 | _ => Layout::Conference, |
| 1091 | }; |
| 1092 | let peer_mri = match &spec { |
| 1093 | Some(CallSpec::People { callees, .. }) if callees.len() == 1 => { |
| 1094 | Some(callees[0].mri.clone()) |
| 1095 | } |
| 1096 | _ => incoming_media |
| 1097 | .as_ref() |
| 1098 | .map(|(notification, _)| notification.caller.mri.clone()), |
| 1099 | }; |
| 1100 | let mut layout_plan: OfferPlan; |
| 1101 | let mut direct_video_mid: Option<String> = None; |
| 1102 | let mut sending_camera = false; |
| 1103 | let mut media_links: BTreeMap<String, String> = BTreeMap::new(); |
| 1104 | |
| 1105 | let conversation = match (spec, incoming_media) { |
| 1106 | (Some(spec), None) => { |
| 1107 | let direct_invite = spec.target().is_one_to_one() && !options.concurrent; |
| 1108 | let offer_started = Instant::now(); |
| 1109 | let media = control |
| 1110 | .until_hangup(create_offer( |
| 1111 | ¤t.peer, |
| 1112 | &factory, |
| 1113 | &track, |
| 1114 | layout, |
| 1115 | direct_invite.then_some(¤t.gathered), |
| 1116 | )) |
| 1117 | .await??; |
| 1118 | timeline.record( |
| 1119 | "offer created", |
| 1120 | format!("{} ms", offer_started.elapsed().as_millis()), |
| 1121 | ); |
| 1122 | layout_plan = media.plan.clone(); |
| 1123 | if layout == Layout::OneToOne { |
| 1124 | direct_video_mid = Some(CAMERA_MID.to_owned()); |
| 1125 | } |
| 1126 | timeline.record( |
| 1127 | "setLocalDescription", |
| 1128 | format!("{} m-line(s) signaled", media.signaled.lines.len()), |
| 1129 | ); |
| 1130 | timeline.record_sdp("local offer", &media.signaled.sdp); |
| 1131 | dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer); |
| 1132 | dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp); |
| 1133 | let target = spec.target(); |
| 1134 | let invitation = Invitation { |
| 1135 | from: &participant, |
| 1136 | offer_sdp: &media.signaled.sdp, |
| 1137 | media_leg_id: &media_leg_id, |
| 1138 | callbacks: &links, |
| 1139 | target: &target, |
| 1140 | modalities: &media.modalities, |
| 1141 | direct: !options.concurrent, |
| 1142 | }; |
| 1143 | let threadless = invitation.is_direct(); |
| 1144 | let conversation = match &target { |
| 1145 | InviteTarget::Meeting(meeting) => { |
| 1146 | let subscribed = control |
| 1147 | .until_hangup(signaling.subscribe_meeting(&participant, &links, meeting)) |
| 1148 | .await??; |
| 1149 | setup_step(control, signaling.join_meeting(&subscribed, &invitation)).await? |
| 1150 | } |
| 1151 | _ => setup_step(control, signaling.create_conversation(&invitation)).await?, |
| 1152 | }; |
| 1153 | if spec.is_people() { |
| 1154 | control.send(CallUpdate::Progress(Progress::Calling)); |
| 1155 | if threadless { |
| 1156 | outgoing_limit = DIRECT_OUTGOING_TIMEOUT; |
| 1157 | } |
| 1158 | outgoing_deadline = Some(Instant::now() + outgoing_limit); |
| 1159 | } |
| 1160 | if let Err(error) = local_video.set_lines(media.video.clone()) { |
| 1161 | timeline.record("video lines not attached", error.to_string()); |
| 1162 | } |
| 1163 | offered = Some(media); |
| 1164 | live.remote = Some(RemoteCall { |
| 1165 | signaling: signaling.clone(), |
| 1166 | conversation: conversation.clone(), |
| 1167 | participant: participant.clone(), |
| 1168 | threadless, |
| 1169 | }); |
| 1170 | conversation |
| 1171 | } |
| 1172 | (None, Some((notification, attached))) => { |
| 1173 | let teams_offer = attached |
| 1174 | .offer_sdp |
| 1175 | .clone() |
| 1176 | .ok_or_else(|| Error::Signaling("attach answer without an offer".into()))?; |
| 1177 | let conversation = attached |
| 1178 | .conversation |
| 1179 | .clone() |
| 1180 | .ok_or_else(|| Error::Signaling("attach answer without a conversation".into()))?; |
| 1181 | live.remote = Some(RemoteCall { |
| 1182 | signaling: signaling.clone(), |
| 1183 | conversation: conversation.clone(), |
| 1184 | participant: participant.clone(), |
| 1185 | threadless: notification.thread_id.is_none(), |
| 1186 | }); |
| 1187 | let one_to_one = !attached.from_mixer && !notification.is_multi_party; |
| 1188 | layout = if one_to_one { |
| 1189 | Layout::OneToOne |
| 1190 | } else { |
| 1191 | Layout::Conference |
| 1192 | }; |
| 1193 | let camera_track = local_video.camera_track(); |
| 1194 | let video_answer = match accept_mode { |
| 1195 | _ if !one_to_one => AnswerVideo::Reject, |
| 1196 | AcceptMode::Video if local_video.is_available() => AnswerVideo::Send(&camera_track), |
| 1197 | _ => AnswerVideo::Receive, |
| 1198 | }; |
| 1199 | dump_sdp(options, "3-teams-offer.sdp", &teams_offer); |
| 1200 | let answered = answer_offer( |
| 1201 | ¤t.peer, |
| 1202 | Some(&track), |
| 1203 | &teams_offer, |
| 1204 | video_answer, |
| 1205 | None, |
| 1206 | false, |
| 1207 | one_to_one.then_some(¤t.gathered), |
| 1208 | ) |
| 1209 | .await?; |
| 1210 | layout_plan = answered.remote.plan(); |
| 1211 | direct_video_mid = answered.camera_mid.clone(); |
| 1212 | timeline.record( |
| 1213 | "setRemoteDescription", |
| 1214 | format!( |
| 1215 | "offer applied, {} signaled line(s)", |
| 1216 | answered.remote.lines.len() |
| 1217 | ), |
| 1218 | ); |
| 1219 | if one_to_one { |
| 1220 | timeline.record("ice gathered", current.gathered.summary()); |
| 1221 | } |
| 1222 | timeline.record_sdp("remote offer", &teams_offer); |
| 1223 | timeline.record_sdp("local answer", &answered.answer_sdp); |
| 1224 | dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp); |
| 1225 | let acceptance_url = attached.links.get("acceptance").ok_or_else(|| { |
| 1226 | Error::Signaling("attach answer without an acceptance link".into()) |
| 1227 | })?; |
| 1228 | let modalities = accepted_modalities( |
| 1229 | matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some(), |
| 1230 | ); |
| 1231 | let acknowledged = signaling |
| 1232 | .accept( |
| 1233 | acceptance_url, |
| 1234 | &Answer { |
| 1235 | from: &participant, |
| 1236 | answer_sdp: &answered.answer_sdp, |
| 1237 | media_leg_id: &media_leg_id, |
| 1238 | callbacks: &links, |
| 1239 | modalities: &modalities, |
| 1240 | }, |
| 1241 | ) |
| 1242 | .await?; |
| 1243 | negotiator.answered_incoming(attached.from_mixer); |
| 1244 | remote_set = true; |
| 1245 | media_links.extend(attached.links.clone()); |
| 1246 | media_links.extend(acknowledged); |
| 1247 | if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) { |
| 1248 | let camera = peer_transceiver(¤t.peer, mid); |
| 1249 | match camera.map(|camera| { |
| 1250 | local_video.set_lines(VideoLines { |
| 1251 | camera, |
| 1252 | share: None, |
| 1253 | }) |
| 1254 | }) { |
| 1255 | Some(Ok(())) => match local_video.start_camera(&camera_choice) { |
| 1256 | Ok(()) => sending_camera = true, |
| 1257 | Err(error) => control.send(CallUpdate::Notice(notice_with_detail( |
| 1258 | CAMERA_START_NOTICE, |
| 1259 | error, |
| 1260 | ))), |
| 1261 | }, |
| 1262 | Some(Err(error)) => { |
| 1263 | timeline.record("video lines not attached", error.to_string()) |
| 1264 | } |
| 1265 | None => timeline.record( |
| 1266 | "video lines not attached", |
| 1267 | "no transceiver for the camera line", |
| 1268 | ), |
| 1269 | } |
| 1270 | } |
| 1271 | keep_alive_link = media_links.get("callLeg").cloned(); |
| 1272 | keep_alive_at = Some(Instant::now() + keep_alive_period(None)); |
| 1273 | conversation |
| 1274 | } |
| 1275 | _ => { |
| 1276 | return Err(Error::Callback( |
| 1277 | "call plan without an offer or an invitation".into(), |
| 1278 | )); |
| 1279 | } |
| 1280 | }; |
| 1281 | let remote = live.remote.clone().expect("remote call set above"); |
| 1282 | live.broker_running.store(true, Ordering::SeqCst); |
| 1283 | live.broker = Some(tokio::spawn(poll_broker( |
| 1284 | signaling.clone(), |
| 1285 | conversation.clone(), |
| 1286 | live.broker_running.clone(), |
| 1287 | ))); |
| 1288 | |
| 1289 | let initial = MuteEffect::initial(is_meeting); |
| 1290 | let mut muted = initial.muted; |
| 1291 | live.audio |
| 1292 | .as_ref() |
| 1293 | .expect("audio set above") |
| 1294 | .track |
| 1295 | .set_enabled(initial.track_enabled); |
| 1296 | if muted { |
| 1297 | control.send(CallUpdate::Muted(true)); |
| 1298 | } |
| 1299 | match setup_step( |
| 1300 | control, |
| 1301 | signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted), |
| 1302 | ) |
| 1303 | .await |
| 1304 | { |
| 1305 | Err(Error::Cancelled) => return Err(Error::Cancelled), |
| 1306 | Err(error) => timeline.record("updateEndpointState failed", error.to_string()), |
| 1307 | Ok(()) => {} |
| 1308 | } |
| 1309 | |
| 1310 | let mut stats_tick = interval(STATS_PERIOD); |
| 1311 | let mut speaking_sources: Vec<u32> = Vec::new(); |
| 1312 | let mut speaker_sources_seen = false; |
| 1313 | let hard_deadline = options.hard_limit.map(|limit| call_started + limit); |
| 1314 | let mut leave_at = hard_deadline; |
| 1315 | let mut reconnect_deadline: Option<Instant> = None; |
| 1316 | let mut next: Option<NextPeer> = None; |
| 1317 | let mut roster = Roster::default(); |
| 1318 | if let Some(snapshot) = &conversation.roster |
| 1319 | && roster.apply_snapshot(snapshot) |
| 1320 | { |
| 1321 | let entries = roster.entries(); |
| 1322 | timeline.record( |
| 1323 | "roster", |
| 1324 | format!( |
| 1325 | "{} participant(s) from the conversation answer", |
| 1326 | entries.len() |
| 1327 | ), |
| 1328 | ); |
| 1329 | control.send(CallUpdate::Roster(entries)); |
| 1330 | } |
| 1331 | let mut lobby = false; |
| 1332 | let mut capability = MeetingCapability::default(); |
| 1333 | let mut previous_packets = 0u64; |
| 1334 | let mut ticks = 0u32; |
| 1335 | let mut segmentation_model: Option<&'static str> = None; |
| 1336 | let mut health_sampler = HealthSampler::default(); |
| 1337 | let mut quality_tracker = QualityTracker::default(); |
| 1338 | let mut second = 0u32; |
| 1339 | let echo_thread = thread_id; |
| 1340 | let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default()); |
| 1341 | if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) { |
| 1342 | video.router().set(mid, Some(VideoKey::Person(mri.clone()))); |
| 1343 | } |
| 1344 | if sending_camera { |
| 1345 | control.send(CallUpdate::Camera(true)); |
| 1346 | } |
| 1347 | let mut software_audio: Option<SoftwareAudio> = None; |
| 1348 | let mut share_sound_wanted = false; |
| 1349 | let mut mic_settings = MicSettings::default(); |
| 1350 | crate::noise_stage::apply(mic_settings); |
| 1351 | let mut audio_disabled = false; |
| 1352 | let mut remote_audio: Option<RtcAudioTrack> = None; |
| 1353 | sync_software_audio( |
| 1354 | &factory, |
| 1355 | options, |
| 1356 | &input, |
| 1357 | muted, |
| 1358 | None, |
| 1359 | ¤t.peer, |
| 1360 | &track, |
| 1361 | software_wanted( |
| 1362 | mic_settings, |
| 1363 | share_sound_wanted, |
| 1364 | &local_video, |
| 1365 | live.audio.as_ref(), |
| 1366 | ), |
| 1367 | false, |
| 1368 | &mut software_audio, |
| 1369 | control, |
| 1370 | timeline, |
| 1371 | ); |
| 1372 | let mut own_hand: Option<String> = None; |
| 1373 | let mut depacketizer = Depacketizer::default(); |
| 1374 | let mut caption_flow = CaptionFlow::default(); |
| 1375 | let mut caption_deadline: Option<Instant> = None; |
| 1376 | let mut recording_flow = CaptionFlow::default(); |
| 1377 | let mut recording_deadline: Option<Instant> = None; |
| 1378 | let mut recording_plan = RecordingPlan::default(); |
| 1379 | let mut recording_audio_only = false; |
| 1380 | let mut recording_status = RecordingStatus::default(); |
| 1381 | let mut bot_pending = false; |
| 1382 | let mut consent_pending = false; |
| 1383 | let mut room_watcher = RoomWatcher::default(); |
| 1384 | let mut main_meeting_sent = false; |
| 1385 | let mut local_hold = false; |
| 1386 | let mut remote_hold = false; |
| 1387 | let mut same_peer: Option<SamePeerOffer> = None; |
| 1388 | let mut send_requests = RequestFilter::default(); |
| 1389 | let mut send_capabilities = SendCapabilityReporter::default(); |
| 1390 | let mut same_peer_deadline: Option<Instant> = None; |
| 1391 | let mut same_peer_grace_until: Option<Instant> = None; |
| 1392 | let mut meeting_chat = conversation.chat_thread.clone(); |
| 1393 | if let Some(thread) = &meeting_chat { |
| 1394 | control.send(CallUpdate::MeetingChat(thread.clone())); |
| 1395 | } |
| 1396 | if let Some(target) = &meeting_target { |
| 1397 | control.send(CallUpdate::MeetingTenant(target.tenant_id.clone())); |
| 1398 | } |
| 1399 | if meeting_chat.is_none() { |
| 1400 | meeting_chat = people_thread; |
| 1401 | } |
| 1402 | let mut start_camera_pending = options.start_camera; |
| 1403 | let mut share_pending: Option<ShareSource> = None; |
| 1404 | let mut portal_pending: Option<ShareKind> = None; |
| 1405 | let mut glare_resend: Option<GlareResend> = None; |
| 1406 | let mut deferred_changes: Vec<Change> = Vec::new(); |
| 1407 | let mut remote_direct_share: Option<String> = None; |
| 1408 | let mut sent_replacement: Option<Replacement> = None; |
| 1409 | loop { |
| 1410 | if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) { |
| 1411 | start_camera_pending = false; |
| 1412 | control.defer(CallCommand::SetCamera(true)); |
| 1413 | } |
| 1414 | if video_possible(remote_set, layout, negotiator.path()) |
| 1415 | && let Some(source) = share_pending.take() |
| 1416 | { |
| 1417 | control.defer(CallCommand::StartShare(source)); |
| 1418 | } |
| 1419 | if video_possible(remote_set, layout, negotiator.path()) |
| 1420 | && let Some(kind) = portal_pending.take() |
| 1421 | { |
| 1422 | control.defer(CallCommand::StartPortalShare(kind)); |
| 1423 | } |
| 1424 | if next.as_ref().is_some_and(|pending| { |
| 1425 | pending.connected && (pending.offered.is_some() || pending.retargeted) |
| 1426 | }) && let Some(pending) = next.take() |
| 1427 | { |
| 1428 | timeline.record( |
| 1429 | "escalation", |
| 1430 | "new peer connection connected, old one dropped", |
| 1431 | ); |
| 1432 | deferred_changes.clear(); |
| 1433 | negotiator.server_escalation_done(); |
| 1434 | if let Some(mid) = remote_direct_share.take() { |
| 1435 | video.router().set(&mid, None); |
| 1436 | control.send(CallUpdate::ScreenShare(None)); |
| 1437 | } |
| 1438 | let old = std::mem::replace(&mut current, pending.session); |
| 1439 | old.peer.close(); |
| 1440 | if let Some(audio) = &software_audio |
| 1441 | && let Err(error) = swap_audio_track(¤t.peer, &audio.track) |
| 1442 | { |
| 1443 | timeline.record("computer sound not carried over", error.to_string()); |
| 1444 | } |
| 1445 | offered = pending.offered; |
| 1446 | if let Some(mid) = direct_video_mid.take() { |
| 1447 | video.router().set(&mid, None); |
| 1448 | } |
| 1449 | if let Some(media) = &offered { |
| 1450 | layout = Layout::Conference; |
| 1451 | layout_plan = media.plan.clone(); |
| 1452 | if let Err(error) = local_video.set_lines(media.video.clone()) { |
| 1453 | timeline.record("video lines not attached", error.to_string()); |
| 1454 | } |
| 1455 | if local_video.camera_on() { |
| 1456 | tell_media_descriptions( |
| 1457 | &remote, |
| 1458 | &media_links, |
| 1459 | MediaDescription::camera(true), |
| 1460 | &mut media_description_request, |
| 1461 | timeline, |
| 1462 | ); |
| 1463 | } |
| 1464 | if local_video.sharing() { |
| 1465 | tell_media_descriptions( |
| 1466 | &remote, |
| 1467 | &media_links, |
| 1468 | MediaDescription::share(true), |
| 1469 | &mut media_description_request, |
| 1470 | timeline, |
| 1471 | ); |
| 1472 | } |
| 1473 | } |
| 1474 | remote_set = true; |
| 1475 | if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() { |
| 1476 | let pending = escalate( |
| 1477 | &factory, |
| 1478 | &grant, |
| 1479 | options, |
| 1480 | outgoing_track(software_audio.as_ref(), &track), |
| 1481 | &remote, |
| 1482 | &links, |
| 1483 | &media_leg_id, |
| 1484 | &media_links, |
| 1485 | &mut negotiator, |
| 1486 | live, |
| 1487 | timeline, |
| 1488 | ) |
| 1489 | .await; |
| 1490 | if pending.is_none() { |
| 1491 | drop_local_media(&mut local_video, control); |
| 1492 | } |
| 1493 | next = pending.or(next); |
| 1494 | } |
| 1495 | } |
| 1496 | let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline); |
| 1497 | let glare_at = glare_resend.as_ref().map(|resend| resend.at); |
| 1498 | tokio::select! { |
| 1499 | Some(callback) = callbacks.recv() => { |
| 1500 | match handle_callback(&callback, timeline) { |
| 1501 | Ok(CallEvent::Acceptance(acceptance)) => { |
| 1502 | if !acceptance.from_mixer |
| 1503 | && let Some(accepted_by) = &acceptance.accepted_by |
| 1504 | && roster.apply(&direct_roster(&[(own_mri.as_str(), participant.display_name.as_str()), (accepted_by.mri.as_str(), accepted_by.display_name.as_str())])) |
| 1505 | { |
| 1506 | control.send(CallUpdate::Roster(roster.entries())); |
| 1507 | } |
| 1508 | if !acceptance.from_mixer && callee_gate.callee_joined() { |
| 1509 | advance(state, CallSignal::MediaConnected, control); |
| 1510 | } |
| 1511 | let action = negotiator.on_acceptance(acceptance.from_mixer, layout == Layout::OneToOne); |
| 1512 | match action { |
| 1513 | MediaAction::ApplyAnswer | MediaAction::ApplyAnswerThenEscalate => { |
| 1514 | let Some(media) = offered.as_ref() else { continue }; |
| 1515 | dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp); |
| 1516 | if let Ok(answer) = to_browser_answer(&acceptance.sdp, &media.signaled, &media.browser_offer) { |
| 1517 | dump_sdp(options, "4-browser-answer.sdp", &answer); |
| 1518 | } |
| 1519 | apply_answer(¤t.peer, &acceptance.sdp, &media.signaled, &media.browser_offer) |
| 1520 | .await |
| 1521 | .inspect_err(|error| timeline.record("answer rejected", error.to_string()))?; |
| 1522 | remote_set = true; |
| 1523 | media_links.extend(acceptance.links.clone()); |
| 1524 | if layout == Layout::Conference { |
| 1525 | negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster); |
| 1526 | } |
| 1527 | if let Some(link) = acceptance.links.get("replacement") |
| 1528 | && sent_replacement.as_ref().is_none_or(|sent| sent.participant_id.is_none()) |
| 1529 | { |
| 1530 | let replacement = Replacement::of_call(link.clone()); |
| 1531 | sent_replacement = Some(replacement.clone()); |
| 1532 | control.send(CallUpdate::ReplacementLink(replacement)); |
| 1533 | } |
| 1534 | if !callee_gate.is_waiting() { |
| 1535 | outgoing_deadline = None; |
| 1536 | } |
| 1537 | let directions: Vec<String> = current |
| 1538 | .peer |
| 1539 | .transceivers() |
| 1540 | .iter() |
| 1541 | .map(|transceiver| format!("{:?}", transceiver.current_direction())) |
| 1542 | .collect(); |
| 1543 | timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(","))); |
| 1544 | if acceptance.in_lobby() { |
| 1545 | lobby = true; |
| 1546 | control.send(CallUpdate::Lobby(true)); |
| 1547 | } |
| 1548 | keep_alive_link = acceptance.links.get("callLeg").cloned(); |
| 1549 | keep_alive_seconds = acceptance.keep_alive_seconds; |
| 1550 | keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds)); |
| 1551 | if action == MediaAction::ApplyAnswerThenEscalate { |
| 1552 | let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &acceptance.links, &mut negotiator, live, timeline).await; |
| 1553 | next = pending.or(next); |
| 1554 | } |
| 1555 | let remote = remote.clone(); |
| 1556 | let links = links.clone(); |
| 1557 | let thread_id = echo_thread.clone(); |
| 1558 | tokio::spawn(async move { |
| 1559 | if is_echo { |
| 1560 | let _ = remote.signaling.add_echo_bot(&remote.conversation, &remote.participant, thread_id.as_deref(), &links).await; |
| 1561 | } |
| 1562 | let _ = remote.signaling.update_endpoint_metadata(&remote.conversation, &remote.participant).await; |
| 1563 | }); |
| 1564 | } |
| 1565 | MediaAction::Escalate => { |
| 1566 | let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &acceptance.links, &mut negotiator, live, timeline).await; |
| 1567 | next = pending.or(next); |
| 1568 | } |
| 1569 | _ => {} |
| 1570 | } |
| 1571 | } |
| 1572 | Ok(CallEvent::MediaAnswer(answer)) if !remote_set && !answer.from_mixer && same_peer.is_none() && next.is_none() && outgoing_deadline.is_some() => { |
| 1573 | timeline.record("provisional answer", if answer.no_ring_back { "no ringback" } else { "ringing" }); |
| 1574 | outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT); |
| 1575 | if !answer.no_ring_back { |
| 1576 | control.send(CallUpdate::Progress(Progress::Ringing)); |
| 1577 | } |
| 1578 | } |
| 1579 | Ok(CallEvent::MediaAnswer(answer)) |
| 1580 | if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) => |
| 1581 | { |
| 1582 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 1583 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 1584 | } |
| 1585 | if answer.from_mixer { |
| 1586 | negotiator.note_mixer_path(); |
| 1587 | } |
| 1588 | if let Some(resend) = glare_resend.as_mut() { |
| 1589 | resend.at = Instant::now(); |
| 1590 | } |
| 1591 | } |
| 1592 | Ok(CallEvent::MediaAnswer(answer)) => { |
| 1593 | let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) |
| 1594 | || next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)); |
| 1595 | if (same_peer.is_some() || next.is_some()) && !belongs { |
| 1596 | timeline.record("media answer ignored", "it answers an offer that is no longer pending"); |
| 1597 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 1598 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 1599 | } |
| 1600 | continue; |
| 1601 | } |
| 1602 | let action = negotiator.on_media_answer(); |
| 1603 | if action == MediaAction::Ignore |
| 1604 | && let Some(url) = answer.links.get("mediaAcknowledgement") |
| 1605 | { |
| 1606 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 1607 | } |
| 1608 | if action == MediaAction::ApplyOnSamePeer |
| 1609 | && let Some(pending) = same_peer.take() |
| 1610 | { |
| 1611 | same_peer_deadline = None; |
| 1612 | same_peer_grace_until = None; |
| 1613 | let applied = match pending.change { |
| 1614 | Change::Hold(_) => apply_hold_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await, |
| 1615 | Change::Camera(_) | Change::Share(_) => apply_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await, |
| 1616 | }; |
| 1617 | match applied { |
| 1618 | Ok(()) => { |
| 1619 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 1620 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 1621 | } |
| 1622 | match pending.change { |
| 1623 | Change::Hold(hold) => { |
| 1624 | local_hold = hold; |
| 1625 | silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref()); |
| 1626 | control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold))); |
| 1627 | } |
| 1628 | Change::Camera(on) => control.send(CallUpdate::Camera(on)), |
| 1629 | Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => { |
| 1630 | local_video.stop_share(); |
| 1631 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline); |
| 1632 | clear_share(control); |
| 1633 | control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into())); |
| 1634 | } |
| 1635 | Change::Share(_) => {} |
| 1636 | } |
| 1637 | if answer.from_mixer { |
| 1638 | media_links.extend(answer.links.clone()); |
| 1639 | let wants_video = !local_hold && (local_video.camera_on() || local_video.sharing()); |
| 1640 | let upgrade = wants_video |
| 1641 | && (negotiator.escalate_after_mixer_answer() || (layout == Layout::OneToOne && next.is_none() && negotiator.begin_conference_upgrade())); |
| 1642 | if !wants_video { |
| 1643 | negotiator.note_mixer_path(); |
| 1644 | } else if upgrade { |
| 1645 | let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await; |
| 1646 | if pending.is_none() { |
| 1647 | drop_local_media(&mut local_video, control); |
| 1648 | } |
| 1649 | next = pending.or(next); |
| 1650 | } |
| 1651 | } |
| 1652 | } |
| 1653 | Err(error) => { |
| 1654 | timeline.record("same-peer answer rejected", error.to_string()); |
| 1655 | undo_change(pending.change, &mut local_video, control); |
| 1656 | } |
| 1657 | } |
| 1658 | } |
| 1659 | if action == MediaAction::ApplyOnNewPeer { |
| 1660 | let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) { |
| 1661 | Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await, |
| 1662 | None => Err(Error::Webrtc("no pending peer connection for the answer".into())), |
| 1663 | }; |
| 1664 | match applied { |
| 1665 | Ok(()) => { |
| 1666 | if let Some(media) = next.as_ref().and_then(|pending| pending.offered.as_ref()) { |
| 1667 | media_links.extend(answer.links.clone()); |
| 1668 | negotiate_video(&mut video, &signaling, control, timeline, &answer.sdp, media, true, &media_links, &roster); |
| 1669 | } |
| 1670 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 1671 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 1672 | } |
| 1673 | } |
| 1674 | Err(error) => { |
| 1675 | negotiator.escalation_failed(); |
| 1676 | if let Some(pending) = next.take() { |
| 1677 | pending.session.peer.close(); |
| 1678 | } |
| 1679 | if layout == Layout::OneToOne { |
| 1680 | drop_local_media(&mut local_video, control); |
| 1681 | } |
| 1682 | timeline.record("escalation answer rejected", error.to_string()); |
| 1683 | } |
| 1684 | } |
| 1685 | } |
| 1686 | } |
| 1687 | Ok(CallEvent::MediaRenegotiation(renegotiation)) => { |
| 1688 | if !renegotiation.escalation |
| 1689 | && !renegotiation.new_offer |
| 1690 | && let Some(pending) = same_peer.take() |
| 1691 | { |
| 1692 | same_peer_deadline = None; |
| 1693 | same_peer_grace_until = None; |
| 1694 | negotiator.same_peer_offer_failed(); |
| 1695 | rollback_offer(¤t.peer).await; |
| 1696 | timeline.record("glare", "the remote offer is answered first, ours goes out again after"); |
| 1697 | glare_resend = Some(GlareResend { change: pending.change, reply_tags: pending.reply_tags, at: Instant::now() + GLARE_RESEND_LIMIT }); |
| 1698 | } |
| 1699 | let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation); |
| 1700 | let rejection_link = renegotiation.links.get("rejection").cloned(); |
| 1701 | let result = match action { |
| 1702 | MediaAction::AnswerOnNewPeer => { |
| 1703 | if let Some(pending) = same_peer.take() { |
| 1704 | same_peer_deadline = None; |
| 1705 | same_peer_grace_until = None; |
| 1706 | timeline.record("same-peer offer", "superseded by the escalation offer"); |
| 1707 | rollback_offer(¤t.peer).await; |
| 1708 | defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control); |
| 1709 | } |
| 1710 | if let Some(resend) = glare_resend.take() { |
| 1711 | defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control); |
| 1712 | } |
| 1713 | match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await { |
| 1714 | Ok((session, answered)) => { |
| 1715 | timeline.record_sdp("local answer", &answered.answer_sdp); |
| 1716 | live.peers.push(session.peer.clone()); |
| 1717 | let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await; |
| 1718 | if let Some(replaced) = next.take() { |
| 1719 | replaced.session.peer.close(); |
| 1720 | } |
| 1721 | next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: Some(Instant::now() + NEXT_PEER_LIMIT), connected: false, retargeted: false }); |
| 1722 | sent |
| 1723 | } |
| 1724 | Err(error) => { |
| 1725 | if next.is_none() { |
| 1726 | negotiator.server_escalation_failed(); |
| 1727 | } |
| 1728 | for change in deferred_changes.drain(..) { |
| 1729 | undo_change(change, &mut local_video, control); |
| 1730 | } |
| 1731 | if let Some(url) = &rejection_link { |
| 1732 | let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await; |
| 1733 | } |
| 1734 | Err(error) |
| 1735 | } |
| 1736 | } |
| 1737 | } |
| 1738 | MediaAction::AnswerOnSamePeer => { |
| 1739 | let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject }; |
| 1740 | match answer_offer(¤t.peer, None, &renegotiation.sdp, video_answer, local_video.sharing().then(|| local_video.share_mid()).flatten(), local_video.camera_on(), (layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct).then_some(¤t.gathered)).await { |
| 1741 | Ok(answered) => { |
| 1742 | timeline.record_sdp("local answer", &answered.answer_sdp); |
| 1743 | let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await; |
| 1744 | for mid in answered.remote.plan().screen_share_mids { |
| 1745 | if !layout_plan.screen_share_mids.contains(&mid) { |
| 1746 | layout_plan.screen_share_mids.push(mid); |
| 1747 | } |
| 1748 | } |
| 1749 | if layout == Layout::OneToOne && answered.receiving_share_mid != remote_direct_share { |
| 1750 | if let Some(mid) = &remote_direct_share { |
| 1751 | video.router().set(mid, None); |
| 1752 | } |
| 1753 | if let Some(mid) = &answered.receiving_share_mid { |
| 1754 | video.router().set(mid, Some(VideoKey::Screen)); |
| 1755 | } |
| 1756 | remote_direct_share = answered.receiving_share_mid.clone(); |
| 1757 | control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone()))); |
| 1758 | } |
| 1759 | if layout == Layout::OneToOne |
| 1760 | && !offer_sends_video(&renegotiation.sdp) |
| 1761 | && let Some(key) = main_video_mid(&answered.remote).and_then(|mid| video.router().key_for(&mid)) |
| 1762 | { |
| 1763 | control.video.forget(&key); |
| 1764 | control.send(CallUpdate::VideoStopped(key)); |
| 1765 | } |
| 1766 | let held = is_hold(&renegotiation.sdp).unwrap_or(false); |
| 1767 | if held != remote_hold { |
| 1768 | remote_hold = held; |
| 1769 | control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold))); |
| 1770 | } |
| 1771 | sent |
| 1772 | } |
| 1773 | Err(error) => { |
| 1774 | if current.peer.signaling_state() == SignalingState::HaveRemoteOffer { |
| 1775 | rollback_remote_offer(¤t.peer).await; |
| 1776 | } |
| 1777 | if let Some(url) = &rejection_link { |
| 1778 | let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await; |
| 1779 | } |
| 1780 | Err(error) |
| 1781 | } |
| 1782 | } |
| 1783 | } |
| 1784 | MediaAction::RejectGlare => { |
| 1785 | if let Some(url) = &rejection_link { |
| 1786 | let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::InProgress).await; |
| 1787 | } |
| 1788 | Ok(()) |
| 1789 | } |
| 1790 | _ => Ok(()), |
| 1791 | }; |
| 1792 | if let Err(error) = result { |
| 1793 | timeline.record("renegotiation failed", error.to_string()); |
| 1794 | } |
| 1795 | } |
| 1796 | Ok(CallEvent::RosterUpdate(body)) => { |
| 1797 | if roster.apply(&body) { |
| 1798 | let entries = roster.entries(); |
| 1799 | timeline.record("roster", format!("{} participant(s)", entries.len())); |
| 1800 | control.send(CallUpdate::Roster(entries)); |
| 1801 | if is_echo && echo_watch.bot_left(roster.members().iter().map(|member| member.mri.as_str())) { |
| 1802 | timeline.record("echo bot left", "test call ends like in Teams"); |
| 1803 | advance(state, CallSignal::RemoteEnd(EndKind::Normal), control); |
| 1804 | break; |
| 1805 | } |
| 1806 | if callee_gate.is_waiting() && roster_has_callee(roster.members().iter().map(|member| member.mri.as_str()), &own_mri) { |
| 1807 | outgoing_deadline = None; |
| 1808 | if callee_gate.callee_joined() { |
| 1809 | advance(state, CallSignal::MediaConnected, control); |
| 1810 | } |
| 1811 | } |
| 1812 | let own_streams = roster.stream_summaries(&own_mri); |
| 1813 | if own_streams != report.own_streams { |
| 1814 | timeline.record("own media streams", own_streams.join("; ")); |
| 1815 | report.own_streams = own_streams; |
| 1816 | } |
| 1817 | send_receive_change(control, video.reselect(&roster)); |
| 1818 | if let Some(replacement) = roster.transfer_replacement(&own_mri) |
| 1819 | && sent_replacement.as_ref() != Some(&replacement) |
| 1820 | { |
| 1821 | sent_replacement = Some(replacement.clone()); |
| 1822 | control.send(CallUpdate::ReplacementLink(replacement)); |
| 1823 | } |
| 1824 | if let Some(in_lobby) = roster.is_in_lobby(&own_mri) |
| 1825 | && in_lobby != lobby |
| 1826 | { |
| 1827 | lobby = in_lobby; |
| 1828 | control.send(CallUpdate::Lobby(lobby)); |
| 1829 | } |
| 1830 | if roster.caption_bot().is_some() { |
| 1831 | bot_pending = false; |
| 1832 | } |
| 1833 | let audio_only = roster.caption_bot().is_some_and(|bot| bot.recording && bot.audio_only); |
| 1834 | if audio_only != recording_audio_only { |
| 1835 | recording_audio_only = audio_only; |
| 1836 | control.send(CallUpdate::RecordingAudioOnly(audio_only)); |
| 1837 | } |
| 1838 | if caption_flow.wanted() { |
| 1839 | run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), &RecordingPlan::default(), &mut bot_pending, control, timeline).await; |
| 1840 | if caption_flow.on() { |
| 1841 | caption_deadline = None; |
| 1842 | } |
| 1843 | } |
| 1844 | if recording_flow.wanted() { |
| 1845 | run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await; |
| 1846 | } |
| 1847 | } |
| 1848 | } |
| 1849 | Ok(CallEvent::AddParticipantFailure(body)) => { |
| 1850 | let bot_add = bot_pending; |
| 1851 | bot_pending = false; |
| 1852 | if !bot_add && callee_gate.callees_failed(failed_participant_count(&body)) { |
| 1853 | let end = embedded_end(&body); |
| 1854 | let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind); |
| 1855 | report.end = end; |
| 1856 | advance(state, CallSignal::RemoteEnd(kind), control); |
| 1857 | break; |
| 1858 | } |
| 1859 | if recording_flow.wanted() && roster.caption_bot().is_none() { |
| 1860 | timeline.record("recorder bot failed", "addParticipantFailure"); |
| 1861 | recording_flow.failed(); |
| 1862 | recording_deadline = None; |
| 1863 | control.send(CallUpdate::RecordingPending(false)); |
| 1864 | control.send(CallUpdate::Notice(RECORDING_JOIN_FAILED_NOTICE.into())); |
| 1865 | } |
| 1866 | if caption_flow.wanted() && roster.caption_bot().is_none() { |
| 1867 | timeline.record("caption bot failed", "addParticipantFailure"); |
| 1868 | caption_flow.failed(); |
| 1869 | caption_deadline = None; |
| 1870 | control.send(CallUpdate::Captions(CaptionState::Failed( |
| 1871 | CAPTIONS_JOIN_FAILED_NOTICE.into(), |
| 1872 | ))); |
| 1873 | } |
| 1874 | } |
| 1875 | Ok(CallEvent::ConversationUpdate(body)) => { |
| 1876 | if let Some(thread) = chat_thread_id(&body) |
| 1877 | && meeting_chat.as_ref() != Some(&thread) |
| 1878 | { |
| 1879 | control.send(CallUpdate::MeetingChat(thread.clone())); |
| 1880 | meeting_chat = Some(thread); |
| 1881 | } |
| 1882 | if capability.apply(&body) { |
| 1883 | control.send(CallUpdate::Capability(capability)); |
| 1884 | } |
| 1885 | let change = recording_status.apply(&body); |
| 1886 | if let Some(on) = change.recording { |
| 1887 | control.send(CallUpdate::Recording(on)); |
| 1888 | if on { |
| 1889 | recording_deadline = None; |
| 1890 | control.send(CallUpdate::RecordingPending(false)); |
| 1891 | } |
| 1892 | } |
| 1893 | if let Some(on) = change.transcription { |
| 1894 | control.send(CallUpdate::Transcribing(on)); |
| 1895 | if on { |
| 1896 | recording_deadline = None; |
| 1897 | control.send(CallUpdate::RecordingPending(false)); |
| 1898 | } |
| 1899 | } |
| 1900 | if let Some(required) = change.consent_required { |
| 1901 | consent_pending = required; |
| 1902 | control.send(CallUpdate::ConsentRequired(required)); |
| 1903 | if required { |
| 1904 | withhold_media(&mut muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, &mut local_video, control); |
| 1905 | } |
| 1906 | } |
| 1907 | if !main_meeting_sent |
| 1908 | && let Some(main) = breakout::main_meeting_target(&body) |
| 1909 | { |
| 1910 | main_meeting_sent = true; |
| 1911 | control.send(CallUpdate::BreakoutRoom { main }); |
| 1912 | } |
| 1913 | } |
| 1914 | Ok(CallEvent::LocalParticipantUpdate(body)) => { |
| 1915 | let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target)); |
| 1916 | if let Some(moved) = moved { |
| 1917 | timeline.record("breakout", format!("moved to {}", moved.room_name)); |
| 1918 | control.send(CallUpdate::BreakoutMove(moved)); |
| 1919 | } |
| 1920 | } |
| 1921 | Ok(CallEvent::Replacement(body)) => { |
| 1922 | let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target)); |
| 1923 | if let Some(moved) = invited { |
| 1924 | timeline.record("breakout", format!("invited to {}", moved.room_name)); |
| 1925 | control.send(CallUpdate::BreakoutMove(moved)); |
| 1926 | } |
| 1927 | } |
| 1928 | Ok(CallEvent::ContentShareUpdate(body)) => { |
| 1929 | if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) { |
| 1930 | control.send(CallUpdate::Whiteboard(Some(share))); |
| 1931 | } |
| 1932 | } |
| 1933 | Ok(CallEvent::ContentShareEnd(_)) => { |
| 1934 | control.send(CallUpdate::Whiteboard(None)); |
| 1935 | } |
| 1936 | Ok(CallEvent::Transfer(event)) => { |
| 1937 | match event { |
| 1938 | TransferEvent::Accepted => timeline.record("transfer accepted", "by the target"), |
| 1939 | completed if completed.succeeded() => { |
| 1940 | timeline.record("transfer", "completed"); |
| 1941 | control.send(CallUpdate::TransferResult { succeeded: true }); |
| 1942 | control.send(CallUpdate::Notice(CALL_TRANSFERRED_NOTICE.into())); |
| 1943 | advance(state, CallSignal::LocalLeave, control); |
| 1944 | break; |
| 1945 | } |
| 1946 | TransferEvent::Completed { code, sub_code } => { |
| 1947 | timeline.record("transfer failed", format!("code {code} subCode {sub_code}")); |
| 1948 | control.send(CallUpdate::TransferResult { succeeded: false }); |
| 1949 | control.send(CallUpdate::Notice(TRANSFER_FAILED_NOTICE.into())); |
| 1950 | } |
| 1951 | } |
| 1952 | } |
| 1953 | Ok(CallEvent::Reactions(events)) => { |
| 1954 | for event in events { |
| 1955 | control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction }); |
| 1956 | } |
| 1957 | } |
| 1958 | Ok(CallEvent::Progress(status)) => { |
| 1959 | if status == ProgressStatus::Ringing { |
| 1960 | control.send(CallUpdate::Progress(Progress::Ringing)); |
| 1961 | if outgoing_deadline.is_some() { |
| 1962 | outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT); |
| 1963 | } |
| 1964 | } |
| 1965 | } |
| 1966 | Ok(CallEvent::ControlVideoStreaming(body)) => { |
| 1967 | let Some(request) = parse_request(&body) else { continue }; |
| 1968 | let Some(limits) = send_requests.admit(&request) else { continue }; |
| 1969 | let own_screen = roster.screen_source_of(&own_mri).map(i64::from); |
| 1970 | let source = if request.source_id.is_some() && request.source_id == own_screen { SendSource::Screen } else { SendSource::Camera }; |
| 1971 | match local_video.apply_send_limit(source, &limits) { |
| 1972 | Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?}")), |
| 1973 | Ok(None) => {} |
| 1974 | Err(error) => timeline.record("send limits failed", error.to_string()), |
| 1975 | } |
| 1976 | } |
| 1977 | Ok(CallEvent::Speakers(sources)) => { |
| 1978 | let speakers = roster.mris_for_sources(&sources); |
| 1979 | if video.note_speakers(&speakers) { |
| 1980 | send_receive_change(control, video.reselect(&roster)); |
| 1981 | } |
| 1982 | control.send(CallUpdate::Speakers(speakers)); |
| 1983 | } |
| 1984 | Ok(CallEvent::ConversationEnd(body)) if callee_gate.is_waiting() => { |
| 1985 | live.skip_leave = true; |
| 1986 | let end = embedded_end(&body); |
| 1987 | let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind); |
| 1988 | report.end = end; |
| 1989 | advance(state, CallSignal::RemoteEnd(kind), control); |
| 1990 | break; |
| 1991 | } |
| 1992 | Ok(CallEvent::Rejection(_)) |
| 1993 | if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) => |
| 1994 | { |
| 1995 | if let Some(resend) = glare_resend.as_mut() { |
| 1996 | resend.at = Instant::now(); |
| 1997 | } |
| 1998 | } |
| 1999 | Ok(CallEvent::Rejection(_)) |
| 2000 | if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) |
| 2001 | && !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) => |
| 2002 | { |
| 2003 | timeline.record("rejection ignored", "it names an offer that is no longer pending"); |
| 2004 | } |
| 2005 | Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() { |
| 2006 | RejectedOffer::SamePeer => { |
| 2007 | same_peer_deadline = None; |
| 2008 | same_peer_grace_until = None; |
| 2009 | if let Some(pending) = same_peer.take() { |
| 2010 | rollback_offer(¤t.peer).await; |
| 2011 | if is_glare_rejection(&body) { |
| 2012 | timeline.record("glare", "our offer met theirs, it goes out again"); |
| 2013 | glare_resend = Some(GlareResend { change: pending.change, reply_tags: Vec::new(), at: Instant::now() + GLARE_RESEND_LIMIT }); |
| 2014 | } else { |
| 2015 | undo_change(pending.change, &mut local_video, control); |
| 2016 | } |
| 2017 | } |
| 2018 | } |
| 2019 | RejectedOffer::NewPeer => { |
| 2020 | if let Some(pending) = next.take() { |
| 2021 | pending.session.peer.close(); |
| 2022 | } |
| 2023 | if layout == Layout::OneToOne { |
| 2024 | drop_local_media(&mut local_video, control); |
| 2025 | } |
| 2026 | timeline.record("escalation failed", "offer rejected, staying on the old peer connection"); |
| 2027 | } |
| 2028 | RejectedOffer::None => {} |
| 2029 | }, |
| 2030 | Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => { |
| 2031 | if let Some(pending) = next.as_mut() { |
| 2032 | pending.retargeted = true; |
| 2033 | } |
| 2034 | } |
| 2035 | Ok(CallEvent::RetargetCompletion(body)) => { |
| 2036 | if body["retargetCompleted"]["code"].as_i64().is_some() && let Some(pending) = next.take() { |
| 2037 | pending.session.peer.close(); |
| 2038 | negotiator.escalation_failed(); |
| 2039 | settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control); |
| 2040 | timeline.record("escalation failed", "retarget rejected, staying on the old peer connection"); |
| 2041 | } |
| 2042 | } |
| 2043 | Ok(CallEvent::End(end)) => { |
| 2044 | let kind = end.kind(); |
| 2045 | report.end = Some(end); |
| 2046 | advance(state, CallSignal::RemoteEnd(kind), control); |
| 2047 | break; |
| 2048 | } |
| 2049 | Ok(_) => {} |
| 2050 | Err(error) => { |
| 2051 | timeline.record("callback not understood", error.to_string()); |
| 2052 | } |
| 2053 | } |
| 2054 | } |
| 2055 | Some(event) = current.events.recv() => match event { |
| 2056 | PeerEvent::Ice(ice_state) => { |
| 2057 | timeline.record("ICE state", format!("{ice_state:?}")); |
| 2058 | if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() { |
| 2059 | report.ice_connected_ms = Some(timeline.elapsed_ms()); |
| 2060 | } |
| 2061 | } |
| 2062 | PeerEvent::Connection(connection) => { |
| 2063 | timeline.record("PeerConnection state", format!("{connection:?}")); |
| 2064 | match connection { |
| 2065 | PeerConnectionState::Connected => { |
| 2066 | reconnect_deadline = None; |
| 2067 | if callee_gate.media_connected() { |
| 2068 | advance(state, CallSignal::MediaConnected, control); |
| 2069 | } |
| 2070 | if report.peer_connected_ms.is_none() { |
| 2071 | report.peer_connected_ms = Some(timeline.elapsed_ms()); |
| 2072 | if let Some(hold) = options.hold_after_connected { |
| 2073 | let hold_until = Instant::now() + hold; |
| 2074 | leave_at = Some(hard_deadline.map_or(hold_until, |deadline| deadline.min(hold_until))); |
| 2075 | } |
| 2076 | } |
| 2077 | } |
| 2078 | PeerConnectionState::Disconnected => { |
| 2079 | if advance(state, CallSignal::MediaDisconnected, control) { |
| 2080 | reconnect_deadline = Some(Instant::now() + options.reconnect_window); |
| 2081 | } |
| 2082 | } |
| 2083 | PeerConnectionState::Failed => { |
| 2084 | advance(state, CallSignal::MediaFailed, control); |
| 2085 | break; |
| 2086 | } |
| 2087 | _ => {} |
| 2088 | } |
| 2089 | } |
| 2090 | PeerEvent::Track(remote_track) => { |
| 2091 | timeline.record("remote audio track", "receiving"); |
| 2092 | let had_far_end = remote_audio.replace(remote_track.clone()).is_some(); |
| 2093 | if !had_far_end && software_audio.is_some() { |
| 2094 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline); |
| 2095 | } |
| 2096 | if options.record_remote { |
| 2097 | tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz)); |
| 2098 | } |
| 2099 | } |
| 2100 | PeerEvent::VideoTrack { mid, track } => { |
| 2101 | timeline.record("remote video track", format!("mid {mid}")); |
| 2102 | live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone())); |
| 2103 | } |
| 2104 | PeerEvent::Data(frame) => { |
| 2105 | if let Some(message) = depacketizer.push(&frame) |
| 2106 | && message.data_id == CAPTIONS_DATA_ID |
| 2107 | { |
| 2108 | for entry in parse_caption_message(&message.payload) { |
| 2109 | if caption_flow.text_arrived() { |
| 2110 | caption_deadline = None; |
| 2111 | control.send(CallUpdate::Captions(CaptionState::On)); |
| 2112 | } |
| 2113 | control.send(CallUpdate::Caption(named_caption(entry, &roster))); |
| 2114 | } |
| 2115 | } |
| 2116 | } |
| 2117 | }, |
| 2118 | Some(event) = next_peer_event(&mut next) => match event { |
| 2119 | PeerEvent::Connection(PeerConnectionState::Connected) => { |
| 2120 | if let Some(pending) = next.as_mut() { |
| 2121 | pending.connected = true; |
| 2122 | if pending.offered.is_none() && !pending.retargeted { |
| 2123 | pending.deadline = Some(Instant::now() + RETARGET_WAIT); |
| 2124 | timeline.record("escalation", "new peer connection up, waiting for retargetCompletion"); |
| 2125 | } |
| 2126 | } |
| 2127 | } |
| 2128 | PeerEvent::VideoTrack { mid, track } => { |
| 2129 | timeline.record("remote video track", format!("mid {mid} (new peer)")); |
| 2130 | live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone())); |
| 2131 | } |
| 2132 | PeerEvent::Connection(PeerConnectionState::Failed) => { |
| 2133 | negotiator.escalation_failed(); |
| 2134 | if let Some(pending) = next.take() { |
| 2135 | pending.session.peer.close(); |
| 2136 | settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control); |
| 2137 | } |
| 2138 | timeline.record("escalation failed", "new peer connection failed, staying on the old one"); |
| 2139 | } |
| 2140 | _ => {} |
| 2141 | }, |
| 2142 | command = control.recv() => match command { |
| 2143 | Some(CallCommand::Mute(mute)) => { |
| 2144 | if consent_pending && !mute.target(muted) { |
| 2145 | control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into())); |
| 2146 | } else { |
| 2147 | muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control); |
| 2148 | silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref()); |
| 2149 | } |
| 2150 | } |
| 2151 | Some(CallCommand::DisableAudio) => { |
| 2152 | let audio = live.audio.as_ref().expect("audio set above"); |
| 2153 | muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control); |
| 2154 | audio_disabled = true; |
| 2155 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, control, timeline); |
| 2156 | if audio.uses_devices() { |
| 2157 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 2158 | factory.set_adm_recording_enabled(false); |
| 2159 | factory.set_adm_playout_enabled(false); |
| 2160 | } |
| 2161 | control.send(CallUpdate::ListenOnly(true)); |
| 2162 | } |
| 2163 | Some(CallCommand::SelectInput(choice)) => { |
| 2164 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 2165 | timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice))); |
| 2166 | applied_input = devices::applied_device(&device_lists.inputs, &choice, devices::system_default_id(Flow::Capture).as_deref()); |
| 2167 | record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref()); |
| 2168 | } |
| 2169 | input = choice; |
| 2170 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 2171 | if software_audio.is_some() { |
| 2172 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline); |
| 2173 | } |
| 2174 | } |
| 2175 | Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => { |
| 2176 | mic_settings = settings; |
| 2177 | crate::noise_stage::apply(mic_settings); |
| 2178 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline); |
| 2179 | } |
| 2180 | Some(CallCommand::SetMicSettings(settings)) => { |
| 2181 | mic_settings = settings; |
| 2182 | crate::noise_stage::apply(mic_settings); |
| 2183 | } |
| 2184 | Some(CallCommand::SelectOutput(choice)) => { |
| 2185 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 2186 | timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice))); |
| 2187 | applied_output = devices::applied_device(&device_lists.outputs, &choice, devices::system_default_id(Flow::Render).as_deref()); |
| 2188 | record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref()); |
| 2189 | } |
| 2190 | output = choice; |
| 2191 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 2192 | } |
| 2193 | Some(CallCommand::RefreshDevices) => { |
| 2194 | device_lists = devices::list_devices(&factory); |
| 2195 | control.send(CallUpdate::Devices(device_lists.clone())); |
| 2196 | } |
| 2197 | Some(CallCommand::SetCamera(false)) if local_video.camera_previewing() => { |
| 2198 | start_camera_pending = false; |
| 2199 | local_video.stop_camera(); |
| 2200 | control.send(CallUpdate::Camera(false)); |
| 2201 | } |
| 2202 | Some(CallCommand::SetCamera(on)) => { |
| 2203 | let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer; |
| 2204 | if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) { |
| 2205 | if remote_set && next.is_none() && negotiator.begin_conference_upgrade() { |
| 2206 | let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await; |
| 2207 | next = pending.or(next); |
| 2208 | } |
| 2209 | if remote_set && on && next.is_some() { |
| 2210 | start_camera_pending = true; |
| 2211 | } |
| 2212 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 2213 | } else if on && consent_pending { |
| 2214 | control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into())); |
| 2215 | } else if local_hold { |
| 2216 | control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into())); |
| 2217 | } else if on && direct && (same_peer.is_some() || glare_resend.is_some()) { |
| 2218 | control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into())); |
| 2219 | } else if on { |
| 2220 | let started = start_camera_line(&mut local_video, ¤t.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice); |
| 2221 | match started { |
| 2222 | Ok(()) if direct => { |
| 2223 | match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, true, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await { |
| 2224 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2225 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2226 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags }); |
| 2227 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2228 | same_peer_grace_until = None; |
| 2229 | } |
| 2230 | Err(error) => { |
| 2231 | timeline.record("camera offer failed", error.to_string()); |
| 2232 | undo_change(Change::Camera(true), &mut local_video, control); |
| 2233 | } |
| 2234 | } |
| 2235 | } |
| 2236 | Ok(()) => { |
| 2237 | control.send(CallUpdate::Camera(true)); |
| 2238 | tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline); |
| 2239 | } |
| 2240 | Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))), |
| 2241 | } |
| 2242 | } else if direct && (same_peer.is_some() || glare_resend.is_some()) { |
| 2243 | control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into())); |
| 2244 | } else if direct { |
| 2245 | local_video.stop_camera(); |
| 2246 | match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, false, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await { |
| 2247 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2248 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2249 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags }); |
| 2250 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2251 | same_peer_grace_until = None; |
| 2252 | } |
| 2253 | Err(error) => { |
| 2254 | timeline.record("camera offer failed", error.to_string()); |
| 2255 | control.send(CallUpdate::Camera(false)); |
| 2256 | } |
| 2257 | } |
| 2258 | } else { |
| 2259 | local_video.stop_camera(); |
| 2260 | control.send(CallUpdate::Camera(false)); |
| 2261 | tell_media_descriptions(&remote, &media_links, MediaDescription::camera(false), &mut media_description_request, timeline); |
| 2262 | } |
| 2263 | } |
| 2264 | Some(CallCommand::SelectCamera(choice)) => { |
| 2265 | camera_choice = choice; |
| 2266 | if local_video.camera_previewing() |
| 2267 | && let Err(error) = local_video.preview_camera(&camera_choice) |
| 2268 | { |
| 2269 | control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))); |
| 2270 | } else if local_video.camera_on() |
| 2271 | && let Err(error) = local_video.start_camera(&camera_choice) |
| 2272 | { |
| 2273 | control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))); |
| 2274 | } |
| 2275 | } |
| 2276 | Some(CallCommand::SetVideoQuality(quality)) => { |
| 2277 | local_video.set_video_quality(quality); |
| 2278 | if let Err(error) = local_video.refresh_camera_capture(&camera_choice) { |
| 2279 | control.send(CallUpdate::Notice(notice_with_detail(CAMERA_RESTART_NOTICE, error))); |
| 2280 | } |
| 2281 | if video.set_video_quality(quality) { |
| 2282 | send_receive_change(control, video.reselect(&roster)); |
| 2283 | } |
| 2284 | } |
| 2285 | Some(CallCommand::StartPortalShare(kind)) => { |
| 2286 | let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct; |
| 2287 | if !remote_set { |
| 2288 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 2289 | } else if local_hold { |
| 2290 | control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into())); |
| 2291 | } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) { |
| 2292 | control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into())); |
| 2293 | } else if direct |
| 2294 | && !local_video.sharing() |
| 2295 | && !local_video.has_share_line() |
| 2296 | && let Err(error) = attach_share_line(¤t.peer, &factory, &mut local_video, direct_video_mid.as_deref()) |
| 2297 | { |
| 2298 | control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))); |
| 2299 | } else if !local_video.sharing() && !video_possible(remote_set, layout, negotiator.path()) { |
| 2300 | if next.is_none() && negotiator.begin_conference_upgrade() { |
| 2301 | let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await; |
| 2302 | next = pending.or(next); |
| 2303 | } |
| 2304 | if next.is_some() { |
| 2305 | portal_pending = Some(kind); |
| 2306 | control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into())); |
| 2307 | } else { |
| 2308 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 2309 | } |
| 2310 | } else if let Err(error) = local_video.open_portal(kind, control.command_sender()) { |
| 2311 | control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))); |
| 2312 | } |
| 2313 | } |
| 2314 | Some(CallCommand::FinishPortalShare { source, generation }) => { |
| 2315 | if local_video.accept_portal(generation) { |
| 2316 | control.defer(CallCommand::StartShare(source)); |
| 2317 | } |
| 2318 | } |
| 2319 | Some(CallCommand::AbandonPortalShare) => { |
| 2320 | if local_video.portal_is_open() { |
| 2321 | local_video.stop_share(); |
| 2322 | } |
| 2323 | } |
| 2324 | Some(CallCommand::StartShare(source)) => { |
| 2325 | let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct; |
| 2326 | if !remote_set { |
| 2327 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 2328 | } else if local_hold { |
| 2329 | control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into())); |
| 2330 | } else if direct && local_video.share_sending() { |
| 2331 | match local_video.start_share(&source) { |
| 2332 | Ok(()) => announce_share(control, &source), |
| 2333 | Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))), |
| 2334 | } |
| 2335 | } else if direct && (same_peer.is_some() || glare_resend.is_some()) { |
| 2336 | control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into())); |
| 2337 | } else if direct |
| 2338 | && !local_video.has_share_line() |
| 2339 | && let Err(error) = attach_share_line(¤t.peer, &factory, &mut local_video, direct_video_mid.as_deref()) |
| 2340 | { |
| 2341 | control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))); |
| 2342 | } else if direct { |
| 2343 | match local_video.start_share(&source) { |
| 2344 | Ok(()) => { |
| 2345 | announce_share(control, &source); |
| 2346 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline); |
| 2347 | match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await { |
| 2348 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2349 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2350 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags }); |
| 2351 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2352 | same_peer_grace_until = None; |
| 2353 | } |
| 2354 | Err(error) => { |
| 2355 | timeline.record("share offer failed", error.to_string()); |
| 2356 | undo_change(Change::Share(true), &mut local_video, control); |
| 2357 | } |
| 2358 | } |
| 2359 | } |
| 2360 | Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))), |
| 2361 | } |
| 2362 | } else if !video_possible(remote_set, layout, negotiator.path()) { |
| 2363 | if next.is_none() && negotiator.begin_conference_upgrade() { |
| 2364 | let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await; |
| 2365 | next = pending.or(next); |
| 2366 | } |
| 2367 | if next.is_some() { |
| 2368 | share_pending = Some(source); |
| 2369 | control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into())); |
| 2370 | } else { |
| 2371 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 2372 | } |
| 2373 | } else { |
| 2374 | match local_video.start_share(&source) { |
| 2375 | Ok(()) => { |
| 2376 | announce_share(control, &source); |
| 2377 | tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline); |
| 2378 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline); |
| 2379 | } |
| 2380 | Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))), |
| 2381 | } |
| 2382 | } |
| 2383 | } |
| 2384 | Some(CallCommand::StopShare) => { |
| 2385 | let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct; |
| 2386 | share_pending = None; |
| 2387 | portal_pending = None; |
| 2388 | if local_video.portal_is_open() { |
| 2389 | local_video.stop_share(); |
| 2390 | } else if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) { |
| 2391 | control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into())); |
| 2392 | } else if direct && local_video.sharing() { |
| 2393 | local_video.stop_share(); |
| 2394 | clear_share(control); |
| 2395 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline); |
| 2396 | match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await { |
| 2397 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2398 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2399 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags }); |
| 2400 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2401 | same_peer_grace_until = None; |
| 2402 | } |
| 2403 | Err(error) => timeline.record("share offer failed", error.to_string()), |
| 2404 | } |
| 2405 | } else if local_video.sharing() { |
| 2406 | local_video.stop_share(); |
| 2407 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline); |
| 2408 | clear_share(control); |
| 2409 | tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline); |
| 2410 | } |
| 2411 | } |
| 2412 | Some(CallCommand::SetShareSound(on)) => { |
| 2413 | share_sound_wanted = on; |
| 2414 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline); |
| 2415 | } |
| 2416 | Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true), |
| 2417 | Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await { |
| 2418 | Ok(receipt) => { |
| 2419 | own_hand = receipt.state_id; |
| 2420 | control.send(CallUpdate::OwnHand(Some(receipt.rank))); |
| 2421 | } |
| 2422 | Err(error) => { |
| 2423 | timeline.record("raise hand failed", error.to_string()); |
| 2424 | control.send(CallUpdate::OwnHand(None)); |
| 2425 | control.send(CallUpdate::Notice(RAISE_HAND_FAILED_NOTICE.into())); |
| 2426 | } |
| 2427 | }, |
| 2428 | Some(CallCommand::SetHand(false)) => { |
| 2429 | let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect(); |
| 2430 | own_hand = None; |
| 2431 | control.send(CallUpdate::OwnHand(None)); |
| 2432 | if !state_ids.is_empty() |
| 2433 | && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await |
| 2434 | { |
| 2435 | timeline.record("lower hand failed", error.to_string()); |
| 2436 | control.send(CallUpdate::Notice(LOWER_HAND_FAILED_NOTICE.into())); |
| 2437 | } |
| 2438 | } |
| 2439 | Some(CallCommand::LowerHand { mri }) => { |
| 2440 | let state_ids: Vec<String> = roster.hand_of(&mri).map(|hand| hand.state_id.clone()).into_iter().collect(); |
| 2441 | if !state_ids.is_empty() |
| 2442 | && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await |
| 2443 | { |
| 2444 | timeline.record("lower hand failed", error.to_string()); |
| 2445 | control.send(CallUpdate::Notice(LOWER_THAT_HAND_FAILED_NOTICE.into())); |
| 2446 | } |
| 2447 | } |
| 2448 | Some(CallCommand::LowerAllHands) => { |
| 2449 | if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await { |
| 2450 | timeline.record("lower all hands failed", error.to_string()); |
| 2451 | control.send(CallUpdate::Notice(LOWER_ALL_HANDS_FAILED_NOTICE.into())); |
| 2452 | } |
| 2453 | } |
| 2454 | Some(CallCommand::Admit { mri }) => { |
| 2455 | let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 2456 | report_organizer_result(result, "admit", ADMIT_FAILED_NOTICE, control, timeline); |
| 2457 | } |
| 2458 | Some(CallCommand::AdmitAll) => { |
| 2459 | let mut result = Ok(202); |
| 2460 | for mri in roster.lobby_mris() { |
| 2461 | result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 2462 | if result.is_err() { |
| 2463 | break; |
| 2464 | } |
| 2465 | } |
| 2466 | report_organizer_result(result, "admit all", ADMIT_ALL_FAILED_NOTICE, control, timeline); |
| 2467 | } |
| 2468 | Some(CallCommand::Deny { mri }) => { |
| 2469 | let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 2470 | report_organizer_result(result, "deny", DENY_FAILED_NOTICE, control, timeline); |
| 2471 | } |
| 2472 | Some(CallCommand::RemoveParticipant { mri }) => { |
| 2473 | let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 2474 | report_organizer_result(result, "remove participant", REMOVE_PARTICIPANT_FAILED_NOTICE, control, timeline); |
| 2475 | } |
| 2476 | Some(CallCommand::MuteParticipant { mri }) => { |
| 2477 | let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await; |
| 2478 | report_organizer_result(result, "mute participant", MUTE_PARTICIPANT_FAILED_NOTICE, control, timeline); |
| 2479 | } |
| 2480 | Some(CallCommand::MuteAll) => { |
| 2481 | let others: Vec<String> = roster |
| 2482 | .members() |
| 2483 | .iter() |
| 2484 | .filter(|member| member.mri != own_mri && !member.in_lobby && !member.mri.starts_with(BOT_PREFIX)) |
| 2485 | .map(|member| member.mri.clone()) |
| 2486 | .collect(); |
| 2487 | let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await; |
| 2488 | report_organizer_result(result, "mute all", MUTE_ALL_FAILED_NOTICE, control, timeline); |
| 2489 | } |
| 2490 | Some(CallCommand::SetLock(locked)) => { |
| 2491 | let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await; |
| 2492 | if result.is_ok() { |
| 2493 | capability.locked = locked; |
| 2494 | control.send(CallUpdate::Capability(capability)); |
| 2495 | } |
| 2496 | report_organizer_result(result, "lock meeting", MEETING_LOCK_FAILED_NOTICE, control, timeline); |
| 2497 | } |
| 2498 | Some(CallCommand::SetRole { mri, role }) => { |
| 2499 | let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await; |
| 2500 | report_organizer_result(result, "change role", CHANGE_ROLE_FAILED_NOTICE, control, timeline); |
| 2501 | } |
| 2502 | Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => { |
| 2503 | let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default(); |
| 2504 | let mut result = Ok(200); |
| 2505 | for step in modality_steps(modality, allowed, capability, &limits) { |
| 2506 | result = match step { |
| 2507 | StateStep::Publish(state_type) => remote.signaling.publish_attendee_state(&remote.conversation, &remote.participant, state_type, &mri).await, |
| 2508 | StateStep::Remove(state_id) => remote.signaling.lower_hands(&remote.conversation, &remote.participant, &[state_id]).await.map(|()| 200), |
| 2509 | }; |
| 2510 | if result.is_err() { |
| 2511 | break; |
| 2512 | } |
| 2513 | } |
| 2514 | let notice = if modality == Modality::Mic { |
| 2515 | MIC_SETTING_FAILED_NOTICE |
| 2516 | } else { |
| 2517 | CAMERA_SETTING_FAILED_NOTICE |
| 2518 | }; |
| 2519 | report_organizer_result(result, "attendee modality", notice, control, timeline); |
| 2520 | } |
| 2521 | Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => { |
| 2522 | let result = match &meeting_target { |
| 2523 | Some(target) => meeting_options::write(&inner.session, target, &OptionWrite::restrictions(mic_off, camera_off)).await.map(|()| 200), |
| 2524 | None => Err(Error::Signaling("no meeting coordinates for the options".into())), |
| 2525 | }; |
| 2526 | if result.is_ok() { |
| 2527 | capability.attendee_mic_off = mic_off; |
| 2528 | capability.attendee_camera_off = camera_off; |
| 2529 | control.send(CallUpdate::Capability(capability)); |
| 2530 | } |
| 2531 | report_organizer_result(result, "attendee restrictions", ATTENDEE_SETTINGS_FAILED_NOTICE, control, timeline); |
| 2532 | } |
| 2533 | Some(CallCommand::Invite { callees, group_thread }) => { |
| 2534 | let thread = group_thread.or_else(|| meeting_chat.clone()); |
| 2535 | let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await; |
| 2536 | report_organizer_result(result, "invite", INVITE_PERSON_FAILED_NOTICE, control, timeline); |
| 2537 | } |
| 2538 | Some(CallCommand::LoadMeetingOptions) => { |
| 2539 | let update = match &meeting_target { |
| 2540 | Some(target) => meeting_options::fetch(&inner.session, target).await.map_err(|error| error.to_string()), |
| 2541 | None => Err("This meeting has no options page".to_owned()), |
| 2542 | }; |
| 2543 | control.send(CallUpdate::MeetingOptions(update)); |
| 2544 | } |
| 2545 | Some(CallCommand::SaveMeetingOptions(writes)) => { |
| 2546 | let update = match &meeting_target { |
| 2547 | Some(target) => save_meeting_options(&inner.session, target, &writes).await, |
| 2548 | None => Err("This meeting has no options page".to_owned()), |
| 2549 | }; |
| 2550 | if let Ok(options) = &update { |
| 2551 | let (mic_off, camera_off) = options.attendees_off(); |
| 2552 | capability.attendee_mic_off = mic_off; |
| 2553 | capability.attendee_camera_off = camera_off; |
| 2554 | control.send(CallUpdate::Capability(capability)); |
| 2555 | } |
| 2556 | control.send(CallUpdate::MeetingOptionsSaved(update)); |
| 2557 | } |
| 2558 | Some(CallCommand::Spotlight { mri }) => { |
| 2559 | let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await; |
| 2560 | report_organizer_result(result, "spotlight", SPOTLIGHT_FAILED_NOTICE, control, timeline); |
| 2561 | } |
| 2562 | Some(CallCommand::StopSpotlight { mri }) => { |
| 2563 | let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect(); |
| 2564 | if !state_ids.is_empty() { |
| 2565 | let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200); |
| 2566 | report_organizer_result(result, "stop spotlight", STOP_SPOTLIGHT_FAILED_NOTICE, control, timeline); |
| 2567 | } |
| 2568 | } |
| 2569 | Some(CallCommand::SetCaptions(on)) => { |
| 2570 | caption_flow.want(on); |
| 2571 | if on { |
| 2572 | caption_deadline = Some(Instant::now() + CAPTION_START_LIMIT); |
| 2573 | control.send(CallUpdate::Captions(CaptionState::Starting)); |
| 2574 | } else { |
| 2575 | caption_deadline = None; |
| 2576 | control.send(CallUpdate::Captions(CaptionState::Off)); |
| 2577 | } |
| 2578 | run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), &RecordingPlan::default(), &mut bot_pending, control, timeline).await; |
| 2579 | if caption_flow.on() { |
| 2580 | caption_deadline = None; |
| 2581 | } |
| 2582 | } |
| 2583 | Some(CallCommand::StartRecording { kind, title }) => { |
| 2584 | if !is_echo { |
| 2585 | recording_plan = RecordingPlan { title, kind, ..RecordingPlan::default() }; |
| 2586 | recording_flow.want(true); |
| 2587 | recording_deadline = Some(Instant::now() + RECORDING_START_LIMIT); |
| 2588 | control.send(CallUpdate::RecordingPending(true)); |
| 2589 | run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await; |
| 2590 | } |
| 2591 | } |
| 2592 | Some(CallCommand::StopRecording { scope }) => { |
| 2593 | if !is_echo { |
| 2594 | recording_plan.scope = scope; |
| 2595 | recording_flow.stop(); |
| 2596 | recording_deadline = None; |
| 2597 | run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await; |
| 2598 | } |
| 2599 | } |
| 2600 | Some(CallCommand::SetCaptionLanguage(language)) => { |
| 2601 | if let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) |
| 2602 | && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await |
| 2603 | { |
| 2604 | timeline.record("caption language failed", error.to_string()); |
| 2605 | control.send(CallUpdate::Notice(CAPTION_LANGUAGE_FAILED_NOTICE.into())); |
| 2606 | } |
| 2607 | } |
| 2608 | Some(CallCommand::ConsentToRecording) => { |
| 2609 | match remote.signaling.consent_to_recording(&remote.conversation, &remote.participant, Consent::Give).await { |
| 2610 | Ok(_) => { |
| 2611 | consent_pending = false; |
| 2612 | control.send(CallUpdate::ConsentRequired(false)); |
| 2613 | } |
| 2614 | Err(error) => { |
| 2615 | timeline.record("recording consent failed", error.to_string()); |
| 2616 | control.send(CallUpdate::Notice(CONFIRM_RECORDING_FAILED_NOTICE.into())); |
| 2617 | } |
| 2618 | } |
| 2619 | } |
| 2620 | Some(CallCommand::Hold(hold)) => { |
| 2621 | if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || glare_resend.is_some() || next.is_some() { |
| 2622 | continue; |
| 2623 | } |
| 2624 | if hold && local_video.camera_on() { |
| 2625 | local_video.stop_camera(); |
| 2626 | control.send(CallUpdate::Camera(false)); |
| 2627 | } |
| 2628 | let camera = !hold && local_video.camera_on(); |
| 2629 | match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), hold, camera, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await { |
| 2630 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2631 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2632 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags }); |
| 2633 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2634 | same_peer_grace_until = None; |
| 2635 | } |
| 2636 | Err(error) => { |
| 2637 | timeline.record("hold failed", error.to_string()); |
| 2638 | control.send(CallUpdate::Notice(if hold { |
| 2639 | HOLD_FAILED_NOTICE.into() |
| 2640 | } else { |
| 2641 | RESUME_FAILED_NOTICE.into() |
| 2642 | })); |
| 2643 | } |
| 2644 | } |
| 2645 | } |
| 2646 | Some(CallCommand::Transfer { target, replaces }) => { |
| 2647 | let Some(url) = media_links.get("transfer").cloned() else { |
| 2648 | control.send(CallUpdate::TransferResult { succeeded: false }); |
| 2649 | control.send(CallUpdate::Notice(TRANSFER_NOT_ALLOWED_NOTICE.into())); |
| 2650 | continue; |
| 2651 | }; |
| 2652 | let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() }; |
| 2653 | match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await { |
| 2654 | Ok(()) => control.send(CallUpdate::Notice(notice_with_detail( |
| 2655 | TRANSFERRING_NOTICE, |
| 2656 | target.display_name, |
| 2657 | ))), |
| 2658 | Err(error) => { |
| 2659 | timeline.record("transfer failed", error.to_string()); |
| 2660 | control.send(CallUpdate::TransferResult { succeeded: false }); |
| 2661 | control.send(CallUpdate::Notice(TRANSFER_CALL_FAILED_NOTICE.into())); |
| 2662 | } |
| 2663 | } |
| 2664 | } |
| 2665 | Some(CallCommand::OpenWhiteboard { title }) => { |
| 2666 | let Some(target) = meeting_target.clone() else { |
| 2667 | control.send(CallUpdate::Notice(WHITEBOARDS_MEETINGS_ONLY_NOTICE.into())); |
| 2668 | continue; |
| 2669 | }; |
| 2670 | let session = inner.session.clone(); |
| 2671 | let updates = control.updates(); |
| 2672 | tokio::spawn(async move { |
| 2673 | let update = match whiteboard::fetch_board(&session, &target, &title).await { |
| 2674 | Ok(url) => CallUpdate::WhiteboardUrl(url), |
| 2675 | Err(_) => CallUpdate::Notice(WHITEBOARD_OPEN_FAILED_NOTICE.into()), |
| 2676 | }; |
| 2677 | let _ = updates.send(update); |
| 2678 | }); |
| 2679 | } |
| 2680 | Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await, |
| 2681 | Some(CallCommand::SetIncomingVideo(enabled)) => { |
| 2682 | video.set_incoming_enabled(enabled); |
| 2683 | if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) { |
| 2684 | let key = VideoKey::Person(mri.clone()); |
| 2685 | control.video.forget(&key); |
| 2686 | video.router().set(mid, enabled.then_some(key)); |
| 2687 | } |
| 2688 | send_receive_change(control, video.reselect(&roster)); |
| 2689 | control.send(CallUpdate::IncomingVideo(enabled)); |
| 2690 | } |
| 2691 | Some(CallCommand::SetVideoWants(wants)) => { |
| 2692 | if video.set_wants(wants) { |
| 2693 | send_receive_change(control, video.reselect(&roster)); |
| 2694 | } |
| 2695 | } |
| 2696 | Some(CallCommand::SetShareMotion(on)) => local_video.set_motion(on), |
| 2697 | Some(CallCommand::SetShareStandout(on)) => local_video.set_standout(on), |
| 2698 | Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects), |
| 2699 | Some(CallCommand::SendReaction(reaction)) => { |
| 2700 | if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await { |
| 2701 | timeline.record("reaction failed", error.to_string()); |
| 2702 | control.send(CallUpdate::Notice(REACTION_FAILED_NOTICE.into())); |
| 2703 | } |
| 2704 | } |
| 2705 | Some(CallCommand::EndMeeting) => { |
| 2706 | if is_meeting { |
| 2707 | match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await { |
| 2708 | Ok(()) => { |
| 2709 | live.skip_leave = true; |
| 2710 | report.left_cleanly = true; |
| 2711 | } |
| 2712 | Err(error) => timeline.record("end meeting failed", error.to_string()), |
| 2713 | } |
| 2714 | } |
| 2715 | advance(state, CallSignal::LocalLeave, control); |
| 2716 | break; |
| 2717 | } |
| 2718 | Some(CallCommand::Hangup) | None => { |
| 2719 | advance(state, CallSignal::LocalLeave, control); |
| 2720 | break; |
| 2721 | } |
| 2722 | }, |
| 2723 | _ = stats_tick.tick(), if remote_set => { |
| 2724 | let speaking = active_speakers::speaking_sources(&active_speakers::audio_sources(¤t.peer)); |
| 2725 | if speaking != speaking_sources { |
| 2726 | if speaking_sources.is_empty() && !speaker_sources_seen { |
| 2727 | speaker_sources_seen = true; |
| 2728 | timeline.record("active speakers", format!("{} source(s) from RTP", speaking.len())); |
| 2729 | } |
| 2730 | speaking_sources = speaking; |
| 2731 | let mut speakers = roster.mris_for_sources(&speaking_sources); |
| 2732 | if speakers.is_empty() && !speaking_sources.is_empty() && layout == Layout::OneToOne { |
| 2733 | speakers = roster.entries().into_iter().map(|entry| entry.mri).filter(|mri| *mri != own_mri).collect(); |
| 2734 | } |
| 2735 | if video.note_speakers(&speakers) { |
| 2736 | send_receive_change(control, video.reselect(&roster)); |
| 2737 | } |
| 2738 | control.send(CallUpdate::Speakers(speakers)); |
| 2739 | } |
| 2740 | let snapshot = collect_stats(¤t.peer, &layout_plan.screen_share_mids).await; |
| 2741 | ticks += 1; |
| 2742 | if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) { |
| 2743 | caption_deadline = None; |
| 2744 | caption_flow.failed(); |
| 2745 | timeline.record("captions", "did not start in time"); |
| 2746 | control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into()))); |
| 2747 | } |
| 2748 | if recording_deadline.is_some_and(|deadline| Instant::now() >= deadline) { |
| 2749 | recording_deadline = None; |
| 2750 | recording_flow.failed(); |
| 2751 | timeline.record("recording", "did not start in time"); |
| 2752 | control.send(CallUpdate::RecordingPending(false)); |
| 2753 | control.send(CallUpdate::Notice(RECORDING_NOT_STARTED_NOTICE.into())); |
| 2754 | } |
| 2755 | if layout == Layout::Conference |
| 2756 | && let Some(size) = local_video.camera_size() |
| 2757 | && let Some(url) = media_links.get("applyChannelParameters").cloned() |
| 2758 | && let Some(body) = |
| 2759 | send_capabilities.body_for(size, local_video.video_quality()) |
| 2760 | { |
| 2761 | let signaling = signaling.clone(); |
| 2762 | let timeline = timeline.clone(); |
| 2763 | tokio::spawn(async move { |
| 2764 | match signaling.post_json(SEND_CAPABILITIES_LABEL, &url, body).await { |
| 2765 | Ok(()) => timeline.record("send capabilities", format!("{}x{} accepted", size.0, size.1)), |
| 2766 | Err(error) => timeline.record("send capabilities failed", error.to_string()), |
| 2767 | } |
| 2768 | }); |
| 2769 | } |
| 2770 | for (source, refreshed) in local_video.refresh_send_limits() { |
| 2771 | match refreshed { |
| 2772 | Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?} after a frame size change")), |
| 2773 | Ok(None) => {} |
| 2774 | Err(error) => timeline.record("send limits failed", error.to_string()), |
| 2775 | } |
| 2776 | } |
| 2777 | if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS) |
| 2778 | && let Some(average_ms) = local_video.blur_average_ms() |
| 2779 | { |
| 2780 | control.send(CallUpdate::BlurTiming(average_ms)); |
| 2781 | if let Some(model) = local_video.blur_model().filter(|model| Some(*model) != segmentation_model) { |
| 2782 | timeline.record("segmentation model", format!("{model}, effects {average_ms:.1} ms per frame")); |
| 2783 | segmentation_model = Some(model); |
| 2784 | } |
| 2785 | } |
| 2786 | if ticks.is_multiple_of(HEALTH_EVERY_TICKS) { |
| 2787 | control.send(CallUpdate::Sample(StatsSample { |
| 2788 | audio_in_packets: snapshot.inbound_packets, |
| 2789 | audio_out_packets: snapshot.outbound_packets, |
| 2790 | audio_in_level: snapshot.audio_level, |
| 2791 | audio_out_level: snapshot.local_level, |
| 2792 | video: VideoReport { |
| 2793 | frames_received: live.video_counters.received.load(Ordering::Relaxed), |
| 2794 | frames_published: live.video_counters.published.load(Ordering::Relaxed), |
| 2795 | ..snapshot.video.clone() |
| 2796 | }, |
| 2797 | share_in_packets: snapshot.share_inbound_packets, |
| 2798 | share_out_packets: snapshot.share_outbound_packets, |
| 2799 | })); |
| 2800 | } |
| 2801 | if ticks.is_multiple_of(HEALTH_EVERY_TICKS) |
| 2802 | && snapshot.selected_pair.is_some() |
| 2803 | && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health) |
| 2804 | { |
| 2805 | let quality = quality_tracker.observe(std::time::Instant::now(), &sample); |
| 2806 | control.send(CallUpdate::Health(CallHealth { |
| 2807 | level: quality.level, |
| 2808 | cpu_limited: quality.cpu_limited, |
| 2809 | sample, |
| 2810 | transport: snapshot.transport.clone(), |
| 2811 | path: negotiator.path(), |
| 2812 | })); |
| 2813 | } |
| 2814 | let local_level = if muted && software_audio.is_none() { 0.0 } else { snapshot.local_level as f32 }; |
| 2815 | control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 }); |
| 2816 | if snapshot.selected_pair.is_some() { |
| 2817 | report.selected_pair = snapshot.selected_pair.clone(); |
| 2818 | report.tls_version = snapshot.tls_version.clone(); |
| 2819 | report.dtls_cipher = snapshot.dtls_cipher.clone(); |
| 2820 | report.srtp_cipher = snapshot.srtp_cipher.clone(); |
| 2821 | } |
| 2822 | report.inbound_packets = snapshot.inbound_packets; |
| 2823 | report.inbound_bytes = snapshot.inbound_bytes; |
| 2824 | report.outbound_packets = snapshot.outbound_packets; |
| 2825 | report.video = VideoReport { |
| 2826 | frames_received: live.video_counters.received.load(Ordering::Relaxed), |
| 2827 | frames_published: live.video_counters.published.load(Ordering::Relaxed), |
| 2828 | ..snapshot.video.clone() |
| 2829 | }; |
| 2830 | if ticks.is_multiple_of(TICKS_PER_SECOND) { |
| 2831 | second += 1; |
| 2832 | let (decoded_rms, ratio) = { |
| 2833 | let recording = recording.lock().await; |
| 2834 | recording.per_second.last().copied().unwrap_or_default() |
| 2835 | }; |
| 2836 | if snapshot.inbound_packets > previous_packets { |
| 2837 | report.seconds_with_inbound_audio += 1; |
| 2838 | } |
| 2839 | previous_packets = snapshot.inbound_packets; |
| 2840 | report.seconds.push(AudioSecond { |
| 2841 | second, |
| 2842 | packets: snapshot.inbound_packets, |
| 2843 | bytes: snapshot.inbound_bytes, |
| 2844 | audio_level: snapshot.audio_level, |
| 2845 | decoded_rms, |
| 2846 | tone_ratio: ratio, |
| 2847 | }); |
| 2848 | control.send(CallUpdate::Stats { |
| 2849 | inbound_packets: snapshot.inbound_packets, |
| 2850 | outbound_packets: snapshot.outbound_packets, |
| 2851 | }); |
| 2852 | timeline.record( |
| 2853 | "stats", |
| 2854 | format!( |
| 2855 | "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={} video in packets={} decoded={} {}x{} out packets={} encoded={} {}x{} mixer reports {} (rtt {:.0} ms) out bytes={} sources={:?} video senders={:?}{}{}", |
| 2856 | snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state, |
| 2857 | snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height, |
| 2858 | snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height, |
| 2859 | snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders, |
| 2860 | snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default(), |
| 2861 | local_video.camera_capture_summary().unwrap_or_default() |
| 2862 | ), |
| 2863 | ); |
| 2864 | } |
| 2865 | } |
| 2866 | Some(()) = device_changes.recv() => { |
| 2867 | device_debounce.signal(Instant::now()); |
| 2868 | } |
| 2869 | _ = sleep_until(device_debounce.deadline().unwrap_or_else(far_future)), if device_debounce.deadline().is_some() => { |
| 2870 | if device_debounce.take_due(Instant::now()) { |
| 2871 | let previous = std::mem::replace(&mut device_lists, devices::list_devices(&factory)); |
| 2872 | control.send(CallUpdate::Devices(device_lists.clone())); |
| 2873 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 2874 | let input_changed = follow_device_change(Flow::Capture, (&previous.inputs, &device_lists.inputs), &input, &mut applied_input, |index| devices::select_input_index(&factory, index), timeline, control); |
| 2875 | let output_changed = follow_device_change(Flow::Render, (&previous.outputs, &device_lists.outputs), &output, &mut applied_output, |index| devices::select_output_index(&factory, index), timeline, control); |
| 2876 | if input_changed || output_changed { |
| 2877 | record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref()); |
| 2878 | } |
| 2879 | if input_changed && software_audio.is_some() { |
| 2880 | sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline); |
| 2881 | } |
| 2882 | } |
| 2883 | } |
| 2884 | } |
| 2885 | _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => { |
| 2886 | advance(state, CallSignal::ReconnectTimedOut, control); |
| 2887 | break; |
| 2888 | } |
| 2889 | _ = sleep_until(leave_at.unwrap_or_else(far_future)), if leave_at.is_some() => { |
| 2890 | advance(state, CallSignal::LocalLeave, control); |
| 2891 | break; |
| 2892 | } |
| 2893 | _ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => { |
| 2894 | if let Some(pending) = next.as_mut().filter(|pending| pending.connected && pending.offered.is_none()) { |
| 2895 | pending.retargeted = true; |
| 2896 | timeline.record("escalation", "no retargetCompletion, switching anyway"); |
| 2897 | } else if let Some(pending) = next.take() { |
| 2898 | pending.session.peer.close(); |
| 2899 | negotiator.escalation_failed(); |
| 2900 | start_camera_pending = false; |
| 2901 | if local_video.camera_previewing() { |
| 2902 | local_video.stop_camera(); |
| 2903 | control.send(CallUpdate::Camera(false)); |
| 2904 | } |
| 2905 | share_pending = None; |
| 2906 | portal_pending = None; |
| 2907 | settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control); |
| 2908 | timeline.record("escalation failed", "no answer for the new peer connection in time"); |
| 2909 | control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into())); |
| 2910 | } |
| 2911 | } |
| 2912 | _ = sleep_until(glare_at.unwrap_or_else(far_future)), if glare_at.is_some() => { |
| 2913 | let resend = glare_resend.take(); |
| 2914 | if let Some(resend) = resend.as_ref().filter(|_| same_peer.is_some() || next.is_some()) { |
| 2915 | timeline.record("glare", "another change took over, ours is dropped"); |
| 2916 | undo_change(resend.change, &mut local_video, control); |
| 2917 | } else if let Some(resend) = resend.as_ref().filter(|resend| layout == Layout::OneToOne && negotiator.path() == MediaPath::Mixer && !matches!(resend.change, Change::Hold(_))) { |
| 2918 | if negotiator.begin_conference_upgrade() { |
| 2919 | let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await; |
| 2920 | if pending.is_none() { |
| 2921 | drop_local_media(&mut local_video, control); |
| 2922 | } |
| 2923 | next = pending.or(next); |
| 2924 | } else { |
| 2925 | undo_change(resend.change, &mut local_video, control); |
| 2926 | } |
| 2927 | } else if let Some(resend) = resend { |
| 2928 | let (hold, camera, share) = match resend.change { |
| 2929 | Change::Hold(hold) => (hold, !hold && local_video.camera_on(), local_video.sharing()), |
| 2930 | _ => (local_hold, local_video.camera_on(), local_video.sharing()), |
| 2931 | }; |
| 2932 | match offer_same_peer(¤t.peer, ¤t.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), hold, camera, share, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await { |
| 2933 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2934 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2935 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags }); |
| 2936 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2937 | same_peer_grace_until = None; |
| 2938 | } |
| 2939 | Err(error) => { |
| 2940 | timeline.record("offer after glare failed", error.to_string()); |
| 2941 | undo_change(resend.change, &mut local_video, control); |
| 2942 | } |
| 2943 | } |
| 2944 | } |
| 2945 | } |
| 2946 | _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => { |
| 2947 | same_peer_deadline = None; |
| 2948 | if same_peer.is_some() { |
| 2949 | same_peer_grace_until = Some(Instant::now() + SAME_PEER_LATE_GRACE); |
| 2950 | timeline.record( |
| 2951 | "same-peer offer", |
| 2952 | "no answer yet, waiting a little longer", |
| 2953 | ); |
| 2954 | } |
| 2955 | } |
| 2956 | _ = sleep_until(same_peer_grace_until.unwrap_or_else(far_future)), if same_peer_grace_until.is_some() => { |
| 2957 | same_peer_grace_until = None; |
| 2958 | if let Some(pending) = same_peer.take() { |
| 2959 | timeline.record("same-peer offer", "no answer in time"); |
| 2960 | negotiator.same_peer_offer_failed(); |
| 2961 | rollback_offer(¤t.peer).await; |
| 2962 | undo_change(pending.change, &mut local_video, control); |
| 2963 | } |
| 2964 | } |
| 2965 | _ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => { |
| 2966 | timeline.record("no answer", "outgoing call timed out"); |
| 2967 | live.cancel_leave = true; |
| 2968 | advance(state, CallSignal::RemoteEnd(EndKind::NoAnswer), control); |
| 2969 | break; |
| 2970 | } |
| 2971 | _ = sleep_until(keep_alive_at.unwrap_or_else(far_future)), if keep_alive_at.is_some() => { |
| 2972 | keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds)); |
| 2973 | let remote = remote.clone(); |
| 2974 | let links = links.clone(); |
| 2975 | let call_leg = keep_alive_link.clone(); |
| 2976 | tokio::spawn(async move { |
| 2977 | if let Some(url) = call_leg { |
| 2978 | let _ = remote.signaling.keep_call_alive(&url).await; |
| 2979 | } |
| 2980 | let _ = remote.signaling.keep_conversation_alive(&remote.conversation, &remote.participant, &links).await; |
| 2981 | }); |
| 2982 | } |
| 2983 | } |
| 2984 | } |
| 2985 | if software_audio.is_some() { |
| 2986 | timeline.record("software audio", "stopping before tear down"); |
| 2987 | drop(software_audio); |
| 2988 | } |
| 2989 | live.callbacks = Some(callbacks); |
| 2990 | Ok(()) |
| 2991 | } |
| 2992 | |
| 2993 | #[allow(clippy::too_many_arguments)] |
| 2994 | async fn start_escalation( |
| 2995 | factory: &PeerConnectionFactory, |
| 2996 | grant: &RelayGrant, |
| 2997 | options: &CallOptions, |
| 2998 | track: &RtcAudioTrack, |
| 2999 | remote: &RemoteCall, |
| 3000 | links: &CallbackLinks, |
| 3001 | media_leg_id: &str, |
| 3002 | acceptance_links: &BTreeMap<String, String>, |
| 3003 | ) -> Result<NextPeer> { |
| 3004 | let url = acceptance_links |
| 3005 | .get("mediaRenegotiation") |
| 3006 | .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?; |
| 3007 | let session = open_peer(factory, grant, &options.relay_host, false)?; |
| 3008 | let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?; |
| 3009 | let body = renegotiation_body( |
| 3010 | &remote.participant, |
| 3011 | links, |
| 3012 | &media.signaled.sdp, |
| 3013 | media_leg_id, |
| 3014 | &media.modalities, |
| 3015 | true, |
| 3016 | false, |
| 3017 | ); |
| 3018 | let reply_tags = offer_reply_tags(&body); |
| 3019 | remote |
| 3020 | .signaling |
| 3021 | .post_json("POST mediaRenegotiation", url, body) |
| 3022 | .await?; |
| 3023 | Ok(NextPeer { |
| 3024 | session, |
| 3025 | offered: Some(media), |
| 3026 | reply_tags, |
| 3027 | deadline: Some(Instant::now() + NEXT_PEER_LIMIT), |
| 3028 | connected: false, |
| 3029 | retargeted: false, |
| 3030 | }) |
| 3031 | } |
| 3032 | |
| 3033 | #[allow(clippy::too_many_arguments)] |
| 3034 | async fn escalate( |
| 3035 | factory: &PeerConnectionFactory, |
| 3036 | grant: &RelayGrant, |
| 3037 | options: &CallOptions, |
| 3038 | track: &RtcAudioTrack, |
| 3039 | remote: &RemoteCall, |
| 3040 | links: &CallbackLinks, |
| 3041 | media_leg_id: &str, |
| 3042 | acceptance_links: &BTreeMap<String, String>, |
| 3043 | negotiator: &mut MediaNegotiator, |
| 3044 | live: &mut Live, |
| 3045 | timeline: &Timeline, |
| 3046 | ) -> Option<NextPeer> { |
| 3047 | match start_escalation( |
| 3048 | factory, |
| 3049 | grant, |
| 3050 | options, |
| 3051 | track, |
| 3052 | remote, |
| 3053 | links, |
| 3054 | media_leg_id, |
| 3055 | acceptance_links, |
| 3056 | ) |
| 3057 | .await |
| 3058 | { |
| 3059 | Ok(pending) => { |
| 3060 | timeline.record("escalation", "new peer connection, new offer sent"); |
| 3061 | if let Some(media) = &pending.offered { |
| 3062 | timeline.record_sdp("local offer", &media.signaled.sdp); |
| 3063 | } |
| 3064 | live.peers.push(pending.session.peer.clone()); |
| 3065 | Some(pending) |
| 3066 | } |
| 3067 | Err(error) => { |
| 3068 | negotiator.escalation_failed(); |
| 3069 | timeline.record("escalation failed", error.to_string()); |
| 3070 | None |
| 3071 | } |
| 3072 | } |
| 3073 | } |
| 3074 | |
| 3075 | async fn answer_on_new_peer( |
| 3076 | factory: &PeerConnectionFactory, |
| 3077 | grant: &RelayGrant, |
| 3078 | options: &CallOptions, |
| 3079 | track: &RtcAudioTrack, |
| 3080 | teams_offer: &str, |
| 3081 | ) -> Result<(PeerSession, AnsweredMedia)> { |
| 3082 | let session = open_peer(factory, grant, &options.relay_host, false)?; |
| 3083 | let answered = answer_offer( |
| 3084 | &session.peer, |
| 3085 | Some(track), |
| 3086 | teams_offer, |
| 3087 | AnswerVideo::Reject, |
| 3088 | None, |
| 3089 | false, |
| 3090 | None, |
| 3091 | ) |
| 3092 | .await?; |
| 3093 | Ok((session, answered)) |
| 3094 | } |
| 3095 | |
| 3096 | async fn send_media_answer( |
| 3097 | remote: &RemoteCall, |
| 3098 | links: &CallbackLinks, |
| 3099 | reply_links: &BTreeMap<String, String>, |
| 3100 | answered: &AnsweredMedia, |
| 3101 | media_leg_id: &str, |
| 3102 | ) -> Result<()> { |
| 3103 | let url = reply_links |
| 3104 | .get("mediaAnswer") |
| 3105 | .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?; |
| 3106 | let body = escalation_answer_body( |
| 3107 | &remote.participant, |
| 3108 | links, |
| 3109 | &answered.answer_sdp, |
| 3110 | media_leg_id, |
| 3111 | ); |
| 3112 | remote |
| 3113 | .signaling |
| 3114 | .post_json("POST mediaAnswer", url, body) |
| 3115 | .await |
| 3116 | } |
| 3117 | |
| 3118 | #[allow(clippy::too_many_arguments)] |
| 3119 | fn negotiate_video( |
| 3120 | video: &mut VideoReceive, |
| 3121 | signaling: &Arc<Signaling>, |
| 3122 | control: &CallControl, |
| 3123 | timeline: &Timeline, |
| 3124 | answer_sdp: &str, |
| 3125 | media: &OfferedMedia, |
| 3126 | from_mixer: bool, |
| 3127 | links: &BTreeMap<String, String>, |
| 3128 | roster: &Roster, |
| 3129 | ) { |
| 3130 | let streams = match stream_lines(answer_sdp, &media.signaled.lines) { |
| 3131 | Ok(streams) => streams, |
| 3132 | Err(error) => { |
| 3133 | timeline.record("video slots unknown", error.to_string()); |
| 3134 | return; |
| 3135 | } |
| 3136 | }; |
| 3137 | let table = SlotTable::from_streams(&streams); |
| 3138 | let link = links |
| 3139 | .get("applyChannelParameters") |
| 3140 | .or_else(|| links.get("controlVideoStreaming")); |
| 3141 | timeline.record( |
| 3142 | "video slots", |
| 3143 | format!( |
| 3144 | "{} receive slot(s), screen {}, fromMixer={from_mixer}, request link {}", |
| 3145 | table.people.len(), |
| 3146 | table.screen.is_some(), |
| 3147 | link.is_some() |
| 3148 | ), |
| 3149 | ); |
| 3150 | let requester = link.filter(|_| from_mixer).map(|url| { |
| 3151 | SourceRequester::start( |
| 3152 | signaling.clone(), |
| 3153 | url.clone(), |
| 3154 | video.router().clone(), |
| 3155 | control.video.clone(), |
| 3156 | timeline.clone(), |
| 3157 | ) |
| 3158 | }); |
| 3159 | video.negotiated(table, requester); |
| 3160 | send_receive_change(control, video.reselect(roster)); |
| 3161 | } |
| 3162 | |
| 3163 | async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> { |
| 3164 | match mode { |
| 3165 | VideoMode::Pattern => vec![CameraDevice { |
| 3166 | key: "pattern".into(), |
| 3167 | name: "Test pattern".into(), |
| 3168 | }], |
| 3169 | VideoMode::Off => Vec::new(), |
| 3170 | VideoMode::Platform => tokio::task::spawn_blocking(list_cameras) |
| 3171 | .await |
| 3172 | .unwrap_or_default(), |
| 3173 | } |
| 3174 | } |
| 3175 | |
| 3176 | fn refresh_cameras( |
| 3177 | updates: mpsc::UnboundedSender<CallUpdate>, |
| 3178 | mode: VideoMode, |
| 3179 | timeline: Timeline, |
| 3180 | ) { |
| 3181 | tokio::spawn(async move { |
| 3182 | let started = Instant::now(); |
| 3183 | let cameras = camera_devices(mode).await; |
| 3184 | timeline.record( |
| 3185 | "camera list", |
| 3186 | format!( |
| 3187 | "{} camera(s) in {} ms", |
| 3188 | cameras.len(), |
| 3189 | started.elapsed().as_millis() |
| 3190 | ), |
| 3191 | ); |
| 3192 | let _ = updates.send(CallUpdate::Cameras(cameras)); |
| 3193 | }); |
| 3194 | } |
| 3195 | |
| 3196 | const SHARE_THUMBNAIL_WINDOWS: usize = 12; |
| 3197 | const SHARE_THUMBNAIL_WIDTH: u32 = 320; |
| 3198 | const SHARE_THUMBNAIL_HEIGHT: u32 = 180; |
| 3199 | |
| 3200 | fn announce_share(control: &CallControl, source: &ShareSource) { |
| 3201 | control.send(CallUpdate::ShareKind(Some(source.kind))); |
| 3202 | control.send(CallUpdate::LocalShare(Some(source.label()))); |
| 3203 | } |
| 3204 | |
| 3205 | fn clear_share(control: &CallControl) { |
| 3206 | control.send(CallUpdate::ShareKind(None)); |
| 3207 | control.send(CallUpdate::LocalShare(None)); |
| 3208 | } |
| 3209 | |
| 3210 | fn refresh_share_sources( |
| 3211 | updates: mpsc::UnboundedSender<CallUpdate>, |
| 3212 | mode: VideoMode, |
| 3213 | with_thumbnails: bool, |
| 3214 | ) { |
| 3215 | tokio::spawn(async move { |
| 3216 | let picker = current_share_picker(); |
| 3217 | let sources = match mode { |
| 3218 | VideoMode::Pattern => vec![ |
| 3219 | ShareSource { |
| 3220 | id: 1, |
| 3221 | kind: ShareKind::Screen, |
| 3222 | title: "Test screen".into(), |
| 3223 | }, |
| 3224 | ShareSource { |
| 3225 | id: 2, |
| 3226 | kind: ShareKind::Window, |
| 3227 | title: "Test window".into(), |
| 3228 | }, |
| 3229 | ], |
| 3230 | VideoMode::Off => Vec::new(), |
| 3231 | VideoMode::Platform if picker == SharePicker::Portal => Vec::new(), |
| 3232 | VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources) |
| 3233 | .await |
| 3234 | .unwrap_or_default(), |
| 3235 | }; |
| 3236 | let sources = share_sources_for_menu(picker, sources); |
| 3237 | let _ = updates.send(CallUpdate::ShareSources(sources.clone())); |
| 3238 | if picker == SharePicker::Portal || !with_thumbnails { |
| 3239 | return; |
| 3240 | } |
| 3241 | let wanted: Vec<ShareSource> = sources |
| 3242 | .iter() |
| 3243 | .filter(|source| source.kind == ShareKind::Screen) |
| 3244 | .chain( |
| 3245 | sources |
| 3246 | .iter() |
| 3247 | .filter(|source| source.kind == ShareKind::Window) |
| 3248 | .take(SHARE_THUMBNAIL_WINDOWS), |
| 3249 | ) |
| 3250 | .cloned() |
| 3251 | .collect(); |
| 3252 | for source in wanted { |
| 3253 | let picture = match mode { |
| 3254 | VideoMode::Platform => { |
| 3255 | let wanted = source.clone(); |
| 3256 | tokio::task::spawn_blocking(move || { |
| 3257 | share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT) |
| 3258 | }) |
| 3259 | .await |
| 3260 | .ok() |
| 3261 | .flatten() |
| 3262 | } |
| 3263 | VideoMode::Pattern => Some(VideoPicture::solid( |
| 3264 | SHARE_THUMBNAIL_WIDTH, |
| 3265 | SHARE_THUMBNAIL_HEIGHT, |
| 3266 | 120, |
| 3267 | 80, |
| 3268 | 40, |
| 3269 | )), |
| 3270 | VideoMode::Off => None, |
| 3271 | }; |
| 3272 | if let Some(picture) = picture |
| 3273 | && updates |
| 3274 | .send(CallUpdate::ShareThumbnail { |
| 3275 | source, |
| 3276 | picture: Arc::new(picture), |
| 3277 | }) |
| 3278 | .is_err() |
| 3279 | { |
| 3280 | return; |
| 3281 | } |
| 3282 | } |
| 3283 | }); |
| 3284 | } |
| 3285 | |
| 3286 | fn tell_media_descriptions( |
| 3287 | remote: &RemoteCall, |
| 3288 | links: &BTreeMap<String, String>, |
| 3289 | description: MediaDescription, |
| 3290 | request_id: &mut u32, |
| 3291 | timeline: &Timeline, |
| 3292 | ) { |
| 3293 | let Some(url) = links.get("updateMediaDescriptions").cloned() else { |
| 3294 | timeline.record("updateMediaDescriptions skipped", "no link from the mixer"); |
| 3295 | return; |
| 3296 | }; |
| 3297 | *request_id += 1; |
| 3298 | let request_id = *request_id; |
| 3299 | let signaling = remote.signaling.clone(); |
| 3300 | let timeline = timeline.clone(); |
| 3301 | tokio::spawn(async move { |
| 3302 | let sent = format!( |
| 3303 | "{} {} request {request_id}", |
| 3304 | description.mid, description.direction |
| 3305 | ); |
| 3306 | if let Err(error) = signaling |
| 3307 | .update_media_descriptions(&url, &[description], request_id) |
| 3308 | .await |
| 3309 | { |
| 3310 | timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}")); |
| 3311 | } |
| 3312 | }); |
| 3313 | } |
| 3314 | |
| 3315 | fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool { |
| 3316 | own.is_some_and(|own| own.thread_id == target.thread_id) |
| 3317 | } |
| 3318 | |
| 3319 | fn attach_share_line( |
| 3320 | peer: &PeerConnection, |
| 3321 | factory: &PeerConnectionFactory, |
| 3322 | local_video: &mut LocalVideo, |
| 3323 | camera_mid: Option<&str>, |
| 3324 | ) -> Result<()> { |
| 3325 | let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid)); |
| 3326 | if !local_video.has_lines() && camera.is_none() { |
| 3327 | return Err(Error::Webrtc("no video line negotiated".into())); |
| 3328 | } |
| 3329 | let share = add_share_line(peer, factory)?; |
| 3330 | local_video |
| 3331 | .add_share_line(share.clone(), camera) |
| 3332 | .inspect_err(|_| { |
| 3333 | let _ = share.stop(); |
| 3334 | }) |
| 3335 | } |
| 3336 | |
| 3337 | fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> { |
| 3338 | peer.transceivers() |
| 3339 | .into_iter() |
| 3340 | .find(|transceiver| transceiver.mid().as_deref() == Some(mid)) |
| 3341 | } |
| 3342 | |
| 3343 | fn start_camera_line( |
| 3344 | local_video: &mut LocalVideo, |
| 3345 | peer: &PeerConnection, |
| 3346 | direct_mid: Option<&str>, |
| 3347 | choice: &DeviceChoice, |
| 3348 | ) -> Result<()> { |
| 3349 | if !local_video.has_lines() { |
| 3350 | let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?; |
| 3351 | let camera = peer_transceiver(peer, mid) |
| 3352 | .ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?; |
| 3353 | if !matches!( |
| 3354 | camera.direction(), |
| 3355 | RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly |
| 3356 | ) { |
| 3357 | peer.add_track( |
| 3358 | MediaStreamTrack::Video(local_video.camera_track()), |
| 3359 | &[CAMERA_STREAM], |
| 3360 | ) |
| 3361 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 3362 | } |
| 3363 | local_video.set_lines(VideoLines { |
| 3364 | camera, |
| 3365 | share: None, |
| 3366 | })?; |
| 3367 | } |
| 3368 | local_video.start_camera(choice) |
| 3369 | } |
| 3370 | |
| 3371 | #[allow(clippy::too_many_arguments)] |
| 3372 | async fn offer_same_peer( |
| 3373 | peer: &PeerConnection, |
| 3374 | gathered: &Gathered, |
| 3375 | own_share_mid: Option<String>, |
| 3376 | plan: &OfferPlan, |
| 3377 | layout: Layout, |
| 3378 | camera_mid: &str, |
| 3379 | hold: bool, |
| 3380 | camera: bool, |
| 3381 | share: bool, |
| 3382 | remote: &RemoteCall, |
| 3383 | links: &CallbackLinks, |
| 3384 | media_leg_id: &str, |
| 3385 | media_links: &BTreeMap<String, String>, |
| 3386 | negotiator: &mut MediaNegotiator, |
| 3387 | ) -> Result<(String, SignaledOffer, Vec<String>)> { |
| 3388 | let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct; |
| 3389 | let url = media_links |
| 3390 | .get("mediaRenegotiation") |
| 3391 | .cloned() |
| 3392 | .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?; |
| 3393 | if !negotiator.begin_same_peer_offer() { |
| 3394 | return Err(Error::Signaling( |
| 3395 | "another media negotiation is running".into(), |
| 3396 | )); |
| 3397 | } |
| 3398 | let offered = build_same_peer_offer( |
| 3399 | peer, |
| 3400 | plan, |
| 3401 | layout, |
| 3402 | hold, |
| 3403 | camera, |
| 3404 | share, |
| 3405 | camera_mid, |
| 3406 | own_share_mid, |
| 3407 | direct.then_some(gathered), |
| 3408 | ) |
| 3409 | .await; |
| 3410 | let (text, signaled) = match offered { |
| 3411 | Ok(offered) => offered, |
| 3412 | Err(error) => { |
| 3413 | negotiator.same_peer_offer_failed(); |
| 3414 | return Err(error); |
| 3415 | } |
| 3416 | }; |
| 3417 | let modalities = offer_modalities( |
| 3418 | layout == Layout::OneToOne && camera && !hold, |
| 3419 | share && !hold, |
| 3420 | ); |
| 3421 | let body = renegotiation_body( |
| 3422 | &remote.participant, |
| 3423 | links, |
| 3424 | &signaled.sdp, |
| 3425 | media_leg_id, |
| 3426 | &modalities, |
| 3427 | false, |
| 3428 | direct, |
| 3429 | ); |
| 3430 | let reply_tags = offer_reply_tags(&body); |
| 3431 | if let Err(error) = remote |
| 3432 | .signaling |
| 3433 | .post_json("POST mediaRenegotiation (same peer)", &url, body) |
| 3434 | .await |
| 3435 | { |
| 3436 | negotiator.same_peer_offer_failed(); |
| 3437 | rollback_offer(peer).await; |
| 3438 | return Err(error); |
| 3439 | } |
| 3440 | Ok((text, signaled, reply_tags)) |
| 3441 | } |
| 3442 | |
| 3443 | #[allow(clippy::too_many_arguments)] |
| 3444 | async fn build_same_peer_offer( |
| 3445 | peer: &PeerConnection, |
| 3446 | plan: &OfferPlan, |
| 3447 | layout: Layout, |
| 3448 | hold: bool, |
| 3449 | camera: bool, |
| 3450 | share: bool, |
| 3451 | camera_mid: &str, |
| 3452 | own_share_mid: Option<String>, |
| 3453 | gathered: Option<&Gathered>, |
| 3454 | ) -> Result<(String, SignaledOffer)> { |
| 3455 | let offer = peer |
| 3456 | .create_offer(OfferOptions { |
| 3457 | offer_to_receive_audio: true, |
| 3458 | offer_to_receive_video: true, |
| 3459 | ..OfferOptions::default() |
| 3460 | }) |
| 3461 | .await |
| 3462 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 3463 | let offer_text = offer.to_string(); |
| 3464 | let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text)); |
| 3465 | let remote_shares = share_mid.as_deref().is_some_and(|mid| { |
| 3466 | peer.current_remote_description() |
| 3467 | .and_then(|remote| direction_of(&remote.to_string(), mid)) |
| 3468 | .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv")) |
| 3469 | }); |
| 3470 | let text = directions_for( |
| 3471 | layout, |
| 3472 | false, |
| 3473 | camera, |
| 3474 | share, |
| 3475 | camera_mid, |
| 3476 | share_mid.as_deref(), |
| 3477 | remote_shares, |
| 3478 | &offer_text, |
| 3479 | ); |
| 3480 | let description = parse_sdp(&text, SdpType::Offer)?; |
| 3481 | peer.set_local_description(description) |
| 3482 | .await |
| 3483 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 3484 | let mut numbers = random_u32; |
| 3485 | let mut plan = plan.clone(); |
| 3486 | if let Some(mid) = share_mid |
| 3487 | .as_ref() |
| 3488 | .filter(|mid| !plan.screen_share_mids.contains(mid)) |
| 3489 | { |
| 3490 | plan.screen_share_mids.push(mid.clone()); |
| 3491 | } |
| 3492 | let mut signaled = to_teams_offer( |
| 3493 | &directions_for( |
| 3494 | layout, |
| 3495 | hold, |
| 3496 | camera, |
| 3497 | share, |
| 3498 | camera_mid, |
| 3499 | share_mid.as_deref(), |
| 3500 | remote_shares, |
| 3501 | &text, |
| 3502 | ), |
| 3503 | &plan, |
| 3504 | &mut numbers, |
| 3505 | )?; |
| 3506 | signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?; |
| 3507 | if gathered.is_some() |
| 3508 | && let Some(role) = negotiated_setup( |
| 3509 | peer.current_local_description() |
| 3510 | .map(|local| local.to_string()) |
| 3511 | .as_deref(), |
| 3512 | peer.current_remote_description() |
| 3513 | .map(|remote| remote.to_string()) |
| 3514 | .as_deref(), |
| 3515 | ) |
| 3516 | { |
| 3517 | signaled.sdp = signaled |
| 3518 | .sdp |
| 3519 | .replace("a=setup:actpass", &format!("a=setup:{role}")); |
| 3520 | } |
| 3521 | Ok((text, signaled)) |
| 3522 | } |
| 3523 | |
| 3524 | /// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging. |
| 3525 | fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> { |
| 3526 | match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) { |
| 3527 | Ok(Ok(description)) => Ok(description), |
| 3528 | Ok(Err(error)) => Err(Error::Sdp(format!( |
| 3529 | "{kind:?} rejected: {}", |
| 3530 | error.description |
| 3531 | ))), |
| 3532 | Err(_) => Err(Error::Sdp(format!( |
| 3533 | "{kind:?} rejected, libwebrtc gave no readable reason" |
| 3534 | ))), |
| 3535 | } |
| 3536 | } |
| 3537 | |
| 3538 | async fn rollback_offer(peer: &PeerConnection) { |
| 3539 | if let Ok(rollback) = parse_sdp("", SdpType::Rollback) { |
| 3540 | let _ = peer.set_local_description(rollback).await; |
| 3541 | } |
| 3542 | } |
| 3543 | |
| 3544 | async fn rollback_remote_offer(peer: &PeerConnection) { |
| 3545 | if let Ok(rollback) = parse_sdp("", SdpType::Rollback) { |
| 3546 | let _ = peer.set_remote_description(rollback).await; |
| 3547 | } |
| 3548 | } |
| 3549 | |
| 3550 | fn is_glare_rejection(body: &serde_json::Value) -> bool { |
| 3551 | body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE) |
| 3552 | } |
| 3553 | |
| 3554 | fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> { |
| 3555 | let links = &body["mediaNegotiation"]["links"]; |
| 3556 | ["mediaAnswer", "rejection"] |
| 3557 | .iter() |
| 3558 | .filter_map(|name| links[*name].as_str().and_then(callback_tag)) |
| 3559 | .collect() |
| 3560 | } |
| 3561 | |
| 3562 | #[cfg(test)] |
| 3563 | mod reply_tag_tests { |
| 3564 | use super::*; |
| 3565 | |
| 3566 | #[test] |
| 3567 | fn answers_and_rejections_match_the_offer_by_tag() { |
| 3568 | let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]; |
| 3569 | assert!(answers_offer( |
| 3570 | "callAgent/c/aaaa1111/call/mediaAnswer/", |
| 3571 | &tags |
| 3572 | )); |
| 3573 | assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags)); |
| 3574 | assert!(!answers_offer( |
| 3575 | "callAgent/c/cccc3333/call/mediaAnswer/", |
| 3576 | &tags |
| 3577 | )); |
| 3578 | assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[])); |
| 3579 | } |
| 3580 | |
| 3581 | #[test] |
| 3582 | fn an_offer_names_both_reply_tags() { |
| 3583 | let body = serde_json::json!({"mediaNegotiation": {"links": { |
| 3584 | "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/", |
| 3585 | "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}}); |
| 3586 | assert_eq!( |
| 3587 | offer_reply_tags(&body), |
| 3588 | vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()] |
| 3589 | ); |
| 3590 | } |
| 3591 | } |
| 3592 | |
| 3593 | fn defer_to_new_peer( |
| 3594 | change: Change, |
| 3595 | deferred: &mut Vec<Change>, |
| 3596 | local_video: &mut LocalVideo, |
| 3597 | control: &CallControl, |
| 3598 | ) { |
| 3599 | match change { |
| 3600 | Change::Camera(true) => { |
| 3601 | control.send(CallUpdate::Camera(true)); |
| 3602 | deferred.push(change); |
| 3603 | } |
| 3604 | Change::Share(true) => deferred.push(change), |
| 3605 | change => undo_change(change, local_video, control), |
| 3606 | } |
| 3607 | } |
| 3608 | |
| 3609 | /// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone. |
| 3610 | fn settle_failed_escalation( |
| 3611 | server: bool, |
| 3612 | layout: Layout, |
| 3613 | negotiator: &mut MediaNegotiator, |
| 3614 | deferred: &mut Vec<Change>, |
| 3615 | local_video: &mut LocalVideo, |
| 3616 | control: &CallControl, |
| 3617 | ) { |
| 3618 | if server { |
| 3619 | negotiator.server_escalation_failed(); |
| 3620 | for change in deferred.drain(..) { |
| 3621 | undo_change(change, local_video, control); |
| 3622 | } |
| 3623 | } else if layout == Layout::OneToOne { |
| 3624 | drop_local_media(local_video, control); |
| 3625 | } |
| 3626 | } |
| 3627 | |
| 3628 | fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) { |
| 3629 | if local_video.sharing() { |
| 3630 | local_video.stop_share(); |
| 3631 | clear_share(control); |
| 3632 | } |
| 3633 | if local_video.camera_on() { |
| 3634 | local_video.stop_camera(); |
| 3635 | control.send(CallUpdate::Camera(false)); |
| 3636 | } |
| 3637 | } |
| 3638 | |
| 3639 | fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) { |
| 3640 | match change { |
| 3641 | Change::Camera(true) => { |
| 3642 | local_video.stop_camera(); |
| 3643 | control.send(CallUpdate::Camera(false)); |
| 3644 | } |
| 3645 | Change::Camera(false) => control.send(CallUpdate::Camera(false)), |
| 3646 | Change::Share(true) => { |
| 3647 | local_video.stop_share(); |
| 3648 | clear_share(control); |
| 3649 | control.send(CallUpdate::Notice(notice_with_detail( |
| 3650 | SHARING_START_NOTICE, |
| 3651 | "", |
| 3652 | ))); |
| 3653 | } |
| 3654 | Change::Share(false) => {} |
| 3655 | Change::Hold(_) => control.send(CallUpdate::Notice(HOLD_CHANGE_FAILED_NOTICE.into())), |
| 3656 | } |
| 3657 | } |
| 3658 | |
| 3659 | fn withhold_media( |
| 3660 | muted: &mut bool, |
| 3661 | audio: &AudioSetup, |
| 3662 | software_audio: Option<&SoftwareAudio>, |
| 3663 | remote: &RemoteCall, |
| 3664 | local_video: &mut LocalVideo, |
| 3665 | control: &CallControl, |
| 3666 | ) { |
| 3667 | *muted = apply_mute( |
| 3668 | MuteCommand::Mute, |
| 3669 | *muted, |
| 3670 | audio, |
| 3671 | software_audio, |
| 3672 | remote, |
| 3673 | control, |
| 3674 | ); |
| 3675 | if local_video.camera_on() { |
| 3676 | local_video.stop_camera(); |
| 3677 | control.send(CallUpdate::Camera(false)); |
| 3678 | } |
| 3679 | } |
| 3680 | |
| 3681 | async fn apply_background( |
| 3682 | choice: BackgroundChoice, |
| 3683 | local_video: &LocalVideo, |
| 3684 | control: &CallControl, |
| 3685 | timeline: &Timeline, |
| 3686 | ) { |
| 3687 | match choice { |
| 3688 | BackgroundChoice::None => local_video.set_background(false, None), |
| 3689 | BackgroundChoice::Blur => local_video.set_background(true, None), |
| 3690 | BackgroundChoice::Image(path) => { |
| 3691 | match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await { |
| 3692 | Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))), |
| 3693 | Ok(Err(error)) => { |
| 3694 | timeline.record("background image failed", error.to_string()); |
| 3695 | control.send(CallUpdate::Notice(BACKGROUND_IMAGE_FAILED_NOTICE.into())); |
| 3696 | } |
| 3697 | Err(_) => {} |
| 3698 | } |
| 3699 | } |
| 3700 | } |
| 3701 | } |
| 3702 | |
| 3703 | async fn save_meeting_options( |
| 3704 | session: &session::Session, |
| 3705 | target: &MeetingTarget, |
| 3706 | writes: &[OptionWrite], |
| 3707 | ) -> std::result::Result<meeting_options::MeetingOptions, String> { |
| 3708 | for change in writes { |
| 3709 | meeting_options::write(session, target, change) |
| 3710 | .await |
| 3711 | .map_err(|error| error.to_string())?; |
| 3712 | } |
| 3713 | meeting_options::fetch(session, target) |
| 3714 | .await |
| 3715 | .map_err(|error| error.to_string()) |
| 3716 | } |
| 3717 | |
| 3718 | fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> { |
| 3719 | let display_name = roster |
| 3720 | .members() |
| 3721 | .iter() |
| 3722 | .find(|member| member.mri == mri) |
| 3723 | .map_or("", |member| member.display_name.as_str()); |
| 3724 | Target { mri, display_name } |
| 3725 | } |
| 3726 | |
| 3727 | const RECORDING_STOP_RETRIES: usize = 6; |
| 3728 | const RECORDING_STOP_RETRY_WAIT: Duration = Duration::from_secs(5); |
| 3729 | |
| 3730 | /// The recorder answers 409 to a stop sent while its start is still settling. |
| 3731 | fn recorder_busy(error: &Error) -> bool { |
| 3732 | matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409")) |
| 3733 | } |
| 3734 | |
| 3735 | fn report_organizer_result( |
| 3736 | result: Result<u16>, |
| 3737 | label: &str, |
| 3738 | notice: &'static str, |
| 3739 | control: &CallControl, |
| 3740 | timeline: &Timeline, |
| 3741 | ) { |
| 3742 | if let Err(error) = &result { |
| 3743 | timeline.record(format!("{label} failed"), error.to_string()); |
| 3744 | control.send(CallUpdate::Notice(notice.to_owned())); |
| 3745 | } |
| 3746 | control.send(CallUpdate::Organizer { |
| 3747 | action: label.to_owned(), |
| 3748 | outcome: result.map_err(|error| error.to_string()), |
| 3749 | }); |
| 3750 | } |
| 3751 | |
| 3752 | fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry { |
| 3753 | if entry.display_name.is_empty() { |
| 3754 | entry.display_name = roster |
| 3755 | .name_of(&entry.user_id) |
| 3756 | .unwrap_or_default() |
| 3757 | .to_owned(); |
| 3758 | } |
| 3759 | entry |
| 3760 | } |
| 3761 | |
| 3762 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 3763 | enum BotJob { |
| 3764 | Captions, |
| 3765 | Recording, |
| 3766 | } |
| 3767 | |
| 3768 | #[allow(clippy::too_many_arguments)] |
| 3769 | async fn run_bot_steps( |
| 3770 | job: BotJob, |
| 3771 | flow: &mut CaptionFlow, |
| 3772 | roster: &Roster, |
| 3773 | remote: &RemoteCall, |
| 3774 | links: &CallbackLinks, |
| 3775 | meeting_chat: Option<&str>, |
| 3776 | plan: &RecordingPlan, |
| 3777 | bot_pending: &mut bool, |
| 3778 | control: &CallControl, |
| 3779 | timeline: &Timeline, |
| 3780 | ) { |
| 3781 | let is_active: fn(&crate::roster::CaptionBot) -> bool = match job { |
| 3782 | BotJob::Captions => |bot| bot.active, |
| 3783 | BotJob::Recording => |bot| bot.recording, |
| 3784 | }; |
| 3785 | let fail = |flow: &mut CaptionFlow, reason: &str| { |
| 3786 | flow.failed(); |
| 3787 | control.send(match job { |
| 3788 | BotJob::Captions => CallUpdate::Captions(CaptionState::Failed(reason.to_owned())), |
| 3789 | BotJob::Recording => CallUpdate::Notice(reason.to_owned()), |
| 3790 | }); |
| 3791 | if job == BotJob::Recording { |
| 3792 | control.send(CallUpdate::RecordingPending(false)); |
| 3793 | } |
| 3794 | }; |
| 3795 | let (join_failure, start_failure) = match job { |
| 3796 | BotJob::Captions => (CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE), |
| 3797 | BotJob::Recording => (RECORDING_JOIN_FAILED_NOTICE, RECORDING_START_FAILED_NOTICE), |
| 3798 | }; |
| 3799 | loop { |
| 3800 | match flow.next_for(roster.caption_bot(), is_active) { |
| 3801 | CaptionStep::Wait => return, |
| 3802 | CaptionStep::AddBot => { |
| 3803 | if *bot_pending { |
| 3804 | continue; |
| 3805 | } |
| 3806 | let Some(thread) = meeting_chat else { |
| 3807 | return fail( |
| 3808 | flow, |
| 3809 | "This call has no chat for the captions and the recording", |
| 3810 | ); |
| 3811 | }; |
| 3812 | *bot_pending = true; |
| 3813 | let added = remote |
| 3814 | .signaling |
| 3815 | .add_caption_bot( |
| 3816 | &remote.conversation, |
| 3817 | &remote.participant, |
| 3818 | thread, |
| 3819 | links, |
| 3820 | remote.threadless, |
| 3821 | ) |
| 3822 | .await; |
| 3823 | if job == BotJob::Recording { |
| 3824 | report_organizer_result( |
| 3825 | added |
| 3826 | .as_ref() |
| 3827 | .map(|status| *status) |
| 3828 | .map_err(|error| Error::Signaling(error.to_string())), |
| 3829 | "recording add bot", |
| 3830 | join_failure, |
| 3831 | control, |
| 3832 | timeline, |
| 3833 | ); |
| 3834 | } |
| 3835 | if let Err(error) = added { |
| 3836 | timeline.record("bot invitation failed", error.to_string()); |
| 3837 | *bot_pending = false; |
| 3838 | return fail(flow, join_failure); |
| 3839 | } |
| 3840 | } |
| 3841 | CaptionStep::Start => { |
| 3842 | let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { |
| 3843 | return; |
| 3844 | }; |
| 3845 | match job { |
| 3846 | BotJob::Captions => { |
| 3847 | if let Err(error) = remote |
| 3848 | .signaling |
| 3849 | .caption_command(&url, BotAction::Start, &remote.participant) |
| 3850 | .await |
| 3851 | { |
| 3852 | timeline.record("caption start failed", error.to_string()); |
| 3853 | return fail(flow, start_failure); |
| 3854 | } |
| 3855 | if let Err(error) = remote |
| 3856 | .signaling |
| 3857 | .set_caption_preference(&remote.conversation, &remote.participant, true) |
| 3858 | .await |
| 3859 | { |
| 3860 | timeline.record("caption preference failed", error.to_string()); |
| 3861 | } |
| 3862 | } |
| 3863 | BotJob::Recording => { |
| 3864 | let started = remote |
| 3865 | .signaling |
| 3866 | .recording_command(&url, plan.start(), &remote.participant, &plan.title) |
| 3867 | .await; |
| 3868 | let failed = started.is_err(); |
| 3869 | report_organizer_result( |
| 3870 | started, |
| 3871 | "recording start", |
| 3872 | start_failure, |
| 3873 | control, |
| 3874 | timeline, |
| 3875 | ); |
| 3876 | if failed { |
| 3877 | return fail(flow, start_failure); |
| 3878 | } |
| 3879 | } |
| 3880 | } |
| 3881 | } |
| 3882 | CaptionStep::Stop => { |
| 3883 | let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { |
| 3884 | continue; |
| 3885 | }; |
| 3886 | match job { |
| 3887 | BotJob::Captions => { |
| 3888 | if let Err(error) = remote |
| 3889 | .signaling |
| 3890 | .caption_command(&url, BotAction::Stop, &remote.participant) |
| 3891 | .await |
| 3892 | { |
| 3893 | timeline.record("caption stop failed", error.to_string()); |
| 3894 | } |
| 3895 | if let Err(error) = remote |
| 3896 | .signaling |
| 3897 | .set_caption_preference( |
| 3898 | &remote.conversation, |
| 3899 | &remote.participant, |
| 3900 | false, |
| 3901 | ) |
| 3902 | .await |
| 3903 | { |
| 3904 | timeline.record("caption preference failed", error.to_string()); |
| 3905 | } |
| 3906 | } |
| 3907 | BotJob::Recording => { |
| 3908 | let remote = remote.clone(); |
| 3909 | let updates = control.updates(); |
| 3910 | let (command, title) = (plan.stop(), plan.title.clone()); |
| 3911 | tokio::spawn(async move { |
| 3912 | let mut stopped = remote |
| 3913 | .signaling |
| 3914 | .recording_command(&url, command, &remote.participant, &title) |
| 3915 | .await; |
| 3916 | for _ in 0..RECORDING_STOP_RETRIES { |
| 3917 | if !stopped.as_ref().is_err_and(recorder_busy) { |
| 3918 | break; |
| 3919 | } |
| 3920 | tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await; |
| 3921 | stopped = remote |
| 3922 | .signaling |
| 3923 | .recording_command(&url, command, &remote.participant, &title) |
| 3924 | .await; |
| 3925 | } |
| 3926 | if stopped.is_err() { |
| 3927 | let _ = updates |
| 3928 | .send(CallUpdate::Notice(RECORDING_STOP_FAILED_NOTICE.into())); |
| 3929 | } |
| 3930 | let _ = updates.send(CallUpdate::Organizer { |
| 3931 | action: "recording stop".into(), |
| 3932 | outcome: stopped.map_err(|error| error.to_string()), |
| 3933 | }); |
| 3934 | }); |
| 3935 | } |
| 3936 | } |
| 3937 | } |
| 3938 | CaptionStep::ReportOn => { |
| 3939 | if job == BotJob::Captions { |
| 3940 | control.send(CallUpdate::Captions(CaptionState::On)); |
| 3941 | } |
| 3942 | } |
| 3943 | } |
| 3944 | } |
| 3945 | } |
| 3946 | |
| 3947 | fn send_receive_change(control: &CallControl, change: ReceiveChange) { |
| 3948 | if let Some(sharer) = change.screen_sharer { |
| 3949 | control.send(CallUpdate::ScreenShare(sharer)); |
| 3950 | } |
| 3951 | } |
| 3952 | |
| 3953 | fn record_audio_devices( |
| 3954 | timeline: &Timeline, |
| 3955 | lists: &devices::DeviceLists, |
| 3956 | input: Option<&AppliedDevice>, |
| 3957 | output: Option<&AppliedDevice>, |
| 3958 | ) { |
| 3959 | let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| { |
| 3960 | applied |
| 3961 | .and_then(|applied| devices.iter().find(|device| device.index == applied.index)) |
| 3962 | .map_or("none", |device| device.name.as_str()) |
| 3963 | .to_owned() |
| 3964 | }; |
| 3965 | timeline.record( |
| 3966 | "audio devices", |
| 3967 | format!( |
| 3968 | "input={} output={}", |
| 3969 | name(&lists.inputs, input), |
| 3970 | name(&lists.outputs, output) |
| 3971 | ), |
| 3972 | ); |
| 3973 | } |
| 3974 | |
| 3975 | fn follow_device_change( |
| 3976 | flow: Flow, |
| 3977 | (previous, current): (&[AudioDevice], &[AudioDevice]), |
| 3978 | choice: &DeviceChoice, |
| 3979 | applied: &mut Option<AppliedDevice>, |
| 3980 | select: impl Fn(u16) -> bool, |
| 3981 | timeline: &Timeline, |
| 3982 | control: &CallControl, |
| 3983 | ) -> bool { |
| 3984 | let system_default = devices::system_default_id(flow); |
| 3985 | let (index, fell_back) = |
| 3986 | match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) { |
| 3987 | Reselect::Keep => return false, |
| 3988 | Reselect::Select(index) => (index, false), |
| 3989 | Reselect::FallBack(index) => (index, true), |
| 3990 | }; |
| 3991 | let selected = select(index); |
| 3992 | timeline.record( |
| 3993 | "device change", |
| 3994 | format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"), |
| 3995 | ); |
| 3996 | if selected { |
| 3997 | *applied = current |
| 3998 | .iter() |
| 3999 | .find(|device| device.index == index) |
| 4000 | .map(|device| AppliedDevice { |
| 4001 | index, |
| 4002 | key: device.key(), |
| 4003 | }); |
| 4004 | } |
| 4005 | if fell_back { |
| 4006 | let fallback = current.iter().find(|device| device.index == index); |
| 4007 | control.send(CallUpdate::Notice(devices::disconnect_notice( |
| 4008 | previous, choice, fallback, |
| 4009 | ))); |
| 4010 | } |
| 4011 | selected |
| 4012 | } |
| 4013 | |
| 4014 | fn far_future() -> Instant { |
| 4015 | Instant::now() + FAR_FUTURE |
| 4016 | } |
| 4017 | |
| 4018 | fn apply_mute( |
| 4019 | command: MuteCommand, |
| 4020 | currently_muted: bool, |
| 4021 | audio: &AudioSetup, |
| 4022 | software_audio: Option<&SoftwareAudio>, |
| 4023 | remote: &RemoteCall, |
| 4024 | control: &CallControl, |
| 4025 | ) -> bool { |
| 4026 | let effect = MuteEffect::for_muted(command.target(currently_muted)); |
| 4027 | audio.track.set_enabled(effect.track_enabled); |
| 4028 | if let Some(software_audio) = software_audio { |
| 4029 | software_audio.set_microphone_muted(effect.muted); |
| 4030 | } |
| 4031 | control.send(CallUpdate::Muted(effect.muted)); |
| 4032 | let remote = remote.clone(); |
| 4033 | tokio::spawn(async move { |
| 4034 | let _ = remote |
| 4035 | .signaling |
| 4036 | .update_endpoint_state( |
| 4037 | &remote.conversation, |
| 4038 | &remote.participant, |
| 4039 | effect.endpoint_is_muted, |
| 4040 | ) |
| 4041 | .await; |
| 4042 | }); |
| 4043 | effect.muted |
| 4044 | } |
| 4045 | |
| 4046 | fn silence_for_hold( |
| 4047 | on_hold: bool, |
| 4048 | muted: bool, |
| 4049 | audio: Option<&AudioSetup>, |
| 4050 | software_audio: Option<&SoftwareAudio>, |
| 4051 | ) { |
| 4052 | let silent = on_hold || muted; |
| 4053 | if let Some(audio) = audio { |
| 4054 | audio |
| 4055 | .track |
| 4056 | .set_enabled(MuteEffect::for_muted(silent).track_enabled); |
| 4057 | } |
| 4058 | if let Some(software_audio) = software_audio { |
| 4059 | software_audio.set_microphone_muted(silent); |
| 4060 | } |
| 4061 | } |
| 4062 | |
| 4063 | fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> { |
| 4064 | let sender = peer |
| 4065 | .senders() |
| 4066 | .into_iter() |
| 4067 | .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_)))) |
| 4068 | .ok_or_else(|| Error::Webrtc("no audio sender".into()))?; |
| 4069 | sender |
| 4070 | .set_track(Some(MediaStreamTrack::Audio(track.clone()))) |
| 4071 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 4072 | } |
| 4073 | |
| 4074 | fn outgoing_track<'a>( |
| 4075 | software_audio: Option<&'a SoftwareAudio>, |
| 4076 | device_track: &'a RtcAudioTrack, |
| 4077 | ) -> &'a RtcAudioTrack { |
| 4078 | pick_track(software_audio.map(|audio| &audio.track), device_track) |
| 4079 | } |
| 4080 | |
| 4081 | fn pick_track<'a, T>(software: Option<&'a T>, device: &'a T) -> &'a T { |
| 4082 | software.unwrap_or(device) |
| 4083 | } |
| 4084 | |
| 4085 | fn software_wanted( |
| 4086 | mic_settings: MicSettings, |
| 4087 | share_sound_wanted: bool, |
| 4088 | local_video: &LocalVideo, |
| 4089 | audio: Option<&AudioSetup>, |
| 4090 | ) -> Option<SoftwareAudioPlan> { |
| 4091 | let sharing_sound = share_sound_wanted && local_video.sharing(); |
| 4092 | SoftwareAudioPlan::wanted( |
| 4093 | mic_settings, |
| 4094 | sharing_sound, |
| 4095 | audio.is_some_and(AudioSetup::uses_devices), |
| 4096 | ) |
| 4097 | } |
| 4098 | |
| 4099 | fn restore_device_track( |
| 4100 | factory: &PeerConnectionFactory, |
| 4101 | input: &DeviceChoice, |
| 4102 | peer: &PeerConnection, |
| 4103 | device_track: &RtcAudioTrack, |
| 4104 | timeline: &Timeline, |
| 4105 | ) { |
| 4106 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 4107 | if !factory.adm_recording_enabled() { |
| 4108 | factory.set_adm_recording_enabled(true); |
| 4109 | devices::select_input(factory, input); |
| 4110 | } |
| 4111 | if let Err(error) = swap_audio_track(peer, device_track) { |
| 4112 | timeline.record("microphone track not restored", error.to_string()); |
| 4113 | } |
| 4114 | } |
| 4115 | |
| 4116 | #[allow(clippy::too_many_arguments)] |
| 4117 | fn sync_software_audio( |
| 4118 | factory: &PeerConnectionFactory, |
| 4119 | options: &CallOptions, |
| 4120 | input: &DeviceChoice, |
| 4121 | muted: bool, |
| 4122 | remote_audio: Option<RtcAudioTrack>, |
| 4123 | peer: &PeerConnection, |
| 4124 | device_track: &RtcAudioTrack, |
| 4125 | wanted: Option<SoftwareAudioPlan>, |
| 4126 | restart: bool, |
| 4127 | software_audio: &mut Option<SoftwareAudio>, |
| 4128 | control: &CallControl, |
| 4129 | timeline: &Timeline, |
| 4130 | ) { |
| 4131 | let running = software_audio.as_ref().map(|audio| audio.plan); |
| 4132 | if running == wanted && !restart { |
| 4133 | return; |
| 4134 | } |
| 4135 | if running.is_some() { |
| 4136 | timeline.record("software audio", "stopping"); |
| 4137 | } |
| 4138 | *software_audio = None; |
| 4139 | let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound); |
| 4140 | let Some(plan) = wanted else { |
| 4141 | restore_device_track(factory, input, peer, device_track, timeline); |
| 4142 | control.send(CallUpdate::ShareSound(false)); |
| 4143 | return; |
| 4144 | }; |
| 4145 | let started = SoftwareAudio::start( |
| 4146 | factory, |
| 4147 | options.audio, |
| 4148 | options.tone_hz, |
| 4149 | input, |
| 4150 | plan, |
| 4151 | muted, |
| 4152 | remote_audio, |
| 4153 | ) |
| 4154 | .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio)); |
| 4155 | match started { |
| 4156 | Ok(audio) => { |
| 4157 | timeline.record( |
| 4158 | "software audio", |
| 4159 | format!("{:?}, computer sound {:?}", plan.processing, audio.loopback), |
| 4160 | ); |
| 4161 | if let Some(source) = &audio.microphone_source { |
| 4162 | timeline.record("mic capture", source.clone()); |
| 4163 | } |
| 4164 | if audio.microphone_source.is_some() { |
| 4165 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 4166 | factory.set_adm_recording_enabled(false); |
| 4167 | } |
| 4168 | if let Some(warning) = &audio.warning { |
| 4169 | timeline.record("computer sound warning", warning.clone()); |
| 4170 | } |
| 4171 | control.send(CallUpdate::ShareSound(plan.computer_sound)); |
| 4172 | *software_audio = Some(audio); |
| 4173 | } |
| 4174 | Err(error) => { |
| 4175 | timeline.record("software audio failed", error.to_string()); |
| 4176 | restore_device_track(factory, input, peer, device_track, timeline); |
| 4177 | if was_sharing_sound || plan.computer_sound { |
| 4178 | control.send(CallUpdate::ShareSound(false)); |
| 4179 | } |
| 4180 | let notice = if plan.computer_sound { |
| 4181 | "Computer sound could not start, sharing without it" |
| 4182 | } else { |
| 4183 | "Microphone processing could not start, using the standard microphone" |
| 4184 | }; |
| 4185 | control.send(CallUpdate::Notice(notice.into())); |
| 4186 | } |
| 4187 | } |
| 4188 | } |
| 4189 | |
| 4190 | async fn tear_down( |
| 4191 | mut live: Live, |
| 4192 | inner: &Inner, |
| 4193 | timeline: &Timeline, |
| 4194 | report: &mut CallReport, |
| 4195 | cancelled: bool, |
| 4196 | ) { |
| 4197 | for peer in &live.peers { |
| 4198 | peer.close(); |
| 4199 | } |
| 4200 | if let Some(audio) = live.audio.take() { |
| 4201 | audio.stop().await; |
| 4202 | } |
| 4203 | live.broker_running.store(false, Ordering::SeqCst); |
| 4204 | if !live.skip_leave |
| 4205 | && let Some(remote) = &live.remote |
| 4206 | { |
| 4207 | let reason = if cancelled { |
| 4208 | LeaveReason::Cancel |
| 4209 | } else { |
| 4210 | LeaveReason::Hangup |
| 4211 | }; |
| 4212 | match remote |
| 4213 | .signaling |
| 4214 | .leave(&remote.conversation, &remote.participant, reason) |
| 4215 | .await |
| 4216 | { |
| 4217 | Ok(()) => report.left_cleanly = true, |
| 4218 | Err(error) => timeline.record("leave failed", error.to_string()), |
| 4219 | } |
| 4220 | } |
| 4221 | if report.end.is_none() |
| 4222 | && let Some(callbacks) = live.callbacks.as_mut() |
| 4223 | && live.remote.is_some() |
| 4224 | { |
| 4225 | let waited = timeout(END_CALLBACK_WAIT, async { |
| 4226 | while let Some(callback) = callbacks.recv().await { |
| 4227 | let event = handle_callback(&callback, timeline); |
| 4228 | if let Ok(CallEvent::End(end)) = event { |
| 4229 | return Some(end); |
| 4230 | } |
| 4231 | } |
| 4232 | None |
| 4233 | }) |
| 4234 | .await; |
| 4235 | report.end = waited.ok().flatten(); |
| 4236 | } |
| 4237 | if let Some(broker) = live.broker.take() { |
| 4238 | broker.abort(); |
| 4239 | } |
| 4240 | for task in live.video_tasks.drain(..) { |
| 4241 | task.abort(); |
| 4242 | } |
| 4243 | if let Some(route_id) = &live.route_id { |
| 4244 | inner.unregister_route(route_id); |
| 4245 | } |
| 4246 | timeline.record("closed", "peer closed, call route removed"); |
| 4247 | } |
| 4248 | |
| 4249 | fn setup_end_kind(end: &CallEnd) -> EndKind { |
| 4250 | match end.kind() { |
| 4251 | EndKind::Normal | EndKind::Other => EndKind::Unavailable, |
| 4252 | kind => kind, |
| 4253 | } |
| 4254 | } |
| 4255 | |
| 4256 | fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> { |
| 4257 | let body = decode_body(callback)?; |
| 4258 | let (_, event) = classify(&callback.path, body)?; |
| 4259 | let detail = match &event { |
| 4260 | CallEvent::Acceptance(acceptance) => format!( |
| 4261 | "answer sdp {} bytes, fromMixer={}", |
| 4262 | acceptance.sdp.len(), |
| 4263 | acceptance.from_mixer |
| 4264 | ), |
| 4265 | CallEvent::End(end) => format!( |
| 4266 | "code={} subCode={} phrase={}", |
| 4267 | end.code, end.sub_code, end.phrase |
| 4268 | ), |
| 4269 | CallEvent::Progress(status) => format!("{status:?}"), |
| 4270 | CallEvent::ConversationEnd(body) |
| 4271 | | CallEvent::Rejection(body) |
| 4272 | | CallEvent::AddParticipantFailure(body) |
| 4273 | | CallEvent::RetargetCompletion(body) => outcome_summary(body), |
| 4274 | CallEvent::ControlVideoStreaming(body) => parse_request(body) |
| 4275 | .map_or_else(|| "body not understood".to_owned(), |request| request.shape), |
| 4276 | _ => String::new(), |
| 4277 | }; |
| 4278 | timeline.record(format!("Trouter {}", event.name()), detail); |
| 4279 | match &event { |
| 4280 | CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp), |
| 4281 | CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp), |
| 4282 | CallEvent::MediaRenegotiation(renegotiation) => { |
| 4283 | timeline.record_sdp("remote offer", &renegotiation.sdp) |
| 4284 | } |
| 4285 | _ => {} |
| 4286 | } |
| 4287 | Ok(event) |
| 4288 | } |
| 4289 | |
| 4290 | async fn apply_answer( |
| 4291 | peer: &PeerConnection, |
| 4292 | teams_answer: &str, |
| 4293 | signaled: &SignaledOffer, |
| 4294 | browser_offer: &str, |
| 4295 | ) -> Result<()> { |
| 4296 | let answer = to_browser_answer(teams_answer, signaled, browser_offer)?; |
| 4297 | set_browser_answer(peer, &answer).await |
| 4298 | } |
| 4299 | |
| 4300 | /// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes. |
| 4301 | async fn apply_hold_answer( |
| 4302 | peer: &PeerConnection, |
| 4303 | teams_answer: &str, |
| 4304 | signaled: &SignaledOffer, |
| 4305 | browser_offer: &str, |
| 4306 | ) -> Result<()> { |
| 4307 | let answer = to_browser_answer(teams_answer, signaled, browser_offer)?; |
| 4308 | set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await |
| 4309 | } |
| 4310 | |
| 4311 | async fn set_browser_answer(peer: &PeerConnection, answer: &str) -> Result<()> { |
| 4312 | let description = parse_sdp(answer, SdpType::Answer)?; |
| 4313 | peer.set_remote_description(description) |
| 4314 | .await |
| 4315 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 4316 | } |
| 4317 | |
| 4318 | /// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect. |
| 4319 | fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) { |
| 4320 | let Some(directory) = &options.sdp_dump_dir else { |
| 4321 | return; |
| 4322 | }; |
| 4323 | let masked: Vec<String> = sdp |
| 4324 | .lines() |
| 4325 | .map(|line| { |
| 4326 | for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:", "a=crypto:"] { |
| 4327 | if line.starts_with(prefix) { |
| 4328 | return format!("{prefix}<masked>"); |
| 4329 | } |
| 4330 | } |
| 4331 | line.split(' ') |
| 4332 | .map(mask_address) |
| 4333 | .collect::<Vec<_>>() |
| 4334 | .join(" ") |
| 4335 | }) |
| 4336 | .collect(); |
| 4337 | let _ = std::fs::create_dir_all(directory); |
| 4338 | let _ = std::fs::write(directory.join(name), masked.join("\n")); |
| 4339 | } |
| 4340 | |
| 4341 | fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Error>) { |
| 4342 | let Some(directory) = &options.sdp_dump_dir else { |
| 4343 | return; |
| 4344 | }; |
| 4345 | let mut lines: Vec<String> = timeline |
| 4346 | .entries() |
| 4347 | .iter() |
| 4348 | .map(|entry| { |
| 4349 | format!( |
| 4350 | "{:>6} ms {} {}", |
| 4351 | entry.elapsed_ms, entry.label, entry.detail |
| 4352 | ) |
| 4353 | }) |
| 4354 | .collect(); |
| 4355 | lines.push(match failure { |
| 4356 | Some(error) => format!("failed: {error}"), |
| 4357 | None => "ended without error".to_owned(), |
| 4358 | }); |
| 4359 | let _ = std::fs::create_dir_all(directory); |
| 4360 | let _ = std::fs::write(directory.join("timeline.txt"), lines.join("\n")); |
| 4361 | } |
| 4362 | |
| 4363 | fn mask_address(token: &str) -> String { |
| 4364 | let dotted_quad = |
| 4365 | token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok()); |
| 4366 | let colon_address = |
| 4367 | token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn |
| 4368 | … afgekapt |