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