| 1 | use std::collections::BTreeMap; |
| 2 | use std::path::PathBuf; |
| 3 | use std::sync::Arc; |
| 4 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 5 | use std::time::Duration; |
| 6 | |
| 7 | use chatsvc::TrouterCallback; |
| 8 | use futures_util::StreamExt; |
| 9 | use libwebrtc::audio_stream::native::NativeAudioStream; |
| 10 | use libwebrtc::data_channel::{DataChannel, DataChannelInit}; |
| 11 | use libwebrtc::prelude::*; |
| 12 | use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit}; |
| 13 | use libwebrtc::session_description::{SdpType, SessionDescription}; |
| 14 | use libwebrtc::stats::RtcStats; |
| 15 | use session::Session; |
| 16 | use tokio::sync::{Mutex, mpsc}; |
| 17 | use tokio::task::JoinHandle; |
| 18 | use tokio::time::{Instant, interval, sleep_until, timeout}; |
| 19 | |
| 20 | use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav}; |
| 21 | use crate::audio_io::{AudioMode, AudioSetup}; |
| 22 | use crate::background::{BackgroundChoice, BackgroundPicture}; |
| 23 | use crate::breakout::{self, RoomWatcher}; |
| 24 | use crate::callee_gate::{CalleeGate, roster_has_callee}; |
| 25 | use crate::camera::{CameraDevice, list_cameras}; |
| 26 | use crate::captions::{ |
| 27 | BotAction, CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep, |
| 28 | parse_caption_message, |
| 29 | }; |
| 30 | use crate::control::{CallCommand, CallControl, CallUpdate, Progress}; |
| 31 | use crate::data_channel::Depacketizer; |
| 32 | use crate::devices::{self, DeviceChoice}; |
| 33 | use crate::end::EndKind; |
| 34 | use crate::engine::{CallEngine, EngineConfig, Inner}; |
| 35 | use crate::error::{Error, Result}; |
| 36 | use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats}; |
| 37 | use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, rewrite_directions}; |
| 38 | use crate::mute::{MuteCommand, MuteEffect}; |
| 39 | use crate::push::CallNotification; |
| 40 | use crate::share_audio::ShareAudio; |
| 41 | use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant}; |
| 42 | use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath}; |
| 43 | use crate::organizer::Target; |
| 44 | use crate::recording::{Consent, RecordingStatus}; |
| 45 | use crate::roster::Roster; |
| 46 | use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer}; |
| 47 | use crate::signaling::{ |
| 48 | Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling, |
| 49 | TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body, |
| 50 | }; |
| 51 | use crate::state::{CallSignal, CallState}; |
| 52 | use crate::timeline::{Timeline, TimelineEntry}; |
| 53 | use crate::transfer::{TransferEvent, TransferTarget}; |
| 54 | use crate::video_frame::VideoKey; |
| 55 | use crate::video_layout::{ |
| 56 | CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, offer_plan, one_to_one_plan, |
| 57 | }; |
| 58 | use crate::video_send::{LocalVideo, VideoMode}; |
| 59 | use crate::screen::{ShareKind, ShareSource, list_share_sources}; |
| 60 | use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump}; |
| 61 | use crate::trouter_events::{ |
| 62 | CallEnd, CallEvent, CallbackLinks, ProgressStatus, acceptance_acknowledgement, classify, decode_body, |
| 63 | }; |
| 64 | use crate::whiteboard; |
| 65 | |
| 66 | const END_CALLBACK_WAIT: Duration = Duration::from_secs(4); |
| 67 | const STATS_PERIOD: Duration = Duration::from_millis(200); |
| 68 | const TICKS_PER_SECOND: u32 = 5; |
| 69 | const RECONNECT_WINDOW: Duration = Duration::from_secs(30); |
| 70 | const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90); |
| 71 | const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365); |
| 72 | const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700; |
| 73 | const MIN_KEEP_ALIVE_SECONDS: u64 = 60; |
| 74 | const KEEP_ALIVE_FRACTION: f64 = 0.9; |
| 75 | const MIC_STREAM: &str = "microphone"; |
| 76 | const DATA_CHANNEL_LABEL: &str = "main-channel"; |
| 77 | pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL"; |
| 78 | const CAPTION_START_LIMIT: Duration = Duration::from_secs(40); |
| 79 | const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2; |
| 80 | const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2; |
| 81 | const BOT_PREFIX: &str = "28:"; |
| 82 | const RECORDING_START_LIMIT: Duration = Duration::from_secs(40); |
| 83 | const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(15); |
| 84 | const CAMERA_STREAM: &str = "camera"; |
| 85 | const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first"; |
| 86 | |
| 87 | #[derive(Debug, Clone)] |
| 88 | pub struct CallOptions { |
| 89 | pub hold_after_connected: Option<Duration>, |
| 90 | pub hard_limit: Option<Duration>, |
| 91 | pub reconnect_window: Duration, |
| 92 | pub audio: AudioMode, |
| 93 | pub video: VideoMode, |
| 94 | pub camera: DeviceChoice, |
| 95 | pub tone_hz: f32, |
| 96 | pub input: DeviceChoice, |
| 97 | pub output: DeviceChoice, |
| 98 | pub relay_host: String, |
| 99 | pub routing: TenantRouting, |
| 100 | pub record_remote: bool, |
| 101 | pub wav_path: Option<PathBuf>, |
| 102 | pub sdp_dump_dir: Option<PathBuf>, |
| 103 | pub trace: bool, |
| 104 | pub data_channel: bool, |
| 105 | pub concurrent: bool, |
| 106 | pub start_camera: bool, |
| 107 | } |
| 108 | |
| 109 | impl Default for CallOptions { |
| 110 | fn default() -> Self { |
| 111 | CallOptions { |
| 112 | hold_after_connected: None, |
| 113 | hard_limit: None, |
| 114 | reconnect_window: RECONNECT_WINDOW, |
| 115 | audio: AudioMode::from_env(), |
| 116 | video: VideoMode::from_env(), |
| 117 | camera: DeviceChoice::SystemDefault, |
| 118 | tone_hz: 440.0, |
| 119 | input: DeviceChoice::SystemDefault, |
| 120 | output: DeviceChoice::SystemDefault, |
| 121 | relay_host: DEFAULT_RELAY_HOST.to_owned(), |
| 122 | routing: TenantRouting::default(), |
| 123 | record_remote: false, |
| 124 | wav_path: None, |
| 125 | sdp_dump_dir: None, |
| 126 | trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(), |
| 127 | data_channel: data_channel_from_env(), |
| 128 | concurrent: false, |
| 129 | start_camera: false, |
| 130 | } |
| 131 | } |
| 132 | } |
| 133 | |
| 134 | #[derive(Debug, Clone, Default)] |
| 135 | pub struct AudioSecond { |
| 136 | pub second: u32, |
| 137 | pub packets: u64, |
| 138 | pub bytes: u64, |
| 139 | pub audio_level: f64, |
| 140 | pub decoded_rms: f32, |
| 141 | pub tone_ratio: f32, |
| 142 | } |
| 143 | |
| 144 | #[derive(Debug, Clone, Default, PartialEq)] |
| 145 | pub struct VideoReport { |
| 146 | pub inbound_packets: u64, |
| 147 | pub inbound_frames_decoded: u64, |
| 148 | pub inbound_width: u32, |
| 149 | pub inbound_height: u32, |
| 150 | pub frames_received: u64, |
| 151 | pub frames_published: u64, |
| 152 | pub outbound_packets: u64, |
| 153 | pub outbound_frames_encoded: u64, |
| 154 | pub outbound_width: u32, |
| 155 | pub outbound_height: u32, |
| 156 | pub remote_reports: u64, |
| 157 | pub remote_round_trip_ms: f64, |
| 158 | } |
| 159 | |
| 160 | #[derive(Debug, Clone, Default)] |
| 161 | pub struct CallReport { |
| 162 | pub timeline: Vec<TimelineEntry>, |
| 163 | pub ice_connected_ms: Option<u128>, |
| 164 | pub peer_connected_ms: Option<u128>, |
| 165 | pub selected_pair: Option<String>, |
| 166 | pub tls_version: String, |
| 167 | pub dtls_cipher: String, |
| 168 | pub srtp_cipher: String, |
| 169 | pub inbound_packets: u64, |
| 170 | pub inbound_bytes: u64, |
| 171 | pub outbound_packets: u64, |
| 172 | pub video: VideoReport, |
| 173 | pub own_streams: Vec<String>, |
| 174 | pub seconds_with_inbound_audio: u32, |
| 175 | pub seconds: Vec<AudioSecond>, |
| 176 | pub end: Option<CallEnd>, |
| 177 | pub left_cleanly: bool, |
| 178 | pub recorded_samples: usize, |
| 179 | } |
| 180 | |
| 181 | #[derive(Debug, Clone)] |
| 182 | pub enum CallSpec { |
| 183 | Echo, |
| 184 | People { callees: Vec<Callee>, thread_id: String }, |
| 185 | Meeting(MeetingTarget), |
| 186 | } |
| 187 | |
| 188 | impl CallSpec { |
| 189 | fn target(&self) -> InviteTarget { |
| 190 | match self { |
| 191 | CallSpec::Echo => InviteTarget::Echo, |
| 192 | CallSpec::People { callees, thread_id } => InviteTarget::People { |
| 193 | callees: callees.clone(), |
| 194 | thread_id: thread_id.clone(), |
| 195 | }, |
| 196 | CallSpec::Meeting(meeting) => InviteTarget::Meeting(meeting.clone()), |
| 197 | } |
| 198 | } |
| 199 | |
| 200 | fn is_meeting(&self) -> bool { |
| 201 | matches!(self, CallSpec::Meeting(_)) |
| 202 | } |
| 203 | |
| 204 | fn is_people(&self) -> bool { |
| 205 | matches!(self, CallSpec::People { .. }) |
| 206 | } |
| 207 | } |
| 208 | |
| 209 | pub(crate) struct IncomingCall { |
| 210 | pub accept: AcceptMode, |
| 211 | pub notification: CallNotification, |
| 212 | pub attached: Attached, |
| 213 | pub links: CallbackLinks, |
| 214 | pub participant: Participant, |
| 215 | pub callbacks: mpsc::UnboundedReceiver<TrouterCallback>, |
| 216 | } |
| 217 | |
| 218 | pub(crate) enum Plan { |
| 219 | Outgoing(CallSpec), |
| 220 | Incoming(Box<IncomingCall>), |
| 221 | } |
| 222 | |
| 223 | fn data_channel_from_env() -> bool { |
| 224 | !matches!(std::env::var(DATA_CHANNEL_ENV).ok().as_deref(), Some("0" | "off")) |
| 225 | } |
| 226 | |
| 227 | pub fn keep_alive_period(seconds: Option<u64>) -> Duration { |
| 228 | let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS); |
| 229 | Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION) |
| 230 | } |
| 231 | |
| 232 | fn random_u32() -> u32 { |
| 233 | let bytes = uuid::Uuid::new_v4().into_bytes(); |
| 234 | u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff |
| 235 | } |
| 236 | |
| 237 | #[derive(Default)] |
| 238 | struct Recording { |
| 239 | samples: Vec<i16>, |
| 240 | current_second: Vec<i16>, |
| 241 | per_second: Vec<(f32, f32)>, |
| 242 | } |
| 243 | |
| 244 | enum PeerEvent { |
| 245 | Ice(IceConnectionState), |
| 246 | Connection(PeerConnectionState), |
| 247 | Track(RtcAudioTrack), |
| 248 | VideoTrack { mid: String, track: RtcVideoTrack }, |
| 249 | Data(Vec<u8>), |
| 250 | } |
| 251 | |
| 252 | struct PeerSession { |
| 253 | peer: PeerConnection, |
| 254 | events: mpsc::UnboundedReceiver<PeerEvent>, |
| 255 | _data_channel: Option<DataChannel>, |
| 256 | } |
| 257 | |
| 258 | struct OfferedMedia { |
| 259 | browser_offer: String, |
| 260 | signaled: SignaledOffer, |
| 261 | video: VideoLines, |
| 262 | plan: OfferPlan, |
| 263 | modalities: Vec<String>, |
| 264 | } |
| 265 | |
| 266 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 267 | enum Layout { |
| 268 | Conference, |
| 269 | OneToOne, |
| 270 | } |
| 271 | |
| 272 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 273 | pub enum AcceptMode { |
| 274 | Audio, |
| 275 | Video, |
| 276 | } |
| 277 | |
| 278 | #[derive(Clone, Copy)] |
| 279 | enum AnswerVideo<'a> { |
| 280 | Reject, |
| 281 | Receive, |
| 282 | Send(&'a RtcVideoTrack), |
| 283 | } |
| 284 | |
| 285 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 286 | enum Change { |
| 287 | Hold(bool), |
| 288 | Camera(bool), |
| 289 | } |
| 290 | |
| 291 | struct SamePeerOffer { |
| 292 | browser_offer: String, |
| 293 | signaled: SignaledOffer, |
| 294 | change: Change, |
| 295 | } |
| 296 | |
| 297 | struct NextPeer { |
| 298 | session: PeerSession, |
| 299 | offered: Option<OfferedMedia>, |
| 300 | } |
| 301 | |
| 302 | #[derive(Clone)] |
| 303 | struct RemoteCall { |
| 304 | signaling: Arc<Signaling>, |
| 305 | conversation: Conversation, |
| 306 | participant: Participant, |
| 307 | } |
| 308 | |
| 309 | #[derive(Default)] |
| 310 | struct Live { |
| 311 | peers: Vec<PeerConnection>, |
| 312 | audio: Option<AudioSetup>, |
| 313 | remote: Option<RemoteCall>, |
| 314 | broker: Option<JoinHandle<()>>, |
| 315 | broker_running: Arc<AtomicBool>, |
| 316 | callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>, |
| 317 | route_id: Option<String>, |
| 318 | skip_leave: bool, |
| 319 | cancel_leave: bool, |
| 320 | video_tasks: Vec<JoinHandle<()>>, |
| 321 | video_counters: Arc<VideoCounters>, |
| 322 | } |
| 323 | |
| 324 | fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool { |
| 325 | let next = state.next(signal, std::time::Instant::now()); |
| 326 | if next == *state { |
| 327 | return false; |
| 328 | } |
| 329 | *state = next.clone(); |
| 330 | control.send(CallUpdate::State(next)); |
| 331 | true |
| 332 | } |
| 333 | |
| 334 | /// Places the Echo test call on its own non-ringable Trouter instance; the app uses a shared engine instead. |
| 335 | pub async fn run_test_call( |
| 336 | session: &Session, |
| 337 | poll_session: &Session, |
| 338 | options: CallOptions, |
| 339 | control: CallControl, |
| 340 | ) -> Result<CallReport> { |
| 341 | let config = EngineConfig { |
| 342 | ringable: false, |
| 343 | routing: options.routing.clone(), |
| 344 | relay_host: options.relay_host.clone(), |
| 345 | trace: options.trace, |
| 346 | dump_dir: None, |
| 347 | instance: chatsvc::InstanceNames { |
| 348 | global: "__testCallTrouter".into(), |
| 349 | binding: "__testCallRealtime".into(), |
| 350 | endpoint_storage_key: "__testCallEpid".into(), |
| 351 | }, |
| 352 | }; |
| 353 | let (engine, _events) = CallEngine::start(session.clone(), poll_session.clone(), config).await?; |
| 354 | let report = engine.run(Plan::Outgoing(CallSpec::Echo), options, control).await; |
| 355 | engine.stop().await; |
| 356 | report |
| 357 | } |
| 358 | |
| 359 | impl CallEngine { |
| 360 | pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> { |
| 361 | let inner = self.inner.as_ref(); |
| 362 | let _one_call_at_a_time = if options.concurrent { None } else { Some(inner.gate.lock().await) }; |
| 363 | let timeline = Timeline::new(options.trace); |
| 364 | let mut report = CallReport::default(); |
| 365 | let mut state = CallState::Idle; |
| 366 | advance(&mut state, CallSignal::Dial, &control); |
| 367 | let mut live = Live::default(); |
| 368 | let recording = Arc::new(Mutex::new(Recording::default())); |
| 369 | let outcome = drive( |
| 370 | inner, |
| 371 | &options, |
| 372 | &timeline, |
| 373 | &recording, |
| 374 | plan, |
| 375 | &mut live, |
| 376 | &mut control, |
| 377 | &mut state, |
| 378 | &mut report, |
| 379 | ) |
| 380 | .await; |
| 381 | let failure = match outcome { |
| 382 | Ok(()) => None, |
| 383 | Err(Error::Cancelled) => { |
| 384 | advance(&mut state, CallSignal::LocalLeave, &control); |
| 385 | None |
| 386 | } |
| 387 | Err(error) => { |
| 388 | advance(&mut state, CallSignal::Error(error.to_string()), &control); |
| 389 | Some(error) |
| 390 | } |
| 391 | }; |
| 392 | dump_timeline(&options, &timeline, failure.as_ref()); |
| 393 | let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled }); |
| 394 | tear_down(live, inner, &timeline, &mut report, cancelled).await; |
| 395 | let recording = recording.lock().await; |
| 396 | report.recorded_samples = recording.samples.len(); |
| 397 | if let Some(path) = &options.wav_path { |
| 398 | write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?; |
| 399 | } |
| 400 | report.timeline = timeline.entries(); |
| 401 | match failure { |
| 402 | Some(error) => Err(error), |
| 403 | None => Ok(report), |
| 404 | } |
| 405 | } |
| 406 | } |
| 407 | |
| 408 | fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str, with_data_channel: bool) -> Result<PeerSession> { |
| 409 | let mut configuration = RtcConfiguration::default(); |
| 410 | configuration.ice_servers = vec![grant.ice_server(relay_host)]; |
| 411 | let peer = factory |
| 412 | .create_peer_connection(configuration) |
| 413 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 414 | let (sender, events) = mpsc::unbounded_channel(); |
| 415 | let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?; |
| 416 | let ice_sender = sender.clone(); |
| 417 | peer.on_ice_connection_state_change(Some(Box::new(move |state| { |
| 418 | let _ = ice_sender.send(PeerEvent::Ice(state)); |
| 419 | }))); |
| 420 | let connection_sender = sender.clone(); |
| 421 | peer.on_connection_state_change(Some(Box::new(move |state| { |
| 422 | let _ = connection_sender.send(PeerEvent::Connection(state)); |
| 423 | }))); |
| 424 | peer.on_track(Some(Box::new(move |event| match event.track { |
| 425 | MediaStreamTrack::Audio(track) => { |
| 426 | let _ = sender.send(PeerEvent::Track(track)); |
| 427 | } |
| 428 | MediaStreamTrack::Video(track) => { |
| 429 | let mid = event.transceiver.mid().unwrap_or_default(); |
| 430 | let _ = sender.send(PeerEvent::VideoTrack { mid, track }); |
| 431 | } |
| 432 | }))); |
| 433 | Ok(PeerSession { peer, events, _data_channel: data_channel }) |
| 434 | } |
| 435 | |
| 436 | fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> { |
| 437 | let channel = peer |
| 438 | .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default()) |
| 439 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 440 | channel.on_message(Some(Box::new(move |buffer| { |
| 441 | let _ = sender.send(PeerEvent::Data(buffer.data.to_vec())); |
| 442 | }))); |
| 443 | Ok(channel) |
| 444 | } |
| 445 | |
| 446 | fn one_to_one_directions(camera: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> { |
| 447 | move |line| match (line.kind, line.mid) { |
| 448 | ("video", CAMERA_MID) => Some(if camera { "sendrecv" } else { INACTIVE }), |
| 449 | ("video", ONE_TO_ONE_SHARE_MID) => Some(INACTIVE), |
| 450 | _ => None, |
| 451 | } |
| 452 | } |
| 453 | |
| 454 | fn directions_for(layout: Layout, hold: bool, camera: bool, text: &str) -> String { |
| 455 | match (hold, layout) { |
| 456 | (true, _) => rewrite_directions(text, |_| Some(INACTIVE)), |
| 457 | (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera)), |
| 458 | (false, Layout::Conference) => text.to_owned(), |
| 459 | } |
| 460 | } |
| 461 | |
| 462 | async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout) -> Result<OfferedMedia> { |
| 463 | let transceiver_init = RtpTransceiverInit { |
| 464 | direction: RtpTransceiverDirection::SendRecv, |
| 465 | stream_ids: vec![MIC_STREAM.into()], |
| 466 | send_encodings: Vec::new(), |
| 467 | }; |
| 468 | peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init) |
| 469 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 470 | let (video, plan) = match layout { |
| 471 | Layout::Conference => (add_video_lines(peer, factory)?, offer_plan()), |
| 472 | Layout::OneToOne => (add_one_to_one_lines(peer, factory)?, one_to_one_plan()), |
| 473 | }; |
| 474 | let offer = peer |
| 475 | .create_offer(OfferOptions { |
| 476 | offer_to_receive_audio: true, |
| 477 | offer_to_receive_video: true, |
| 478 | ..OfferOptions::default() |
| 479 | }) |
| 480 | .await |
| 481 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 482 | let browser_offer = directions_for(layout, false, false, &offer.to_string()); |
| 483 | let description = parse_sdp(&browser_offer, SdpType::Offer)?; |
| 484 | peer.set_local_description(description) |
| 485 | .await |
| 486 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 487 | let mut numbers = random_u32; |
| 488 | let signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?; |
| 489 | Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) }) |
| 490 | } |
| 491 | |
| 492 | struct AnsweredMedia { |
| 493 | remote: RemoteOffer, |
| 494 | answer_sdp: String, |
| 495 | camera_mid: Option<String>, |
| 496 | } |
| 497 | |
| 498 | fn main_video_mid(remote: &RemoteOffer) -> Option<String> { |
| 499 | remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned()) |
| 500 | } |
| 501 | |
| 502 | async fn answer_offer( |
| 503 | peer: &PeerConnection, |
| 504 | track: Option<&RtcAudioTrack>, |
| 505 | teams_offer: &str, |
| 506 | video: AnswerVideo<'_>, |
| 507 | ) -> Result<AnsweredMedia> { |
| 508 | let remote = from_teams_offer(teams_offer)?; |
| 509 | let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?; |
| 510 | peer.set_remote_description(description) |
| 511 | .await |
| 512 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 513 | let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject)); |
| 514 | for transceiver in peer.transceivers() { |
| 515 | let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_))); |
| 516 | if is_video && transceiver.mid() != camera_mid { |
| 517 | let _ = transceiver.stop(); |
| 518 | } |
| 519 | } |
| 520 | if let Some(track) = track { |
| 521 | peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM]) |
| 522 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 523 | } |
| 524 | if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) { |
| 525 | peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM]) |
| 526 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 527 | } |
| 528 | let answer = peer |
| 529 | .create_answer(AnswerOptions::default()) |
| 530 | .await |
| 531 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 532 | peer.set_local_description(answer.clone()) |
| 533 | .await |
| 534 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 535 | let mut numbers = random_u32; |
| 536 | let signaled = to_teams_answer(&answer.to_string(), &remote, &mut numbers)?; |
| 537 | Ok(AnsweredMedia { |
| 538 | remote, |
| 539 | answer_sdp: signaled.sdp, |
| 540 | camera_mid, |
| 541 | }) |
| 542 | } |
| 543 | |
| 544 | fn new_media_leg_id() -> String { |
| 545 | uuid::Uuid::new_v4().simple().to_string().to_uppercase() |
| 546 | } |
| 547 | |
| 548 | async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> { |
| 549 | match next { |
| 550 | Some(next) => next.session.events.recv().await, |
| 551 | None => std::future::pending().await, |
| 552 | } |
| 553 | } |
| 554 | |
| 555 | fn video_possible(remote_set: bool, layout: Layout, path: MediaPath) -> bool { |
| 556 | remote_set && !(layout == Layout::OneToOne && path == MediaPath::Mixer) |
| 557 | } |
| 558 | |
| 559 | #[allow(clippy::too_many_arguments)] |
| 560 | async fn drive( |
| 561 | inner: &Inner, |
| 562 | options: &CallOptions, |
| 563 | timeline: &Timeline, |
| 564 | recording: &Arc<Mutex<Recording>>, |
| 565 | plan: Plan, |
| 566 | live: &mut Live, |
| 567 | control: &mut CallControl, |
| 568 | state: &mut CallState, |
| 569 | report: &mut CallReport, |
| 570 | ) -> Result<()> { |
| 571 | let own_mri = format!("8:orgid:{}", inner.identity.object_id); |
| 572 | control.send(CallUpdate::OwnIdentity { mri: own_mri.clone() }); |
| 573 | let (spec, incoming) = match plan { |
| 574 | Plan::Outgoing(spec) => (Some(spec), None), |
| 575 | Plan::Incoming(incoming) => (None, Some(*incoming)), |
| 576 | }; |
| 577 | let accept_mode = incoming.as_ref().map_or(AcceptMode::Audio, |incoming| incoming.accept); |
| 578 | let (links, participant, mut callbacks, incoming_media) = match incoming { |
| 579 | Some(IncomingCall { |
| 580 | accept: _, |
| 581 | notification, |
| 582 | attached, |
| 583 | links, |
| 584 | participant, |
| 585 | callbacks, |
| 586 | }) => (links, participant, callbacks, Some((notification, attached))), |
| 587 | None => { |
| 588 | let links = inner.callback_links(); |
| 589 | let participant = inner.participant(&uuid::Uuid::new_v4().to_string()); |
| 590 | let callbacks = inner.register_route(links.call_id()); |
| 591 | (links, participant, callbacks, None) |
| 592 | } |
| 593 | }; |
| 594 | live.route_id = Some(links.call_id().to_owned()); |
| 595 | timeline.record("Trouter connected", "callback socket ready"); |
| 596 | |
| 597 | let thread_id = if matches!(spec, Some(CallSpec::Echo)) { |
| 598 | let thread_id = control |
| 599 | .until_hangup(find_echo_bot_thread(&inner.session, &inner.identity.object_id)) |
| 600 | .await??; |
| 601 | timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" }); |
| 602 | thread_id |
| 603 | } else { |
| 604 | None |
| 605 | }; |
| 606 | let grant = control.until_hangup(fetch_relay_grant(&inner.session)).await??; |
| 607 | timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds)); |
| 608 | |
| 609 | let factory = devices::shared_factory(); |
| 610 | let mut input = options.input.clone(); |
| 611 | let mut output = options.output.clone(); |
| 612 | let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output); |
| 613 | control.send(CallUpdate::ListenOnly(audio.listen_only)); |
| 614 | let device_lists = devices::list_devices(&factory); |
| 615 | timeline.record( |
| 616 | "audio setup", |
| 617 | format!("listen only {}, {} input(s), {} output(s); {}", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len(), audio.adm_state), |
| 618 | ); |
| 619 | control.send(CallUpdate::Devices(device_lists)); |
| 620 | control.send(CallUpdate::Selected { |
| 621 | input: input.clone(), |
| 622 | output: output.clone(), |
| 623 | }); |
| 624 | let track = audio.track.clone(); |
| 625 | live.audio = Some(audio); |
| 626 | let mut local_video = LocalVideo::new(&factory, options.video, control.video.clone(), control.updates()); |
| 627 | let mut camera_choice = options.camera.clone(); |
| 628 | let mut media_description_request = 1u32; |
| 629 | control.send(CallUpdate::Cameras(camera_devices(options.video).await)); |
| 630 | refresh_share_sources(control.updates(), options.video); |
| 631 | |
| 632 | let wants_data_channel = options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting); |
| 633 | let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?; |
| 634 | live.peers.push(current.peer.clone()); |
| 635 | |
| 636 | let signaling = Arc::new(inner.signaling(timeline.clone())); |
| 637 | let media_leg_id = new_media_leg_id(); |
| 638 | let call_started = Instant::now(); |
| 639 | let mut offered: Option<OfferedMedia> = None; |
| 640 | let mut negotiator = MediaNegotiator::default(); |
| 641 | let mut remote_set = false; |
| 642 | let mut keep_alive_link: Option<String> = None; |
| 643 | let mut keep_alive_seconds: Option<u64> = None; |
| 644 | let mut keep_alive_at: Option<Instant> = None; |
| 645 | let mut outgoing_deadline: Option<Instant> = None; |
| 646 | let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting); |
| 647 | let is_echo = matches!(spec, Some(CallSpec::Echo)); |
| 648 | let mut callee_gate = CalleeGate::new(spec.as_ref().is_some_and(CallSpec::is_people)); |
| 649 | let meeting_target = match &spec { |
| 650 | Some(CallSpec::Meeting(target)) => Some(target.clone()), |
| 651 | _ => None, |
| 652 | }; |
| 653 | let mut layout = match &spec { |
| 654 | Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne, |
| 655 | _ => Layout::Conference, |
| 656 | }; |
| 657 | let peer_mri = match &spec { |
| 658 | Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Some(callees[0].mri.clone()), |
| 659 | _ => incoming_media.as_ref().map(|(notification, _)| notification.caller.mri.clone()), |
| 660 | }; |
| 661 | let mut layout_plan: OfferPlan; |
| 662 | let mut direct_video_mid: Option<String> = None; |
| 663 | let mut sending_camera = false; |
| 664 | let mut media_links: BTreeMap<String, String> = BTreeMap::new(); |
| 665 | |
| 666 | let conversation = match (spec, incoming_media) { |
| 667 | (Some(spec), None) => { |
| 668 | let media = create_offer(¤t.peer, &factory, &track, layout).await?; |
| 669 | layout_plan = media.plan.clone(); |
| 670 | if layout == Layout::OneToOne { |
| 671 | direct_video_mid = Some(CAMERA_MID.to_owned()); |
| 672 | } |
| 673 | timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len())); |
| 674 | dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer); |
| 675 | dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp); |
| 676 | let target = spec.target(); |
| 677 | let invitation = Invitation { |
| 678 | from: &participant, |
| 679 | offer_sdp: &media.signaled.sdp, |
| 680 | media_leg_id: &media_leg_id, |
| 681 | callbacks: &links, |
| 682 | target: &target, |
| 683 | modalities: &media.modalities, |
| 684 | }; |
| 685 | let conversation = match &target { |
| 686 | InviteTarget::Meeting(meeting) => { |
| 687 | let subscribed = control |
| 688 | .until_hangup(signaling.subscribe_meeting(&participant, &links, meeting)) |
| 689 | .await??; |
| 690 | signaling.join_meeting(&subscribed, &invitation).await? |
| 691 | } |
| 692 | _ => signaling.create_conversation(&invitation).await?, |
| 693 | }; |
| 694 | if spec.is_people() { |
| 695 | control.send(CallUpdate::Progress(Progress::Calling)); |
| 696 | outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT); |
| 697 | } |
| 698 | if let Err(error) = local_video.set_lines(media.video.clone()) { |
| 699 | timeline.record("video lines not attached", error.to_string()); |
| 700 | } |
| 701 | offered = Some(media); |
| 702 | live.remote = Some(RemoteCall { |
| 703 | signaling: signaling.clone(), |
| 704 | conversation: conversation.clone(), |
| 705 | participant: participant.clone(), |
| 706 | }); |
| 707 | conversation |
| 708 | } |
| 709 | (None, Some((notification, attached))) => { |
| 710 | let teams_offer = attached |
| 711 | .offer_sdp |
| 712 | .clone() |
| 713 | .ok_or_else(|| Error::Signaling("attach answer without an offer".into()))?; |
| 714 | let conversation = attached |
| 715 | .conversation |
| 716 | .clone() |
| 717 | .ok_or_else(|| Error::Signaling("attach answer without a conversation".into()))?; |
| 718 | live.remote = Some(RemoteCall { |
| 719 | signaling: signaling.clone(), |
| 720 | conversation: conversation.clone(), |
| 721 | participant: participant.clone(), |
| 722 | }); |
| 723 | let one_to_one = !attached.from_mixer && !notification.is_multi_party; |
| 724 | layout = if one_to_one { Layout::OneToOne } else { Layout::Conference }; |
| 725 | let camera_track = local_video.camera_track(); |
| 726 | let video_answer = match accept_mode { |
| 727 | _ if !one_to_one => AnswerVideo::Reject, |
| 728 | AcceptMode::Video if local_video.is_available() => AnswerVideo::Send(&camera_track), |
| 729 | _ => AnswerVideo::Receive, |
| 730 | }; |
| 731 | dump_sdp(options, "3-teams-offer.sdp", &teams_offer); |
| 732 | let answered = answer_offer(¤t.peer, Some(&track), &teams_offer, video_answer).await?; |
| 733 | layout_plan = answered.remote.plan(); |
| 734 | direct_video_mid = answered.camera_mid.clone(); |
| 735 | timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len())); |
| 736 | dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp); |
| 737 | let acceptance_url = attached |
| 738 | .links |
| 739 | .get("acceptance") |
| 740 | .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?; |
| 741 | let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some()); |
| 742 | signaling |
| 743 | .accept( |
| 744 | acceptance_url, |
| 745 | &Answer { |
| 746 | from: &participant, |
| 747 | answer_sdp: &answered.answer_sdp, |
| 748 | media_leg_id: &media_leg_id, |
| 749 | callbacks: &links, |
| 750 | modalities: &modalities, |
| 751 | }, |
| 752 | ) |
| 753 | .await?; |
| 754 | negotiator.answered_incoming(attached.from_mixer); |
| 755 | remote_set = true; |
| 756 | media_links.extend(attached.links.clone()); |
| 757 | if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) { |
| 758 | let camera = peer_transceiver(¤t.peer, mid); |
| 759 | match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) { |
| 760 | Some(Ok(())) => match local_video.start_camera(&camera_choice) { |
| 761 | Ok(()) => sending_camera = true, |
| 762 | Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))), |
| 763 | }, |
| 764 | Some(Err(error)) => timeline.record("video lines not attached", error.to_string()), |
| 765 | None => timeline.record("video lines not attached", "no transceiver for the camera line"), |
| 766 | } |
| 767 | } |
| 768 | keep_alive_link = attached.links.get("callLeg").cloned(); |
| 769 | keep_alive_at = Some(Instant::now() + keep_alive_period(None)); |
| 770 | conversation |
| 771 | } |
| 772 | _ => return Err(Error::Callback("call plan without an offer or an invitation".into())), |
| 773 | }; |
| 774 | let remote = live.remote.clone().expect("remote call set above"); |
| 775 | live.broker_running.store(true, Ordering::SeqCst); |
| 776 | live.broker = Some(tokio::spawn(poll_broker( |
| 777 | signaling.clone(), |
| 778 | conversation.clone(), |
| 779 | live.broker_running.clone(), |
| 780 | ))); |
| 781 | |
| 782 | let initial = MuteEffect::initial(is_meeting); |
| 783 | let mut muted = initial.muted; |
| 784 | live.audio.as_ref().expect("audio set above").track.set_enabled(initial.track_enabled); |
| 785 | if muted { |
| 786 | control.send(CallUpdate::Muted(true)); |
| 787 | } |
| 788 | if let Err(error) = signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted).await { |
| 789 | timeline.record("updateEndpointState failed", error.to_string()); |
| 790 | } |
| 791 | |
| 792 | let replier = inner.replier.clone(); |
| 793 | let mut stats_tick = interval(STATS_PERIOD); |
| 794 | let hard_deadline = options.hard_limit.map(|limit| call_started + limit); |
| 795 | let mut leave_at = hard_deadline; |
| 796 | let mut reconnect_deadline: Option<Instant> = None; |
| 797 | let mut next: Option<NextPeer> = None; |
| 798 | let mut roster = Roster::default(); |
| 799 | let mut lobby = false; |
| 800 | let mut previous_packets = 0u64; |
| 801 | let mut ticks = 0u32; |
| 802 | let mut health_sampler = HealthSampler::default(); |
| 803 | let mut quality_tracker = QualityTracker::default(); |
| 804 | let mut second = 0u32; |
| 805 | let echo_thread = thread_id; |
| 806 | let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default()); |
| 807 | if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) { |
| 808 | video.router().set(mid, Some(VideoKey::Person(mri.clone()))); |
| 809 | } |
| 810 | if sending_camera { |
| 811 | control.send(CallUpdate::Camera(true)); |
| 812 | } |
| 813 | let mut share_audio: Option<ShareAudio> = None; |
| 814 | let mut share_sound_wanted = false; |
| 815 | let mut remote_audio: Option<RtcAudioTrack> = None; |
| 816 | let mut own_hand: Option<String> = None; |
| 817 | let mut depacketizer = Depacketizer::default(); |
| 818 | let mut caption_flow = CaptionFlow::default(); |
| 819 | let mut caption_deadline: Option<Instant> = None; |
| 820 | let mut recording_flow = CaptionFlow::default(); |
| 821 | let mut recording_deadline: Option<Instant> = None; |
| 822 | let mut recording_title = String::new(); |
| 823 | let mut recording_status = RecordingStatus::default(); |
| 824 | let mut bot_pending = false; |
| 825 | let mut consent_pending = false; |
| 826 | let mut room_watcher = RoomWatcher::default(); |
| 827 | let mut main_meeting_sent = false; |
| 828 | let mut local_hold = false; |
| 829 | let mut remote_hold = false; |
| 830 | let mut same_peer: Option<SamePeerOffer> = None; |
| 831 | let mut same_peer_deadline: Option<Instant> = None; |
| 832 | let mut meeting_chat = conversation.chat_thread.clone(); |
| 833 | if let Some(thread) = &meeting_chat { |
| 834 | control.send(CallUpdate::MeetingChat(thread.clone())); |
| 835 | } |
| 836 | let mut start_camera_pending = options.start_camera; |
| 837 | loop { |
| 838 | if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) { |
| 839 | start_camera_pending = false; |
| 840 | control.defer(CallCommand::SetCamera(true)); |
| 841 | } |
| 842 | tokio::select! { |
| 843 | Some(callback) = callbacks.recv() => { |
| 844 | let request_id = callback.request_id; |
| 845 | match handle_callback(&callback, timeline) { |
| 846 | Ok(CallEvent::Acceptance(acceptance)) => { |
| 847 | replier.reply(request_id, 200, acceptance_acknowledgement(&links).to_string()); |
| 848 | if !acceptance.from_mixer && callee_gate.callee_joined() { |
| 849 | advance(state, CallSignal::MediaConnected, control); |
| 850 | } |
| 851 | let action = negotiator.on_acceptance(acceptance.from_mixer, layout == Layout::OneToOne); |
| 852 | match action { |
| 853 | MediaAction::ApplyAnswer | MediaAction::ApplyAnswerThenEscalate => { |
| 854 | let Some(media) = offered.as_ref() else { continue }; |
| 855 | dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp); |
| 856 | if let Ok(answer) = to_browser_answer(&acceptance.sdp, &media.signaled, &media.browser_offer) { |
| 857 | dump_sdp(options, "4-browser-answer.sdp", &answer); |
| 858 | } |
| 859 | apply_answer(¤t.peer, &acceptance.sdp, &media.signaled, &media.browser_offer) |
| 860 | .await |
| 861 | .inspect_err(|error| timeline.record("answer rejected", error.to_string()))?; |
| 862 | remote_set = true; |
| 863 | media_links.extend(acceptance.links.clone()); |
| 864 | if layout == Layout::Conference { |
| 865 | negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster); |
| 866 | } |
| 867 | if let Some(link) = acceptance.links.get("replacement") { |
| 868 | control.send(CallUpdate::ReplacementLink(link.clone())); |
| 869 | } |
| 870 | if !callee_gate.is_waiting() { |
| 871 | outgoing_deadline = None; |
| 872 | } |
| 873 | let directions: Vec<String> = current |
| 874 | .peer |
| 875 | .transceivers() |
| 876 | .iter() |
| 877 | .map(|transceiver| format!("{:?}", transceiver.current_direction())) |
| 878 | .collect(); |
| 879 | timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(","))); |
| 880 | if acceptance.in_lobby() { |
| 881 | lobby = true; |
| 882 | control.send(CallUpdate::Lobby(true)); |
| 883 | } |
| 884 | keep_alive_link = acceptance.links.get("callLeg").cloned(); |
| 885 | keep_alive_seconds = acceptance.keep_alive_seconds; |
| 886 | keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds)); |
| 887 | if action == MediaAction::ApplyAnswerThenEscalate { |
| 888 | let pending = escalate(&factory, &grant, options, &track, &remote, &links, &media_leg_id, &acceptance.links, &mut negotiator, live, timeline).await; |
| 889 | next = pending.or(next); |
| 890 | } |
| 891 | let remote = remote.clone(); |
| 892 | let links = links.clone(); |
| 893 | let thread_id = echo_thread.clone(); |
| 894 | tokio::spawn(async move { |
| 895 | if is_echo { |
| 896 | let _ = remote.signaling.add_echo_bot(&remote.conversation, &remote.participant, thread_id.as_deref(), &links).await; |
| 897 | } |
| 898 | let _ = remote.signaling.update_endpoint_metadata(&remote.conversation, &remote.participant).await; |
| 899 | }); |
| 900 | } |
| 901 | MediaAction::Escalate => { |
| 902 | let pending = escalate(&factory, &grant, options, &track, &remote, &links, &media_leg_id, &acceptance.links, &mut negotiator, live, timeline).await; |
| 903 | next = pending.or(next); |
| 904 | } |
| 905 | _ => {} |
| 906 | } |
| 907 | } |
| 908 | Ok(CallEvent::MediaAnswer(answer)) => { |
| 909 | replier.reply(request_id, 200, ""); |
| 910 | let action = negotiator.on_media_answer(); |
| 911 | if action == MediaAction::ApplyOnSamePeer |
| 912 | && let Some(pending) = same_peer.take() |
| 913 | { |
| 914 | same_peer_deadline = None; |
| 915 | let applied = apply_answer(¤t.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await; |
| 916 | match applied { |
| 917 | Ok(()) => { |
| 918 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 919 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 920 | } |
| 921 | match pending.change { |
| 922 | Change::Hold(hold) => { |
| 923 | local_hold = hold; |
| 924 | control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold))); |
| 925 | } |
| 926 | Change::Camera(on) => control.send(CallUpdate::Camera(on)), |
| 927 | } |
| 928 | } |
| 929 | Err(error) => { |
| 930 | timeline.record("same-peer answer rejected", error.to_string()); |
| 931 | undo_change(pending.change, &mut local_video, control); |
| 932 | } |
| 933 | } |
| 934 | } |
| 935 | if action == MediaAction::ApplyOnNewPeer { |
| 936 | let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) { |
| 937 | Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await, |
| 938 | None => Err(Error::Webrtc("no pending peer connection for the answer".into())), |
| 939 | }; |
| 940 | match applied { |
| 941 | Ok(()) => { |
| 942 | if let Some(media) = next.as_ref().and_then(|pending| pending.offered.as_ref()) { |
| 943 | media_links.extend(answer.links.clone()); |
| 944 | negotiate_video(&mut video, &signaling, control, timeline, &answer.sdp, media, true, &media_links, &roster); |
| 945 | } |
| 946 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 947 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 948 | } |
| 949 | } |
| 950 | Err(error) => { |
| 951 | negotiator.escalation_failed(); |
| 952 | next = None; |
| 953 | timeline.record("escalation answer rejected", error.to_string()); |
| 954 | } |
| 955 | } |
| 956 | } |
| 957 | } |
| 958 | Ok(CallEvent::MediaRenegotiation(renegotiation)) => { |
| 959 | replier.reply(request_id, 200, ""); |
| 960 | let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation); |
| 961 | let result = match action { |
| 962 | MediaAction::AnswerOnNewPeer => { |
| 963 | match answer_on_new_peer(&factory, &grant, options, &track, &renegotiation.sdp).await { |
| 964 | Ok((session, answered)) => { |
| 965 | live.peers.push(session.peer.clone()); |
| 966 | let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await; |
| 967 | next = Some(NextPeer { session, offered: None }); |
| 968 | sent |
| 969 | } |
| 970 | Err(error) => Err(error), |
| 971 | } |
| 972 | } |
| 973 | MediaAction::AnswerOnSamePeer => { |
| 974 | let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject }; |
| 975 | match answer_offer(¤t.peer, None, &renegotiation.sdp, video_answer).await { |
| 976 | Ok(answered) => { |
| 977 | let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await; |
| 978 | let held = is_hold(&renegotiation.sdp).unwrap_or(false); |
| 979 | if held != remote_hold { |
| 980 | remote_hold = held; |
| 981 | control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold))); |
| 982 | } |
| 983 | sent |
| 984 | } |
| 985 | Err(error) => Err(error), |
| 986 | } |
| 987 | } |
| 988 | _ => Ok(()), |
| 989 | }; |
| 990 | if let Err(error) = result { |
| 991 | timeline.record("renegotiation failed", error.to_string()); |
| 992 | } |
| 993 | } |
| 994 | Ok(CallEvent::RosterUpdate(body)) => { |
| 995 | replier.reply(request_id, 200, ""); |
| 996 | if roster.apply(&body) { |
| 997 | let entries = roster.entries(); |
| 998 | timeline.record("roster", format!("{} participant(s)", entries.len())); |
| 999 | control.send(CallUpdate::Roster(entries)); |
| 1000 | if callee_gate.is_waiting() && roster_has_callee(roster.members().iter().map(|member| member.mri.as_str()), &own_mri) { |
| 1001 | outgoing_deadline = None; |
| 1002 | if callee_gate.callee_joined() { |
| 1003 | advance(state, CallSignal::MediaConnected, control); |
| 1004 | } |
| 1005 | } |
| 1006 | let own_streams = roster.stream_summaries(&own_mri); |
| 1007 | if own_streams != report.own_streams { |
| 1008 | timeline.record("own media streams", own_streams.join("; ")); |
| 1009 | report.own_streams = own_streams; |
| 1010 | } |
| 1011 | send_receive_change(control, video.reselect(&roster)); |
| 1012 | if let Some(in_lobby) = roster.is_in_lobby(&own_mri) |
| 1013 | && in_lobby != lobby |
| 1014 | { |
| 1015 | lobby = in_lobby; |
| 1016 | control.send(CallUpdate::Lobby(lobby)); |
| 1017 | } |
| 1018 | if roster.caption_bot().is_some() { |
| 1019 | bot_pending = false; |
| 1020 | } |
| 1021 | if caption_flow.wanted() { |
| 1022 | run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), "", &mut bot_pending, control, timeline).await; |
| 1023 | if caption_flow.on() { |
| 1024 | caption_deadline = None; |
| 1025 | } |
| 1026 | } |
| 1027 | if recording_flow.wanted() { |
| 1028 | run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_title, &mut bot_pending, control, timeline).await; |
| 1029 | } |
| 1030 | } |
| 1031 | } |
| 1032 | Ok(CallEvent::AddParticipantFailure(_)) => { |
| 1033 | replier.reply(request_id, 200, ""); |
| 1034 | bot_pending = false; |
| 1035 | if recording_flow.wanted() && roster.caption_bot().is_none() { |
| 1036 | timeline.record("recorder bot failed", "addParticipantFailure"); |
| 1037 | recording_flow.failed(); |
| 1038 | recording_deadline = None; |
| 1039 | control.send(CallUpdate::Notice("The recording service could not join".into())); |
| 1040 | } |
| 1041 | if caption_flow.wanted() && roster.caption_bot().is_none() { |
| 1042 | timeline.record("caption bot failed", "addParticipantFailure"); |
| 1043 | caption_flow.failed(); |
| 1044 | caption_deadline = None; |
| 1045 | control.send(CallUpdate::Captions(CaptionState::Failed("The captions service could not join".into()))); |
| 1046 | } |
| 1047 | } |
| 1048 | Ok(CallEvent::ConversationUpdate(body)) => { |
| 1049 | replier.reply(request_id, 200, ""); |
| 1050 | if let Some(thread) = chat_thread_id(&body) |
| 1051 | && meeting_chat.as_ref() != Some(&thread) |
| 1052 | { |
| 1053 | control.send(CallUpdate::MeetingChat(thread.clone())); |
| 1054 | meeting_chat = Some(thread); |
| 1055 | } |
| 1056 | let change = recording_status.apply(&body); |
| 1057 | if let Some(on) = change.recording { |
| 1058 | control.send(CallUpdate::Recording(on)); |
| 1059 | if on { |
| 1060 | recording_deadline = None; |
| 1061 | } |
| 1062 | } |
| 1063 | if let Some(required) = change.consent_required { |
| 1064 | consent_pending = required; |
| 1065 | control.send(CallUpdate::ConsentRequired(required)); |
| 1066 | if required { |
| 1067 | withhold_media(&mut muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, &mut local_video, control); |
| 1068 | } |
| 1069 | } |
| 1070 | if !main_meeting_sent |
| 1071 | && let Some(main) = breakout::main_meeting_target(&body) |
| 1072 | { |
| 1073 | main_meeting_sent = true; |
| 1074 | control.send(CallUpdate::BreakoutRoom { main }); |
| 1075 | } |
| 1076 | } |
| 1077 | Ok(CallEvent::LocalParticipantUpdate(body)) => { |
| 1078 | replier.reply(request_id, 200, ""); |
| 1079 | let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target)); |
| 1080 | if let Some(moved) = moved { |
| 1081 | timeline.record("breakout", format!("moved to {}", moved.room_name)); |
| 1082 | control.send(CallUpdate::BreakoutMove(moved)); |
| 1083 | } |
| 1084 | } |
| 1085 | Ok(CallEvent::Replacement(body)) => { |
| 1086 | replier.reply(request_id, 200, ""); |
| 1087 | let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target)); |
| 1088 | if let Some(moved) = invited { |
| 1089 | timeline.record("breakout", format!("invited to {}", moved.room_name)); |
| 1090 | control.send(CallUpdate::BreakoutMove(moved)); |
| 1091 | } |
| 1092 | } |
| 1093 | Ok(CallEvent::ContentShareUpdate(body)) => { |
| 1094 | replier.reply(request_id, 200, ""); |
| 1095 | if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) { |
| 1096 | control.send(CallUpdate::Whiteboard(Some(share))); |
| 1097 | } |
| 1098 | } |
| 1099 | Ok(CallEvent::ContentShareEnd(_)) => { |
| 1100 | replier.reply(request_id, 200, ""); |
| 1101 | control.send(CallUpdate::Whiteboard(None)); |
| 1102 | } |
| 1103 | Ok(CallEvent::Transfer(event)) => { |
| 1104 | replier.reply(request_id, 200, ""); |
| 1105 | match event { |
| 1106 | TransferEvent::Accepted => timeline.record("transfer", "accepted by the target"), |
| 1107 | completed if completed.succeeded() => { |
| 1108 | control.send(CallUpdate::Notice("Call transferred".into())); |
| 1109 | advance(state, CallSignal::LocalLeave, control); |
| 1110 | break; |
| 1111 | } |
| 1112 | _ => control.send(CallUpdate::Notice("The transfer did not go through".into())), |
| 1113 | } |
| 1114 | } |
| 1115 | Ok(CallEvent::Reactions(events)) => { |
| 1116 | replier.reply(request_id, 200, ""); |
| 1117 | for event in events { |
| 1118 | control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction }); |
| 1119 | } |
| 1120 | } |
| 1121 | Ok(CallEvent::Progress(status)) => { |
| 1122 | replier.reply(request_id, 200, ""); |
| 1123 | if status == ProgressStatus::Ringing { |
| 1124 | control.send(CallUpdate::Progress(Progress::Ringing)); |
| 1125 | } |
| 1126 | } |
| 1127 | Ok(CallEvent::Speakers(sources)) => { |
| 1128 | replier.reply(request_id, 200, ""); |
| 1129 | let speakers = roster.mris_for_sources(&sources); |
| 1130 | if video.note_speakers(&speakers) { |
| 1131 | send_receive_change(control, video.reselect(&roster)); |
| 1132 | } |
| 1133 | control.send(CallUpdate::Speakers(speakers)); |
| 1134 | } |
| 1135 | Ok(CallEvent::End(end)) => { |
| 1136 | replier.reply(request_id, 200, ""); |
| 1137 | let kind = end.kind(); |
| 1138 | report.end = Some(end); |
| 1139 | advance(state, CallSignal::RemoteEnd(kind), control); |
| 1140 | break; |
| 1141 | } |
| 1142 | Ok(_) => replier.reply(request_id, 200, ""), |
| 1143 | Err(error) => { |
| 1144 | replier.reply(request_id, 200, ""); |
| 1145 | timeline.record("callback not understood", error.to_string()); |
| 1146 | } |
| 1147 | } |
| 1148 | } |
| 1149 | Some(event) = current.events.recv() => match event { |
| 1150 | PeerEvent::Ice(ice_state) => { |
| 1151 | timeline.record("ICE state", format!("{ice_state:?}")); |
| 1152 | if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() { |
| 1153 | report.ice_connected_ms = Some(timeline.elapsed_ms()); |
| 1154 | } |
| 1155 | } |
| 1156 | PeerEvent::Connection(connection) => { |
| 1157 | timeline.record("PeerConnection state", format!("{connection:?}")); |
| 1158 | match connection { |
| 1159 | PeerConnectionState::Connected => { |
| 1160 | reconnect_deadline = None; |
| 1161 | if callee_gate.media_connected() { |
| 1162 | advance(state, CallSignal::MediaConnected, control); |
| 1163 | } |
| 1164 | if report.peer_connected_ms.is_none() { |
| 1165 | report.peer_connected_ms = Some(timeline.elapsed_ms()); |
| 1166 | if let Some(hold) = options.hold_after_connected { |
| 1167 | let hold_until = Instant::now() + hold; |
| 1168 | leave_at = Some(hard_deadline.map_or(hold_until, |deadline| deadline.min(hold_until))); |
| 1169 | } |
| 1170 | } |
| 1171 | } |
| 1172 | PeerConnectionState::Disconnected => { |
| 1173 | if advance(state, CallSignal::MediaDisconnected, control) { |
| 1174 | reconnect_deadline = Some(Instant::now() + options.reconnect_window); |
| 1175 | } |
| 1176 | } |
| 1177 | PeerConnectionState::Failed => { |
| 1178 | advance(state, CallSignal::MediaFailed, control); |
| 1179 | break; |
| 1180 | } |
| 1181 | _ => {} |
| 1182 | } |
| 1183 | } |
| 1184 | PeerEvent::Track(remote_track) => { |
| 1185 | timeline.record("remote audio track", "receiving"); |
| 1186 | remote_audio = Some(remote_track.clone()); |
| 1187 | if options.record_remote { |
| 1188 | tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz)); |
| 1189 | } |
| 1190 | } |
| 1191 | PeerEvent::VideoTrack { mid, track } => { |
| 1192 | timeline.record("remote video track", format!("mid {mid}")); |
| 1193 | live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone())); |
| 1194 | } |
| 1195 | PeerEvent::Data(frame) => { |
| 1196 | if let Some(message) = depacketizer.push(&frame) |
| 1197 | && message.data_id == CAPTIONS_DATA_ID |
| 1198 | { |
| 1199 | for entry in parse_caption_message(&message.payload) { |
| 1200 | if caption_flow.text_arrived() { |
| 1201 | caption_deadline = None; |
| 1202 | control.send(CallUpdate::Captions(CaptionState::On)); |
| 1203 | } |
| 1204 | control.send(CallUpdate::Caption(named_caption(entry, &roster))); |
| 1205 | } |
| 1206 | } |
| 1207 | } |
| 1208 | }, |
| 1209 | Some(event) = next_peer_event(&mut next) => match event { |
| 1210 | PeerEvent::Connection(PeerConnectionState::Connected) => { |
| 1211 | if let Some(pending) = next.take() { |
| 1212 | timeline.record("escalation", "new peer connection connected, old one dropped"); |
| 1213 | let old = std::mem::replace(&mut current, pending.session); |
| 1214 | old.peer.close(); |
| 1215 | if let Some(audio) = &share_audio |
| 1216 | && let Err(error) = swap_audio_track(¤t.peer, &audio.track) |
| 1217 | { |
| 1218 | timeline.record("computer sound not carried over", error.to_string()); |
| 1219 | } |
| 1220 | offered = pending.offered; |
| 1221 | if let Some(mid) = direct_video_mid.take() { |
| 1222 | video.router().set(&mid, None); |
| 1223 | } |
| 1224 | if let Some(media) = &offered { |
| 1225 | layout = Layout::Conference; |
| 1226 | layout_plan = media.plan.clone(); |
| 1227 | if let Err(error) = local_video.set_lines(media.video.clone()) { |
| 1228 | timeline.record("video lines not attached", error.to_string()); |
| 1229 | } |
| 1230 | } |
| 1231 | remote_set = true; |
| 1232 | } |
| 1233 | } |
| 1234 | PeerEvent::VideoTrack { mid, track } => { |
| 1235 | timeline.record("remote video track", format!("mid {mid} (new peer)")); |
| 1236 | live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone())); |
| 1237 | } |
| 1238 | PeerEvent::Connection(PeerConnectionState::Failed) => { |
| 1239 | negotiator.escalation_failed(); |
| 1240 | if let Some(pending) = next.take() { |
| 1241 | pending.session.peer.close(); |
| 1242 | } |
| 1243 | timeline.record("escalation failed", "new peer connection failed, staying on the old one"); |
| 1244 | } |
| 1245 | _ => {} |
| 1246 | }, |
| 1247 | command = control.recv() => match command { |
| 1248 | Some(CallCommand::Mute(mute)) => { |
| 1249 | if consent_pending && !mute.target(muted) { |
| 1250 | control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into())); |
| 1251 | } else { |
| 1252 | muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control); |
| 1253 | } |
| 1254 | } |
| 1255 | Some(CallCommand::SelectInput(choice)) => { |
| 1256 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 1257 | timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice))); |
| 1258 | } |
| 1259 | input = choice; |
| 1260 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 1261 | } |
| 1262 | Some(CallCommand::SelectOutput(choice)) => { |
| 1263 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 1264 | timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice))); |
| 1265 | } |
| 1266 | output = choice; |
| 1267 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 1268 | } |
| 1269 | Some(CallCommand::RefreshDevices) => { |
| 1270 | control.send(CallUpdate::Devices(devices::list_devices(&factory))); |
| 1271 | } |
| 1272 | Some(CallCommand::SetCamera(on)) => { |
| 1273 | let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer; |
| 1274 | if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) { |
| 1275 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 1276 | } else if on && consent_pending { |
| 1277 | control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into())); |
| 1278 | } else if local_hold { |
| 1279 | control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into())); |
| 1280 | } else if on { |
| 1281 | let started = start_camera_line(&mut local_video, ¤t.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice); |
| 1282 | match started { |
| 1283 | Ok(()) if direct => { |
| 1284 | match offer_same_peer(¤t.peer, &layout_plan, layout, false, true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await { |
| 1285 | Ok((browser_offer, signaled)) => { |
| 1286 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true) }); |
| 1287 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 1288 | } |
| 1289 | Err(error) => { |
| 1290 | timeline.record("camera offer failed", error.to_string()); |
| 1291 | undo_change(Change::Camera(true), &mut local_video, control); |
| 1292 | } |
| 1293 | } |
| 1294 | } |
| 1295 | Ok(()) => { |
| 1296 | control.send(CallUpdate::Camera(true)); |
| 1297 | tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline); |
| 1298 | } |
| 1299 | Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))), |
| 1300 | } |
| 1301 | } else if direct { |
| 1302 | local_video.stop_camera(); |
| 1303 | match offer_same_peer(¤t.peer, &layout_plan, layout, false, false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await { |
| 1304 | Ok((browser_offer, signaled)) => { |
| 1305 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false) }); |
| 1306 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 1307 | } |
| 1308 | Err(error) => { |
| 1309 | timeline.record("camera offer failed", error.to_string()); |
| 1310 | control.send(CallUpdate::Camera(false)); |
| 1311 | } |
| 1312 | } |
| 1313 | } else { |
| 1314 | local_video.stop_camera(); |
| 1315 | control.send(CallUpdate::Camera(false)); |
| 1316 | tell_media_descriptions(&remote, &media_links, MediaDescription::camera(false), &mut media_description_request, timeline); |
| 1317 | } |
| 1318 | } |
| 1319 | Some(CallCommand::SelectCamera(choice)) => { |
| 1320 | camera_choice = choice; |
| 1321 | if local_video.camera_on() |
| 1322 | && let Err(error) = local_video.start_camera(&camera_choice) |
| 1323 | { |
| 1324 | control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))); |
| 1325 | } |
| 1326 | } |
| 1327 | Some(CallCommand::StartShare(source)) => { |
| 1328 | if !remote_set { |
| 1329 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 1330 | } else { |
| 1331 | match local_video.start_share(&source) { |
| 1332 | Ok(()) => { |
| 1333 | control.send(CallUpdate::LocalShare(Some(source.label()))); |
| 1334 | tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline); |
| 1335 | if share_sound_wanted && share_audio.is_none() { |
| 1336 | share_audio = engage_share_sound(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, control, timeline); |
| 1337 | } |
| 1338 | } |
| 1339 | Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))), |
| 1340 | } |
| 1341 | } |
| 1342 | } |
| 1343 | Some(CallCommand::StopShare) => { |
| 1344 | if local_video.sharing() { |
| 1345 | local_video.stop_share(); |
| 1346 | release_share_sound(¤t.peer, &track, &mut share_audio, control, timeline); |
| 1347 | control.send(CallUpdate::LocalShare(None)); |
| 1348 | tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline); |
| 1349 | } |
| 1350 | } |
| 1351 | Some(CallCommand::SetShareSound(on)) => { |
| 1352 | share_sound_wanted = on; |
| 1353 | if local_video.sharing() { |
| 1354 | if on && share_audio.is_none() { |
| 1355 | share_audio = engage_share_sound(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, control, timeline); |
| 1356 | } else if !on { |
| 1357 | release_share_sound(¤t.peer, &track, &mut share_audio, control, timeline); |
| 1358 | } |
| 1359 | } |
| 1360 | } |
| 1361 | Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video), |
| 1362 | Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await { |
| 1363 | Ok(receipt) => { |
| 1364 | own_hand = receipt.state_id; |
| 1365 | control.send(CallUpdate::OwnHand(Some(receipt.rank))); |
| 1366 | } |
| 1367 | Err(error) => { |
| 1368 | timeline.record("raise hand failed", error.to_string()); |
| 1369 | control.send(CallUpdate::OwnHand(None)); |
| 1370 | control.send(CallUpdate::Notice("Could not raise your hand".into())); |
| 1371 | } |
| 1372 | }, |
| 1373 | Some(CallCommand::SetHand(false)) => { |
| 1374 | let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect(); |
| 1375 | own_hand = None; |
| 1376 | control.send(CallUpdate::OwnHand(None)); |
| 1377 | if !state_ids.is_empty() |
| 1378 | && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await |
| 1379 | { |
| 1380 | timeline.record("lower hand failed", error.to_string()); |
| 1381 | control.send(CallUpdate::Notice("Could not lower your hand".into())); |
| 1382 | } |
| 1383 | } |
| 1384 | Some(CallCommand::LowerHand { mri }) => { |
| 1385 | let state_ids: Vec<String> = roster.hand_of(&mri).map(|hand| hand.state_id.clone()).into_iter().collect(); |
| 1386 | if !state_ids.is_empty() |
| 1387 | && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await |
| 1388 | { |
| 1389 | timeline.record("lower hand failed", error.to_string()); |
| 1390 | control.send(CallUpdate::Notice("Could not lower that hand".into())); |
| 1391 | } |
| 1392 | } |
| 1393 | Some(CallCommand::LowerAllHands) => { |
| 1394 | if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await { |
| 1395 | timeline.record("lower all hands failed", error.to_string()); |
| 1396 | control.send(CallUpdate::Notice("Could not lower all hands".into())); |
| 1397 | } |
| 1398 | } |
| 1399 | Some(CallCommand::Admit { mri }) => { |
| 1400 | let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 1401 | report_organizer_result(result, "admit", "Could not admit that person", control, timeline); |
| 1402 | } |
| 1403 | Some(CallCommand::AdmitAll) => { |
| 1404 | let result = remote.signaling.admit_all(&remote.conversation, &remote.participant, &links).await; |
| 1405 | report_organizer_result(result, "admit all", "Could not admit everyone", control, timeline); |
| 1406 | } |
| 1407 | Some(CallCommand::Deny { mri }) => { |
| 1408 | let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 1409 | report_organizer_result(result, "deny", "Could not deny that person", control, timeline); |
| 1410 | } |
| 1411 | Some(CallCommand::RemoveParticipant { mri }) => { |
| 1412 | let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await; |
| 1413 | report_organizer_result(result, "remove participant", "Could not remove that person", control, timeline); |
| 1414 | } |
| 1415 | Some(CallCommand::MuteParticipant { mri }) => { |
| 1416 | let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await; |
| 1417 | report_organizer_result(result, "mute participant", "Could not mute that person", control, timeline); |
| 1418 | } |
| 1419 | Some(CallCommand::MuteAll) => { |
| 1420 | let others: Vec<String> = roster |
| 1421 | .members() |
| 1422 | .iter() |
| 1423 | .filter(|member| member.mri != own_mri && !member.in_lobby && !member.mri.starts_with(BOT_PREFIX)) |
| 1424 | .map(|member| member.mri.clone()) |
| 1425 | .collect(); |
| 1426 | let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await; |
| 1427 | report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline); |
| 1428 | } |
| 1429 | Some(CallCommand::Spotlight { mri }) => { |
| 1430 | let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await; |
| 1431 | report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline); |
| 1432 | } |
| 1433 | Some(CallCommand::StopSpotlight { mri }) => { |
| 1434 | let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect(); |
| 1435 | if !state_ids.is_empty() { |
| 1436 | let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200); |
| 1437 | report_organizer_result(result, "stop spotlight", "Could not stop the spotlight", control, timeline); |
| 1438 | } |
| 1439 | } |
| 1440 | Some(CallCommand::SetCaptions(on)) => { |
| 1441 | caption_flow.want(on); |
| 1442 | if on { |
| 1443 | caption_deadline = Some(Instant::now() + CAPTION_START_LIMIT); |
| 1444 | control.send(CallUpdate::Captions(CaptionState::Starting)); |
| 1445 | } else { |
| 1446 | caption_deadline = None; |
| 1447 | control.send(CallUpdate::Captions(CaptionState::Off)); |
| 1448 | } |
| 1449 | run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), "", &mut bot_pending, control, timeline).await; |
| 1450 | if caption_flow.on() { |
| 1451 | caption_deadline = None; |
| 1452 | } |
| 1453 | } |
| 1454 | Some(CallCommand::SetRecording { on, title }) => { |
| 1455 | if is_meeting { |
| 1456 | recording_title = title; |
| 1457 | recording_flow.want(on); |
| 1458 | recording_deadline = on.then(|| Instant::now() + RECORDING_START_LIMIT); |
| 1459 | run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_title, &mut bot_pending, control, timeline).await; |
| 1460 | } |
| 1461 | } |
| 1462 | Some(CallCommand::ConsentToRecording) => { |
| 1463 | match remote.signaling.consent_to_recording(&remote.conversation, &remote.participant, Consent::Give).await { |
| 1464 | Ok(_) => { |
| 1465 | consent_pending = false; |
| 1466 | control.send(CallUpdate::ConsentRequired(false)); |
| 1467 | } |
| 1468 | Err(error) => { |
| 1469 | timeline.record("recording consent failed", error.to_string()); |
| 1470 | control.send(CallUpdate::Notice("Could not confirm the recording notice".into())); |
| 1471 | } |
| 1472 | } |
| 1473 | } |
| 1474 | Some(CallCommand::Hold(hold)) => { |
| 1475 | if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() { |
| 1476 | continue; |
| 1477 | } |
| 1478 | if hold && local_video.camera_on() { |
| 1479 | local_video.stop_camera(); |
| 1480 | control.send(CallUpdate::Camera(false)); |
| 1481 | } |
| 1482 | let camera = !hold && local_video.camera_on(); |
| 1483 | match offer_same_peer(¤t.peer, &layout_plan, layout, hold, camera, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await { |
| 1484 | Ok((browser_offer, signaled)) => { |
| 1485 | same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold) }); |
| 1486 | same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT); |
| 1487 | } |
| 1488 | Err(error) => { |
| 1489 | timeline.record("hold failed", error.to_string()); |
| 1490 | control.send(CallUpdate::Notice(if hold { "Could not put the call on hold".into() } else { "Could not resume the call".into() })); |
| 1491 | } |
| 1492 | } |
| 1493 | } |
| 1494 | Some(CallCommand::Transfer { target, replaces }) => { |
| 1495 | let Some(url) = media_links.get("transfer").cloned() else { |
| 1496 | control.send(CallUpdate::Notice("This call cannot be transferred".into())); |
| 1497 | continue; |
| 1498 | }; |
| 1499 | let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_deref() }; |
| 1500 | match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await { |
| 1501 | Ok(()) => control.send(CallUpdate::Notice(format!("Transferring to {}...", target.display_name))), |
| 1502 | Err(error) => { |
| 1503 | timeline.record("transfer failed", error.to_string()); |
| 1504 | control.send(CallUpdate::Notice("Could not transfer the call".into())); |
| 1505 | } |
| 1506 | } |
| 1507 | } |
| 1508 | Some(CallCommand::OpenWhiteboard { title }) => { |
| 1509 | let Some(target) = meeting_target.clone() else { |
| 1510 | control.send(CallUpdate::Notice("Whiteboards belong to meetings".into())); |
| 1511 | continue; |
| 1512 | }; |
| 1513 | let session = inner.session.clone(); |
| 1514 | let updates = control.updates(); |
| 1515 | tokio::spawn(async move { |
| 1516 | let update = match whiteboard::fetch_board(&session, &target, &title).await { |
| 1517 | Ok(url) => CallUpdate::WhiteboardUrl(url), |
| 1518 | Err(_) => CallUpdate::Notice("The whiteboard could not be opened".into()), |
| 1519 | }; |
| 1520 | let _ = updates.send(update); |
| 1521 | }); |
| 1522 | } |
| 1523 | Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await, |
| 1524 | Some(CallCommand::SetIncomingVideo(enabled)) => { |
| 1525 | video.set_incoming_enabled(enabled); |
| 1526 | if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) { |
| 1527 | let key = VideoKey::Person(mri.clone()); |
| 1528 | control.video.forget(&key); |
| 1529 | video.router().set(mid, enabled.then_some(key)); |
| 1530 | } |
| 1531 | send_receive_change(control, video.reselect(&roster)); |
| 1532 | control.send(CallUpdate::IncomingVideo(enabled)); |
| 1533 | } |
| 1534 | Some(CallCommand::SendReaction(reaction)) => { |
| 1535 | if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await { |
| 1536 | timeline.record("reaction failed", error.to_string()); |
| 1537 | control.send(CallUpdate::Notice("Could not send the reaction".into())); |
| 1538 | } |
| 1539 | } |
| 1540 | Some(CallCommand::EndMeeting) => { |
| 1541 | if is_meeting { |
| 1542 | match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await { |
| 1543 | Ok(()) => { |
| 1544 | live.skip_leave = true; |
| 1545 | report.left_cleanly = true; |
| 1546 | } |
| 1547 | Err(error) => timeline.record("end meeting failed", error.to_string()), |
| 1548 | } |
| 1549 | } |
| 1550 | advance(state, CallSignal::LocalLeave, control); |
| 1551 | break; |
| 1552 | } |
| 1553 | Some(CallCommand::Hangup) | None => { |
| 1554 | advance(state, CallSignal::LocalLeave, control); |
| 1555 | break; |
| 1556 | } |
| 1557 | }, |
| 1558 | _ = stats_tick.tick(), if remote_set => { |
| 1559 | let snapshot = collect_stats(¤t.peer).await; |
| 1560 | ticks += 1; |
| 1561 | if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) { |
| 1562 | caption_deadline = None; |
| 1563 | caption_flow.failed(); |
| 1564 | timeline.record("captions", "did not start in time"); |
| 1565 | control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into()))); |
| 1566 | } |
| 1567 | if recording_deadline.is_some_and(|deadline| Instant::now() >= deadline) { |
| 1568 | recording_deadline = None; |
| 1569 | recording_flow.failed(); |
| 1570 | timeline.record("recording", "did not start in time"); |
| 1571 | control.send(CallUpdate::Notice("The recording did not start".into())); |
| 1572 | } |
| 1573 | if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS) |
| 1574 | && let Some(average_ms) = local_video.blur_average_ms() |
| 1575 | { |
| 1576 | control.send(CallUpdate::BlurTiming(average_ms)); |
| 1577 | } |
| 1578 | if ticks.is_multiple_of(HEALTH_EVERY_TICKS) |
| 1579 | && snapshot.selected_pair.is_some() |
| 1580 | && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health) |
| 1581 | { |
| 1582 | let quality = quality_tracker.observe(std::time::Instant::now(), &sample); |
| 1583 | control.send(CallUpdate::Health(CallHealth { |
| 1584 | level: quality.level, |
| 1585 | cpu_limited: quality.cpu_limited, |
| 1586 | sample, |
| 1587 | transport: snapshot.transport.clone(), |
| 1588 | path: negotiator.path(), |
| 1589 | })); |
| 1590 | } |
| 1591 | let local_level = if muted && share_audio.is_none() { 0.0 } else { snapshot.local_level as f32 }; |
| 1592 | control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 }); |
| 1593 | if snapshot.selected_pair.is_some() { |
| 1594 | report.selected_pair = snapshot.selected_pair.clone(); |
| 1595 | report.tls_version = snapshot.tls_version.clone(); |
| 1596 | report.dtls_cipher = snapshot.dtls_cipher.clone(); |
| 1597 | report.srtp_cipher = snapshot.srtp_cipher.clone(); |
| 1598 | } |
| 1599 | report.inbound_packets = snapshot.inbound_packets; |
| 1600 | report.inbound_bytes = snapshot.inbound_bytes; |
| 1601 | report.outbound_packets = snapshot.outbound_packets; |
| 1602 | report.video = VideoReport { |
| 1603 | frames_received: live.video_counters.received.load(Ordering::Relaxed), |
| 1604 | frames_published: live.video_counters.published.load(Ordering::Relaxed), |
| 1605 | ..snapshot.video.clone() |
| 1606 | }; |
| 1607 | if ticks.is_multiple_of(TICKS_PER_SECOND) { |
| 1608 | second += 1; |
| 1609 | let (decoded_rms, ratio) = { |
| 1610 | let recording = recording.lock().await; |
| 1611 | recording.per_second.last().copied().unwrap_or_default() |
| 1612 | }; |
| 1613 | if snapshot.inbound_packets > previous_packets { |
| 1614 | report.seconds_with_inbound_audio += 1; |
| 1615 | } |
| 1616 | previous_packets = snapshot.inbound_packets; |
| 1617 | report.seconds.push(AudioSecond { |
| 1618 | second, |
| 1619 | packets: snapshot.inbound_packets, |
| 1620 | bytes: snapshot.inbound_bytes, |
| 1621 | audio_level: snapshot.audio_level, |
| 1622 | decoded_rms, |
| 1623 | tone_ratio: ratio, |
| 1624 | }); |
| 1625 | control.send(CallUpdate::Stats { |
| 1626 | inbound_packets: snapshot.inbound_packets, |
| 1627 | outbound_packets: snapshot.outbound_packets, |
| 1628 | }); |
| 1629 | timeline.record( |
| 1630 | "stats", |
| 1631 | format!( |
| 1632 | "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)", |
| 1633 | snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state, |
| 1634 | snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height, |
| 1635 | snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height, |
| 1636 | snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms |
| 1637 | ), |
| 1638 | ); |
| 1639 | } |
| 1640 | } |
| 1641 | _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => { |
| 1642 | advance(state, CallSignal::ReconnectTimedOut, control); |
| 1643 | break; |
| 1644 | } |
| 1645 | _ = sleep_until(leave_at.unwrap_or_else(far_future)), if leave_at.is_some() => { |
| 1646 | advance(state, CallSignal::LocalLeave, control); |
| 1647 | break; |
| 1648 | } |
| 1649 | _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => { |
| 1650 | same_peer_deadline = None; |
| 1651 | if let Some(pending) = same_peer.take() { |
| 1652 | timeline.record("same-peer offer", "no answer in time"); |
| 1653 | negotiator.same_peer_offer_failed(); |
| 1654 | rollback_offer(¤t.peer).await; |
| 1655 | undo_change(pending.change, &mut local_video, control); |
| 1656 | } |
| 1657 | } |
| 1658 | _ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => { |
| 1659 | timeline.record("no answer", "outgoing call timed out"); |
| 1660 | live.cancel_leave = true; |
| 1661 | advance(state, CallSignal::RemoteEnd(EndKind::NoAnswer), control); |
| 1662 | break; |
| 1663 | } |
| 1664 | _ = sleep_until(keep_alive_at.unwrap_or_else(far_future)), if keep_alive_at.is_some() => { |
| 1665 | keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds)); |
| 1666 | let remote = remote.clone(); |
| 1667 | let links = links.clone(); |
| 1668 | let call_leg = keep_alive_link.clone(); |
| 1669 | tokio::spawn(async move { |
| 1670 | if let Some(url) = call_leg { |
| 1671 | let _ = remote.signaling.keep_call_alive(&url).await; |
| 1672 | } |
| 1673 | let _ = remote.signaling.keep_conversation_alive(&remote.conversation, &remote.participant, &links).await; |
| 1674 | }); |
| 1675 | } |
| 1676 | } |
| 1677 | } |
| 1678 | live.callbacks = Some(callbacks); |
| 1679 | Ok(()) |
| 1680 | } |
| 1681 | |
| 1682 | #[allow(clippy::too_many_arguments)] |
| 1683 | async fn start_escalation( |
| 1684 | factory: &PeerConnectionFactory, |
| 1685 | grant: &RelayGrant, |
| 1686 | options: &CallOptions, |
| 1687 | track: &RtcAudioTrack, |
| 1688 | remote: &RemoteCall, |
| 1689 | links: &CallbackLinks, |
| 1690 | media_leg_id: &str, |
| 1691 | acceptance_links: &BTreeMap<String, String>, |
| 1692 | ) -> Result<NextPeer> { |
| 1693 | let url = acceptance_links |
| 1694 | .get("mediaRenegotiation") |
| 1695 | .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?; |
| 1696 | let session = open_peer(factory, grant, &options.relay_host, false)?; |
| 1697 | let media = create_offer(&session.peer, factory, track, Layout::Conference).await?; |
| 1698 | let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true); |
| 1699 | remote.signaling.post_json("POST mediaRenegotiation", url, body).await?; |
| 1700 | Ok(NextPeer { |
| 1701 | session, |
| 1702 | offered: Some(media), |
| 1703 | }) |
| 1704 | } |
| 1705 | |
| 1706 | #[allow(clippy::too_many_arguments)] |
| 1707 | async fn escalate( |
| 1708 | factory: &PeerConnectionFactory, |
| 1709 | grant: &RelayGrant, |
| 1710 | options: &CallOptions, |
| 1711 | track: &RtcAudioTrack, |
| 1712 | remote: &RemoteCall, |
| 1713 | links: &CallbackLinks, |
| 1714 | media_leg_id: &str, |
| 1715 | acceptance_links: &BTreeMap<String, String>, |
| 1716 | negotiator: &mut MediaNegotiator, |
| 1717 | live: &mut Live, |
| 1718 | timeline: &Timeline, |
| 1719 | ) -> Option<NextPeer> { |
| 1720 | match start_escalation( |
| 1721 | factory, |
| 1722 | grant, |
| 1723 | options, |
| 1724 | track, |
| 1725 | remote, |
| 1726 | links, |
| 1727 | media_leg_id, |
| 1728 | acceptance_links, |
| 1729 | ) |
| 1730 | .await |
| 1731 | { |
| 1732 | Ok(pending) => { |
| 1733 | timeline.record("escalation", "new peer connection, new offer sent"); |
| 1734 | live.peers.push(pending.session.peer.clone()); |
| 1735 | Some(pending) |
| 1736 | } |
| 1737 | Err(error) => { |
| 1738 | negotiator.escalation_failed(); |
| 1739 | timeline.record("escalation failed", error.to_string()); |
| 1740 | None |
| 1741 | } |
| 1742 | } |
| 1743 | } |
| 1744 | |
| 1745 | async fn answer_on_new_peer( |
| 1746 | factory: &PeerConnectionFactory, |
| 1747 | grant: &RelayGrant, |
| 1748 | options: &CallOptions, |
| 1749 | track: &RtcAudioTrack, |
| 1750 | teams_offer: &str, |
| 1751 | ) -> Result<(PeerSession, AnsweredMedia)> { |
| 1752 | let session = open_peer(factory, grant, &options.relay_host, false)?; |
| 1753 | let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject).await?; |
| 1754 | Ok((session, answered)) |
| 1755 | } |
| 1756 | |
| 1757 | async fn send_media_answer( |
| 1758 | remote: &RemoteCall, |
| 1759 | links: &CallbackLinks, |
| 1760 | reply_links: &BTreeMap<String, String>, |
| 1761 | answered: &AnsweredMedia, |
| 1762 | media_leg_id: &str, |
| 1763 | ) -> Result<()> { |
| 1764 | let url = reply_links |
| 1765 | .get("mediaAnswer") |
| 1766 | .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?; |
| 1767 | let body = escalation_answer_body(&remote.participant, links, &answered.answer_sdp, media_leg_id); |
| 1768 | remote.signaling.post_json("POST mediaAnswer", url, body).await |
| 1769 | } |
| 1770 | |
| 1771 | #[allow(clippy::too_many_arguments)] |
| 1772 | fn negotiate_video( |
| 1773 | video: &mut VideoReceive, |
| 1774 | signaling: &Arc<Signaling>, |
| 1775 | control: &CallControl, |
| 1776 | timeline: &Timeline, |
| 1777 | answer_sdp: &str, |
| 1778 | media: &OfferedMedia, |
| 1779 | from_mixer: bool, |
| 1780 | links: &BTreeMap<String, String>, |
| 1781 | roster: &Roster, |
| 1782 | ) { |
| 1783 | let streams = match stream_lines(answer_sdp, &media.signaled.lines) { |
| 1784 | Ok(streams) => streams, |
| 1785 | Err(error) => { |
| 1786 | timeline.record("video slots unknown", error.to_string()); |
| 1787 | return; |
| 1788 | } |
| 1789 | }; |
| 1790 | let table = SlotTable::from_streams(&streams); |
| 1791 | let link = links.get("applyChannelParameters").or_else(|| links.get("controlVideoStreaming")); |
| 1792 | timeline.record( |
| 1793 | "video slots", |
| 1794 | format!( |
| 1795 | "{} receive slot(s), screen {}, fromMixer={from_mixer}, request link {}", |
| 1796 | table.people.len(), |
| 1797 | table.screen.is_some(), |
| 1798 | link.is_some() |
| 1799 | ), |
| 1800 | ); |
| 1801 | let requester = link |
| 1802 | .filter(|_| from_mixer) |
| 1803 | .map(|url| SourceRequester::start(signaling.clone(), url.clone(), video.router().clone(), control.video.clone(), timeline.clone())); |
| 1804 | video.negotiated(table, requester); |
| 1805 | send_receive_change(control, video.reselect(roster)); |
| 1806 | } |
| 1807 | |
| 1808 | const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected"; |
| 1809 | const ON_HOLD_NOTICE: &str = "Resume the call first"; |
| 1810 | |
| 1811 | async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> { |
| 1812 | match mode { |
| 1813 | VideoMode::Pattern => vec![CameraDevice { key: "pattern".into(), name: "Test pattern".into() }], |
| 1814 | VideoMode::Off => Vec::new(), |
| 1815 | VideoMode::Platform => tokio::task::spawn_blocking(list_cameras).await.unwrap_or_default(), |
| 1816 | } |
| 1817 | } |
| 1818 | |
| 1819 | fn refresh_share_sources(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode) { |
| 1820 | tokio::spawn(async move { |
| 1821 | let sources = match mode { |
| 1822 | VideoMode::Pattern => vec![ |
| 1823 | ShareSource { id: 1, kind: ShareKind::Screen, title: "Test screen".into() }, |
| 1824 | ShareSource { id: 2, kind: ShareKind::Window, title: "Test window".into() }, |
| 1825 | ], |
| 1826 | VideoMode::Off => Vec::new(), |
| 1827 | VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources).await.unwrap_or_default(), |
| 1828 | }; |
| 1829 | let _ = updates.send(CallUpdate::ShareSources(sources)); |
| 1830 | }); |
| 1831 | } |
| 1832 | |
| 1833 | fn tell_media_descriptions( |
| 1834 | remote: &RemoteCall, |
| 1835 | links: &BTreeMap<String, String>, |
| 1836 | description: MediaDescription, |
| 1837 | request_id: &mut u32, |
| 1838 | timeline: &Timeline, |
| 1839 | ) { |
| 1840 | let Some(url) = links.get("updateMediaDescriptions").cloned() else { |
| 1841 | timeline.record("updateMediaDescriptions skipped", "no link from the mixer"); |
| 1842 | return; |
| 1843 | }; |
| 1844 | *request_id += 1; |
| 1845 | let request_id = *request_id; |
| 1846 | let signaling = remote.signaling.clone(); |
| 1847 | let timeline = timeline.clone(); |
| 1848 | tokio::spawn(async move { |
| 1849 | let sent = format!("{} {} request {request_id}", description.mid, description.direction); |
| 1850 | if let Err(error) = signaling.update_media_descriptions(&url, &[description], request_id).await { |
| 1851 | timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}")); |
| 1852 | } |
| 1853 | }); |
| 1854 | } |
| 1855 | |
| 1856 | fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool { |
| 1857 | own.is_some_and(|own| own.thread_id == target.thread_id) |
| 1858 | } |
| 1859 | |
| 1860 | fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> { |
| 1861 | peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid)) |
| 1862 | } |
| 1863 | |
| 1864 | fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct_mid: Option<&str>, choice: &DeviceChoice) -> Result<()> { |
| 1865 | if !local_video.has_lines() { |
| 1866 | let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?; |
| 1867 | let camera = peer_transceiver(peer, mid).ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?; |
| 1868 | if !matches!(camera.direction(), RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly) { |
| 1869 | peer.add_track(MediaStreamTrack::Video(local_video.camera_track()), &[CAMERA_STREAM]) |
| 1870 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 1871 | } |
| 1872 | local_video.set_lines(VideoLines { camera, share: None })?; |
| 1873 | } |
| 1874 | local_video.start_camera(choice) |
| 1875 | } |
| 1876 | |
| 1877 | #[allow(clippy::too_many_arguments)] |
| 1878 | async fn offer_same_peer( |
| 1879 | peer: &PeerConnection, |
| 1880 | plan: &OfferPlan, |
| 1881 | layout: Layout, |
| 1882 | hold: bool, |
| 1883 | camera: bool, |
| 1884 | remote: &RemoteCall, |
| 1885 | links: &CallbackLinks, |
| 1886 | media_leg_id: &str, |
| 1887 | media_links: &BTreeMap<String, String>, |
| 1888 | negotiator: &mut MediaNegotiator, |
| 1889 | ) -> Result<(String, SignaledOffer)> { |
| 1890 | let url = media_links |
| 1891 | .get("mediaRenegotiation") |
| 1892 | .cloned() |
| 1893 | .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?; |
| 1894 | if !negotiator.begin_same_peer_offer() { |
| 1895 | return Err(Error::Signaling("another media negotiation is running".into())); |
| 1896 | } |
| 1897 | let offered = build_same_peer_offer(peer, plan, layout, hold, camera).await; |
| 1898 | let (text, signaled) = match offered { |
| 1899 | Ok(offered) => offered, |
| 1900 | Err(error) => { |
| 1901 | negotiator.same_peer_offer_failed(); |
| 1902 | return Err(error); |
| 1903 | } |
| 1904 | }; |
| 1905 | let modalities = accepted_modalities(layout == Layout::OneToOne && camera && !hold); |
| 1906 | let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false); |
| 1907 | if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await { |
| 1908 | negotiator.same_peer_offer_failed(); |
| 1909 | rollback_offer(peer).await; |
| 1910 | return Err(error); |
| 1911 | } |
| 1912 | Ok((text, signaled)) |
| 1913 | } |
| 1914 | |
| 1915 | async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool) -> Result<(String, SignaledOffer)> { |
| 1916 | let offer = peer |
| 1917 | .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() }) |
| 1918 | .await |
| 1919 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 1920 | let text = directions_for(layout, hold, camera, &offer.to_string()); |
| 1921 | let description = parse_sdp(&text, SdpType::Offer)?; |
| 1922 | peer.set_local_description(description) |
| 1923 | .await |
| 1924 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 1925 | let mut numbers = random_u32; |
| 1926 | let signaled = to_teams_offer(&text, plan, &mut numbers)?; |
| 1927 | Ok((text, signaled)) |
| 1928 | } |
| 1929 | |
| 1930 | /// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging. |
| 1931 | fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> { |
| 1932 | match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) { |
| 1933 | Ok(Ok(description)) => Ok(description), |
| 1934 | Ok(Err(error)) => Err(Error::Sdp(format!("{kind:?} rejected: {}", error.description))), |
| 1935 | Err(_) => Err(Error::Sdp(format!("{kind:?} rejected, libwebrtc gave no readable reason"))), |
| 1936 | } |
| 1937 | } |
| 1938 | |
| 1939 | async fn rollback_offer(peer: &PeerConnection) { |
| 1940 | if let Ok(rollback) = parse_sdp("", SdpType::Rollback) { |
| 1941 | let _ = peer.set_local_description(rollback).await; |
| 1942 | } |
| 1943 | } |
| 1944 | |
| 1945 | fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) { |
| 1946 | match change { |
| 1947 | Change::Camera(true) => { |
| 1948 | local_video.stop_camera(); |
| 1949 | control.send(CallUpdate::Camera(false)); |
| 1950 | } |
| 1951 | Change::Camera(false) => control.send(CallUpdate::Camera(false)), |
| 1952 | Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())), |
| 1953 | } |
| 1954 | } |
| 1955 | |
| 1956 | fn withhold_media( |
| 1957 | muted: &mut bool, |
| 1958 | audio: &AudioSetup, |
| 1959 | share_audio: Option<&ShareAudio>, |
| 1960 | remote: &RemoteCall, |
| 1961 | local_video: &mut LocalVideo, |
| 1962 | control: &CallControl, |
| 1963 | ) { |
| 1964 | *muted = apply_mute(MuteCommand::Mute, *muted, audio, share_audio, remote, control); |
| 1965 | if local_video.camera_on() { |
| 1966 | local_video.stop_camera(); |
| 1967 | control.send(CallUpdate::Camera(false)); |
| 1968 | } |
| 1969 | } |
| 1970 | |
| 1971 | async fn apply_background(choice: BackgroundChoice, local_video: &LocalVideo, control: &CallControl, timeline: &Timeline) { |
| 1972 | match choice { |
| 1973 | BackgroundChoice::None => local_video.set_background(false, None), |
| 1974 | BackgroundChoice::Blur => local_video.set_background(true, None), |
| 1975 | BackgroundChoice::Image(path) => match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await { |
| 1976 | Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))), |
| 1977 | Ok(Err(error)) => { |
| 1978 | timeline.record("background image failed", error.to_string()); |
| 1979 | control.send(CallUpdate::Notice("That background image could not be used".into())); |
| 1980 | } |
| 1981 | Err(_) => {} |
| 1982 | }, |
| 1983 | } |
| 1984 | } |
| 1985 | |
| 1986 | fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> { |
| 1987 | let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str()); |
| 1988 | Target { mri, display_name } |
| 1989 | } |
| 1990 | |
| 1991 | fn report_organizer_result(result: Result<u16>, label: &str, notice: &str, control: &CallControl, timeline: &Timeline) { |
| 1992 | if let Err(error) = &result { |
| 1993 | timeline.record(format!("{label} failed"), error.to_string()); |
| 1994 | control.send(CallUpdate::Notice(notice.into())); |
| 1995 | } |
| 1996 | control.send(CallUpdate::Organizer { action: label.to_owned(), outcome: result.map_err(|error| error.to_string()) }); |
| 1997 | } |
| 1998 | |
| 1999 | fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry { |
| 2000 | if entry.display_name.is_empty() { |
| 2001 | entry.display_name = roster.name_of(&entry.user_id).unwrap_or_default().to_owned(); |
| 2002 | } |
| 2003 | entry |
| 2004 | } |
| 2005 | |
| 2006 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 2007 | enum BotJob { |
| 2008 | Captions, |
| 2009 | Recording, |
| 2010 | } |
| 2011 | |
| 2012 | #[allow(clippy::too_many_arguments)] |
| 2013 | async fn run_bot_steps( |
| 2014 | job: BotJob, |
| 2015 | flow: &mut CaptionFlow, |
| 2016 | roster: &Roster, |
| 2017 | remote: &RemoteCall, |
| 2018 | links: &CallbackLinks, |
| 2019 | meeting_chat: Option<&str>, |
| 2020 | title: &str, |
| 2021 | bot_pending: &mut bool, |
| 2022 | control: &CallControl, |
| 2023 | timeline: &Timeline, |
| 2024 | ) { |
| 2025 | let is_active: fn(&crate::roster::CaptionBot) -> bool = match job { |
| 2026 | BotJob::Captions => |bot| bot.active, |
| 2027 | BotJob::Recording => |bot| bot.recording, |
| 2028 | }; |
| 2029 | let fail = |flow: &mut CaptionFlow, reason: &str| { |
| 2030 | flow.failed(); |
| 2031 | control.send(match job { |
| 2032 | BotJob::Captions => CallUpdate::Captions(CaptionState::Failed(reason.to_owned())), |
| 2033 | BotJob::Recording => CallUpdate::Notice(reason.to_owned()), |
| 2034 | }); |
| 2035 | }; |
| 2036 | let (join_failure, start_failure) = match job { |
| 2037 | BotJob::Captions => ("The captions service could not join", "Captions could not start"), |
| 2038 | BotJob::Recording => ("The recording service could not join", "The recording could not start"), |
| 2039 | }; |
| 2040 | loop { |
| 2041 | match flow.next_for(roster.caption_bot(), is_active) { |
| 2042 | CaptionStep::Wait => return, |
| 2043 | CaptionStep::AddBot => { |
| 2044 | if *bot_pending { |
| 2045 | continue; |
| 2046 | } |
| 2047 | let Some(thread) = meeting_chat else { |
| 2048 | return fail(flow, "This meeting has no chat for the captions and the recording"); |
| 2049 | }; |
| 2050 | *bot_pending = true; |
| 2051 | let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links).await; |
| 2052 | if job == BotJob::Recording { |
| 2053 | report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline); |
| 2054 | } |
| 2055 | if let Err(error) = added { |
| 2056 | timeline.record("bot invitation failed", error.to_string()); |
| 2057 | *bot_pending = false; |
| 2058 | return fail(flow, join_failure); |
| 2059 | } |
| 2060 | } |
| 2061 | CaptionStep::Start => { |
| 2062 | let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return }; |
| 2063 | match job { |
| 2064 | BotJob::Captions => { |
| 2065 | if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await { |
| 2066 | timeline.record("caption start failed", error.to_string()); |
| 2067 | return fail(flow, start_failure); |
| 2068 | } |
| 2069 | if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await { |
| 2070 | timeline.record("caption preference failed", error.to_string()); |
| 2071 | } |
| 2072 | } |
| 2073 | BotJob::Recording => { |
| 2074 | let started = remote.signaling.recording_command(&url, BotAction::Start, &remote.participant, title).await; |
| 2075 | let failed = started.is_err(); |
| 2076 | report_organizer_result(started, "recording start", start_failure, control, timeline); |
| 2077 | if failed { |
| 2078 | return fail(flow, start_failure); |
| 2079 | } |
| 2080 | } |
| 2081 | } |
| 2082 | } |
| 2083 | CaptionStep::Stop => { |
| 2084 | let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { continue }; |
| 2085 | match job { |
| 2086 | BotJob::Captions => { |
| 2087 | if let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await { |
| 2088 | timeline.record("caption stop failed", error.to_string()); |
| 2089 | } |
| 2090 | if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await { |
| 2091 | timeline.record("caption preference failed", error.to_string()); |
| 2092 | } |
| 2093 | } |
| 2094 | BotJob::Recording => { |
| 2095 | let stopped = remote.signaling.recording_command(&url, BotAction::Stop, &remote.participant, title).await; |
| 2096 | report_organizer_result(stopped, "recording stop", "The recording could not be stopped", control, timeline); |
| 2097 | } |
| 2098 | } |
| 2099 | } |
| 2100 | CaptionStep::ReportOn => { |
| 2101 | if job == BotJob::Captions { |
| 2102 | control.send(CallUpdate::Captions(CaptionState::On)); |
| 2103 | } |
| 2104 | } |
| 2105 | } |
| 2106 | } |
| 2107 | } |
| 2108 | |
| 2109 | fn send_receive_change(control: &CallControl, change: ReceiveChange) { |
| 2110 | if let Some(sharer) = change.screen_sharer { |
| 2111 | control.send(CallUpdate::ScreenShare(sharer)); |
| 2112 | } |
| 2113 | } |
| 2114 | |
| 2115 | fn far_future() -> Instant { |
| 2116 | Instant::now() + FAR_FUTURE |
| 2117 | } |
| 2118 | |
| 2119 | fn apply_mute( |
| 2120 | command: MuteCommand, |
| 2121 | currently_muted: bool, |
| 2122 | audio: &AudioSetup, |
| 2123 | share_audio: Option<&ShareAudio>, |
| 2124 | remote: &RemoteCall, |
| 2125 | control: &CallControl, |
| 2126 | ) -> bool { |
| 2127 | let effect = MuteEffect::for_muted(command.target(currently_muted)); |
| 2128 | audio.track.set_enabled(effect.track_enabled); |
| 2129 | if let Some(share_audio) = share_audio { |
| 2130 | share_audio.set_microphone_muted(effect.muted); |
| 2131 | } |
| 2132 | control.send(CallUpdate::Muted(effect.muted)); |
| 2133 | let remote = remote.clone(); |
| 2134 | tokio::spawn(async move { |
| 2135 | let _ = remote |
| 2136 | .signaling |
| 2137 | .update_endpoint_state(&remote.conversation, &remote.participant, effect.endpoint_is_muted) |
| 2138 | .await; |
| 2139 | }); |
| 2140 | effect.muted |
| 2141 | } |
| 2142 | |
| 2143 | fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> { |
| 2144 | let sender = peer |
| 2145 | .senders() |
| 2146 | .into_iter() |
| 2147 | .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_)))) |
| 2148 | .ok_or_else(|| Error::Webrtc("no audio sender".into()))?; |
| 2149 | sender |
| 2150 | .set_track(Some(MediaStreamTrack::Audio(track.clone()))) |
| 2151 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 2152 | } |
| 2153 | |
| 2154 | #[allow(clippy::too_many_arguments)] |
| 2155 | fn engage_share_sound( |
| 2156 | factory: &PeerConnectionFactory, |
| 2157 | options: &CallOptions, |
| 2158 | input: &DeviceChoice, |
| 2159 | muted: bool, |
| 2160 | remote_audio: Option<RtcAudioTrack>, |
| 2161 | peer: &PeerConnection, |
| 2162 | control: &CallControl, |
| 2163 | timeline: &Timeline, |
| 2164 | ) -> Option<ShareAudio> { |
| 2165 | let started = ShareAudio::start(factory, options.audio, options.tone_hz, input, muted, remote_audio) |
| 2166 | .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio)); |
| 2167 | match started { |
| 2168 | Ok(audio) => { |
| 2169 | timeline.record("computer sound", format!("{:?}, own playback excluded: {}", audio.loopback, audio.loopback.excludes_own_playback())); |
| 2170 | if let Some(warning) = &audio.warning { |
| 2171 | timeline.record("computer sound warning", warning.clone()); |
| 2172 | } |
| 2173 | control.send(CallUpdate::ShareSound(true)); |
| 2174 | Some(audio) |
| 2175 | } |
| 2176 | Err(error) => { |
| 2177 | timeline.record("computer sound failed", error.to_string()); |
| 2178 | control.send(CallUpdate::Notice("Computer sound could not start, sharing without it".into())); |
| 2179 | None |
| 2180 | } |
| 2181 | } |
| 2182 | } |
| 2183 | |
| 2184 | fn release_share_sound( |
| 2185 | peer: &PeerConnection, |
| 2186 | device_track: &RtcAudioTrack, |
| 2187 | share_audio: &mut Option<ShareAudio>, |
| 2188 | control: &CallControl, |
| 2189 | timeline: &Timeline, |
| 2190 | ) { |
| 2191 | if share_audio.take().is_none() { |
| 2192 | return; |
| 2193 | } |
| 2194 | if let Err(error) = swap_audio_track(peer, device_track) { |
| 2195 | timeline.record("microphone track not restored", error.to_string()); |
| 2196 | } |
| 2197 | control.send(CallUpdate::ShareSound(false)); |
| 2198 | } |
| 2199 | |
| 2200 | async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) { |
| 2201 | if let Some(audio) = &live.audio { |
| 2202 | audio.track.set_enabled(false); |
| 2203 | } |
| 2204 | live.broker_running.store(false, Ordering::SeqCst); |
| 2205 | if !live.skip_leave |
| 2206 | && let Some(remote) = &live.remote |
| 2207 | { |
| 2208 | let reason = if cancelled { LeaveReason::Cancel } else { LeaveReason::Hangup }; |
| 2209 | match remote.signaling.leave(&remote.conversation, &remote.participant, reason).await { |
| 2210 | Ok(()) => report.left_cleanly = true, |
| 2211 | Err(error) => timeline.record("leave failed", error.to_string()), |
| 2212 | } |
| 2213 | } |
| 2214 | if report.end.is_none() |
| 2215 | && let Some(callbacks) = live.callbacks.as_mut() |
| 2216 | && live.remote.is_some() |
| 2217 | { |
| 2218 | let waited = timeout(END_CALLBACK_WAIT, async { |
| 2219 | while let Some(callback) = callbacks.recv().await { |
| 2220 | let request_id = callback.request_id; |
| 2221 | let event = handle_callback(&callback, timeline); |
| 2222 | inner.replier.reply(request_id, 200, ""); |
| 2223 | if let Ok(CallEvent::End(end)) = event { |
| 2224 | return Some(end); |
| 2225 | } |
| 2226 | } |
| 2227 | None |
| 2228 | }) |
| 2229 | .await; |
| 2230 | report.end = waited.ok().flatten(); |
| 2231 | } |
| 2232 | for peer in &live.peers { |
| 2233 | peer.close(); |
| 2234 | } |
| 2235 | if let Some(audio) = live.audio.take() { |
| 2236 | audio.stop().await; |
| 2237 | } |
| 2238 | if let Some(broker) = live.broker.take() { |
| 2239 | broker.abort(); |
| 2240 | } |
| 2241 | for task in live.video_tasks.drain(..) { |
| 2242 | task.abort(); |
| 2243 | } |
| 2244 | if let Some(route_id) = &live.route_id { |
| 2245 | inner.unregister_route(route_id); |
| 2246 | } |
| 2247 | timeline.record("closed", "peer closed, call route removed"); |
| 2248 | } |
| 2249 | |
| 2250 | fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> { |
| 2251 | let body = decode_body(callback)?; |
| 2252 | let (_, event) = classify(&callback.path, body)?; |
| 2253 | let detail = match &event { |
| 2254 | CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer), |
| 2255 | CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase), |
| 2256 | CallEvent::Progress(status) => format!("{status:?}"), |
| 2257 | _ => String::new(), |
| 2258 | }; |
| 2259 | timeline.record(format!("Trouter {}", event.name()), detail); |
| 2260 | Ok(event) |
| 2261 | } |
| 2262 | |
| 2263 | |
| 2264 | async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> { |
| 2265 | let answer = to_browser_answer(teams_answer, signaled, browser_offer)?; |
| 2266 | let description = parse_sdp(&answer, SdpType::Answer)?; |
| 2267 | peer.set_remote_description(description) |
| 2268 | .await |
| 2269 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 2270 | } |
| 2271 | |
| 2272 | /// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect. |
| 2273 | fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) { |
| 2274 | let Some(directory) = &options.sdp_dump_dir else { |
| 2275 | return; |
| 2276 | }; |
| 2277 | let masked: Vec<String> = sdp |
| 2278 | .lines() |
| 2279 | .map(|line| { |
| 2280 | for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:", "a=crypto:"] { |
| 2281 | if line.starts_with(prefix) { |
| 2282 | return format!("{prefix}<masked>"); |
| 2283 | } |
| 2284 | } |
| 2285 | line.split(' ').map(mask_address).collect::<Vec<_>>().join(" ") |
| 2286 | }) |
| 2287 | .collect(); |
| 2288 | let _ = std::fs::create_dir_all(directory); |
| 2289 | let _ = std::fs::write(directory.join(name), masked.join("\n")); |
| 2290 | } |
| 2291 | |
| 2292 | fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Error>) { |
| 2293 | let Some(directory) = &options.sdp_dump_dir else { |
| 2294 | return; |
| 2295 | }; |
| 2296 | let mut lines: Vec<String> = |
| 2297 | timeline.entries().iter().map(|entry| format!("{:>6} ms {} {}", entry.elapsed_ms, entry.label, entry.detail)).collect(); |
| 2298 | lines.push(match failure { |
| 2299 | Some(error) => format!("failed: {error}"), |
| 2300 | None => "ended without error".to_owned(), |
| 2301 | }); |
| 2302 | let _ = std::fs::create_dir_all(directory); |
| 2303 | let _ = std::fs::write(directory.join("timeline.txt"), lines.join("\n")); |
| 2304 | } |
| 2305 | |
| 2306 | fn mask_address(token: &str) -> String { |
| 2307 | let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok()); |
| 2308 | let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:"); |
| 2309 | if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1") || colon_address { |
| 2310 | "<addr>".to_owned() |
| 2311 | } else { |
| 2312 | token.to_owned() |
| 2313 | } |
| 2314 | } |
| 2315 | |
| 2316 | async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, tone_hz: f32) { |
| 2317 | let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1); |
| 2318 | while let Some(frame) = stream.next().await { |
| 2319 | let mut recording = recording.lock().await; |
| 2320 | recording.samples.extend_from_slice(&frame.data); |
| 2321 | recording.current_second.extend_from_slice(&frame.data); |
| 2322 | if recording.current_second.len() >= SAMPLE_RATE as usize { |
| 2323 | let second: Vec<i16> = std::mem::take(&mut recording.current_second); |
| 2324 | let summary = (rms(&second), tone_ratio(&second, tone_hz)); |
| 2325 | recording.per_second.push(summary); |
| 2326 | } |
| 2327 | } |
| 2328 | } |
| 2329 | |
| 2330 | async fn poll_broker(signaling: Arc<Signaling>, conversation: Conversation, running: Arc<AtomicBool>) { |
| 2331 | let Ok(first) = conversation.link("subscribe") else { |
| 2332 | return; |
| 2333 | }; |
| 2334 | let mut url = first.to_owned(); |
| 2335 | while running.load(Ordering::SeqCst) { |
| 2336 | match signaling.poll_broker(&url).await { |
| 2337 | Ok(Some(next)) => url = next, |
| 2338 | Ok(None) => {} |
| 2339 | Err(_) => return, |
| 2340 | } |
| 2341 | } |
| 2342 | } |
| 2343 | |
| 2344 | #[derive(Debug, Default)] |
| 2345 | struct StatsSnapshot { |
| 2346 | inbound_packets: u64, |
| 2347 | inbound_bytes: u64, |
| 2348 | outbound_packets: u64, |
| 2349 | audio_level: f64, |
| 2350 | local_level: f64, |
| 2351 | echo_return_loss_enhancement: f64, |
| 2352 | video: VideoReport, |
| 2353 | dtls_state: String, |
| 2354 | tls_version: String, |
| 2355 | dtls_cipher: String, |
| 2356 | srtp_cipher: String, |
| 2357 | selected_pair: Option<String>, |
| 2358 | health: HealthCounters, |
| 2359 | transport: TransportDetails, |
| 2360 | } |
| 2361 | |
| 2362 | async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot { |
| 2363 | let Ok(stats) = peer.get_stats().await else { |
| 2364 | return StatsSnapshot::default(); |
| 2365 | }; |
| 2366 | let mut snapshot = StatsSnapshot::default(); |
| 2367 | (snapshot.health, snapshot.transport) = health_from_stats(&stats); |
| 2368 | let mut selected_pair_id = None; |
| 2369 | for entry in &stats { |
| 2370 | match entry { |
| 2371 | RtcStats::InboundRtp(inbound) if inbound.stream.kind == "audio" => { |
| 2372 | snapshot.inbound_packets += inbound.received.packets_received; |
| 2373 | snapshot.inbound_bytes += inbound.inbound.bytes_received; |
| 2374 | snapshot.audio_level = snapshot.audio_level.max(inbound.inbound.audio_level); |
| 2375 | } |
| 2376 | RtcStats::MediaSource(source) if source.source.kind == "audio" => { |
| 2377 | snapshot.local_level = snapshot.local_level.max(source.audio.audio_level); |
| 2378 | snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement; |
| 2379 | } |
| 2380 | RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => { |
| 2381 | snapshot.outbound_packets += outbound.sent.packets_sent; |
| 2382 | } |
| 2383 | RtcStats::InboundRtp(inbound) if inbound.stream.kind == "video" => { |
| 2384 | snapshot.video.inbound_packets += inbound.received.packets_received; |
| 2385 | snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded); |
| 2386 | snapshot.video.inbound_width = snapshot.video.inbound_width.max(inbound.inbound.frame_width); |
| 2387 | snapshot.video.inbound_height = snapshot.video.inbound_height.max(inbound.inbound.frame_height); |
| 2388 | } |
| 2389 | RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => { |
| 2390 | snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements; |
| 2391 | snapshot.video.remote_round_trip_ms = snapshot.video.remote_round_trip_ms.max(remote.remote_inbound.round_trip_time * 1000.0); |
| 2392 | } |
| 2393 | RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => { |
| 2394 | snapshot.video.outbound_packets += outbound.sent.packets_sent; |
| 2395 | snapshot.video.outbound_frames_encoded += u64::from(outbound.outbound.frames_encoded); |
| 2396 | snapshot.video.outbound_width = snapshot.video.outbound_width.max(outbound.outbound.frame_width); |
| 2397 | snapshot.video.outbound_height = snapshot.video.outbound_height.max(outbound.outbound.frame_height); |
| 2398 | } |
| 2399 | RtcStats::Transport(transport) => { |
| 2400 | snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state); |
| 2401 | snapshot.tls_version = transport.transport.tls_version.clone(); |
| 2402 | snapshot.dtls_cipher = transport.transport.dtls_cipher.clone(); |
| 2403 | snapshot.srtp_cipher = transport.transport.srtp_cipher.clone(); |
| 2404 | if !transport.transport.selected_candidate_pair_id.is_empty() { |
| 2405 | selected_pair_id = Some(transport.transport.selected_candidate_pair_id.clone()); |
| 2406 | } |
| 2407 | } |
| 2408 | _ => {} |
| 2409 | } |
| 2410 | } |
| 2411 | if let Some(pair_id) = selected_pair_id { |
| 2412 | let pair = stats.iter().find_map(|entry| match entry { |
| 2413 | RtcStats::CandidatePair(pair) if pair.rtc.id == pair_id => Some(pair), |
| 2414 | _ => None, |
| 2415 | }); |
| 2416 | if let Some(pair) = pair { |
| 2417 | let describe = |candidate_id: &str| { |
| 2418 | stats |
| 2419 | .iter() |
| 2420 | .find_map(|entry| match entry { |
| 2421 | RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => Some(&local.local_candidate), |
| 2422 | RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => Some(&remote.remote_candidate), |
| 2423 | _ => None, |
| 2424 | }) |
| 2425 | .map(|candidate| { |
| 2426 | let kind = candidate.candidate_type.map(|kind| format!("{kind:?}")).unwrap_or_default(); |
| 2427 | let relay = candidate.relay_protocol.map(|relay| format!(" via {relay:?}")).unwrap_or_default(); |
| 2428 | format!("{kind}/{}{relay}", candidate.protocol) |
| 2429 | }) |
| 2430 | .unwrap_or_else(|| "?".into()) |
| 2431 | }; |
| 2432 | snapshot.selected_pair = Some(format!( |
| 2433 | "local {} <-> remote {}", |
| 2434 | describe(&pair.candidate_pair.local_candidate_id), |
| 2435 | describe(&pair.candidate_pair.remote_candidate_id) |
| 2436 | )); |
| 2437 | } |
| 2438 | } |
| 2439 | snapshot |
| 2440 | } |
| 2441 | |
| 2442 | #[cfg(test)] |
| 2443 | mod tests { |
| 2444 | use super::*; |
| 2445 | |
| 2446 | #[test] |
| 2447 | fn video_is_possible_once_connected_and_not_waiting_on_a_mixer_escalation() { |
| 2448 | assert!(video_possible(true, Layout::OneToOne, MediaPath::Direct)); |
| 2449 | assert!(video_possible(true, Layout::Conference, MediaPath::Mixer)); |
| 2450 | assert!(!video_possible(true, Layout::OneToOne, MediaPath::Mixer)); |
| 2451 | assert!(!video_possible( |
| 2452 | false, |
| 2453 | Layout::Conference, |
| 2454 | MediaPath::Direct |
| 2455 | )); |
| 2456 | } |
| 2457 | |
| 2458 | #[test] |
| 2459 | fn keep_alive_fires_at_ninety_percent_of_the_interval() { |
| 2460 | assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430)); |
| 2461 | assert_eq!(keep_alive_period(None), Duration::from_secs(2430)); |
| 2462 | assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54)); |
| 2463 | } |
| 2464 | |
| 2465 | 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"; |
| 2466 | |
| 2467 | fn directions(sdp: &str) -> Vec<String> { |
| 2468 | crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect() |
| 2469 | } |
| 2470 | |
| 2471 | async fn local_offer(layout: Layout) -> Result<OfferedMedia> { |
| 2472 | use libwebrtc::audio_source::native::NativeAudioSource; |
| 2473 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 2474 | let factory = devices::shared_factory(); |
| 2475 | let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap(); |
| 2476 | let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100); |
| 2477 | let track = factory.create_audio_track("microphone", source); |
| 2478 | create_offer(&peer, &factory, &track, layout).await |
| 2479 | } |
| 2480 | |
| 2481 | #[tokio::test] |
| 2482 | async fn libwebrtc_accepts_its_own_offer_after_the_direction_rewrite() { |
| 2483 | for layout in [Layout::OneToOne, Layout::Conference] { |
| 2484 | if let Err(error) = local_offer(layout).await { |
| 2485 | panic!("{layout:?}: {error}"); |
| 2486 | } |
| 2487 | } |
| 2488 | } |
| 2489 | |
| 2490 | #[tokio::test] |
| 2491 | async fn a_peer_to_peer_offer_from_the_teams_client_gets_an_answer() { |
| 2492 | use libwebrtc::audio_source::native::NativeAudioSource; |
| 2493 | use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt; |
| 2494 | let factory = devices::shared_factory(); |
| 2495 | let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap(); |
| 2496 | let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100); |
| 2497 | let track = factory.create_audio_track("microphone", source); |
| 2498 | let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp"); |
| 2499 | if let Err(error) = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive).await { |
| 2500 | panic!("{error}"); |
| 2501 | } |
| 2502 | } |
| 2503 | |
| 2504 | #[test] |
| 2505 | fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() { |
| 2506 | assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]); |
| 2507 | assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]); |
| 2508 | } |
| 2509 | |
| 2510 | #[test] |
| 2511 | fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() { |
| 2512 | for layout in [Layout::OneToOne, Layout::Conference] { |
| 2513 | assert_eq!(directions(&directions_for(layout, true, true, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]); |
| 2514 | } |
| 2515 | assert_eq!(directions_for(Layout::Conference, false, true, BROWSER_OFFER), BROWSER_OFFER); |
| 2516 | } |
| 2517 | |
| 2518 | #[test] |
| 2519 | fn a_move_into_the_meeting_you_are_already_in_is_ignored() { |
| 2520 | let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None }; |
| 2521 | assert!(is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_a@thread.v2"))); |
| 2522 | assert!(!is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_b@thread.v2"))); |
| 2523 | assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2"))); |
| 2524 | } |
| 2525 | |
| 2526 | #[test] |
| 2527 | fn a_video_call_names_the_video_modality_only_when_the_camera_sends() { |
| 2528 | assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]); |
| 2529 | assert_eq!(accepted_modalities(true), vec!["Audio".to_owned(), "Video".to_owned()]); |
| 2530 | } |
| 2531 | |
| 2532 | #[test] |
| 2533 | fn specs_map_to_invitation_targets() { |
| 2534 | assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo); |
| 2535 | let people = CallSpec::People { |
| 2536 | callees: vec![Callee { mri: "8:orgid:b".into(), display_name: "Bea".into() }], |
| 2537 | thread_id: "19:t@thread.v2".into(), |
| 2538 | }; |
| 2539 | assert!(people.is_people() && !people.is_meeting()); |
| 2540 | assert!(matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2")); |
| 2541 | let meeting = CallSpec::Meeting(MeetingTarget { |
| 2542 | thread_id: "19:meeting@thread.v2".into(), |
| 2543 | tenant_id: "t".into(), |
| 2544 | organizer_id: "o".into(), |
| 2545 | meeting_data: None, |
| 2546 | }); |
| 2547 | assert!(meeting.is_meeting() && !meeting.is_people()); |
| 2548 | } |
| 2549 | } |