| 1 | mod audio_switch; |
| 2 | mod bots; |
| 3 | mod escalation; |
| 4 | mod peer_sdp; |
| 5 | mod stats; |
| 6 | mod teardown; |
| 7 | |
| 8 | use std::collections::BTreeMap; |
| 9 | use std::path::PathBuf; |
| 10 | use std::sync::Arc; |
| 11 | use std::sync::atomic::{AtomicBool, AtomicU64, Ordering}; |
| 12 | use std::time::Duration; |
| 13 | |
| 14 | use self::{audio_switch::*, bots::*, escalation::*, peer_sdp::*, stats::*, teardown::*}; |
| 15 | |
| 16 | use chatsvc::TrouterCallback; |
| 17 | use futures_util::StreamExt; |
| 18 | use libwebrtc::audio_stream::native::NativeAudioStream; |
| 19 | use libwebrtc::data_channel::{DataChannel, DataChannelInit}; |
| 20 | use libwebrtc::prelude::*; |
| 21 | use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit}; |
| 22 | use libwebrtc::session_description::{SdpType, SessionDescription}; |
| 23 | use libwebrtc::stats::RtcStats; |
| 24 | use session::Session; |
| 25 | use tokio::sync::{Mutex, mpsc}; |
| 26 | use tokio::task::JoinHandle; |
| 27 | use tokio::time::{Instant, interval, sleep_until, timeout}; |
| 28 | |
| 29 | use crate::active_speakers; |
| 30 | use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav}; |
| 31 | use crate::audio_io::{AudioMode, AudioSetup}; |
| 32 | use crate::background::{BackgroundChoice, BackgroundPicture}; |
| 33 | use crate::breakout::{self, RoomWatcher}; |
| 34 | use crate::callee_gate::{CalleeGate, EchoWatch, roster_has_callee}; |
| 35 | use crate::camera::{CameraDevice, list_cameras}; |
| 36 | use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates}; |
| 37 | use crate::captions::{ |
| 38 | BotAction, CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep, |
| 39 | parse_caption_message, |
| 40 | }; |
| 41 | use crate::control::{CallCommand, CallControl, CallUpdate, Progress}; |
| 42 | use crate::data_channel::Depacketizer; |
| 43 | use crate::device_watch::{self, Debounce}; |
| 44 | use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect}; |
| 45 | use crate::diagnostics::{CallDiagnostics, StatsSample}; |
| 46 | use crate::end::EndKind; |
| 47 | use crate::engine::{CallEngine, EngineConfig, Inner}; |
| 48 | use crate::error::{Error, Result}; |
| 49 | use crate::health::{ |
| 50 | CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats, |
| 51 | }; |
| 52 | use crate::hold::{ |
| 53 | HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, is_hold, keep_media_running, |
| 54 | offer_modalities, offer_sends_video, rewrite_directions, stop_sending_on, |
| 55 | }; |
| 56 | use crate::meeting_options::{self, OptionWrite}; |
| 57 | use crate::mic_processing::MicSettings; |
| 58 | use crate::mute::{MuteCommand, MuteEffect, sync_server_mute}; |
| 59 | use crate::notices::{ |
| 60 | ADMIT_ALL_FAILED_NOTICE, ADMIT_FAILED_NOTICE, ATTENDEE_SETTINGS_FAILED_NOTICE, |
| 61 | BACKGROUND_IMAGE_FAILED_NOTICE, CALL_TRANSFERRED_NOTICE, CAMERA_RESTART_NOTICE, |
| 62 | CAMERA_SETTING_FAILED_NOTICE, CAMERA_START_NOTICE, CAPTION_LANGUAGE_FAILED_NOTICE, |
| 63 | CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE, CHANGE_ROLE_FAILED_NOTICE, |
| 64 | CHANGE_RUNNING_NOTICE, CONFIRM_RECORDING_FAILED_NOTICE, CONSENT_FIRST_NOTICE, |
| 65 | DENY_FAILED_NOTICE, ECHO_TEST_FAILED_NOTICE, HOLD_CHANGE_FAILED_NOTICE, HOLD_FAILED_NOTICE, |
| 66 | INVITE_PERSON_FAILED_NOTICE, LOWER_ALL_HANDS_FAILED_NOTICE, LOWER_HAND_FAILED_NOTICE, |
| 67 | LOWER_THAT_HAND_FAILED_NOTICE, MEETING_LOCK_FAILED_NOTICE, MIC_SETTING_FAILED_NOTICE, |
| 68 | MUTE_ALL_FAILED_NOTICE, MUTE_PARTICIPANT_FAILED_NOTICE, NOT_CONNECTED_FOR_VIDEO, |
| 69 | ON_HOLD_NOTICE, RAISE_HAND_FAILED_NOTICE, REACTION_FAILED_NOTICE, RECORDING_JOIN_FAILED_NOTICE, |
| 70 | RECORDING_NOT_STARTED_NOTICE, RECORDING_START_FAILED_NOTICE, RECORDING_STOP_FAILED_NOTICE, |
| 71 | REMOVE_PARTICIPANT_FAILED_NOTICE, RESUME_FAILED_NOTICE, SHARE_QUEUED_NOTICE, |
| 72 | SHARE_REFUSED_NOTICE, SHARING_START_NOTICE, SPOTLIGHT_FAILED_NOTICE, |
| 73 | STOP_SPOTLIGHT_FAILED_NOTICE, TRANSFER_CALL_FAILED_NOTICE, TRANSFER_FAILED_NOTICE, |
| 74 | TRANSFER_NOT_ALLOWED_NOTICE, TRANSFERRING_NOTICE, VIDEO_FAILED_NOTICE, |
| 75 | WHITEBOARD_OPEN_FAILED_NOTICE, WHITEBOARDS_MEETINGS_ONLY_NOTICE, notice_with_detail, |
| 76 | }; |
| 77 | use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps}; |
| 78 | use crate::outcome::{embedded_end, failed_participant_count, outcome_summary}; |
| 79 | use crate::push::CallNotification; |
| 80 | use crate::recording::{Consent, RecordingPlan, RecordingStatus}; |
| 81 | use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant}; |
| 82 | use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer}; |
| 83 | use crate::roster::{Roster, direct_roster}; |
| 84 | use crate::screen::{ |
| 85 | ShareKind, SharePicker, ShareSource, current_share_picker, list_share_sources, |
| 86 | share_sources_for_menu, share_thumbnail, |
| 87 | }; |
| 88 | use crate::sdp::{ |
| 89 | LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, |
| 90 | to_browser_answer, to_teams_answer, to_teams_offer, |
| 91 | }; |
| 92 | use crate::send_control::{BitrateGovernor, RequestFilter, parse_request}; |
| 93 | use crate::signaling::{ |
| 94 | Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, |
| 95 | NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id, |
| 96 | ensure_echo_bot_thread, escalation_answer_body, one_to_one_thread, renegotiation_body, |
| 97 | }; |
| 98 | use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan}; |
| 99 | use crate::state::{CallSignal, CallState}; |
| 100 | use crate::timeline::{Timeline, TimelineEntry}; |
| 101 | use crate::transfer::{Replacement, TransferEvent, TransferTarget}; |
| 102 | use crate::trouter_events::{ |
| 103 | CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body, |
| 104 | nested_links, object_keys, |
| 105 | }; |
| 106 | use crate::video_frame::{VideoKey, VideoPicture}; |
| 107 | use crate::video_layout::{ |
| 108 | CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SHARE_MID, |
| 109 | SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, |
| 110 | add_share_line, add_video_lines, offer_plan, one_to_one_plan, |
| 111 | }; |
| 112 | use crate::video_receive::{ |
| 113 | ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump, |
| 114 | }; |
| 115 | use crate::video_send::{LocalVideo, SendSource, VideoMode}; |
| 116 | use crate::whiteboard; |
| 117 | |
| 118 | const END_CALLBACK_WAIT: Duration = Duration::from_secs(4); |
| 119 | const STATS_PERIOD: Duration = Duration::from_millis(200); |
| 120 | const TICKS_PER_SECOND: u32 = 5; |
| 121 | const RECONNECT_WINDOW: Duration = Duration::from_secs(30); |
| 122 | const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90); |
| 123 | const BROKER_IDLE_WAIT: Duration = Duration::from_millis(500); |
| 124 | const BROKER_RETRY_WAIT: Duration = Duration::from_secs(3); |
| 125 | const CAMERA_EFFECTS_FAILED_NOTICE: &str = |
| 126 | "Background effects could not start, your camera is sent without them"; |
| 127 | const SETUP_STEP_TIMEOUT: Duration = Duration::from_secs(30); |
| 128 | const DIRECT_OUTGOING_TIMEOUT: Duration = Duration::from_secs(185); |
| 129 | const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365); |
| 130 | const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700; |
| 131 | const MIN_KEEP_ALIVE_SECONDS: u64 = 60; |
| 132 | const KEEP_ALIVE_FRACTION: f64 = 0.9; |
| 133 | const MIC_STREAM: &str = "microphone"; |
| 134 | const DATA_CHANNEL_LABEL: &str = "main-channel"; |
| 135 | pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL"; |
| 136 | const CAPTION_START_LIMIT: Duration = Duration::from_secs(40); |
| 137 | const SEND_CAPABILITIES_LABEL: &str = "POST applyChannelParameters"; |
| 138 | const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2; |
| 139 | const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2; |
| 140 | const BOT_PREFIX: &str = "28:"; |
| 141 | const RECORDING_START_LIMIT: Duration = Duration::from_secs(40); |
| 142 | const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40); |
| 143 | /// Teams sometimes answers a few seconds after the soft limit; keep the local offer until this grace ends. |
| 144 | const SAME_PEER_LATE_GRACE: Duration = Duration::from_secs(15); |
| 145 | const GATHERING_LIMIT: Duration = Duration::from_secs(5); |
| 146 | const RELAY_SETTLE: Duration = Duration::from_millis(200); |
| 147 | const GATHERING_POLL: Duration = Duration::from_millis(50); |
| 148 | const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40); |
| 149 | const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3); |
| 150 | const GLARE_CODE: i64 = 491; |
| 151 | const RETARGET_WAIT: Duration = Duration::from_secs(20); |
| 152 | const CAMERA_STREAM: &str = "camera"; |
| 153 | |
| 154 | #[derive(Debug, Clone)] |
| 155 | pub struct CallOptions { |
| 156 | pub hold_after_connected: Option<Duration>, |
| 157 | pub hard_limit: Option<Duration>, |
| 158 | pub reconnect_window: Duration, |
| 159 | pub audio: AudioMode, |
| 160 | pub video: VideoMode, |
| 161 | pub camera: DeviceChoice, |
| 162 | pub tone_hz: f32, |
| 163 | pub input: DeviceChoice, |
| 164 | pub output: DeviceChoice, |
| 165 | pub relay_host: String, |
| 166 | pub routing: TenantRouting, |
| 167 | pub record_remote: bool, |
| 168 | pub wav_path: Option<PathBuf>, |
| 169 | pub sdp_dump_dir: Option<PathBuf>, |
| 170 | pub trace: bool, |
| 171 | pub data_channel: bool, |
| 172 | pub concurrent: bool, |
| 173 | pub start_camera: bool, |
| 174 | pub mic: MicSettings, |
| 175 | } |
| 176 | |
| 177 | impl Default for CallOptions { |
| 178 | fn default() -> Self { |
| 179 | CallOptions { |
| 180 | hold_after_connected: None, |
| 181 | hard_limit: None, |
| 182 | reconnect_window: RECONNECT_WINDOW, |
| 183 | audio: AudioMode::from_env(), |
| 184 | video: VideoMode::from_env(), |
| 185 | camera: DeviceChoice::SystemDefault, |
| 186 | tone_hz: 440.0, |
| 187 | input: DeviceChoice::SystemDefault, |
| 188 | output: DeviceChoice::SystemDefault, |
| 189 | relay_host: DEFAULT_RELAY_HOST.to_owned(), |
| 190 | routing: TenantRouting::default(), |
| 191 | record_remote: false, |
| 192 | wav_path: None, |
| 193 | sdp_dump_dir: None, |
| 194 | trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(), |
| 195 | data_channel: data_channel_from_env(), |
| 196 | concurrent: false, |
| 197 | start_camera: false, |
| 198 | mic: MicSettings::default(), |
| 199 | } |
| 200 | } |
| 201 | } |
| 202 | |
| 203 | #[derive(Debug, Clone, Default)] |
| 204 | pub struct AudioSecond { |
| 205 | pub second: u32, |
| 206 | pub packets: u64, |
| 207 | pub bytes: u64, |
| 208 | pub audio_level: f64, |
| 209 | pub decoded_rms: f32, |
| 210 | pub tone_ratio: f32, |
| 211 | } |
| 212 | |
| 213 | #[derive(Debug, Clone, Default, PartialEq)] |
| 214 | pub struct VideoReport { |
| 215 | pub inbound_packets: u64, |
| 216 | pub inbound_frames_decoded: u64, |
| 217 | pub inbound_width: u32, |
| 218 | pub inbound_height: u32, |
| 219 | pub frames_received: u64, |
| 220 | pub frames_published: u64, |
| 221 | pub outbound_packets: u64, |
| 222 | pub outbound_frames_encoded: u64, |
| 223 | pub outbound_width: u32, |
| 224 | pub outbound_height: u32, |
| 225 | pub remote_reports: u64, |
| 226 | pub remote_round_trip_ms: f64, |
| 227 | } |
| 228 | |
| 229 | #[derive(Debug, Clone, Default)] |
| 230 | pub struct CallReport { |
| 231 | pub timeline: Vec<TimelineEntry>, |
| 232 | pub ice_connected_ms: Option<u128>, |
| 233 | pub peer_connected_ms: Option<u128>, |
| 234 | pub selected_pair: Option<String>, |
| 235 | pub tls_version: String, |
| 236 | pub dtls_cipher: String, |
| 237 | pub srtp_cipher: String, |
| 238 | pub inbound_packets: u64, |
| 239 | pub inbound_bytes: u64, |
| 240 | pub outbound_packets: u64, |
| 241 | pub video: VideoReport, |
| 242 | pub own_streams: Vec<String>, |
| 243 | pub seconds_with_inbound_audio: u32, |
| 244 | pub seconds: Vec<AudioSecond>, |
| 245 | pub end: Option<CallEnd>, |
| 246 | pub left_cleanly: bool, |
| 247 | pub recorded_samples: usize, |
| 248 | } |
| 249 | |
| 250 | #[derive(Debug, Clone)] |
| 251 | pub enum CallSpec { |
| 252 | Echo, |
| 253 | People { |
| 254 | callees: Vec<Callee>, |
| 255 | thread_id: String, |
| 256 | }, |
| 257 | Meeting(MeetingTarget), |
| 258 | } |
| 259 | |
| 260 | impl CallSpec { |
| 261 | fn target(&self) -> InviteTarget { |
| 262 | match self { |
| 263 | CallSpec::Echo => InviteTarget::Echo, |
| 264 | CallSpec::People { callees, thread_id } => InviteTarget::People { |
| 265 | callees: callees.clone(), |
| 266 | thread_id: thread_id.clone(), |
| 267 | }, |
| 268 | CallSpec::Meeting(meeting) => InviteTarget::Meeting(meeting.clone()), |
| 269 | } |
| 270 | } |
| 271 | |
| 272 | fn is_meeting(&self) -> bool { |
| 273 | matches!(self, CallSpec::Meeting(_)) |
| 274 | } |
| 275 | |
| 276 | fn is_people(&self) -> bool { |
| 277 | matches!(self, CallSpec::People { .. }) |
| 278 | } |
| 279 | |
| 280 | fn callee_count(&self) -> usize { |
| 281 | match self { |
| 282 | CallSpec::People { callees, .. } => callees.len(), |
| 283 | CallSpec::Echo => 1, |
| 284 | CallSpec::Meeting(_) => 0, |
| 285 | } |
| 286 | } |
| 287 | } |
| 288 | |
| 289 | pub(crate) struct IncomingCall { |
| 290 | pub accept: AcceptMode, |
| 291 | pub notification: CallNotification, |
| 292 | pub attached: Attached, |
| 293 | pub links: CallbackLinks, |
| 294 | pub participant: Participant, |
| 295 | pub callbacks: mpsc::UnboundedReceiver<TrouterCallback>, |
| 296 | } |
| 297 | |
| 298 | pub(crate) enum Plan { |
| 299 | Outgoing(CallSpec), |
| 300 | Incoming(Box<IncomingCall>), |
| 301 | } |
| 302 | |
| 303 | fn data_channel_from_env() -> bool { |
| 304 | !matches!( |
| 305 | std::env::var(DATA_CHANNEL_ENV).ok().as_deref(), |
| 306 | Some("0" | "off") |
| 307 | ) |
| 308 | } |
| 309 | |
| 310 | pub fn keep_alive_period(seconds: Option<u64>) -> Duration { |
| 311 | let seconds = seconds |
| 312 | .unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS) |
| 313 | .max(MIN_KEEP_ALIVE_SECONDS); |
| 314 | Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION) |
| 315 | } |
| 316 | |
| 317 | fn random_u32() -> u32 { |
| 318 | let bytes = uuid::Uuid::new_v4().into_bytes(); |
| 319 | u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff |
| 320 | } |
| 321 | |
| 322 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 323 | enum Layout { |
| 324 | Conference, |
| 325 | OneToOne, |
| 326 | } |
| 327 | |
| 328 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 329 | pub enum AcceptMode { |
| 330 | Audio, |
| 331 | Video, |
| 332 | } |
| 333 | |
| 334 | fn remember_call_leg(live: &mut Live, url: Option<&str>) { |
| 335 | let Some(url) = url.filter(|url| !url.is_empty()) else { |
| 336 | return; |
| 337 | }; |
| 338 | if !live.call_legs.iter().any(|known| known == url) { |
| 339 | live.call_legs.push(url.to_owned()); |
| 340 | } |
| 341 | } |
| 342 | |
| 343 | fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool { |
| 344 | let next = state.next(signal, std::time::Instant::now()); |
| 345 | if next == *state { |
| 346 | return false; |
| 347 | } |
| 348 | *state = next.clone(); |
| 349 | control.send(CallUpdate::State(next)); |
| 350 | true |
| 351 | } |
| 352 | |
| 353 | /// Places the Echo test call on its own non-ringable Trouter instance; the app uses a shared engine instead. |
| 354 | pub async fn run_test_call( |
| 355 | session: &Session, |
| 356 | poll_session: &Session, |
| 357 | options: CallOptions, |
| 358 | control: CallControl, |
| 359 | ) -> Result<CallReport> { |
| 360 | let config = EngineConfig { |
| 361 | ringable: false, |
| 362 | routing: options.routing.clone(), |
| 363 | relay_host: options.relay_host.clone(), |
| 364 | trace: options.trace, |
| 365 | dump_dir: None, |
| 366 | instance: chatsvc::InstanceNames { |
| 367 | global: "__testCallTrouter".into(), |
| 368 | binding: "__testCallRealtime".into(), |
| 369 | endpoint_storage_key: "__testCallEpid".into(), |
| 370 | }, |
| 371 | }; |
| 372 | let (engine, _events) = |
| 373 | CallEngine::start(session.clone(), poll_session.clone(), config).await?; |
| 374 | let report = engine |
| 375 | .run(Plan::Outgoing(CallSpec::Echo), options, control) |
| 376 | .await; |
| 377 | engine.stop().await; |
| 378 | report |
| 379 | } |
| 380 | |
| 381 | impl CallEngine { |
| 382 | pub(crate) async fn run( |
| 383 | &self, |
| 384 | plan: Plan, |
| 385 | options: CallOptions, |
| 386 | mut control: CallControl, |
| 387 | ) -> Result<CallReport> { |
| 388 | let inner = self.inner.as_ref(); |
| 389 | let _one_call_at_a_time = if options.concurrent { |
| 390 | None |
| 391 | } else { |
| 392 | match control.until_hangup(inner.gate.lock()).await { |
| 393 | Ok(guard) => Some(guard), |
| 394 | Err(_) => { |
| 395 | if let Plan::Incoming(incoming) = &plan { |
| 396 | inner.unregister_route(incoming.links.call_id()); |
| 397 | if let Some(call_leg) = incoming.attached.links.get("callLeg") { |
| 398 | let signaling = inner.signaling(Timeline::new(options.trace)); |
| 399 | let _ = signaling.decline(call_leg).await; |
| 400 | } |
| 401 | } |
| 402 | let mut state = CallState::Idle; |
| 403 | advance(&mut state, CallSignal::Dial, &control); |
| 404 | advance(&mut state, CallSignal::LocalLeave, &control); |
| 405 | return Ok(CallReport::default()); |
| 406 | } |
| 407 | } |
| 408 | }; |
| 409 | let timeline = Timeline::new(options.trace); |
| 410 | let stay_awake = crate::awake::StayAwake::new(); |
| 411 | timeline.record( |
| 412 | "stay awake", |
| 413 | if stay_awake.holding() { |
| 414 | "system and display kept awake" |
| 415 | } else { |
| 416 | "not available" |
| 417 | }, |
| 418 | ); |
| 419 | let mut report = CallReport::default(); |
| 420 | let mut state = CallState::Idle; |
| 421 | advance(&mut state, CallSignal::Dial, &control); |
| 422 | let mut live = Live::default(); |
| 423 | let recording = Arc::new(Mutex::new(Recording::default())); |
| 424 | let outcome = drive( |
| 425 | inner, |
| 426 | &options, |
| 427 | &timeline, |
| 428 | &recording, |
| 429 | plan, |
| 430 | &mut live, |
| 431 | &mut control, |
| 432 | &mut state, |
| 433 | &mut report, |
| 434 | ) |
| 435 | .await; |
| 436 | let failure = match outcome { |
| 437 | Ok(()) => None, |
| 438 | Err(Error::Cancelled) => { |
| 439 | advance(&mut state, CallSignal::LocalLeave, &control); |
| 440 | None |
| 441 | } |
| 442 | Err(error) |
| 443 | if accept_found_no_call(&error) && matches!(state, CallState::Connecting) => |
| 444 | { |
| 445 | advance(&mut state, CallSignal::LocalLeave, &control); |
| 446 | None |
| 447 | } |
| 448 | Err(error) => { |
| 449 | advance(&mut state, CallSignal::Error(error.to_string()), &control); |
| 450 | Some(error) |
| 451 | } |
| 452 | }; |
| 453 | dump_timeline(&options, &timeline, failure.as_ref()); |
| 454 | let cancelled = live.cancel_leave |
| 455 | || matches!( |
| 456 | &state, |
| 457 | CallState::Ended { |
| 458 | reason: crate::state::EndReason::Cancelled |
| 459 | } |
| 460 | ); |
| 461 | tear_down(live, inner, &timeline, &mut report, cancelled).await; |
| 462 | let recording = recording.lock().await; |
| 463 | report.recorded_samples = recording.samples.len(); |
| 464 | report.timeline = timeline.entries(); |
| 465 | control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new( |
| 466 | &report, |
| 467 | timeline.sdp_summaries(), |
| 468 | )))); |
| 469 | if let Some(path) = &options.wav_path { |
| 470 | write_wav(path, &recording.samples) |
| 471 | .map_err(|error| Error::Webrtc(format!("wav: {error}")))?; |
| 472 | } |
| 473 | match failure { |
| 474 | Some(error) => Err(error), |
| 475 | None => Ok(report), |
| 476 | } |
| 477 | } |
| 478 | } |
| 479 | |
| 480 | /// Teams answers 404 when the caller already hung up. While we are still connecting |
| 481 | /// that is a cancelled ring, not a failed call. |
| 482 | pub(super) fn accept_found_no_call(error: &Error) -> bool { |
| 483 | let Error::Signaling(reason) = error else { |
| 484 | return false; |
| 485 | }; |
| 486 | let reason = reason.to_ascii_lowercase(); |
| 487 | reason.contains("post acceptance") |
| 488 | && reason.contains("http 404") |
| 489 | && reason.contains("does not exist") |
| 490 | } |
| 491 | |
| 492 | async fn setup_step<T, E>( |
| 493 | control: &mut CallControl, |
| 494 | step: impl std::future::Future<Output = std::result::Result<T, E>>, |
| 495 | ) -> Result<T> |
| 496 | where |
| 497 | Error: From<E>, |
| 498 | { |
| 499 | setup_step_within(control, SETUP_STEP_TIMEOUT, step).await |
| 500 | } |
| 501 | |
| 502 | async fn setup_step_within<T, E>( |
| 503 | control: &mut CallControl, |
| 504 | limit: Duration, |
| 505 | step: impl std::future::Future<Output = std::result::Result<T, E>>, |
| 506 | ) -> Result<T> |
| 507 | where |
| 508 | Error: From<E>, |
| 509 | { |
| 510 | match control.until_hangup(timeout(limit, step)).await? { |
| 511 | Ok(result) => Ok(result?), |
| 512 | Err(_) => Err(Error::Signaling("Teams did not answer in time".into())), |
| 513 | } |
| 514 | } |
| 515 | |
| 516 | #[allow(clippy::too_many_arguments)] |
| 517 | async fn drive( |
| 518 | inner: &Inner, |
| 519 | options: &CallOptions, |
| 520 | timeline: &Timeline, |
| 521 | recording: &Arc<Mutex<Recording>>, |
| 522 | plan: Plan, |
| 523 | live: &mut Live, |
| 524 | control: &mut CallControl, |
| 525 | state: &mut CallState, |
| 526 | report: &mut CallReport, |
| 527 | ) -> Result<()> { |
| 528 | let own_mri = format!("8:orgid:{}", inner.identity.object_id); |
| 529 | control.send(CallUpdate::OwnIdentity { |
| 530 | mri: own_mri.clone(), |
| 531 | }); |
| 532 | let (spec, incoming) = match plan { |
| 533 | Plan::Outgoing(spec) => (Some(spec), None), |
| 534 | Plan::Incoming(incoming) => (None, Some(*incoming)), |
| 535 | }; |
| 536 | let accept_mode = incoming |
| 537 | .as_ref() |
| 538 | .map_or(AcceptMode::Audio, |incoming| incoming.accept); |
| 539 | let (links, participant, mut callbacks, incoming_media) = match incoming { |
| 540 | Some(IncomingCall { |
| 541 | accept: _, |
| 542 | notification, |
| 543 | attached, |
| 544 | links, |
| 545 | participant, |
| 546 | callbacks, |
| 547 | }) => ( |
| 548 | links, |
| 549 | participant, |
| 550 | callbacks, |
| 551 | Some((notification, attached)), |
| 552 | ), |
| 553 | None => { |
| 554 | let links = inner.callback_links(); |
| 555 | let participant = inner.participant(&uuid::Uuid::new_v4().to_string()); |
| 556 | let callbacks = inner.register_route(&links); |
| 557 | (links, participant, callbacks, None) |
| 558 | } |
| 559 | }; |
| 560 | live.route_id = Some(links.call_id().to_owned()); |
| 561 | timeline.record("Trouter connected", "callback socket ready"); |
| 562 | |
| 563 | let thread_id = if matches!(spec, Some(CallSpec::Echo)) { |
| 564 | let thread_id = control |
| 565 | .until_hangup(ensure_echo_bot_thread( |
| 566 | &inner.session, |
| 567 | &inner.identity.object_id, |
| 568 | )) |
| 569 | .await??; |
| 570 | timeline.record("echo bot chat", thread_id.clone()); |
| 571 | Some(thread_id) |
| 572 | } else { |
| 573 | None |
| 574 | }; |
| 575 | let grant = control |
| 576 | .until_hangup(inner.relay.grant(&inner.session)) |
| 577 | .await??; |
| 578 | timeline.record( |
| 579 | "GET trap/tokens", |
| 580 | format!("relay grant, expires in {} s", grant.expires_in_seconds), |
| 581 | ); |
| 582 | |
| 583 | let factory = devices::shared_factory(); |
| 584 | let mut input = options.input.clone(); |
| 585 | let mut output = options.output.clone(); |
| 586 | let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output); |
| 587 | audio.set_device_tracks_enabled(false); |
| 588 | control.send(CallUpdate::ListenOnly(audio.listen_only)); |
| 589 | let mut device_lists = devices::list_devices(&factory); |
| 590 | let mut applied_input = devices::applied_device( |
| 591 | &device_lists.inputs, |
| 592 | &input, |
| 593 | devices::system_default_id(Flow::Capture).as_deref(), |
| 594 | ); |
| 595 | let mut applied_output = devices::applied_device( |
| 596 | &device_lists.outputs, |
| 597 | &output, |
| 598 | devices::system_default_id(Flow::Render).as_deref(), |
| 599 | ); |
| 600 | let (_device_watcher, mut device_changes) = device_watch::watch(); |
| 601 | let mut device_debounce = Debounce::default(); |
| 602 | timeline.record( |
| 603 | "audio setup", |
| 604 | format!( |
| 605 | "listen only {}, {} input(s), {} output(s); {}", |
| 606 | audio.listen_only, |
| 607 | device_lists.inputs.len(), |
| 608 | device_lists.outputs.len(), |
| 609 | audio.adm_state |
| 610 | ), |
| 611 | ); |
| 612 | record_audio_devices( |
| 613 | timeline, |
| 614 | &device_lists, |
| 615 | applied_input.as_ref(), |
| 616 | applied_output.as_ref(), |
| 617 | ); |
| 618 | control.send(CallUpdate::Devices(device_lists.clone())); |
| 619 | control.send(CallUpdate::Selected { |
| 620 | input: input.clone(), |
| 621 | output: output.clone(), |
| 622 | }); |
| 623 | let mut mic_settings = options.mic; |
| 624 | let mut track = audio.device_track(mic_settings).clone(); |
| 625 | live.audio = Some(audio); |
| 626 | let mut local_video = LocalVideo::new( |
| 627 | &factory, |
| 628 | options.video, |
| 629 | control.video.clone(), |
| 630 | control.updates(), |
| 631 | ); |
| 632 | local_video.attach_timeline(timeline.clone()); |
| 633 | local_video.attach_commands(control.command_sender()); |
| 634 | let mut camera_choice = options.camera.clone(); |
| 635 | if options.start_camera { |
| 636 | match local_video.preview_camera(&camera_choice) { |
| 637 | Ok(()) => control.send(CallUpdate::Camera(true)), |
| 638 | Err(error) => timeline.record("camera preview failed", error.to_string()), |
| 639 | } |
| 640 | } |
| 641 | let mut media_description_request = 1u32; |
| 642 | refresh_cameras(control.updates(), options.video, timeline.clone()); |
| 643 | control.send(CallUpdate::SharePicker(current_share_picker())); |
| 644 | refresh_share_sources(control.updates(), options.video, false); |
| 645 | |
| 646 | let wants_data_channel = |
| 647 | options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting); |
| 648 | let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?; |
| 649 | live.peers.push(current.peer.clone()); |
| 650 | |
| 651 | let signaling = Arc::new(inner.signaling(timeline.clone())); |
| 652 | let media_leg_id = new_media_leg_id(); |
| 653 | let call_started = Instant::now(); |
| 654 | let mut offered: Option<OfferedMedia> = None; |
| 655 | let mut negotiator = MediaNegotiator::default(); |
| 656 | let mut remote_set = false; |
| 657 | let mut keep_alive_link: Option<String> = None; |
| 658 | let mut keep_alive_seconds: Option<u64> = None; |
| 659 | let mut keep_alive_at: Option<Instant> = None; |
| 660 | let mut outgoing_deadline: Option<Instant> = None; |
| 661 | let mut outgoing_limit = OUTGOING_TIMEOUT; |
| 662 | let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting); |
| 663 | let is_echo = matches!(spec, Some(CallSpec::Echo)); |
| 664 | let mut echo_watch = EchoWatch::default(); |
| 665 | let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count)); |
| 666 | let meeting_target = match &spec { |
| 667 | Some(CallSpec::Meeting(target)) => Some(target.clone()), |
| 668 | _ => None, |
| 669 | }; |
| 670 | let people_thread = match &spec { |
| 671 | Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => { |
| 672 | Some(thread_id.clone()) |
| 673 | } |
| 674 | _ => incoming_media |
| 675 | .as_ref() |
| 676 | .filter(|(notification, _)| !notification.is_multi_party) |
| 677 | .and_then(|(notification, _)| { |
| 678 | notification |
| 679 | .thread_id |
| 680 | .clone() |
| 681 | .filter(|thread| *thread != notification.caller.mri) |
| 682 | .or_else(|| { |
| 683 | one_to_one_thread(&inner.identity.object_id, ¬ification.caller.mri) |
| 684 | }) |
| 685 | }), |
| 686 | }; |
| 687 | let mut layout = match &spec { |
| 688 | Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne, |
| 689 | _ => Layout::Conference, |
| 690 | }; |
| 691 | let peer_mri = match &spec { |
| 692 | Some(CallSpec::People { callees, .. }) if callees.len() == 1 => { |
| 693 | Some(callees[0].mri.clone()) |
| 694 | } |
| 695 | _ => incoming_media |
| 696 | .as_ref() |
| 697 | .map(|(notification, _)| notification.caller.mri.clone()), |
| 698 | }; |
| 699 | let mut layout_plan: OfferPlan; |
| 700 | let mut direct_video_mid: Option<String> = None; |
| 701 | let mut initial_share_mid: Option<String> = None; |
| 702 | let mut sending_camera = false; |
| 703 | let mut media_links: BTreeMap<String, String> = BTreeMap::new(); |
| 704 | |
| 705 | let conversation = match (spec, incoming_media) { |
| 706 | (Some(spec), None) => { |
| 707 | let direct_invite = spec.target().is_one_to_one() && !options.concurrent; |
| 708 | let offer_started = Instant::now(); |
| 709 | let media = control |
| 710 | .until_hangup(create_offer( |
| 711 | ¤t.peer, |
| 712 | &factory, |
| 713 | &track, |
| 714 | layout, |
| 715 | direct_invite.then_some(¤t.gathered), |
| 716 | )) |
| 717 | .await??; |
| 718 | timeline.record( |
| 719 | "offer created", |
| 720 | format!("{} ms", offer_started.elapsed().as_millis()), |
| 721 | ); |
| 722 | layout_plan = media.plan.clone(); |
| 723 | if layout == Layout::OneToOne { |
| 724 | direct_video_mid = Some(CAMERA_MID.to_owned()); |
| 725 | } |
| 726 | timeline.record( |
| 727 | "setLocalDescription", |
| 728 | format!("{} m-line(s) signaled", media.signaled.lines.len()), |
| 729 | ); |
| 730 | timeline.record_sdp("local offer", &media.signaled.sdp); |
| 731 | dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer); |
| 732 | dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp); |
| 733 | let target = spec.target(); |
| 734 | let invitation = Invitation { |
| 735 | from: &participant, |
| 736 | offer_sdp: &media.signaled.sdp, |
| 737 | media_leg_id: &media_leg_id, |
| 738 | callbacks: &links, |
| 739 | target: &target, |
| 740 | modalities: &media.modalities, |
| 741 | direct: !options.concurrent, |
| 742 | }; |
| 743 | let threadless = invitation.is_direct(); |
| 744 | let conversation = match &target { |
| 745 | InviteTarget::Meeting(meeting) => { |
| 746 | let subscribed = control |
| 747 | .until_hangup(signaling.subscribe_meeting(&participant, &links, meeting)) |
| 748 | .await??; |
| 749 | setup_step(control, signaling.join_meeting(&subscribed, &invitation)).await? |
| 750 | } |
| 751 | _ => setup_step(control, signaling.create_conversation(&invitation)).await?, |
| 752 | }; |
| 753 | // People and the Echo test call share outgoing ringback while connecting. |
| 754 | if spec.is_people() || matches!(spec, CallSpec::Echo) { |
| 755 | control.send(CallUpdate::Progress(Progress::Calling)); |
| 756 | } |
| 757 | if spec.is_people() { |
| 758 | if threadless { |
| 759 | outgoing_limit = DIRECT_OUTGOING_TIMEOUT; |
| 760 | } |
| 761 | outgoing_deadline = Some(Instant::now() + outgoing_limit); |
| 762 | } |
| 763 | if let Err(error) = local_video.set_lines(media.video.clone()) { |
| 764 | timeline.record("video lines not attached", error.to_string()); |
| 765 | } |
| 766 | offered = Some(media); |
| 767 | live.remote = Some(RemoteCall { |
| 768 | signaling: signaling.clone(), |
| 769 | conversation: conversation.clone(), |
| 770 | participant: participant.clone(), |
| 771 | threadless, |
| 772 | }); |
| 773 | conversation |
| 774 | } |
| 775 | (None, Some((notification, attached))) => { |
| 776 | let teams_offer = attached |
| 777 | .offer_sdp |
| 778 | .clone() |
| 779 | .ok_or_else(|| Error::Signaling("attach answer without an offer".into()))?; |
| 780 | let conversation = attached |
| 781 | .conversation |
| 782 | .clone() |
| 783 | .ok_or_else(|| Error::Signaling("attach answer without a conversation".into()))?; |
| 784 | live.remote = Some(RemoteCall { |
| 785 | signaling: signaling.clone(), |
| 786 | conversation: conversation.clone(), |
| 787 | participant: participant.clone(), |
| 788 | threadless: notification.thread_id.is_none(), |
| 789 | }); |
| 790 | let one_to_one = !attached.from_mixer && !notification.is_multi_party; |
| 791 | layout = if one_to_one { |
| 792 | Layout::OneToOne |
| 793 | } else { |
| 794 | Layout::Conference |
| 795 | }; |
| 796 | let camera_track = local_video.camera_track(); |
| 797 | let video_answer = match accept_mode { |
| 798 | _ if !one_to_one => AnswerVideo::Reject, |
| 799 | AcceptMode::Video if local_video.is_available() => AnswerVideo::Send(&camera_track), |
| 800 | _ => AnswerVideo::Receive, |
| 801 | }; |
| 802 | dump_sdp(options, "3-teams-offer.sdp", &teams_offer); |
| 803 | let answered = answer_offer( |
| 804 | ¤t.peer, |
| 805 | Some(&track), |
| 806 | &teams_offer, |
| 807 | video_answer, |
| 808 | None, |
| 809 | false, |
| 810 | one_to_one.then_some(¤t.gathered), |
| 811 | ) |
| 812 | .await?; |
| 813 | layout_plan = answered.remote.plan(); |
| 814 | direct_video_mid = answered.camera_mid.clone(); |
| 815 | initial_share_mid = answered.receiving_share_mid.clone(); |
| 816 | timeline.record( |
| 817 | "setRemoteDescription", |
| 818 | format!( |
| 819 | "offer applied, {} signaled line(s)", |
| 820 | answered.remote.lines.len() |
| 821 | ), |
| 822 | ); |
| 823 | if one_to_one { |
| 824 | timeline.record("ice gathered", current.gathered.summary()); |
| 825 | } |
| 826 | timeline.record_sdp("remote offer", &teams_offer); |
| 827 | timeline.record_sdp("local answer", &answered.answer_sdp); |
| 828 | dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp); |
| 829 | let acceptance_url = attached.links.get("acceptance").ok_or_else(|| { |
| 830 | Error::Signaling("attach answer without an acceptance link".into()) |
| 831 | })?; |
| 832 | let modalities = accepted_modalities( |
| 833 | matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some(), |
| 834 | ); |
| 835 | let acknowledged = setup_step( |
| 836 | control, |
| 837 | signaling.accept( |
| 838 | acceptance_url, |
| 839 | &Answer { |
| 840 | from: &participant, |
| 841 | answer_sdp: &answered.answer_sdp, |
| 842 | media_leg_id: &media_leg_id, |
| 843 | callbacks: &links, |
| 844 | modalities: &modalities, |
| 845 | }, |
| 846 | ), |
| 847 | ) |
| 848 | .await?; |
| 849 | negotiator.answered_incoming(attached.from_mixer); |
| 850 | remote_set = true; |
| 851 | media_links.extend(attached.links.clone()); |
| 852 | media_links.extend(acknowledged); |
| 853 | if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) { |
| 854 | let camera = peer_transceiver(¤t.peer, mid); |
| 855 | match camera.map(|camera| { |
| 856 | local_video.set_lines(VideoLines { |
| 857 | camera, |
| 858 | share: None, |
| 859 | }) |
| 860 | }) { |
| 861 | Some(Ok(())) => match local_video.start_camera(&camera_choice) { |
| 862 | Ok(()) => sending_camera = true, |
| 863 | Err(error) => control.send(CallUpdate::Notice(notice_with_detail( |
| 864 | CAMERA_START_NOTICE, |
| 865 | error, |
| 866 | ))), |
| 867 | }, |
| 868 | Some(Err(error)) => { |
| 869 | timeline.record("video lines not attached", error.to_string()) |
| 870 | } |
| 871 | None => timeline.record( |
| 872 | "video lines not attached", |
| 873 | "no transceiver for the camera line", |
| 874 | ), |
| 875 | } |
| 876 | } |
| 877 | keep_alive_link = media_links.get("callLeg").cloned(); |
| 878 | remember_call_leg(live, keep_alive_link.as_deref()); |
| 879 | keep_alive_at = Some(Instant::now() + keep_alive_period(None)); |
| 880 | conversation |
| 881 | } |
| 882 | _ => { |
| 883 | return Err(Error::Callback( |
| 884 | "call plan without an offer or an invitation".into(), |
| 885 | )); |
| 886 | } |
| 887 | }; |
| 888 | let remote = live.remote.clone().expect("remote call set above"); |
| 889 | live.broker_running.store(true, Ordering::SeqCst); |
| 890 | live.broker = Some(tokio::spawn(poll_broker( |
| 891 | signaling.clone(), |
| 892 | conversation.clone(), |
| 893 | live.broker_running.clone(), |
| 894 | ))); |
| 895 | |
| 896 | let initial = MuteEffect::initial(is_meeting); |
| 897 | let mut muted = initial.muted; |
| 898 | let mut server_mute_cleared = false; |
| 899 | live.audio |
| 900 | .as_ref() |
| 901 | .expect("audio set above") |
| 902 | .set_device_tracks_enabled(initial.track_enabled); |
| 903 | if muted { |
| 904 | control.send(CallUpdate::Muted(true)); |
| 905 | } |
| 906 | match setup_step( |
| 907 | control, |
| 908 | signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted), |
| 909 | ) |
| 910 | .await |
| 911 | { |
| 912 | Err(Error::Cancelled) => return Err(Error::Cancelled), |
| 913 | Err(error) => timeline.record("updateEndpointState failed", error.to_string()), |
| 914 | Ok(()) => {} |
| 915 | } |
| 916 | |
| 917 | let mut stats_tick = interval(STATS_PERIOD); |
| 918 | let mut speaking_sources: Vec<u32> = Vec::new(); |
| 919 | let mut speaker_sources_seen = false; |
| 920 | let hard_deadline = options.hard_limit.map(|limit| call_started + limit); |
| 921 | let mut leave_at = hard_deadline; |
| 922 | let mut reconnect_deadline: Option<Instant> = None; |
| 923 | let mut next: Option<NextPeer> = None; |
| 924 | let mut roster = Roster::default(); |
| 925 | if let Some(snapshot) = &conversation.roster |
| 926 | && roster.apply_snapshot(snapshot) |
| 927 | { |
| 928 | let entries = roster.entries(); |
| 929 | timeline.record( |
| 930 | "roster", |
| 931 | format!( |
| 932 | "{} participant(s) from the conversation answer", |
| 933 | entries.len() |
| 934 | ), |
| 935 | ); |
| 936 | control.send(CallUpdate::Roster(entries)); |
| 937 | } |
| 938 | let mut lobby = false; |
| 939 | let mut capability = MeetingCapability::default(); |
| 940 | let mut previous_packets = 0u64; |
| 941 | let mut ticks = 0u32; |
| 942 | let mut host_cpu = std::collections::HashMap::new(); |
| 943 | let mut segmentation_model: Option<&'static str> = None; |
| 944 | let mut health_sampler = HealthSampler::default(); |
| 945 | let mut quality_tracker = QualityTracker::default(); |
| 946 | let mut second = 0u32; |
| 947 | let echo_thread = thread_id; |
| 948 | let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default()); |
| 949 | if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) { |
| 950 | video.router().set(mid, Some(VideoKey::Person(mri.clone()))); |
| 951 | } |
| 952 | if let Some(mid) = &initial_share_mid { |
| 953 | video.router().set(mid, Some(VideoKey::Screen)); |
| 954 | control.send(CallUpdate::ScreenShare(peer_mri.clone())); |
| 955 | } |
| 956 | if sending_camera { |
| 957 | control.send(CallUpdate::Camera(true)); |
| 958 | } |
| 959 | let mut software_audio: Option<SoftwareAudio> = None; |
| 960 | let mut share_sound_wanted = false; |
| 961 | let mut audio_disabled = false; |
| 962 | let mut remote_audio: Option<RtcAudioTrack> = None; |
| 963 | sync_software_audio( |
| 964 | &factory, |
| 965 | options, |
| 966 | &input, |
| 967 | muted, |
| 968 | None, |
| 969 | ¤t.peer, |
| 970 | &track, |
| 971 | software_wanted( |
| 972 | mic_settings, |
| 973 | share_sound_wanted, |
| 974 | &local_video, |
| 975 | live.audio.as_ref(), |
| 976 | ), |
| 977 | false, |
| 978 | &mut software_audio, |
| 979 | mic_settings, |
| 980 | control, |
| 981 | timeline, |
| 982 | ); |
| 983 | let mut own_hand: Option<String> = None; |
| 984 | let mut depacketizer = Depacketizer::default(); |
| 985 | let mut caption_flow = CaptionFlow::default(); |
| 986 | let mut caption_deadline: Option<Instant> = None; |
| 987 | let mut recording_flow = CaptionFlow::default(); |
| 988 | let mut recording_deadline: Option<Instant> = None; |
| 989 | let mut recording_plan = RecordingPlan::default(); |
| 990 | let mut recording_audio_only = false; |
| 991 | let mut recording_status = RecordingStatus::default(); |
| 992 | let mut bot_pending = false; |
| 993 | let mut consent_pending = false; |
| 994 | let mut room_watcher = RoomWatcher::default(); |
| 995 | let mut main_meeting_sent = false; |
| 996 | let mut local_hold = false; |
| 997 | let mut remote_hold = false; |
| 998 | let mut same_peer: Option<SamePeerOffer> = None; |
| 999 | let mut send_requests = RequestFilter::default(); |
| 1000 | let mut send_capabilities = SendCapabilityReporter::default(); |
| 1001 | let mut bitrate_governor = BitrateGovernor::default(); |
| 1002 | let mut same_peer_deadline: Option<Instant> = None; |
| 1003 | let mut same_peer_grace_until: Option<Instant> = None; |
| 1004 | let mut meeting_chat = conversation.chat_thread.clone(); |
| 1005 | if let Some(thread) = &meeting_chat { |
| 1006 | control.send(CallUpdate::MeetingChat(thread.clone())); |
| 1007 | } |
| 1008 | if let Some(target) = &meeting_target { |
| 1009 | control.send(CallUpdate::MeetingTenant(target.tenant_id.clone())); |
| 1010 | } |
| 1011 | if meeting_chat.is_none() { |
| 1012 | meeting_chat = people_thread; |
| 1013 | } |
| 1014 | let mut start_camera_pending = options.start_camera; |
| 1015 | let mut share_pending: Option<ShareSource> = None; |
| 1016 | let mut portal_pending: Option<ShareKind> = None; |
| 1017 | let mut glare_resend: Option<GlareResend> = None; |
| 1018 | let mut deferred_changes: Vec<Change> = Vec::new(); |
| 1019 | let mut remote_direct_share: Option<String> = initial_share_mid.clone(); |
| 1020 | let mut sent_replacement: Option<Replacement> = None; |
| 1021 | let (echo_add_tx, mut echo_add_rx) = mpsc::unbounded_channel::<Result<()>>(); |
| 1022 | let mut echo_add_pending = false; |
| 1023 | loop { |
| 1024 | let possible = video_possible(remote_set, layout, negotiator.path()); |
| 1025 | if camera_may_start(start_camera_pending, next.is_some(), possible) { |
| 1026 | start_camera_pending = false; |
| 1027 | control.defer(CallCommand::SetCamera(true)); |
| 1028 | } |
| 1029 | if camera_may_start(share_pending.is_some(), next.is_some(), possible) |
| 1030 | && let Some(source) = share_pending.take() |
| 1031 | { |
| 1032 | control.defer(CallCommand::StartShare(source)); |
| 1033 | } |
| 1034 | if camera_may_start(portal_pending.is_some(), next.is_some(), possible) |
| 1035 | && let Some(kind) = portal_pending.take() |
| 1036 | { |
| 1037 | control.defer(CallCommand::StartPortalShare(kind)); |
| 1038 | } |
| 1039 | if next.as_ref().is_some_and(|pending| { |
| 1040 | pending.connected && (pending.offered.is_some() || pending.retargeted) |
| 1041 | }) && let Some(pending) = next.take() |
| 1042 | { |
| 1043 | timeline.record( |
| 1044 | "escalation", |
| 1045 | "new peer connection connected, old one dropped", |
| 1046 | ); |
| 1047 | deferred_changes.clear(); |
| 1048 | negotiator.server_escalation_done(); |
| 1049 | // New mixer leg starts sequence numbers from 1 and has not heard our send capabilities yet. |
| 1050 | send_requests = RequestFilter::default(); |
| 1051 | send_capabilities = SendCapabilityReporter::default(); |
| 1052 | if let Some(mid) = remote_direct_share.take() { |
| 1053 | video.router().set(&mid, None); |
| 1054 | control.send(CallUpdate::ScreenShare(None)); |
| 1055 | } |
| 1056 | // Detach local senders before closing: otherwise peer.close can hang |
| 1057 | // while the camera/share capture threads still feed the old track. |
| 1058 | local_video.clear_lines(); |
| 1059 | replace_leg_media_links(&mut media_links, &pending.leg_links); |
| 1060 | let leg_names = pending |
| 1061 | .leg_links |
| 1062 | .keys() |
| 1063 | .cloned() |
| 1064 | .collect::<Vec<_>>() |
| 1065 | .join(","); |
| 1066 | timeline.record( |
| 1067 | "leg links", |
| 1068 | if leg_names.is_empty() { |
| 1069 | "none".to_owned() |
| 1070 | } else { |
| 1071 | leg_names |
| 1072 | }, |
| 1073 | ); |
| 1074 | if let Some(url) = media_links.get("callLeg").cloned() |
| 1075 | && keep_alive_link.as_deref() != Some(url.as_str()) |
| 1076 | { |
| 1077 | keep_alive_link = Some(url.clone()); |
| 1078 | remember_call_leg(live, Some(&url)); |
| 1079 | } |
| 1080 | if let Some(track) = pending.remote_audio { |
| 1081 | remote_audio = Some(track.clone()); |
| 1082 | if options.record_remote { |
| 1083 | tokio::spawn(record_track(track, recording.clone(), options.tone_hz)); |
| 1084 | } |
| 1085 | } |
| 1086 | let old = std::mem::replace(&mut current, pending.session); |
| 1087 | old.peer.close(); |
| 1088 | reconnect_deadline = None; |
| 1089 | if callee_gate.media_connected() { |
| 1090 | advance(state, CallSignal::MediaConnected, control); |
| 1091 | } |
| 1092 | if let Some(audio) = &software_audio |
| 1093 | && let Err(error) = swap_audio_track(¤t.peer, &audio.track) |
| 1094 | { |
| 1095 | timeline.record("computer sound not carried over", error.to_string()); |
| 1096 | } |
| 1097 | if remote_audio.is_some() { |
| 1098 | sync_software_audio( |
| 1099 | &factory, |
| 1100 | options, |
| 1101 | &input, |
| 1102 | muted || local_hold, |
| 1103 | remote_audio.clone(), |
| 1104 | ¤t.peer, |
| 1105 | &track, |
| 1106 | software_wanted( |
| 1107 | mic_settings, |
| 1108 | share_sound_wanted, |
| 1109 | &local_video, |
| 1110 | live.audio.as_ref(), |
| 1111 | ), |
| 1112 | true, |
| 1113 | &mut software_audio, |
| 1114 | mic_settings, |
| 1115 | control, |
| 1116 | timeline, |
| 1117 | ); |
| 1118 | } |
| 1119 | offered = pending.offered; |
| 1120 | let answered = pending.answered; |
| 1121 | if let Some(mid) = direct_video_mid.take() { |
| 1122 | video.router().set(&mid, None); |
| 1123 | } |
| 1124 | if let Some(media) = &offered { |
| 1125 | layout = Layout::Conference; |
| 1126 | layout_plan = media.plan.clone(); |
| 1127 | if let Err(error) = local_video.set_lines(media.video.clone()) { |
| 1128 | timeline.record("video lines not attached", error.to_string()); |
| 1129 | } |
| 1130 | tell_bound_camera( |
| 1131 | &remote, |
| 1132 | &media_links, |
| 1133 | &local_video, |
| 1134 | &mut media_description_request, |
| 1135 | timeline, |
| 1136 | ); |
| 1137 | tell_bound_share( |
| 1138 | &remote, |
| 1139 | &media_links, |
| 1140 | &local_video, |
| 1141 | &mut media_description_request, |
| 1142 | timeline, |
| 1143 | ); |
| 1144 | } else if let Some(answered) = answered { |
| 1145 | // Server escalation answered on a new peer: drop the old peer's |
| 1146 | // senders and bind the camera/share lines that stayed alive there. |
| 1147 | layout = Layout::Conference; |
| 1148 | layout_plan = answered.remote.plan(); |
| 1149 | match video_lines_from_answer(¤t.peer, &answered) { |
| 1150 | Some(lines) => { |
| 1151 | if let Err(error) = local_video.set_lines(lines) { |
| 1152 | timeline.record("video lines not attached", error.to_string()); |
| 1153 | } |
| 1154 | } |
| 1155 | None => { |
| 1156 | local_video.clear_lines(); |
| 1157 | timeline.record( |
| 1158 | "video lines not attached", |
| 1159 | "no transceiver for the answered camera line", |
| 1160 | ); |
| 1161 | } |
| 1162 | } |
| 1163 | negotiate_video_lines( |
| 1164 | &mut video, |
| 1165 | &signaling, |
| 1166 | control, |
| 1167 | timeline, |
| 1168 | &answered.offer_sdp, |
| 1169 | &answered.remote.lines, |
| 1170 | true, |
| 1171 | &media_links, |
| 1172 | &roster, |
| 1173 | ); |
| 1174 | tell_bound_camera( |
| 1175 | &remote, |
| 1176 | &media_links, |
| 1177 | &local_video, |
| 1178 | &mut media_description_request, |
| 1179 | timeline, |
| 1180 | ); |
| 1181 | tell_bound_share( |
| 1182 | &remote, |
| 1183 | &media_links, |
| 1184 | &local_video, |
| 1185 | &mut media_description_request, |
| 1186 | timeline, |
| 1187 | ); |
| 1188 | } else { |
| 1189 | local_video.clear_lines(); |
| 1190 | } |
| 1191 | remote_set = true; |
| 1192 | if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() { |
| 1193 | let pending = escalate( |
| 1194 | &factory, |
| 1195 | &grant, |
| 1196 | options, |
| 1197 | outgoing_track(software_audio.as_ref(), &track), |
| 1198 | &remote, |
| 1199 | &links, |
| 1200 | &media_leg_id, |
| 1201 | &media_links, |
| 1202 | &mut negotiator, |
| 1203 | live, |
| 1204 | timeline, |
| 1205 | ) |
| 1206 | .await; |
| 1207 | if pending.is_none() { |
| 1208 | drop_local_media(&mut local_video, control); |
| 1209 | } |
| 1210 | next = pending.or(next); |
| 1211 | } |
| 1212 | } |
| 1213 | let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline); |
| 1214 | let glare_at = glare_resend.as_ref().map(|resend| resend.at); |
| 1215 | tokio::select! { |
| 1216 | Some(callback) = callbacks.recv() => { |
| 1217 | match handle_callback(&callback, timeline) { |
| 1218 | Ok(CallEvent::Acceptance(acceptance)) => { |
| 1219 | if !acceptance.from_mixer |
| 1220 | && let Some(accepted_by) = &acceptance.accepted_by |
| 1221 | && roster.apply(&direct_roster(&[(own_mri.as_str(), participant.display_name.as_str()), (accepted_by.mri.as_str(), accepted_by.display_name.as_str())])) |
| 1222 | { |
| 1223 | control.send(CallUpdate::Roster(roster.entries())); |
| 1224 | } |
| 1225 | if !acceptance.from_mixer && callee_gate.callee_joined() { |
| 1226 | advance(state, CallSignal::MediaConnected, control); |
| 1227 | } |
| 1228 | let action = negotiator.on_acceptance(acceptance.from_mixer, layout == Layout::OneToOne); |
| 1229 | match action { |
| 1230 | MediaAction::ApplyAnswer | MediaAction::ApplyAnswerThenEscalate => { |
| 1231 | let Some(media) = offered.as_ref() else { continue }; |
| 1232 | dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp); |
| 1233 | if let Ok(answer) = to_browser_answer(&acceptance.sdp, &media.signaled, &media.browser_offer) { |
| 1234 | dump_sdp(options, "4-browser-answer.sdp", &answer); |
| 1235 | } |
| 1236 | apply_answer(¤t.peer, &acceptance.sdp, &media.signaled, &media.browser_offer) |
| 1237 | .await |
| 1238 | .inspect_err(|error| timeline.record("answer rejected", error.to_string()))?; |
| 1239 | remote_set = true; |
| 1240 | media_links.extend(acceptance.links.clone()); |
| 1241 | if layout == Layout::Conference { |
| 1242 | negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster); |
| 1243 | } |
| 1244 | if let Some(link) = acceptance.links.get("replacement") |
| 1245 | && sent_replacement.as_ref().is_none_or(|sent| sent.participant_id.is_none()) |
| 1246 | { |
| 1247 | let replacement = Replacement::of_call(link.clone()); |
| 1248 | sent_replacement = Some(replacement.clone()); |
| 1249 | control.send(CallUpdate::ReplacementLink(replacement)); |
| 1250 | } |
| 1251 | if !callee_gate.is_waiting() { |
| 1252 | outgoing_deadline = None; |
| 1253 | } |
| 1254 | let directions: Vec<String> = current |
| 1255 | .peer |
| 1256 | .transceivers() |
| 1257 | .iter() |
| 1258 | .map(|transceiver| format!("{:?}", transceiver.current_direction())) |
| 1259 | .collect(); |
| 1260 | timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(","))); |
| 1261 | if acceptance.in_lobby() { |
| 1262 | lobby = true; |
| 1263 | control.send(CallUpdate::Lobby(true)); |
| 1264 | } |
| 1265 | keep_alive_link = acceptance.links.get("callLeg").cloned(); |
| 1266 | remember_call_leg(live, keep_alive_link.as_deref()); |
| 1267 | keep_alive_seconds = acceptance.keep_alive_seconds; |
| 1268 | keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds)); |
| 1269 | if action == MediaAction::ApplyAnswerThenEscalate { |
| 1270 | 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; |
| 1271 | next = pending.or(next); |
| 1272 | } |
| 1273 | let remote = remote.clone(); |
| 1274 | let links = links.clone(); |
| 1275 | let thread_id = echo_thread.clone(); |
| 1276 | let echo_add_tx = echo_add_tx.clone(); |
| 1277 | if is_echo { |
| 1278 | echo_add_pending = true; |
| 1279 | } |
| 1280 | tokio::spawn(async move { |
| 1281 | if is_echo { |
| 1282 | let result = remote |
| 1283 | .signaling |
| 1284 | .add_echo_bot( |
| 1285 | &remote.conversation, |
| 1286 | &remote.participant, |
| 1287 | thread_id.as_deref(), |
| 1288 | &links, |
| 1289 | ) |
| 1290 | .await; |
| 1291 | let ok = result.is_ok(); |
| 1292 | let _ = echo_add_tx.send(result); |
| 1293 | if !ok { |
| 1294 | return; |
| 1295 | } |
| 1296 | } |
| 1297 | let _ = remote |
| 1298 | .signaling |
| 1299 | .update_endpoint_metadata( |
| 1300 | &remote.conversation, |
| 1301 | &remote.participant, |
| 1302 | ) |
| 1303 | .await; |
| 1304 | }); |
| 1305 | } |
| 1306 | MediaAction::Escalate => { |
| 1307 | 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; |
| 1308 | next = pending.or(next); |
| 1309 | } |
| 1310 | _ => {} |
| 1311 | } |
| 1312 | } |
| 1313 | Ok(CallEvent::MediaAnswer(answer)) if !remote_set && !answer.from_mixer && same_peer.is_none() && next.is_none() && outgoing_deadline.is_some() => { |
| 1314 | timeline.record("provisional answer", if answer.no_ring_back { "no ringback" } else { "ringing" }); |
| 1315 | outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT); |
| 1316 | if !answer.no_ring_back { |
| 1317 | control.send(CallUpdate::Progress(Progress::Ringing)); |
| 1318 | } |
| 1319 | } |
| 1320 | Ok(CallEvent::MediaAnswer(answer)) |
| 1321 | if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) => |
| 1322 | { |
| 1323 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 1324 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 1325 | } |
| 1326 | if answer.from_mixer { |
| 1327 | negotiator.note_mixer_path(); |
| 1328 | } |
| 1329 | if let Some(resend) = glare_resend.as_mut() { |
| 1330 | resend.at = Instant::now(); |
| 1331 | } |
| 1332 | } |
| 1333 | Ok(CallEvent::MediaAnswer(answer)) => { |
| 1334 | let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) |
| 1335 | || next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)); |
| 1336 | if (same_peer.is_some() || next.is_some()) && !belongs { |
| 1337 | timeline.record("media answer ignored", "it answers an offer that is no longer pending"); |
| 1338 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 1339 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 1340 | } |
| 1341 | continue; |
| 1342 | } |
| 1343 | let action = negotiator.on_media_answer(); |
| 1344 | if action == MediaAction::Ignore |
| 1345 | && let Some(url) = answer.links.get("mediaAcknowledgement") |
| 1346 | { |
| 1347 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 1348 | } |
| 1349 | if action == MediaAction::ApplyOnSamePeer |
| 1350 | && let Some(pending) = same_peer.take() |
| 1351 | { |
| 1352 | same_peer_deadline = None; |
| 1353 | same_peer_grace_until = None; |
| 1354 | let applied = match pending.change { |
| 1355 | Change::Hold(_) => apply_hold_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await, |
| 1356 | Change::Camera(_) | Change::Share(_) => apply_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await, |
| 1357 | }; |
| 1358 | match applied { |
| 1359 | Ok(()) => { |
| 1360 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 1361 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 1362 | } |
| 1363 | match pending.change { |
| 1364 | Change::Hold(hold) => { |
| 1365 | local_hold = hold; |
| 1366 | silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref()); |
| 1367 | control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold))); |
| 1368 | } |
| 1369 | Change::Camera(on) => control.send(CallUpdate::Camera(on)), |
| 1370 | Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => { |
| 1371 | local_video.stop_share(); |
| 1372 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline); |
| 1373 | clear_share(control); |
| 1374 | control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into())); |
| 1375 | } |
| 1376 | Change::Share(_) => {} |
| 1377 | } |
| 1378 | if answer.from_mixer { |
| 1379 | media_links.extend(answer.links.clone()); |
| 1380 | let wants_video = !local_hold && (local_video.camera_on() || local_video.sharing()); |
| 1381 | let upgrade = wants_video |
| 1382 | && (negotiator.escalate_after_mixer_answer() || (layout == Layout::OneToOne && next.is_none() && negotiator.begin_conference_upgrade())); |
| 1383 | if !wants_video { |
| 1384 | negotiator.note_mixer_path(); |
| 1385 | } else if upgrade { |
| 1386 | 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; |
| 1387 | if pending.is_none() { |
| 1388 | drop_local_media(&mut local_video, control); |
| 1389 | } |
| 1390 | next = pending.or(next); |
| 1391 | } |
| 1392 | } |
| 1393 | } |
| 1394 | Err(error) => { |
| 1395 | timeline.record("same-peer answer rejected", error.to_string()); |
| 1396 | undo_change(pending.change, &mut local_video, control); |
| 1397 | } |
| 1398 | } |
| 1399 | } |
| 1400 | if action == MediaAction::ApplyOnNewPeer { |
| 1401 | let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) { |
| 1402 | Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await, |
| 1403 | None => Err(Error::Webrtc("no pending peer connection for the answer".into())), |
| 1404 | }; |
| 1405 | match applied { |
| 1406 | Ok(()) => { |
| 1407 | if let Some(pending) = next.as_mut() { |
| 1408 | pending.leg_links.extend(answer.links.clone()); |
| 1409 | } |
| 1410 | if let Some(media) = next.as_ref().and_then(|pending| pending.offered.as_ref()) { |
| 1411 | media_links.extend(answer.links.clone()); |
| 1412 | negotiate_video(&mut video, &signaling, control, timeline, &answer.sdp, media, true, &media_links, &roster); |
| 1413 | } |
| 1414 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 1415 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 1416 | } |
| 1417 | } |
| 1418 | Err(error) => { |
| 1419 | negotiator.escalation_failed(); |
| 1420 | if let Some(pending) = next.take() { |
| 1421 | pending.session.peer.close(); |
| 1422 | } |
| 1423 | if layout == Layout::OneToOne { |
| 1424 | drop_local_media(&mut local_video, control); |
| 1425 | } |
| 1426 | timeline.record("escalation answer rejected", error.to_string()); |
| 1427 | } |
| 1428 | } |
| 1429 | } |
| 1430 | } |
| 1431 | Ok(CallEvent::MediaRenegotiation(renegotiation)) => { |
| 1432 | if !renegotiation.escalation |
| 1433 | && !renegotiation.new_offer |
| 1434 | && let Some(pending) = same_peer.take() |
| 1435 | { |
| 1436 | same_peer_deadline = None; |
| 1437 | same_peer_grace_until = None; |
| 1438 | negotiator.same_peer_offer_failed(); |
| 1439 | rollback_offer(¤t.peer).await; |
| 1440 | timeline.record("glare", "the remote offer is answered first, ours goes out again after"); |
| 1441 | glare_resend = Some(GlareResend { change: pending.change, reply_tags: pending.reply_tags, at: Instant::now() + GLARE_RESEND_LIMIT }); |
| 1442 | } |
| 1443 | let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation); |
| 1444 | let rejection_link = renegotiation.links.get("rejection").cloned(); |
| 1445 | let result = match action { |
| 1446 | MediaAction::AnswerOnNewPeer => { |
| 1447 | if let Some(pending) = same_peer.take() { |
| 1448 | same_peer_deadline = None; |
| 1449 | same_peer_grace_until = None; |
| 1450 | timeline.record("same-peer offer", "superseded by the escalation offer"); |
| 1451 | rollback_offer(¤t.peer).await; |
| 1452 | defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control); |
| 1453 | } |
| 1454 | if let Some(resend) = glare_resend.take() { |
| 1455 | defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control); |
| 1456 | } |
| 1457 | let camera_track = local_video.camera_track(); |
| 1458 | let share_track = local_video.share_track(); |
| 1459 | match answer_on_new_peer( |
| 1460 | &factory, |
| 1461 | &grant, |
| 1462 | options, |
| 1463 | outgoing_track(software_audio.as_ref(), &track), |
| 1464 | &renegotiation.sdp, |
| 1465 | local_video.camera_on(), |
| 1466 | local_video.camera_on().then_some(&camera_track), |
| 1467 | local_video.sharing().then_some(&share_track), |
| 1468 | ) |
| 1469 | .await |
| 1470 | { |
| 1471 | Ok((session, answered)) => { |
| 1472 | timeline.record_sdp("local answer", &answered.answer_sdp); |
| 1473 | live.peers.push(session.peer.clone()); |
| 1474 | let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await; |
| 1475 | if let Some(replaced) = next.take() { |
| 1476 | replaced.session.peer.close(); |
| 1477 | } |
| 1478 | let mut leg_links = renegotiation.links.clone(); |
| 1479 | if let Ok((extra, keys)) = &sent { |
| 1480 | absorb_answered_links(&mut leg_links, extra, timeline, keys); |
| 1481 | } |
| 1482 | next = Some(NextPeer { |
| 1483 | session, |
| 1484 | offered: None, |
| 1485 | answered: Some(answered), |
| 1486 | leg_links, |
| 1487 | remote_audio: None, |
| 1488 | reply_tags: Vec::new(), |
| 1489 | deadline: Some(Instant::now() + NEXT_PEER_LIMIT), |
| 1490 | connected: false, |
| 1491 | retargeted: false, |
| 1492 | }); |
| 1493 | sent.map(|_| ()) |
| 1494 | } |
| 1495 | Err(error) => { |
| 1496 | if next.is_none() { |
| 1497 | negotiator.server_escalation_failed(); |
| 1498 | } |
| 1499 | for change in deferred_changes.drain(..) { |
| 1500 | undo_change(change, &mut local_video, control); |
| 1501 | } |
| 1502 | if let Some(url) = &rejection_link { |
| 1503 | let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await; |
| 1504 | } |
| 1505 | Err(error) |
| 1506 | } |
| 1507 | } |
| 1508 | } |
| 1509 | MediaAction::AnswerOnSamePeer => { |
| 1510 | // After a server escalation the follow-up offer matches the |
| 1511 | // pending peer's m-line order: never answer it on the old peer. |
| 1512 | let on_pending = next.as_ref().is_some_and(|pending| pending.answered.is_some()); |
| 1513 | let peer = if on_pending { |
| 1514 | &next.as_ref().unwrap().session.peer |
| 1515 | } else { |
| 1516 | ¤t.peer |
| 1517 | }; |
| 1518 | let camera_track = local_video.camera_track(); |
| 1519 | let share_track = local_video.share_track(); |
| 1520 | let video_answer = if local_video.camera_on() { |
| 1521 | AnswerVideo::Send(&camera_track) |
| 1522 | } else { |
| 1523 | AnswerVideo::Receive |
| 1524 | }; |
| 1525 | let keep_slots = on_pending || layout == Layout::Conference; |
| 1526 | let gathered = (!on_pending |
| 1527 | && layout == Layout::OneToOne |
| 1528 | && negotiator.path() == MediaPath::Direct) |
| 1529 | .then_some(¤t.gathered); |
| 1530 | match answer_offer_with( |
| 1531 | peer, |
| 1532 | None, |
| 1533 | &renegotiation.sdp, |
| 1534 | video_answer, |
| 1535 | local_video.sharing().then(|| local_video.share_mid()).flatten(), |
| 1536 | local_video.sharing().then_some(&share_track), |
| 1537 | local_video.camera_on(), |
| 1538 | gathered, |
| 1539 | keep_slots, |
| 1540 | keep_slots, |
| 1541 | ) |
| 1542 | .await |
| 1543 | { |
| 1544 | Ok(answered) => { |
| 1545 | timeline.record_sdp("local answer", &answered.answer_sdp); |
| 1546 | if on_pending { |
| 1547 | if let Some(pending) = next.as_mut() { |
| 1548 | pending.leg_links.extend(renegotiation.links.clone()); |
| 1549 | } |
| 1550 | } else { |
| 1551 | media_links.extend(renegotiation.links.clone()); |
| 1552 | } |
| 1553 | let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await; |
| 1554 | if let Ok((extra, keys)) = &sent { |
| 1555 | if on_pending { |
| 1556 | if let Some(pending) = next.as_mut() { |
| 1557 | absorb_answered_links(&mut pending.leg_links, extra, timeline, keys); |
| 1558 | } |
| 1559 | } else { |
| 1560 | absorb_answered_links(&mut media_links, extra, timeline, keys); |
| 1561 | } |
| 1562 | } |
| 1563 | for mid in answered.remote.plan().screen_share_mids { |
| 1564 | if !layout_plan.screen_share_mids.contains(&mid) { |
| 1565 | layout_plan.screen_share_mids.push(mid); |
| 1566 | } |
| 1567 | } |
| 1568 | if on_pending { |
| 1569 | if let Some(pending) = next.as_mut() { |
| 1570 | pending.answered = Some(answered); |
| 1571 | } |
| 1572 | } else if layout == Layout::Conference { |
| 1573 | negotiate_video_lines( |
| 1574 | &mut video, |
| 1575 | &signaling, |
| 1576 | control, |
| 1577 | timeline, |
| 1578 | &answered.offer_sdp, |
| 1579 | &answered.remote.lines, |
| 1580 | true, |
| 1581 | &media_links, |
| 1582 | &roster, |
| 1583 | ); |
| 1584 | } else if layout == Layout::OneToOne { |
| 1585 | if answered.receiving_share_mid != remote_direct_share { |
| 1586 | if let Some(mid) = &remote_direct_share { |
| 1587 | video.router().set(mid, None); |
| 1588 | } |
| 1589 | if let Some(mid) = &answered.receiving_share_mid { |
| 1590 | video.router().set(mid, Some(VideoKey::Screen)); |
| 1591 | } |
| 1592 | remote_direct_share = answered.receiving_share_mid.clone(); |
| 1593 | control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone()))); |
| 1594 | } |
| 1595 | if !offer_sends_video(&renegotiation.sdp) |
| 1596 | && let Some(key) = main_video_mid(&answered.remote).and_then(|mid| video.router().key_for(&mid)) |
| 1597 | { |
| 1598 | control.video.forget(&key); |
| 1599 | control.send(CallUpdate::VideoStopped(key)); |
| 1600 | } |
| 1601 | } |
| 1602 | let held = is_hold(&renegotiation.sdp).unwrap_or(false); |
| 1603 | if held != remote_hold { |
| 1604 | remote_hold = held; |
| 1605 | control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold))); |
| 1606 | } |
| 1607 | sent.map(|_| ()) |
| 1608 | } |
| 1609 | Err(error) => { |
| 1610 | if on_pending { |
| 1611 | if let Some(pending) = next.as_ref() |
| 1612 | && pending.session.peer.signaling_state() |
| 1613 | == SignalingState::HaveRemoteOffer |
| 1614 | { |
| 1615 | rollback_remote_offer(&pending.session.peer).await; |
| 1616 | } |
| 1617 | } else if current.peer.signaling_state() |
| 1618 | == SignalingState::HaveRemoteOffer |
| 1619 | { |
| 1620 | rollback_remote_offer(¤t.peer).await; |
| 1621 | } |
| 1622 | if let Some(url) = &rejection_link { |
| 1623 | let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await; |
| 1624 | } |
| 1625 | Err(error) |
| 1626 | } |
| 1627 | } |
| 1628 | } |
| 1629 | MediaAction::RejectGlare => { |
| 1630 | if let Some(url) = &rejection_link { |
| 1631 | let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::InProgress).await; |
| 1632 | } |
| 1633 | Ok(()) |
| 1634 | } |
| 1635 | _ => Ok(()), |
| 1636 | }; |
| 1637 | if let Err(error) = result { |
| 1638 | timeline.record("renegotiation failed", error.to_string()); |
| 1639 | } |
| 1640 | } |
| 1641 | Ok(CallEvent::RosterUpdate(body)) => { |
| 1642 | if roster.apply(&body) { |
| 1643 | let entries = roster.entries(); |
| 1644 | timeline.record("roster", format!("{} participant(s)", entries.len())); |
| 1645 | control.send(CallUpdate::Roster(entries)); |
| 1646 | let own_server_muted = roster |
| 1647 | .members() |
| 1648 | .iter() |
| 1649 | .any(|member| member.mri == own_mri && member.server_muted); |
| 1650 | let decision = sync_server_mute(own_server_muted, muted, server_mute_cleared); |
| 1651 | server_mute_cleared = decision.cleared; |
| 1652 | if decision.silence_without_signal |
| 1653 | && let Some(audio) = live.audio.as_ref() |
| 1654 | { |
| 1655 | silence_for_server_mute(audio, software_audio.as_ref(), control); |
| 1656 | muted = true; |
| 1657 | } |
| 1658 | if is_echo && echo_watch.bot_left(roster.members().iter().map(|member| member.mri.as_str())) { |
| 1659 | timeline.record("echo bot left", "test call ends like in Teams"); |
| 1660 | advance(state, CallSignal::RemoteEnd(EndKind::Normal), control); |
| 1661 | break; |
| 1662 | } |
| 1663 | if callee_gate.is_waiting() && roster_has_callee(roster.members().iter().map(|member| member.mri.as_str()), &own_mri) { |
| 1664 | outgoing_deadline = None; |
| 1665 | if callee_gate.callee_joined() { |
| 1666 | advance(state, CallSignal::MediaConnected, control); |
| 1667 | } |
| 1668 | } |
| 1669 | let own_streams = roster.stream_summaries(&own_mri); |
| 1670 | if own_streams != report.own_streams { |
| 1671 | timeline.record("own media streams", own_streams.join("; ")); |
| 1672 | report.own_streams = own_streams; |
| 1673 | } |
| 1674 | send_receive_change(control, video.reselect(&roster)); |
| 1675 | if let Some(replacement) = roster.transfer_replacement(&own_mri) |
| 1676 | && sent_replacement.as_ref() != Some(&replacement) |
| 1677 | { |
| 1678 | sent_replacement = Some(replacement.clone()); |
| 1679 | control.send(CallUpdate::ReplacementLink(replacement)); |
| 1680 | } |
| 1681 | if let Some(in_lobby) = roster.is_in_lobby(&own_mri) |
| 1682 | && in_lobby != lobby |
| 1683 | { |
| 1684 | lobby = in_lobby; |
| 1685 | control.send(CallUpdate::Lobby(lobby)); |
| 1686 | } |
| 1687 | if roster.caption_bot().is_some() { |
| 1688 | bot_pending = false; |
| 1689 | } |
| 1690 | let audio_only = roster.caption_bot().is_some_and(|bot| bot.recording && bot.audio_only); |
| 1691 | if audio_only != recording_audio_only { |
| 1692 | recording_audio_only = audio_only; |
| 1693 | control.send(CallUpdate::RecordingAudioOnly(audio_only)); |
| 1694 | } |
| 1695 | if caption_flow.wanted() { |
| 1696 | run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), &RecordingPlan::default(), &mut bot_pending, control, timeline).await; |
| 1697 | if caption_flow.on() { |
| 1698 | caption_deadline = None; |
| 1699 | } |
| 1700 | } |
| 1701 | if recording_flow.wanted() { |
| 1702 | run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await; |
| 1703 | } |
| 1704 | } |
| 1705 | } |
| 1706 | Ok(CallEvent::AddParticipantFailure(body)) => { |
| 1707 | let bot_add = bot_pending; |
| 1708 | bot_pending = false; |
| 1709 | if !bot_add && callee_gate.callees_failed(failed_participant_count(&body)) { |
| 1710 | let end = embedded_end(&body); |
| 1711 | let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind); |
| 1712 | report.end = end; |
| 1713 | advance(state, CallSignal::RemoteEnd(kind), control); |
| 1714 | break; |
| 1715 | } |
| 1716 | if recording_flow.wanted() && roster.caption_bot().is_none() { |
| 1717 | timeline.record("recorder bot failed", "addParticipantFailure"); |
| 1718 | recording_flow.failed(); |
| 1719 | recording_deadline = None; |
| 1720 | control.send(CallUpdate::RecordingPending(false)); |
| 1721 | control.send(CallUpdate::Notice(RECORDING_JOIN_FAILED_NOTICE.into())); |
| 1722 | } |
| 1723 | if caption_flow.wanted() && roster.caption_bot().is_none() { |
| 1724 | timeline.record("caption bot failed", "addParticipantFailure"); |
| 1725 | caption_flow.failed(); |
| 1726 | caption_deadline = None; |
| 1727 | control.send(CallUpdate::Captions(CaptionState::Failed( |
| 1728 | CAPTIONS_JOIN_FAILED_NOTICE.into(), |
| 1729 | ))); |
| 1730 | } |
| 1731 | } |
| 1732 | Ok(CallEvent::ConversationUpdate(body)) => { |
| 1733 | if let Some(thread) = chat_thread_id(&body) |
| 1734 | && meeting_chat.as_ref() != Some(&thread) |
| 1735 | { |
| 1736 | control.send(CallUpdate::MeetingChat(thread.clone())); |
| 1737 | meeting_chat = Some(thread); |
| 1738 | } |
| 1739 | if capability.apply(&body) { |
| 1740 | control.send(CallUpdate::Capability(capability)); |
| 1741 | } |
| 1742 | let change = recording_status.apply(&body); |
| 1743 | if let Some(on) = change.recording { |
| 1744 | control.send(CallUpdate::Recording(on)); |
| 1745 | if on { |
| 1746 | recording_deadline = None; |
| 1747 | control.send(CallUpdate::RecordingPending(false)); |
| 1748 | } |
| 1749 | } |
| 1750 | if let Some(on) = change.transcription { |
| 1751 | control.send(CallUpdate::Transcribing(on)); |
| 1752 | if on { |
| 1753 | recording_deadline = None; |
| 1754 | control.send(CallUpdate::RecordingPending(false)); |
| 1755 | } |
| 1756 | } |
| 1757 | if let Some(required) = change.consent_required { |
| 1758 | consent_pending = required; |
| 1759 | control.send(CallUpdate::ConsentRequired(required)); |
| 1760 | if required { |
| 1761 | withhold_media(&mut muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, &mut local_video, control); |
| 1762 | } |
| 1763 | } |
| 1764 | if !main_meeting_sent |
| 1765 | && let Some(main) = breakout::main_meeting_target(&body) |
| 1766 | { |
| 1767 | main_meeting_sent = true; |
| 1768 | control.send(CallUpdate::BreakoutRoom { main }); |
| 1769 | } |
| 1770 | } |
| 1771 | Ok(CallEvent::LocalParticipantUpdate(body)) => { |
| 1772 | let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target)); |
| 1773 | if let Some(moved) = moved { |
| 1774 | timeline.record("breakout", format!("moved to {}", moved.room_name)); |
| 1775 | control.send(CallUpdate::BreakoutMove(moved)); |
| 1776 | } |
| 1777 | } |
| 1778 | Ok(CallEvent::Replacement(body)) => { |
| 1779 | let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target)); |
| 1780 | if let Some(moved) = invited { |
| 1781 | timeline.record("breakout", format!("invited to {}", moved.room_name)); |
| 1782 | control.send(CallUpdate::BreakoutMove(moved)); |
| 1783 | } |
| 1784 | } |
| 1785 | Ok(CallEvent::ContentShareUpdate(body)) => { |
| 1786 | if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) { |
| 1787 | control.send(CallUpdate::Whiteboard(Some(share))); |
| 1788 | } |
| 1789 | } |
| 1790 | Ok(CallEvent::ContentShareEnd(_)) => { |
| 1791 | control.send(CallUpdate::Whiteboard(None)); |
| 1792 | } |
| 1793 | Ok(CallEvent::Transfer(event)) => { |
| 1794 | match event { |
| 1795 | TransferEvent::Accepted => timeline.record("transfer accepted", "by the target"), |
| 1796 | completed if completed.succeeded() => { |
| 1797 | timeline.record("transfer", "completed"); |
| 1798 | control.send(CallUpdate::TransferResult { succeeded: true }); |
| 1799 | control.send(CallUpdate::Notice(CALL_TRANSFERRED_NOTICE.into())); |
| 1800 | advance(state, CallSignal::LocalLeave, control); |
| 1801 | break; |
| 1802 | } |
| 1803 | TransferEvent::Completed { code, sub_code } => { |
| 1804 | timeline.record("transfer failed", format!("code {code} subCode {sub_code}")); |
| 1805 | control.send(CallUpdate::TransferResult { succeeded: false }); |
| 1806 | control.send(CallUpdate::Notice(TRANSFER_FAILED_NOTICE.into())); |
| 1807 | } |
| 1808 | } |
| 1809 | } |
| 1810 | Ok(CallEvent::Reactions(events)) => { |
| 1811 | for event in events { |
| 1812 | control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction }); |
| 1813 | } |
| 1814 | } |
| 1815 | Ok(CallEvent::Progress(status)) => { |
| 1816 | if status == ProgressStatus::Ringing { |
| 1817 | control.send(CallUpdate::Progress(Progress::Ringing)); |
| 1818 | if outgoing_deadline.is_some() { |
| 1819 | outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT); |
| 1820 | } |
| 1821 | } |
| 1822 | } |
| 1823 | Ok(CallEvent::ControlVideoStreaming(body)) => { |
| 1824 | let Some(request) = parse_request(&body) else { continue }; |
| 1825 | let Some(limits) = send_requests.admit(&request) else { continue }; |
| 1826 | let own_screen = roster.screen_source_of(&own_mri).map(i64::from); |
| 1827 | let source = if request.source_id.is_some() && request.source_id == own_screen { SendSource::Screen } else { SendSource::Camera }; |
| 1828 | match local_video.apply_send_limit(source, &limits) { |
| 1829 | Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?}")), |
| 1830 | Ok(None) => {} |
| 1831 | Err(error) => timeline.record("send limits failed", error.to_string()), |
| 1832 | } |
| 1833 | } |
| 1834 | Ok(CallEvent::Speakers(sources)) => { |
| 1835 | let speakers = roster.mris_for_sources(&sources); |
| 1836 | if video.note_speakers(&speakers) { |
| 1837 | send_receive_change(control, video.reselect(&roster)); |
| 1838 | } |
| 1839 | control.send(CallUpdate::Speakers(speakers)); |
| 1840 | } |
| 1841 | Ok(CallEvent::ConversationEnd(body)) if callee_gate.is_waiting() => { |
| 1842 | live.skip_leave = true; |
| 1843 | let end = embedded_end(&body); |
| 1844 | let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind); |
| 1845 | report.end = end; |
| 1846 | advance(state, CallSignal::RemoteEnd(kind), control); |
| 1847 | break; |
| 1848 | } |
| 1849 | Ok(CallEvent::Rejection(_)) |
| 1850 | if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) => |
| 1851 | { |
| 1852 | if let Some(resend) = glare_resend.as_mut() { |
| 1853 | resend.at = Instant::now(); |
| 1854 | } |
| 1855 | } |
| 1856 | Ok(CallEvent::Rejection(_)) |
| 1857 | if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) |
| 1858 | && !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) => |
| 1859 | { |
| 1860 | timeline.record("rejection ignored", "it names an offer that is no longer pending"); |
| 1861 | } |
| 1862 | Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() { |
| 1863 | RejectedOffer::SamePeer => { |
| 1864 | same_peer_deadline = None; |
| 1865 | same_peer_grace_until = None; |
| 1866 | if let Some(pending) = same_peer.take() { |
| 1867 | rollback_offer(¤t.peer).await; |
| 1868 | if is_glare_rejection(&body) { |
| 1869 | timeline.record("glare", "our offer met theirs, it goes out again"); |
| 1870 | glare_resend = Some(GlareResend { change: pending.change, reply_tags: Vec::new(), at: Instant::now() + GLARE_RESEND_LIMIT }); |
| 1871 | } else { |
| 1872 | undo_change(pending.change, &mut local_video, control); |
| 1873 | } |
| 1874 | } |
| 1875 | } |
| 1876 | RejectedOffer::NewPeer => { |
| 1877 | if let Some(pending) = next.take() { |
| 1878 | pending.session.peer.close(); |
| 1879 | } |
| 1880 | if layout == Layout::OneToOne { |
| 1881 | drop_local_media(&mut local_video, control); |
| 1882 | } |
| 1883 | timeline.record("escalation failed", "offer rejected, staying on the old peer connection"); |
| 1884 | } |
| 1885 | RejectedOffer::None => {} |
| 1886 | }, |
| 1887 | Ok(CallEvent::MediaAcknowledgement(ack)) => { |
| 1888 | if let Some(pending) = next.as_mut() { |
| 1889 | pending.leg_links.extend(ack.links); |
| 1890 | if pending.answered.is_some() { |
| 1891 | // Server-initiated mixer leg switch sends mediaAcknowledgement |
| 1892 | // instead of retargetCompletion; switch as soon as ICE connects. |
| 1893 | pending.retargeted = true; |
| 1894 | } |
| 1895 | } else if !ack.links.is_empty() { |
| 1896 | let old_request = media_links |
| 1897 | .get("applyChannelParameters") |
| 1898 | .or_else(|| media_links.get("controlVideoStreaming")) |
| 1899 | .cloned(); |
| 1900 | let old_update = media_links.get("updateMediaDescriptions").cloned(); |
| 1901 | replace_leg_media_links(&mut media_links, &ack.links); |
| 1902 | if let Some(url) = media_links.get("callLeg").cloned() |
| 1903 | && keep_alive_link.as_deref() != Some(url.as_str()) |
| 1904 | { |
| 1905 | keep_alive_link = Some(url.clone()); |
| 1906 | remember_call_leg(live, Some(&url)); |
| 1907 | } |
| 1908 | let new_request = media_links |
| 1909 | .get("applyChannelParameters") |
| 1910 | .or_else(|| media_links.get("controlVideoStreaming")) |
| 1911 | .cloned(); |
| 1912 | if layout == Layout::Conference |
| 1913 | && new_request != old_request |
| 1914 | && let Some(url) = new_request |
| 1915 | { |
| 1916 | video.replace_requester(SourceRequester::start( |
| 1917 | signaling.clone(), |
| 1918 | url, |
| 1919 | video.router().clone(), |
| 1920 | control.video.clone(), |
| 1921 | timeline.clone(), |
| 1922 | )); |
| 1923 | send_receive_change(control, video.reselect(&roster)); |
| 1924 | } |
| 1925 | if layout == Layout::Conference |
| 1926 | && media_links.get("updateMediaDescriptions") != old_update.as_ref() |
| 1927 | && local_video.has_lines() |
| 1928 | { |
| 1929 | send_capabilities = SendCapabilityReporter::default(); |
| 1930 | if local_video.camera_on() { |
| 1931 | tell_bound_camera( |
| 1932 | &remote, |
| 1933 | &media_links, |
| 1934 | &local_video, |
| 1935 | &mut media_description_request, |
| 1936 | timeline, |
| 1937 | ); |
| 1938 | } |
| 1939 | if local_video.sharing() { |
| 1940 | tell_bound_share( |
| 1941 | &remote, |
| 1942 | &media_links, |
| 1943 | &local_video, |
| 1944 | &mut media_description_request, |
| 1945 | timeline, |
| 1946 | ); |
| 1947 | } |
| 1948 | } |
| 1949 | } |
| 1950 | } |
| 1951 | Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => { |
| 1952 | if let Some(pending) = next.as_mut() { |
| 1953 | pending.retargeted = true; |
| 1954 | } |
| 1955 | } |
| 1956 | Ok(CallEvent::RetargetCompletion(body)) => { |
| 1957 | if body["retargetCompleted"]["code"].as_i64().is_some() && let Some(pending) = next.take() { |
| 1958 | pending.session.peer.close(); |
| 1959 | negotiator.escalation_failed(); |
| 1960 | settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control); |
| 1961 | timeline.record("escalation failed", "retarget rejected, staying on the old peer connection"); |
| 1962 | } |
| 1963 | } |
| 1964 | Ok(CallEvent::End(end)) => { |
| 1965 | let kind = end.kind(); |
| 1966 | report.end = Some(end); |
| 1967 | advance(state, CallSignal::RemoteEnd(kind), control); |
| 1968 | break; |
| 1969 | } |
| 1970 | Ok(_) => {} |
| 1971 | Err(error) => { |
| 1972 | timeline.record("callback not understood", error.to_string()); |
| 1973 | } |
| 1974 | } |
| 1975 | } |
| 1976 | Some(result) = echo_add_rx.recv(), if echo_add_pending => { |
| 1977 | echo_add_pending = false; |
| 1978 | if let Err(error) = result { |
| 1979 | timeline.record("echo bot add failed", error.to_string()); |
| 1980 | control.send(CallUpdate::Notice(ECHO_TEST_FAILED_NOTICE.into())); |
| 1981 | live.cancel_leave = true; |
| 1982 | advance(state, CallSignal::RemoteEnd(EndKind::Unavailable), control); |
| 1983 | break; |
| 1984 | } |
| 1985 | } |
| 1986 | Some(event) = current.events.recv() => match event { |
| 1987 | PeerEvent::Ice(ice_state) => { |
| 1988 | timeline.record("ICE state", format!("{ice_state:?}")); |
| 1989 | if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() { |
| 1990 | report.ice_connected_ms = Some(timeline.elapsed_ms()); |
| 1991 | } |
| 1992 | } |
| 1993 | PeerEvent::Connection(connection) => { |
| 1994 | timeline.record("PeerConnection state", format!("{connection:?}")); |
| 1995 | match connection { |
| 1996 | PeerConnectionState::Connected => { |
| 1997 | reconnect_deadline = None; |
| 1998 | if callee_gate.media_connected() { |
| 1999 | advance(state, CallSignal::MediaConnected, control); |
| 2000 | } |
| 2001 | if report.peer_connected_ms.is_none() { |
| 2002 | report.peer_connected_ms = Some(timeline.elapsed_ms()); |
| 2003 | if let Some(hold) = options.hold_after_connected { |
| 2004 | let hold_until = Instant::now() + hold; |
| 2005 | leave_at = Some(hard_deadline.map_or(hold_until, |deadline| deadline.min(hold_until))); |
| 2006 | } |
| 2007 | } |
| 2008 | } |
| 2009 | // Planned mixer escalation: ignore old-peer death while the new peer is pending. |
| 2010 | PeerConnectionState::Disconnected | PeerConnectionState::Failed |
| 2011 | if next.is_some() => {} |
| 2012 | PeerConnectionState::Disconnected => { |
| 2013 | if advance(state, CallSignal::MediaDisconnected, control) { |
| 2014 | reconnect_deadline = Some(Instant::now() + options.reconnect_window); |
| 2015 | } |
| 2016 | } |
| 2017 | PeerConnectionState::Failed => { |
| 2018 | advance(state, CallSignal::MediaFailed, control); |
| 2019 | break; |
| 2020 | } |
| 2021 | _ => {} |
| 2022 | } |
| 2023 | } |
| 2024 | PeerEvent::Track(remote_track) => { |
| 2025 | timeline.record("remote audio track", "receiving"); |
| 2026 | let had_far_end = remote_audio.replace(remote_track.clone()).is_some(); |
| 2027 | if !had_far_end && software_audio.is_some() { |
| 2028 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline); |
| 2029 | } |
| 2030 | if options.record_remote { |
| 2031 | tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz)); |
| 2032 | } |
| 2033 | } |
| 2034 | PeerEvent::VideoTrack { mid, track } => { |
| 2035 | timeline.record("remote video track", format!("mid {mid}")); |
| 2036 | live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone())); |
| 2037 | } |
| 2038 | PeerEvent::Data(frame) => { |
| 2039 | if let Some(message) = depacketizer.push(&frame) |
| 2040 | && message.data_id == CAPTIONS_DATA_ID |
| 2041 | { |
| 2042 | for entry in parse_caption_message(&message.payload) { |
| 2043 | if caption_flow.text_arrived() { |
| 2044 | caption_deadline = None; |
| 2045 | control.send(CallUpdate::Captions(CaptionState::On)); |
| 2046 | } |
| 2047 | control.send(CallUpdate::Caption(named_caption(entry, &roster))); |
| 2048 | } |
| 2049 | } |
| 2050 | } |
| 2051 | }, |
| 2052 | Some(event) = next_peer_event(&mut next) => match event { |
| 2053 | PeerEvent::Connection(PeerConnectionState::Connected) => { |
| 2054 | if let Some(pending) = next.as_mut() { |
| 2055 | pending.connected = true; |
| 2056 | if pending.offered.is_none() && !pending.retargeted { |
| 2057 | pending.deadline = Some(Instant::now() + RETARGET_WAIT); |
| 2058 | timeline.record("escalation", "new peer connection up, waiting for retargetCompletion"); |
| 2059 | } |
| 2060 | } |
| 2061 | } |
| 2062 | PeerEvent::VideoTrack { mid, track } => { |
| 2063 | timeline.record("remote video track", format!("mid {mid} (new peer)")); |
| 2064 | live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone())); |
| 2065 | } |
| 2066 | PeerEvent::Track(remote_track) => { |
| 2067 | timeline.record("remote audio track", "receiving (new peer)"); |
| 2068 | if let Some(pending) = next.as_mut() { |
| 2069 | pending.remote_audio = Some(remote_track); |
| 2070 | } |
| 2071 | } |
| 2072 | PeerEvent::Connection(PeerConnectionState::Failed) => { |
| 2073 | negotiator.escalation_failed(); |
| 2074 | if let Some(pending) = next.take() { |
| 2075 | pending.session.peer.close(); |
| 2076 | settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control); |
| 2077 | } |
| 2078 | timeline.record("escalation failed", "new peer connection failed, staying on the old one"); |
| 2079 | } |
| 2080 | _ => {} |
| 2081 | }, |
| 2082 | command = control.recv() => match command { |
| 2083 | Some(CallCommand::Mute(mute)) => { |
| 2084 | let own_server_muted = roster |
| 2085 | .members() |
| 2086 | .iter() |
| 2087 | .any(|member| member.mri == own_mri && member.server_muted); |
| 2088 | if !mute.target(muted) && own_server_muted { |
| 2089 | server_mute_cleared = true; |
| 2090 | } |
| 2091 | if consent_pending && !mute.target(muted) { |
| 2092 | control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into())); |
| 2093 | } else { |
| 2094 | muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control); |
| 2095 | silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref()); |
| 2096 | } |
| 2097 | } |
| 2098 | Some(CallCommand::DisableAudio) => { |
| 2099 | let audio = live.audio.as_ref().expect("audio set above"); |
| 2100 | muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control); |
| 2101 | audio_disabled = true; |
| 2102 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline); |
| 2103 | if audio.uses_devices() { |
| 2104 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 2105 | factory.set_adm_recording_enabled(false); |
| 2106 | factory.set_adm_playout_enabled(false); |
| 2107 | } |
| 2108 | control.send(CallUpdate::ListenOnly(true)); |
| 2109 | } |
| 2110 | Some(CallCommand::SelectInput(choice)) => { |
| 2111 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 2112 | timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice))); |
| 2113 | applied_input = devices::applied_device(&device_lists.inputs, &choice, devices::system_default_id(Flow::Capture).as_deref()); |
| 2114 | record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref()); |
| 2115 | } |
| 2116 | input = choice; |
| 2117 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 2118 | if software_audio.is_some() { |
| 2119 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline); |
| 2120 | } |
| 2121 | } |
| 2122 | Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => { |
| 2123 | let device_ns_changed = |
| 2124 | mic_settings.ml_noise_suppression() != settings.ml_noise_suppression(); |
| 2125 | mic_settings = settings; |
| 2126 | if let Some(audio) = live.audio.as_ref() { |
| 2127 | track = audio.device_track(mic_settings).clone(); |
| 2128 | } |
| 2129 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), device_ns_changed, &mut software_audio, mic_settings, control, timeline); |
| 2130 | } |
| 2131 | Some(CallCommand::SetMicSettings(settings)) => { |
| 2132 | mic_settings = settings; |
| 2133 | crate::noise_stage::apply_for_outgoing(mic_settings, false); |
| 2134 | } |
| 2135 | Some(CallCommand::SelectOutput(choice)) => { |
| 2136 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 2137 | timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice))); |
| 2138 | applied_output = devices::applied_device(&device_lists.outputs, &choice, devices::system_default_id(Flow::Render).as_deref()); |
| 2139 | record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref()); |
| 2140 | } |
| 2141 | output = choice; |
| 2142 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 2143 | } |
| 2144 | Some(CallCommand::RefreshDevices) => { |
| 2145 | device_lists = devices::list_devices(&factory); |
| 2146 | control.send(CallUpdate::Devices(device_lists.clone())); |
| 2147 | } |
| 2148 | Some(CallCommand::SetCamera(false)) if local_video.camera_previewing() => { |
| 2149 | start_camera_pending = false; |
| 2150 | local_video.stop_camera(); |
| 2151 | control.send(CallUpdate::Camera(false)); |
| 2152 | } |
| 2153 | Some(CallCommand::SetCamera(on)) => { |
| 2154 | let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer; |
| 2155 | if on && next.is_some() { |
| 2156 | let first = !start_camera_pending; |
| 2157 | start_camera_pending = true; |
| 2158 | if local_video.is_available() |
| 2159 | && !local_video.camera_on() |
| 2160 | && !local_video.camera_previewing() |
| 2161 | && let Err(error) = local_video.preview_camera(&camera_choice) |
| 2162 | { |
| 2163 | control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))); |
| 2164 | } |
| 2165 | if first { |
| 2166 | control.send(CallUpdate::Camera(true)); |
| 2167 | } |
| 2168 | } else if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) { |
| 2169 | if remote_set && next.is_none() && negotiator.begin_conference_upgrade() { |
| 2170 | 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; |
| 2171 | next = pending.or(next); |
| 2172 | } |
| 2173 | if remote_set && on && next.is_some() { |
| 2174 | start_camera_pending = true; |
| 2175 | } |
| 2176 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 2177 | } else if on && consent_pending { |
| 2178 | control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into())); |
| 2179 | } else if local_hold { |
| 2180 | control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into())); |
| 2181 | } else if on && direct && (same_peer.is_some() || glare_resend.is_some()) { |
| 2182 | control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into())); |
| 2183 | } else if on { |
| 2184 | let started = start_camera_line(&mut local_video, ¤t.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice); |
| 2185 | match started { |
| 2186 | Ok(()) if direct => { |
| 2187 | 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 { |
| 2188 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2189 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2190 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags }); |
| 2191 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2192 | same_peer_grace_until = None; |
| 2193 | } |
| 2194 | Err(error) => { |
| 2195 | timeline.record("camera offer failed", error.to_string()); |
| 2196 | undo_change(Change::Camera(true), &mut local_video, control); |
| 2197 | } |
| 2198 | } |
| 2199 | } |
| 2200 | Ok(()) => { |
| 2201 | control.send(CallUpdate::Camera(true)); |
| 2202 | tell_media_descriptions( |
| 2203 | &remote, |
| 2204 | &media_links, |
| 2205 | MediaDescription::camera_line( |
| 2206 | local_video.camera_mid().unwrap_or_else(|| CAMERA_MID.to_owned()), |
| 2207 | true, |
| 2208 | ), |
| 2209 | &mut media_description_request, |
| 2210 | timeline, |
| 2211 | ); |
| 2212 | } |
| 2213 | Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))), |
| 2214 | } |
| 2215 | } else if direct && (same_peer.is_some() || glare_resend.is_some()) { |
| 2216 | control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into())); |
| 2217 | } else if direct { |
| 2218 | local_video.stop_camera(); |
| 2219 | 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 { |
| 2220 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2221 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2222 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags }); |
| 2223 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2224 | same_peer_grace_until = None; |
| 2225 | } |
| 2226 | Err(error) => { |
| 2227 | timeline.record("camera offer failed", error.to_string()); |
| 2228 | control.send(CallUpdate::Camera(false)); |
| 2229 | } |
| 2230 | } |
| 2231 | } else { |
| 2232 | local_video.stop_camera(); |
| 2233 | control.send(CallUpdate::Camera(false)); |
| 2234 | tell_media_descriptions( |
| 2235 | &remote, |
| 2236 | &media_links, |
| 2237 | MediaDescription::camera_line( |
| 2238 | local_video.camera_mid().unwrap_or_else(|| CAMERA_MID.to_owned()), |
| 2239 | false, |
| 2240 | ), |
| 2241 | &mut media_description_request, |
| 2242 | timeline, |
| 2243 | ); |
| 2244 | } |
| 2245 | } |
| 2246 | Some(CallCommand::SelectCamera(choice)) => { |
| 2247 | camera_choice = choice; |
| 2248 | if local_video.camera_previewing() |
| 2249 | && let Err(error) = local_video.preview_camera(&camera_choice) |
| 2250 | { |
| 2251 | control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))); |
| 2252 | } else if local_video.camera_on() |
| 2253 | && let Err(error) = local_video.start_camera(&camera_choice) |
| 2254 | { |
| 2255 | control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))); |
| 2256 | } |
| 2257 | } |
| 2258 | Some(CallCommand::SetVideoQuality(quality)) => { |
| 2259 | local_video.set_video_quality(quality); |
| 2260 | if let Err(error) = local_video.refresh_camera_capture(&camera_choice) { |
| 2261 | control.send(CallUpdate::Notice(notice_with_detail(CAMERA_RESTART_NOTICE, error))); |
| 2262 | } |
| 2263 | if video.set_video_quality(quality) { |
| 2264 | send_receive_change(control, video.reselect(&roster)); |
| 2265 | } |
| 2266 | } |
| 2267 | Some(CallCommand::StartPortalShare(kind)) => { |
| 2268 | let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct; |
| 2269 | if !remote_set { |
| 2270 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 2271 | } else if local_hold { |
| 2272 | control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into())); |
| 2273 | } else if !local_video.sharing() && next.is_some() { |
| 2274 | portal_pending = Some(kind); |
| 2275 | control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into())); |
| 2276 | } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) { |
| 2277 | control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into())); |
| 2278 | } else if direct |
| 2279 | && !local_video.sharing() |
| 2280 | && !local_video.has_share_line() |
| 2281 | && let Err(error) = attach_share_line(¤t.peer, &factory, &mut local_video, direct_video_mid.as_deref()) |
| 2282 | { |
| 2283 | control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))); |
| 2284 | } else if !local_video.sharing() |
| 2285 | && (!video_possible(remote_set, layout, negotiator.path()) |
| 2286 | || !local_video.share_sending()) |
| 2287 | { |
| 2288 | if next.is_none() && negotiator.begin_conference_upgrade() { |
| 2289 | 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; |
| 2290 | next = pending.or(next); |
| 2291 | } |
| 2292 | if next.is_some() { |
| 2293 | portal_pending = Some(kind); |
| 2294 | control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into())); |
| 2295 | } else { |
| 2296 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 2297 | } |
| 2298 | } else if let Err(error) = local_video.open_portal(kind, control.command_sender()) { |
| 2299 | control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))); |
| 2300 | } |
| 2301 | } |
| 2302 | Some(CallCommand::FinishPortalShare { source, generation }) => { |
| 2303 | if local_video.accept_portal(generation) { |
| 2304 | control.defer(CallCommand::StartShare(source)); |
| 2305 | } |
| 2306 | } |
| 2307 | Some(CallCommand::AbandonPortalShare) => { |
| 2308 | if local_video.portal_is_open() { |
| 2309 | local_video.stop_share(); |
| 2310 | } |
| 2311 | } |
| 2312 | Some(CallCommand::StartShare(source)) => { |
| 2313 | let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct; |
| 2314 | if !remote_set { |
| 2315 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 2316 | } else if local_hold { |
| 2317 | control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into())); |
| 2318 | } else if next.is_some() { |
| 2319 | share_pending = Some(source); |
| 2320 | control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into())); |
| 2321 | } else if direct && local_video.share_sending() { |
| 2322 | match local_video.start_share(&source) { |
| 2323 | Ok(()) => announce_share(control, &source), |
| 2324 | Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))), |
| 2325 | } |
| 2326 | } else if direct && (same_peer.is_some() || glare_resend.is_some()) { |
| 2327 | control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into())); |
| 2328 | } else if direct |
| 2329 | && !local_video.has_share_line() |
| 2330 | && let Err(error) = attach_share_line(¤t.peer, &factory, &mut local_video, direct_video_mid.as_deref()) |
| 2331 | { |
| 2332 | control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))); |
| 2333 | } else if direct { |
| 2334 | match local_video.start_share(&source) { |
| 2335 | Ok(()) => { |
| 2336 | announce_share(control, &source); |
| 2337 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline); |
| 2338 | 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 { |
| 2339 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2340 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2341 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags }); |
| 2342 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2343 | same_peer_grace_until = None; |
| 2344 | } |
| 2345 | Err(error) => { |
| 2346 | timeline.record("share offer failed", error.to_string()); |
| 2347 | undo_change(Change::Share(true), &mut local_video, control); |
| 2348 | } |
| 2349 | } |
| 2350 | } |
| 2351 | Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))), |
| 2352 | } |
| 2353 | } else if !video_possible(remote_set, layout, negotiator.path()) |
| 2354 | || !local_video.share_sending() |
| 2355 | { |
| 2356 | if next.is_none() && negotiator.begin_conference_upgrade() { |
| 2357 | 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; |
| 2358 | next = pending.or(next); |
| 2359 | } |
| 2360 | if next.is_some() { |
| 2361 | share_pending = Some(source); |
| 2362 | control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into())); |
| 2363 | } else { |
| 2364 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 2365 | } |
| 2366 | } else { |
| 2367 | match local_video.start_share(&source) { |
| 2368 | Ok(()) => { |
| 2369 | announce_share(control, &source); |
| 2370 | tell_media_descriptions( |
| 2371 | &remote, |
| 2372 | &media_links, |
| 2373 | MediaDescription::share_line( |
| 2374 | local_video.share_mid().unwrap_or_else(|| SHARE_MID.to_owned()), |
| 2375 | true, |
| 2376 | ), |
| 2377 | &mut media_description_request, |
| 2378 | timeline, |
| 2379 | ); |
| 2380 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline); |
| 2381 | } |
| 2382 | Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))), |
| 2383 | } |
| 2384 | } |
| 2385 | } |
| 2386 | Some(CallCommand::StopShare) => { |
| 2387 | let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct; |
| 2388 | share_pending = None; |
| 2389 | portal_pending = None; |
| 2390 | if local_video.portal_is_open() { |
| 2391 | local_video.stop_share(); |
| 2392 | } else if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) { |
| 2393 | control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into())); |
| 2394 | } else if direct && local_video.sharing() { |
| 2395 | local_video.stop_share(); |
| 2396 | clear_share(control); |
| 2397 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline); |
| 2398 | 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 { |
| 2399 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2400 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2401 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags }); |
| 2402 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2403 | same_peer_grace_until = None; |
| 2404 | } |
| 2405 | Err(error) => timeline.record("share offer failed", error.to_string()), |
| 2406 | } |
| 2407 | } else if local_video.sharing() { |
| 2408 | local_video.stop_share(); |
| 2409 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline); |
| 2410 | clear_share(control); |
| 2411 | tell_media_descriptions( |
| 2412 | &remote, |
| 2413 | &media_links, |
| 2414 | MediaDescription::share_line( |
| 2415 | local_video.share_mid().unwrap_or_else(|| SHARE_MID.to_owned()), |
| 2416 | false, |
| 2417 | ), |
| 2418 | &mut media_description_request, |
| 2419 | timeline, |
| 2420 | ); |
| 2421 | } |
| 2422 | } |
| 2423 | Some(CallCommand::SetShareSound(on)) => { |
| 2424 | share_sound_wanted = on; |
| 2425 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline); |
| 2426 | } |
| 2427 | Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true), |
| 2428 | Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await { |
| 2429 | Ok(receipt) => { |
| 2430 | own_hand = receipt.state_id; |
| 2431 | control.send(CallUpdate::OwnHand(Some(receipt.rank))); |
| 2432 | } |
| 2433 | Err(error) => { |
| 2434 | timeline.record("raise hand failed", error.to_string()); |
| 2435 | control.send(CallUpdate::OwnHand(None)); |
| 2436 | control.send(CallUpdate::Notice(RAISE_HAND_FAILED_NOTICE.into())); |
| 2437 | } |
| 2438 | }, |
| 2439 | Some(CallCommand::SetHand(false)) => { |
| 2440 | let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect(); |
| 2441 | own_hand = None; |
| 2442 | control.send(CallUpdate::OwnHand(None)); |
| 2443 | if !state_ids.is_empty() |
| 2444 | && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await |
| 2445 | { |
| 2446 | timeline.record("lower hand failed", error.to_string()); |
| 2447 | control.send(CallUpdate::Notice(LOWER_HAND_FAILED_NOTICE.into())); |
| 2448 | } |
| 2449 | } |
| 2450 | Some(CallCommand::LowerHand { mri }) => { |
| 2451 | let state_ids: Vec<String> = roster.hand_of(&mri).map(|hand| hand.state_id.clone()).into_iter().collect(); |
| 2452 | if !state_ids.is_empty() |
| 2453 | && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await |
| 2454 | { |
| 2455 | timeline.record("lower hand failed", error.to_string()); |
| 2456 | control.send(CallUpdate::Notice(LOWER_THAT_HAND_FAILED_NOTICE.into())); |
| 2457 | } |
| 2458 | } |
| 2459 | Some(CallCommand::LowerAllHands) => { |
| 2460 | if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await { |
| 2461 | timeline.record("lower all hands failed", error.to_string()); |
| 2462 | control.send(CallUpdate::Notice(LOWER_ALL_HANDS_FAILED_NOTICE.into())); |
| 2463 | } |
| 2464 | } |
| 2465 | Some(CallCommand::Admit { mri }) => { |
| 2466 | let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 2467 | report_organizer_result(result, "admit", ADMIT_FAILED_NOTICE, control, timeline); |
| 2468 | } |
| 2469 | Some(CallCommand::AdmitAll) => { |
| 2470 | let mut result = Ok(202); |
| 2471 | for mri in roster.lobby_mris() { |
| 2472 | result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 2473 | if result.is_err() { |
| 2474 | break; |
| 2475 | } |
| 2476 | } |
| 2477 | report_organizer_result(result, "admit all", ADMIT_ALL_FAILED_NOTICE, control, timeline); |
| 2478 | } |
| 2479 | Some(CallCommand::Deny { mri }) => { |
| 2480 | let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 2481 | report_organizer_result(result, "deny", DENY_FAILED_NOTICE, control, timeline); |
| 2482 | } |
| 2483 | Some(CallCommand::RemoveParticipant { mri }) => { |
| 2484 | let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 2485 | report_organizer_result(result, "remove participant", REMOVE_PARTICIPANT_FAILED_NOTICE, control, timeline); |
| 2486 | } |
| 2487 | Some(CallCommand::MuteParticipant { mri }) => { |
| 2488 | let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await; |
| 2489 | report_organizer_result(result, "mute participant", MUTE_PARTICIPANT_FAILED_NOTICE, control, timeline); |
| 2490 | } |
| 2491 | Some(CallCommand::MuteAll) => { |
| 2492 | let others: Vec<String> = roster |
| 2493 | .members() |
| 2494 | .iter() |
| 2495 | .filter(|member| member.mri != own_mri && !member.in_lobby && !member.mri.starts_with(BOT_PREFIX)) |
| 2496 | .map(|member| member.mri.clone()) |
| 2497 | .collect(); |
| 2498 | let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await; |
| 2499 | report_organizer_result(result, "mute all", MUTE_ALL_FAILED_NOTICE, control, timeline); |
| 2500 | } |
| 2501 | Some(CallCommand::SetLock(locked)) => { |
| 2502 | let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await; |
| 2503 | if result.is_ok() { |
| 2504 | capability.locked = locked; |
| 2505 | control.send(CallUpdate::Capability(capability)); |
| 2506 | } |
| 2507 | report_organizer_result(result, "lock meeting", MEETING_LOCK_FAILED_NOTICE, control, timeline); |
| 2508 | } |
| 2509 | Some(CallCommand::SetRole { mri, role }) => { |
| 2510 | let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await; |
| 2511 | report_organizer_result(result, "change role", CHANGE_ROLE_FAILED_NOTICE, control, timeline); |
| 2512 | } |
| 2513 | Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => { |
| 2514 | let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default(); |
| 2515 | let mut result = Ok(200); |
| 2516 | for step in modality_steps(modality, allowed, capability, &limits) { |
| 2517 | result = match step { |
| 2518 | StateStep::Publish(state_type) => remote.signaling.publish_attendee_state(&remote.conversation, &remote.participant, state_type, &mri).await, |
| 2519 | StateStep::Remove(state_id) => remote.signaling.lower_hands(&remote.conversation, &remote.participant, &[state_id]).await.map(|()| 200), |
| 2520 | }; |
| 2521 | if result.is_err() { |
| 2522 | break; |
| 2523 | } |
| 2524 | } |
| 2525 | let notice = if modality == Modality::Mic { |
| 2526 | MIC_SETTING_FAILED_NOTICE |
| 2527 | } else { |
| 2528 | CAMERA_SETTING_FAILED_NOTICE |
| 2529 | }; |
| 2530 | report_organizer_result(result, "attendee modality", notice, control, timeline); |
| 2531 | } |
| 2532 | Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => { |
| 2533 | let result = match &meeting_target { |
| 2534 | Some(target) => meeting_options::write(&inner.session, target, &OptionWrite::restrictions(mic_off, camera_off)).await.map(|()| 200), |
| 2535 | None => Err(Error::Signaling("no meeting coordinates for the options".into())), |
| 2536 | }; |
| 2537 | if result.is_ok() { |
| 2538 | capability.attendee_mic_off = mic_off; |
| 2539 | capability.attendee_camera_off = camera_off; |
| 2540 | control.send(CallUpdate::Capability(capability)); |
| 2541 | } |
| 2542 | report_organizer_result(result, "attendee restrictions", ATTENDEE_SETTINGS_FAILED_NOTICE, control, timeline); |
| 2543 | } |
| 2544 | Some(CallCommand::Invite { callees, group_thread }) => { |
| 2545 | let thread = group_thread.or_else(|| meeting_chat.clone()); |
| 2546 | let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await; |
| 2547 | report_organizer_result(result, "invite", INVITE_PERSON_FAILED_NOTICE, control, timeline); |
| 2548 | } |
| 2549 | Some(CallCommand::LoadMeetingOptions) => { |
| 2550 | let update = match &meeting_target { |
| 2551 | Some(target) => meeting_options::fetch(&inner.session, target).await.map_err(|error| error.to_string()), |
| 2552 | None => Err("This meeting has no options page".to_owned()), |
| 2553 | }; |
| 2554 | control.send(CallUpdate::MeetingOptions(update)); |
| 2555 | } |
| 2556 | Some(CallCommand::SaveMeetingOptions(writes)) => { |
| 2557 | let update = match &meeting_target { |
| 2558 | Some(target) => save_meeting_options(&inner.session, target, &writes).await, |
| 2559 | None => Err("This meeting has no options page".to_owned()), |
| 2560 | }; |
| 2561 | if let Ok(options) = &update { |
| 2562 | let (mic_off, camera_off) = options.attendees_off(); |
| 2563 | capability.attendee_mic_off = mic_off; |
| 2564 | capability.attendee_camera_off = camera_off; |
| 2565 | control.send(CallUpdate::Capability(capability)); |
| 2566 | } |
| 2567 | control.send(CallUpdate::MeetingOptionsSaved(update)); |
| 2568 | } |
| 2569 | Some(CallCommand::Spotlight { mri }) => { |
| 2570 | let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await; |
| 2571 | report_organizer_result(result, "spotlight", SPOTLIGHT_FAILED_NOTICE, control, timeline); |
| 2572 | } |
| 2573 | Some(CallCommand::StopSpotlight { mri }) => { |
| 2574 | let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect(); |
| 2575 | if !state_ids.is_empty() { |
| 2576 | let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200); |
| 2577 | report_organizer_result(result, "stop spotlight", STOP_SPOTLIGHT_FAILED_NOTICE, control, timeline); |
| 2578 | } |
| 2579 | } |
| 2580 | Some(CallCommand::SetCaptions(on)) => { |
| 2581 | caption_flow.want(on); |
| 2582 | if on { |
| 2583 | caption_deadline = Some(Instant::now() + CAPTION_START_LIMIT); |
| 2584 | control.send(CallUpdate::Captions(CaptionState::Starting)); |
| 2585 | } else { |
| 2586 | caption_deadline = None; |
| 2587 | control.send(CallUpdate::Captions(CaptionState::Off)); |
| 2588 | } |
| 2589 | run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), &RecordingPlan::default(), &mut bot_pending, control, timeline).await; |
| 2590 | if caption_flow.on() { |
| 2591 | caption_deadline = None; |
| 2592 | } |
| 2593 | } |
| 2594 | Some(CallCommand::StartRecording { kind, title }) => { |
| 2595 | if !is_echo { |
| 2596 | recording_plan = RecordingPlan { title, kind, ..RecordingPlan::default() }; |
| 2597 | recording_flow.want(true); |
| 2598 | recording_deadline = Some(Instant::now() + RECORDING_START_LIMIT); |
| 2599 | control.send(CallUpdate::RecordingPending(true)); |
| 2600 | run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await; |
| 2601 | } |
| 2602 | } |
| 2603 | Some(CallCommand::StopRecording { scope }) => { |
| 2604 | if !is_echo { |
| 2605 | recording_plan.scope = scope; |
| 2606 | recording_flow.stop(); |
| 2607 | recording_deadline = None; |
| 2608 | run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await; |
| 2609 | } |
| 2610 | } |
| 2611 | Some(CallCommand::SetCaptionLanguage(language)) => { |
| 2612 | if let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) |
| 2613 | && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await |
| 2614 | { |
| 2615 | timeline.record("caption language failed", error.to_string()); |
| 2616 | control.send(CallUpdate::Notice(CAPTION_LANGUAGE_FAILED_NOTICE.into())); |
| 2617 | } |
| 2618 | } |
| 2619 | Some(CallCommand::ConsentToRecording) => { |
| 2620 | match remote.signaling.consent_to_recording(&remote.conversation, &remote.participant, Consent::Give).await { |
| 2621 | Ok(_) => { |
| 2622 | consent_pending = false; |
| 2623 | control.send(CallUpdate::ConsentRequired(false)); |
| 2624 | } |
| 2625 | Err(error) => { |
| 2626 | timeline.record("recording consent failed", error.to_string()); |
| 2627 | control.send(CallUpdate::Notice(CONFIRM_RECORDING_FAILED_NOTICE.into())); |
| 2628 | } |
| 2629 | } |
| 2630 | } |
| 2631 | Some(CallCommand::Hold(hold)) => { |
| 2632 | if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || glare_resend.is_some() || next.is_some() { |
| 2633 | continue; |
| 2634 | } |
| 2635 | if hold && local_video.camera_on() { |
| 2636 | local_video.stop_camera(); |
| 2637 | control.send(CallUpdate::Camera(false)); |
| 2638 | } |
| 2639 | let camera = !hold && local_video.camera_on(); |
| 2640 | 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 { |
| 2641 | Ok((browser_offer, signaled, reply_tags)) => { |
| 2642 | timeline.record_sdp("local offer", &signaled.sdp); |
| 2643 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags }); |
| 2644 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 2645 | same_peer_grace_until = None; |
| 2646 | } |
| 2647 | Err(error) => { |
| 2648 | timeline.record("hold failed", error.to_string()); |
| 2649 | control.send(CallUpdate::Notice(if hold { |
| 2650 | HOLD_FAILED_NOTICE.into() |
| 2651 | } else { |
| 2652 | RESUME_FAILED_NOTICE.into() |
| 2653 | })); |
| 2654 | } |
| 2655 | } |
| 2656 | } |
| 2657 | Some(CallCommand::Transfer { target, replaces }) => { |
| 2658 | let Some(url) = media_links.get("transfer").cloned() else { |
| 2659 | control.send(CallUpdate::TransferResult { succeeded: false }); |
| 2660 | control.send(CallUpdate::Notice(TRANSFER_NOT_ALLOWED_NOTICE.into())); |
| 2661 | continue; |
| 2662 | }; |
| 2663 | let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() }; |
| 2664 | match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await { |
| 2665 | Ok(()) => control.send(CallUpdate::Notice(notice_with_detail( |
| 2666 | TRANSFERRING_NOTICE, |
| 2667 | target.display_name, |
| 2668 | ))), |
| 2669 | Err(error) => { |
| 2670 | timeline.record("transfer failed", error.to_string()); |
| 2671 | control.send(CallUpdate::TransferResult { succeeded: false }); |
| 2672 | control.send(CallUpdate::Notice(TRANSFER_CALL_FAILED_NOTICE.into())); |
| 2673 | } |
| 2674 | } |
| 2675 | } |
| 2676 | Some(CallCommand::OpenWhiteboard { title }) => { |
| 2677 | let Some(target) = meeting_target.clone() else { |
| 2678 | control.send(CallUpdate::Notice(WHITEBOARDS_MEETINGS_ONLY_NOTICE.into())); |
| 2679 | continue; |
| 2680 | }; |
| 2681 | let session = inner.session.clone(); |
| 2682 | let updates = control.updates(); |
| 2683 | tokio::spawn(async move { |
| 2684 | let update = match whiteboard::fetch_board(&session, &target, &title).await { |
| 2685 | Ok(url) => CallUpdate::WhiteboardUrl(url), |
| 2686 | Err(_) => CallUpdate::Notice(WHITEBOARD_OPEN_FAILED_NOTICE.into()), |
| 2687 | }; |
| 2688 | let _ = updates.send(update); |
| 2689 | }); |
| 2690 | } |
| 2691 | Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await, |
| 2692 | Some(CallCommand::SetIncomingVideo(enabled)) => { |
| 2693 | video.set_incoming_enabled(enabled); |
| 2694 | if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) { |
| 2695 | let key = VideoKey::Person(mri.clone()); |
| 2696 | control.video.forget(&key); |
| 2697 | video.router().set(mid, enabled.then_some(key)); |
| 2698 | } |
| 2699 | send_receive_change(control, video.reselect(&roster)); |
| 2700 | control.send(CallUpdate::IncomingVideo(enabled)); |
| 2701 | } |
| 2702 | Some(CallCommand::SetVideoWants(wants)) => { |
| 2703 | if video.set_wants(wants) { |
| 2704 | send_receive_change(control, video.reselect(&roster)); |
| 2705 | } |
| 2706 | } |
| 2707 | Some(CallCommand::SetShareMotion(on)) => local_video.set_motion(on), |
| 2708 | Some(CallCommand::SetShareStandout(on)) => local_video.set_standout(on), |
| 2709 | Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects), |
| 2710 | Some(CallCommand::SendReaction(reaction)) => { |
| 2711 | if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await { |
| 2712 | timeline.record("reaction failed", error.to_string()); |
| 2713 | control.send(CallUpdate::Notice(REACTION_FAILED_NOTICE.into())); |
| 2714 | } |
| 2715 | } |
| 2716 | Some(CallCommand::EndMeeting) => { |
| 2717 | stop_local_publish( |
| 2718 | &mut local_video, |
| 2719 | &remote, |
| 2720 | &media_links, |
| 2721 | &mut media_description_request, |
| 2722 | control, |
| 2723 | timeline, |
| 2724 | ) |
| 2725 | .await; |
| 2726 | if is_meeting { |
| 2727 | match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await { |
| 2728 | Ok(()) => { |
| 2729 | live.skip_leave = true; |
| 2730 | report.left_cleanly = true; |
| 2731 | } |
| 2732 | Err(error) => timeline.record("end meeting failed", error.to_string()), |
| 2733 | } |
| 2734 | } |
| 2735 | advance(state, CallSignal::LocalLeave, control); |
| 2736 | break; |
| 2737 | } |
| 2738 | Some(CallCommand::Hangup) | None => { |
| 2739 | // Stop publishing before leave so remotes do not keep a frozen camera tile. |
| 2740 | stop_local_publish( |
| 2741 | &mut local_video, |
| 2742 | &remote, |
| 2743 | &media_links, |
| 2744 | &mut media_description_request, |
| 2745 | control, |
| 2746 | timeline, |
| 2747 | ) |
| 2748 | .await; |
| 2749 | advance(state, CallSignal::LocalLeave, control); |
| 2750 | break; |
| 2751 | } |
| 2752 | }, |
| 2753 | _ = stats_tick.tick(), if remote_set => { |
| 2754 | if local_video.take_effects_failure() { |
| 2755 | timeline.record("camera effects failed", "segmentation model did not load"); |
| 2756 | control.send(CallUpdate::Notice(CAMERA_EFFECTS_FAILED_NOTICE.into())); |
| 2757 | } |
| 2758 | let speaking = active_speakers::speaking_sources(&active_speakers::audio_sources(¤t.peer)); |
| 2759 | if speaking != speaking_sources { |
| 2760 | if speaking_sources.is_empty() && !speaker_sources_seen { |
| 2761 | speaker_sources_seen = true; |
| 2762 | timeline.record("active speakers", format!("{} source(s) from RTP", speaking.len())); |
| 2763 | } |
| 2764 | speaking_sources = speaking; |
| 2765 | let mut speakers = roster.mris_for_sources(&speaking_sources); |
| 2766 | if speakers.is_empty() && !speaking_sources.is_empty() && layout == Layout::OneToOne { |
| 2767 | speakers = roster.entries().into_iter().map(|entry| entry.mri).filter(|mri| *mri != own_mri).collect(); |
| 2768 | } |
| 2769 | if video.note_speakers(&speakers) { |
| 2770 | send_receive_change(control, video.reselect(&roster)); |
| 2771 | } |
| 2772 | control.send(CallUpdate::Speakers(speakers)); |
| 2773 | } |
| 2774 | let snapshot = collect_stats(¤t.peer, &layout_plan.screen_share_mids).await; |
| 2775 | ticks += 1; |
| 2776 | if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) { |
| 2777 | caption_deadline = None; |
| 2778 | caption_flow.failed(); |
| 2779 | timeline.record("captions", "did not start in time"); |
| 2780 | control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into()))); |
| 2781 | } |
| 2782 | if recording_deadline.is_some_and(|deadline| Instant::now() >= deadline) { |
| 2783 | recording_deadline = None; |
| 2784 | recording_flow.failed(); |
| 2785 | timeline.record("recording", "did not start in time"); |
| 2786 | control.send(CallUpdate::RecordingPending(false)); |
| 2787 | control.send(CallUpdate::Notice(RECORDING_NOT_STARTED_NOTICE.into())); |
| 2788 | } |
| 2789 | if layout == Layout::Conference |
| 2790 | && let Some(size) = local_video.camera_size() |
| 2791 | && let Some(url) = media_links.get("applyChannelParameters").cloned() |
| 2792 | && let Some(body) = send_capabilities.body_for_mid( |
| 2793 | local_video |
| 2794 | .camera_mid() |
| 2795 | .as_deref() |
| 2796 | .unwrap_or(CAMERA_MID), |
| 2797 | size, |
| 2798 | local_video.video_quality(), |
| 2799 | ) |
| 2800 | { |
| 2801 | let signaling = signaling.clone(); |
| 2802 | let timeline = timeline.clone(); |
| 2803 | tokio::spawn(async move { |
| 2804 | match signaling.post_json(SEND_CAPABILITIES_LABEL, &url, body).await { |
| 2805 | Ok(()) => timeline.record("send capabilities", format!("{}x{} accepted", size.0, size.1)), |
| 2806 | Err(error) => timeline.record("send capabilities failed", error.to_string()), |
| 2807 | } |
| 2808 | }); |
| 2809 | } |
| 2810 | for (source, refreshed) in local_video.refresh_send_limits() { |
| 2811 | match refreshed { |
| 2812 | Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?} after a frame size change")), |
| 2813 | Ok(None) => {} |
| 2814 | Err(error) => timeline.record("send limits failed", error.to_string()), |
| 2815 | } |
| 2816 | } |
| 2817 | if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS) |
| 2818 | && let Some(average_ms) = local_video.blur_average_ms() |
| 2819 | { |
| 2820 | control.send(CallUpdate::BlurTiming(average_ms)); |
| 2821 | if let Some(model) = local_video.blur_model().filter(|model| Some(*model) != segmentation_model) { |
| 2822 | timeline.record("segmentation model", format!("{model}, effects {average_ms:.1} ms per frame")); |
| 2823 | segmentation_model = Some(model); |
| 2824 | } |
| 2825 | } |
| 2826 | if crate::host_load::recorded_on_this_platform() |
| 2827 | && ticks.is_multiple_of(HEALTH_EVERY_TICKS) |
| 2828 | { |
| 2829 | let current = crate::host_load::thread_cpu(); |
| 2830 | let deltas = crate::host_load::cpu_deltas(¤t, &mut host_cpu); |
| 2831 | timeline.record( |
| 2832 | "host load", |
| 2833 | crate::host_load::host_load_line( |
| 2834 | &deltas, |
| 2835 | &local_video.effects_label(), |
| 2836 | crate::host_load::thermal_state(), |
| 2837 | ), |
| 2838 | ); |
| 2839 | } |
| 2840 | if ticks.is_multiple_of(HEALTH_EVERY_TICKS) { |
| 2841 | control.send(CallUpdate::Sample(StatsSample { |
| 2842 | audio_in_packets: snapshot.inbound_packets, |
| 2843 | audio_out_packets: snapshot.outbound_packets, |
| 2844 | audio_in_level: snapshot.audio_level, |
| 2845 | audio_out_level: snapshot.local_level, |
| 2846 | video: VideoReport { |
| 2847 | frames_received: live.video_counters.received.load(Ordering::Relaxed), |
| 2848 | frames_published: live.video_counters.published.load(Ordering::Relaxed), |
| 2849 | ..snapshot.video.clone() |
| 2850 | }, |
| 2851 | share_in_packets: snapshot.share_inbound_packets, |
| 2852 | share_out_packets: snapshot.share_outbound_packets, |
| 2853 | })); |
| 2854 | } |
| 2855 | if ticks.is_multiple_of(HEALTH_EVERY_TICKS) |
| 2856 | && snapshot.selected_pair.is_some() |
| 2857 | && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health) |
| 2858 | { |
| 2859 | let quality = quality_tracker.observe(std::time::Instant::now(), &sample); |
| 2860 | if local_video.camera_on() |
| 2861 | && snapshot.camera_target_bitrate > 0 |
| 2862 | && bitrate_governor.observe( |
| 2863 | std::time::Instant::now(), |
| 2864 | snapshot.video.remote_round_trip_ms, |
| 2865 | sample.loss_percent, |
| 2866 | snapshot.camera_target_bitrate, |
| 2867 | ) |
| 2868 | { |
| 2869 | let cap = bitrate_governor.cap_bps(); |
| 2870 | if let Err(error) = local_video.cap_camera_bitrate(cap) { |
| 2871 | timeline.record("bitrate cap failed", error.to_string()); |
| 2872 | } else { |
| 2873 | timeline.record( |
| 2874 | "bitrate cap", |
| 2875 | match cap { |
| 2876 | Some(bps) => format!("{} kbit/s", bps / 1000), |
| 2877 | None => "cleared".into(), |
| 2878 | }, |
| 2879 | ); |
| 2880 | } |
| 2881 | } |
| 2882 | control.send(CallUpdate::Health(CallHealth { |
| 2883 | level: quality.level, |
| 2884 | cpu_limited: quality.cpu_limited, |
| 2885 | sample, |
| 2886 | transport: snapshot.transport.clone(), |
| 2887 | path: negotiator.path(), |
| 2888 | })); |
| 2889 | } |
| 2890 | let local_level = if muted && software_audio.is_none() { 0.0 } else { snapshot.local_level as f32 }; |
| 2891 | control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 }); |
| 2892 | if snapshot.selected_pair.is_some() { |
| 2893 | report.selected_pair = snapshot.selected_pair.clone(); |
| 2894 | report.tls_version = snapshot.tls_version.clone(); |
| 2895 | report.dtls_cipher = snapshot.dtls_cipher.clone(); |
| 2896 | report.srtp_cipher = snapshot.srtp_cipher.clone(); |
| 2897 | } |
| 2898 | report.inbound_packets = snapshot.inbound_packets; |
| 2899 | report.inbound_bytes = snapshot.inbound_bytes; |
| 2900 | report.outbound_packets = snapshot.outbound_packets; |
| 2901 | report.video = VideoReport { |
| 2902 | frames_received: live.video_counters.received.load(Ordering::Relaxed), |
| 2903 | frames_published: live.video_counters.published.load(Ordering::Relaxed), |
| 2904 | ..snapshot.video.clone() |
| 2905 | }; |
| 2906 | if ticks.is_multiple_of(TICKS_PER_SECOND) { |
| 2907 | second += 1; |
| 2908 | let (decoded_rms, ratio) = { |
| 2909 | let recording = recording.lock().await; |
| 2910 | recording.per_second.last().copied().unwrap_or_default() |
| 2911 | }; |
| 2912 | if snapshot.inbound_packets > previous_packets { |
| 2913 | report.seconds_with_inbound_audio += 1; |
| 2914 | } |
| 2915 | previous_packets = snapshot.inbound_packets; |
| 2916 | report.seconds.push(AudioSecond { |
| 2917 | second, |
| 2918 | packets: snapshot.inbound_packets, |
| 2919 | bytes: snapshot.inbound_bytes, |
| 2920 | audio_level: snapshot.audio_level, |
| 2921 | decoded_rms, |
| 2922 | tone_ratio: ratio, |
| 2923 | }); |
| 2924 | control.send(CallUpdate::Stats { |
| 2925 | inbound_packets: snapshot.inbound_packets, |
| 2926 | outbound_packets: snapshot.outbound_packets, |
| 2927 | }); |
| 2928 | timeline.record( |
| 2929 | "stats", |
| 2930 | format!( |
| 2931 | "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={:?}{}{}", |
| 2932 | snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state, |
| 2933 | snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height, |
| 2934 | snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height, |
| 2935 | snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders, |
| 2936 | snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default(), |
| 2937 | local_video.camera_capture_summary().unwrap_or_default() |
| 2938 | ), |
| 2939 | ); |
| 2940 | #[cfg(not(windows))] |
| 2941 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 2942 | let listed = devices::list_devices(&factory); |
| 2943 | let previous_ids: Vec<String> = device_lists |
| 2944 | .inputs |
| 2945 | .iter() |
| 2946 | .chain(device_lists.outputs.iter()) |
| 2947 | .map(|device| device.key()) |
| 2948 | .collect(); |
| 2949 | let current_ids: Vec<String> = listed |
| 2950 | .inputs |
| 2951 | .iter() |
| 2952 | .chain(listed.outputs.iter()) |
| 2953 | .map(|device| device.key()) |
| 2954 | .collect(); |
| 2955 | for id in device_watch::endpoint_delta(&previous_ids, ¤t_ids) { |
| 2956 | device_debounce.signal_device(Instant::now(), Some(id)); |
| 2957 | } |
| 2958 | } |
| 2959 | } |
| 2960 | } |
| 2961 | Some(device_id) = device_changes.recv() => { |
| 2962 | device_debounce.signal_device(Instant::now(), device_id); |
| 2963 | } |
| 2964 | _ = sleep_until(device_debounce.deadline().unwrap_or_else(far_future)), if device_debounce.deadline().is_some() => { |
| 2965 | if let Some(touched_ids) = device_debounce.take_due_devices(Instant::now()) { |
| 2966 | let previous = std::mem::replace(&mut device_lists, devices::list_devices(&factory)); |
| 2967 | control.send(CallUpdate::Devices(device_lists.clone())); |
| 2968 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 2969 | let input_changed = follow_device_change(Flow::Capture, (&previous.inputs, &device_lists.inputs), &input, &mut applied_input, &touched_ids, |index| devices::select_input_index(&factory, index), timeline, control); |
| 2970 | let output_changed = follow_device_change(Flow::Render, (&previous.outputs, &device_lists.outputs), &output, &mut applied_output, &touched_ids, |index| devices::select_output_index(&factory, index), timeline, control); |
| 2971 | if input_changed || output_changed { |
| 2972 | record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref()); |
| 2973 | } |
| 2974 | if input_changed && software_audio.is_some() { |
| 2975 | sync_software_audio(&factory, options, &input, muted || local_hold, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, mic_settings, control, timeline); |
| 2976 | } |
| 2977 | } |
| 2978 | } |
| 2979 | } |
| 2980 | _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => { |
| 2981 | advance(state, CallSignal::ReconnectTimedOut, control); |
| 2982 | break; |
| 2983 | } |
| 2984 | _ = sleep_until(leave_at.unwrap_or_else(far_future)), if leave_at.is_some() => { |
| 2985 | advance(state, CallSignal::LocalLeave, control); |
| 2986 | break; |
| 2987 | } |
| 2988 | _ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => { |
| 2989 | if let Some(pending) = next.as_mut().filter(|pending| pending.connected && pending.offered.is_none()) { |
| 2990 | pending.retargeted = true; |
| 2991 | timeline.record("escalation", "no retargetCompletion, switching anyway"); |
| 2992 | } else if let Some(pending) = next.take() { |
| 2993 | pending.session.peer.close(); |
| 2994 | negotiator.escalation_failed(); |
| 2995 | start_camera_pending = false; |
| 2996 | if local_video.camera_previewing() { |
| 2997 | local_video.stop_camera(); |
| 2998 | control.send(CallUpdate::Camera(false)); |
| 2999 | } |
| 3000 | share_pending = None; |
| 3001 | portal_pending = None; |
| 3002 | settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control); |
| 3003 | timeline.record("escalation failed", "no answer for the new peer connection in time"); |
| 3004 | control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into())); |
| 3005 | } |
| 3006 | } |
| 3007 | _ = sleep_until(glare_at.unwrap_or_else(far_future)), if glare_at.is_some() => { |
| 3008 | let resend = glare_resend.take(); |
| 3009 | if let Some(resend) = resend.as_ref().filter(|_| same_peer.is_some() || next.is_some()) { |
| 3010 | timeline.record("glare", "another change took over, ours is dropped"); |
| 3011 | undo_change(resend.change, &mut local_video, control); |
| 3012 | } else if let Some(resend) = resend.as_ref().filter(|resend| layout == Layout::OneToOne && negotiator.path() == MediaPath::Mixer && !matches!(resend.change, Change::Hold(_))) { |
| 3013 | if negotiator.begin_conference_upgrade() { |
| 3014 | 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; |
| 3015 | if pending.is_none() { |
| 3016 | drop_local_media(&mut local_video, control); |
| 3017 | } |
| 3018 | next = pending.or(next); |
| 3019 | } else { |
| 3020 | undo_change(resend.change, &mut local_video, control); |
| 3021 | } |
| 3022 | } else if let Some(resend) = resend { |
| 3023 | let (hold, camera, share) = match resend.change { |
| 3024 | Change::Hold(hold) => (hold, !hold && local_video.camera_on(), local_video.sharing()), |
| 3025 | _ => (local_hold, local_video.camera_on(), local_video.sharing()), |
| 3026 | }; |
| 3027 | 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 { |
| 3028 | Ok((browser_offer, signaled, reply_tags)) => { |
| 3029 | timeline.record_sdp("local offer", &signaled.sdp); |
| 3030 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags }); |
| 3031 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 3032 | same_peer_grace_until = None; |
| 3033 | } |
| 3034 | Err(error) => { |
| 3035 | timeline.record("offer after glare failed", error.to_string()); |
| 3036 | undo_change(resend.change, &mut local_video, control); |
| 3037 | } |
| 3038 | } |
| 3039 | } |
| 3040 | } |
| 3041 | _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => { |
| 3042 | same_peer_deadline = None; |
| 3043 | if same_peer.is_some() { |
| 3044 | same_peer_grace_until = Some(Instant::now() + SAME_PEER_LATE_GRACE); |
| 3045 | timeline.record( |
| 3046 | "same-peer offer", |
| 3047 | "no answer yet, waiting a little longer", |
| 3048 | ); |
| 3049 | } |
| 3050 | } |
| 3051 | _ = sleep_until(same_peer_grace_until.unwrap_or_else(far_future)), if same_peer_grace_until.is_some() => { |
| 3052 | same_peer_grace_until = None; |
| 3053 | if let Some(pending) = same_peer.take() { |
| 3054 | timeline.record("same-peer offer", "no answer in time"); |
| 3055 | negotiator.same_peer_offer_failed(); |
| 3056 | rollback_offer(¤t.peer).await; |
| 3057 | undo_change(pending.change, &mut local_video, control); |
| 3058 | } |
| 3059 | } |
| 3060 | _ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => { |
| 3061 | timeline.record("no answer", "outgoing call timed out"); |
| 3062 | live.cancel_leave = true; |
| 3063 | advance(state, CallSignal::RemoteEnd(EndKind::NoAnswer), control); |
| 3064 | break; |
| 3065 | } |
| 3066 | _ = sleep_until(keep_alive_at.unwrap_or_else(far_future)), if keep_alive_at.is_some() => { |
| 3067 | keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds)); |
| 3068 | let remote = remote.clone(); |
| 3069 | let links = links.clone(); |
| 3070 | let call_leg = keep_alive_link.clone(); |
| 3071 | tokio::spawn(async move { |
| 3072 | if let Some(url) = call_leg { |
| 3073 | let _ = remote.signaling.keep_call_alive(&url).await; |
| 3074 | } |
| 3075 | let _ = remote.signaling.keep_conversation_alive(&remote.conversation, &remote.participant, &links).await; |
| 3076 | }); |
| 3077 | } |
| 3078 | } |
| 3079 | } |
| 3080 | if software_audio.is_some() { |
| 3081 | timeline.record("software audio", "stopping before tear down"); |
| 3082 | drop(software_audio); |
| 3083 | } |
| 3084 | live.callbacks = Some(callbacks); |
| 3085 | Ok(()) |
| 3086 | } |
| 3087 | |
| 3088 | fn far_future() -> Instant { |
| 3089 | Instant::now() + FAR_FUTURE |
| 3090 | } |
| 3091 | |
| 3092 | #[cfg(test)] |
| 3093 | mod tests { |
| 3094 | #[test] |
| 3095 | fn a_missing_call_on_accept_while_connecting_is_a_cancel() { |
| 3096 | let gone = Error::Signaling( |
| 3097 | "POST acceptance answered HTTP 404 {\"Message\":\"The requested call does not exist.\"}" |
| 3098 | .into(), |
| 3099 | ); |
| 3100 | assert!(accept_found_no_call(&gone)); |
| 3101 | let other = Error::Signaling("POST acceptance answered HTTP 500 boom".into()); |
| 3102 | assert!(!accept_found_no_call(&other)); |
| 3103 | let roster = Error::Signaling( |
| 3104 | "POST roster answered HTTP 404 {\"Message\":\"The requested call does not exist.\"}" |
| 3105 | .into(), |
| 3106 | ); |
| 3107 | assert!(!accept_found_no_call(&roster)); |
| 3108 | assert!(!accept_found_no_call(&Error::Cancelled)); |
| 3109 | } |
| 3110 | |
| 3111 | #[test] |
| 3112 | fn gathering_settles_shortly_after_a_udp_relay_or_when_complete() { |
| 3113 | assert!(!gathering_settled(false, None)); |
| 3114 | assert!(!gathering_settled(false, Some(Duration::from_millis(50)))); |
| 3115 | assert!(gathering_settled(false, Some(RELAY_SETTLE))); |
| 3116 | assert!(gathering_settled(true, None)); |
| 3117 | } |
| 3118 | |
| 3119 | #[tokio::test] |
| 3120 | async fn a_hanging_setup_step_ends_on_cancel_or_after_the_step_timeout() { |
| 3121 | let (handle, mut control) = crate::control::call_channel(); |
| 3122 | handle.commands.send(CallCommand::Hangup).unwrap(); |
| 3123 | let limit = Duration::from_millis(20); |
| 3124 | let cancelled = setup_step_within( |
| 3125 | &mut control, |
| 3126 | limit, |
| 3127 | std::future::pending::<std::result::Result<(), Error>>(), |
| 3128 | ) |
| 3129 | .await; |
| 3130 | assert!(matches!(cancelled, Err(Error::Cancelled))); |
| 3131 | let timed_out = setup_step_within( |
| 3132 | &mut control, |
| 3133 | limit, |
| 3134 | std::future::pending::<std::result::Result<(), Error>>(), |
| 3135 | ) |
| 3136 | .await; |
| 3137 | assert!(matches!(timed_out, Err(Error::Signaling(_)))); |
| 3138 | } |
| 3139 | |
| 3140 | use super::*; |
| 3141 | |
| 3142 | #[test] |
| 3143 | fn an_echo_call_waits_for_the_echo_bot_before_it_counts_as_connected() { |
| 3144 | let mut gate = CalleeGate::new(CallSpec::Echo.callee_count()); |
| 3145 | assert!(!gate.media_connected()); |
| 3146 | assert!(gate.callee_joined()); |
| 3147 | } |
| 3148 | |
| 3149 | #[test] |
| 3150 | fn only_a_conflict_answer_retries_a_recording_stop() { |
| 3151 | assert!(recorder_busy(&Error::Signaling( |
| 3152 | "recording command answered HTTP 409 no answer".into() |
| 3153 | ))); |
| 3154 | assert!(!recorder_busy(&Error::Signaling( |
| 3155 | "recording command answered HTTP 500 no answer".into() |
| 3156 | ))); |
| 3157 | assert!(!recorder_busy(&Error::Cancelled)); |
| 3158 | } |
| 3159 | |
| 3160 | #[test] |
| 3161 | fn escalation_keeps_the_software_track_when_it_runs() { |
| 3162 | assert_eq!(*pick_track(Some(&1), &0), 1); |
| 3163 | assert_eq!(*pick_track(None, &0), 0); |
| 3164 | } |
| 3165 | |
| 3166 | #[test] |
| 3167 | fn video_is_possible_once_connected_and_not_waiting_on_a_mixer_escalation() { |
| 3168 | assert!(video_possible(true, Layout::OneToOne, MediaPath::Direct)); |
| 3169 | assert!(video_possible(true, Layout::Conference, MediaPath::Mixer)); |
| 3170 | assert!(!video_possible(true, Layout::OneToOne, MediaPath::Mixer)); |
| 3171 | assert!(!video_possible( |
| 3172 | false, |
| 3173 | Layout::Conference, |
| 3174 | MediaPath::Direct |
| 3175 | )); |
| 3176 | } |
| 3177 | |
| 3178 | #[test] |
| 3179 | fn camera_does_not_start_while_a_peer_escalation_is_pending() { |
| 3180 | assert!(camera_may_start(true, false, true)); |
| 3181 | assert!(!camera_may_start(true, true, true)); |
| 3182 | assert!(!camera_may_start(false, false, true)); |
| 3183 | assert!(!camera_may_start(true, false, false)); |
| 3184 | } |
| 3185 | |
| 3186 | #[test] |
| 3187 | fn leg_switch_keeps_mixer_control_links_when_renegotiation_omits_them() { |
| 3188 | let mut media_links = BTreeMap::from([ |
| 3189 | ( |
| 3190 | "updateMediaDescriptions".to_owned(), |
| 3191 | "https://m/update".to_owned(), |
| 3192 | ), |
| 3193 | ( |
| 3194 | "applyChannelParameters".to_owned(), |
| 3195 | "https://m/apply".to_owned(), |
| 3196 | ), |
| 3197 | ("callLeg".to_owned(), "https://m/leg".to_owned()), |
| 3198 | ]); |
| 3199 | replace_leg_media_links( |
| 3200 | &mut media_links, |
| 3201 | &BTreeMap::from([("mediaAnswer".to_owned(), "https://m/answer".to_owned())]), |
| 3202 | ); |
| 3203 | assert_eq!( |
| 3204 | media_links |
| 3205 | .get("updateMediaDescriptions") |
| 3206 | .map(String::as_str), |
| 3207 | Some("https://m/update") |
| 3208 | ); |
| 3209 | assert_eq!( |
| 3210 | media_links |
| 3211 | .get("applyChannelParameters") |
| 3212 | .map(String::as_str), |
| 3213 | Some("https://m/apply") |
| 3214 | ); |
| 3215 | assert_eq!( |
| 3216 | media_links.get("mediaAnswer").map(String::as_str), |
| 3217 | Some("https://m/answer") |
| 3218 | ); |
| 3219 | replace_leg_media_links( |
| 3220 | &mut media_links, |
| 3221 | &BTreeMap::from([( |
| 3222 | "updateMediaDescriptions".to_owned(), |
| 3223 | "https://m/update-new".to_owned(), |
| 3224 | )]), |
| 3225 | ); |
| 3226 | assert_eq!( |
| 3227 | media_links |
| 3228 | .get("updateMediaDescriptions") |
| 3229 | .map(String::as_str), |
| 3230 | Some("https://m/update-new") |
| 3231 | ); |
| 3232 | } |
| 3233 | |
| 3234 | #[test] |
| 3235 | fn keep_alive_fires_at_ninety_percent_of_the_interval() { |
| 3236 | assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430)); |
| 3237 | assert_eq!(keep_alive_period(None), Duration::from_secs(2430)); |
| 3238 | assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54)); |
| 3239 | } |
| 3240 | |
| 3241 | const BROWSER_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:1\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:2\r\na=recvonly\r\n"; |
| 3242 | |
| 3243 | fn directions(sdp: &str) -> Vec<String> { |
| 3244 | crate::sdp::parse(sdp) |
| 3245 | .unwrap() |
| 3246 | .media |
| 3247 | .iter() |
| 3248 | .map(|line| line.direction().unwrap_or("none").to_owned()) |
| 3249 | .collect() |
| 3250 | } |
| 3251 | |
| 3252 | async fn local_offer(layout: Layout) -> Result<OfferedMedia> { |
| 3253 | use libwebrtc::audio_source::native::NativeAudioSource; |
| 3254 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 3255 | let factory = devices::shared_factory(); |
| 3256 | let peer = factory |
| 3257 | .create_peer_connection(RtcConfiguration::default()) |
| 3258 | .unwrap(); |
| 3259 | let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100); |
| 3260 | let track = factory.create_audio_track("microphone", source); |
| 3261 | let offer = create_offer(&peer, &factory, &track, layout, None).await; |
| 3262 | peer.close(); |
| 3263 | offer |
| 3264 | } |
| 3265 | |
| 3266 | #[tokio::test] |
| 3267 | async fn libwebrtc_accepts_its_own_offer_after_the_direction_rewrite() { |
| 3268 | for layout in [Layout::OneToOne, Layout::Conference] { |
| 3269 | if let Err(error) = local_offer(layout).await { |
| 3270 | panic!("{layout:?}: {error}"); |
| 3271 | } |
| 3272 | } |
| 3273 | } |
| 3274 | |
| 3275 | #[tokio::test] |
| 3276 | async fn a_peer_to_peer_offer_from_the_teams_client_gets_an_answer() { |
| 3277 | use libwebrtc::audio_source::native::NativeAudioSource; |
| 3278 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 3279 | let factory = devices::shared_factory(); |
| 3280 | let peer = factory |
| 3281 | .create_peer_connection(RtcConfiguration::default()) |
| 3282 | .unwrap(); |
| 3283 | let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100); |
| 3284 | let track = factory.create_audio_track("microphone", source); |
| 3285 | let offer = include_str!("../../tests/fixtures/teams_p2p_offer.sdp"); |
| 3286 | let answered = answer_offer( |
| 3287 | &peer, |
| 3288 | Some(&track), |
| 3289 | offer, |
| 3290 | AnswerVideo::Receive, |
| 3291 | None, |
| 3292 | false, |
| 3293 | None, |
| 3294 | ) |
| 3295 | .await; |
| 3296 | peer.close(); |
| 3297 | if let Err(error) = answered { |
| 3298 | panic!("{error}"); |
| 3299 | } |
| 3300 | } |
| 3301 | |
| 3302 | #[test] |
| 3303 | fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() { |
| 3304 | assert_eq!( |
| 3305 | directions(&directions_for( |
| 3306 | Layout::OneToOne, |
| 3307 | false, |
| 3308 | false, |
| 3309 | false, |
| 3310 | CAMERA_MID, |
| 3311 | Some(ONE_TO_ONE_SHARE_MID), |
| 3312 | false, |
| 3313 | BROWSER_OFFER |
| 3314 | )), |
| 3315 | vec!["sendrecv", "inactive", "inactive"] |
| 3316 | ); |
| 3317 | assert_eq!( |
| 3318 | directions(&directions_for( |
| 3319 | Layout::OneToOne, |
| 3320 | false, |
| 3321 | true, |
| 3322 | false, |
| 3323 | CAMERA_MID, |
| 3324 | Some(ONE_TO_ONE_SHARE_MID), |
| 3325 | false, |
| 3326 | BROWSER_OFFER |
| 3327 | )), |
| 3328 | vec!["sendrecv", "sendrecv", "inactive"] |
| 3329 | ); |
| 3330 | assert_eq!( |
| 3331 | directions(&directions_for( |
| 3332 | Layout::OneToOne, |
| 3333 | false, |
| 3334 | false, |
| 3335 | true, |
| 3336 | CAMERA_MID, |
| 3337 | Some(ONE_TO_ONE_SHARE_MID), |
| 3338 | false, |
| 3339 | BROWSER_OFFER |
| 3340 | )), |
| 3341 | vec!["sendrecv", "inactive", "sendonly"] |
| 3342 | ); |
| 3343 | } |
| 3344 | |
| 3345 | #[test] |
| 3346 | fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() { |
| 3347 | for layout in [Layout::OneToOne, Layout::Conference] { |
| 3348 | assert_eq!( |
| 3349 | directions(&directions_for( |
| 3350 | layout, |
| 3351 | true, |
| 3352 | true, |
| 3353 | false, |
| 3354 | CAMERA_MID, |
| 3355 | None, |
| 3356 | false, |
| 3357 | BROWSER_OFFER |
| 3358 | )), |
| 3359 | vec!["inactive", "inactive", "inactive"] |
| 3360 | ); |
| 3361 | } |
| 3362 | assert_eq!( |
| 3363 | directions_for( |
| 3364 | Layout::Conference, |
| 3365 | false, |
| 3366 | true, |
| 3367 | false, |
| 3368 | CAMERA_MID, |
| 3369 | None, |
| 3370 | false, |
| 3371 | BROWSER_OFFER |
| 3372 | ), |
| 3373 | BROWSER_OFFER |
| 3374 | ); |
| 3375 | } |
| 3376 | |
| 3377 | #[test] |
| 3378 | fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() { |
| 3379 | let held = directions_for( |
| 3380 | Layout::Conference, |
| 3381 | true, |
| 3382 | false, |
| 3383 | false, |
| 3384 | CAMERA_MID, |
| 3385 | None, |
| 3386 | false, |
| 3387 | BROWSER_OFFER, |
| 3388 | ); |
| 3389 | let mut numbers = || 7; |
| 3390 | let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers) |
| 3391 | .unwrap() |
| 3392 | .sdp; |
| 3393 | assert_eq!( |
| 3394 | directions(&signaled), |
| 3395 | vec!["inactive", "inactive", "inactive"] |
| 3396 | ); |
| 3397 | assert_eq!(signaled.matches("a=candidate:").count(), 1); |
| 3398 | } |
| 3399 | |
| 3400 | #[test] |
| 3401 | fn a_move_into_the_meeting_you_are_already_in_is_ignored() { |
| 3402 | let target = |thread: &str| MeetingTarget { |
| 3403 | thread_id: thread.into(), |
| 3404 | tenant_id: "t".into(), |
| 3405 | organizer_id: "o".into(), |
| 3406 | meeting_data: None, |
| 3407 | }; |
| 3408 | assert!(is_own_meeting( |
| 3409 | Some(&target("19:meeting_a@thread.v2")), |
| 3410 | &target("19:meeting_a@thread.v2") |
| 3411 | )); |
| 3412 | assert!(!is_own_meeting( |
| 3413 | Some(&target("19:meeting_a@thread.v2")), |
| 3414 | &target("19:meeting_b@thread.v2") |
| 3415 | )); |
| 3416 | assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2"))); |
| 3417 | } |
| 3418 | |
| 3419 | #[test] |
| 3420 | fn a_video_call_names_the_video_modality_only_when_the_camera_sends() { |
| 3421 | assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]); |
| 3422 | assert_eq!( |
| 3423 | accepted_modalities(true), |
| 3424 | vec!["Audio".to_owned(), "Video".to_owned()] |
| 3425 | ); |
| 3426 | } |
| 3427 | |
| 3428 | #[test] |
| 3429 | fn specs_map_to_invitation_targets() { |
| 3430 | assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo); |
| 3431 | let people = CallSpec::People { |
| 3432 | callees: vec![Callee { |
| 3433 | mri: "8:orgid:b".into(), |
| 3434 | display_name: "Bea".into(), |
| 3435 | }], |
| 3436 | thread_id: "19:t@thread.v2".into(), |
| 3437 | }; |
| 3438 | assert!(people.is_people() && !people.is_meeting()); |
| 3439 | assert!( |
| 3440 | matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2") |
| 3441 | ); |
| 3442 | let meeting = CallSpec::Meeting(MeetingTarget { |
| 3443 | thread_id: "19:meeting@thread.v2".into(), |
| 3444 | tenant_id: "t".into(), |
| 3445 | organizer_id: "o".into(), |
| 3446 | meeting_data: None, |
| 3447 | }); |
| 3448 | assert!(meeting.is_meeting() && !meeting.is_people()); |
| 3449 | } |
| 3450 | } |