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