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