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