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