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