| 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::prelude::*; |
| 11 | use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit}; |
| 12 | use libwebrtc::session_description::{SdpType, SessionDescription}; |
| 13 | use libwebrtc::stats::RtcStats; |
| 14 | use session::Session; |
| 15 | use tokio::sync::{Mutex, mpsc}; |
| 16 | use tokio::task::JoinHandle; |
| 17 | use tokio::time::{Instant, interval, sleep_until, timeout}; |
| 18 | |
| 19 | use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav}; |
| 20 | use crate::audio_io::{AudioMode, AudioSetup}; |
| 21 | use crate::control::{CallCommand, CallControl, CallUpdate, Progress}; |
| 22 | use crate::devices::{self, DeviceChoice}; |
| 23 | use crate::end::EndKind; |
| 24 | use crate::engine::{CallEngine, EngineConfig, Inner}; |
| 25 | use crate::error::{Error, Result}; |
| 26 | use crate::mute::{MuteCommand, MuteEffect}; |
| 27 | use crate::push::CallNotification; |
| 28 | use crate::share_audio::ShareAudio; |
| 29 | use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant}; |
| 30 | use crate::renegotiation::{MediaAction, MediaNegotiator}; |
| 31 | use crate::roster::Roster; |
| 32 | use crate::sdp::{RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer}; |
| 33 | use crate::signaling::{ |
| 34 | Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling, |
| 35 | TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body, |
| 36 | }; |
| 37 | use crate::state::{CallSignal, CallState}; |
| 38 | use crate::timeline::{Timeline, TimelineEntry}; |
| 39 | use crate::video_layout::{MediaDescription, SlotTable, VideoLines, VideoRouter, add_video_lines, offer_plan}; |
| 40 | use crate::video_send::{LocalVideo, VideoMode}; |
| 41 | use crate::camera::{CameraDevice, list_cameras}; |
| 42 | use crate::screen::{ShareKind, ShareSource, list_share_sources}; |
| 43 | use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump}; |
| 44 | use crate::trouter_events::{ |
| 45 | CallEnd, CallEvent, CallbackLinks, ProgressStatus, acceptance_acknowledgement, classify, decode_body, |
| 46 | }; |
| 47 | |
| 48 | const END_CALLBACK_WAIT: Duration = Duration::from_secs(4); |
| 49 | const STATS_PERIOD: Duration = Duration::from_millis(200); |
| 50 | const TICKS_PER_SECOND: u32 = 5; |
| 51 | const RECONNECT_WINDOW: Duration = Duration::from_secs(30); |
| 52 | const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90); |
| 53 | const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365); |
| 54 | const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700; |
| 55 | const MIN_KEEP_ALIVE_SECONDS: u64 = 60; |
| 56 | const KEEP_ALIVE_FRACTION: f64 = 0.9; |
| 57 | const MIC_STREAM: &str = "microphone"; |
| 58 | |
| 59 | #[derive(Debug, Clone)] |
| 60 | pub struct CallOptions { |
| 61 | pub hold_after_connected: Option<Duration>, |
| 62 | pub hard_limit: Option<Duration>, |
| 63 | pub reconnect_window: Duration, |
| 64 | pub audio: AudioMode, |
| 65 | pub video: VideoMode, |
| 66 | pub camera: DeviceChoice, |
| 67 | pub tone_hz: f32, |
| 68 | pub input: DeviceChoice, |
| 69 | pub output: DeviceChoice, |
| 70 | pub relay_host: String, |
| 71 | pub routing: TenantRouting, |
| 72 | pub record_remote: bool, |
| 73 | pub wav_path: Option<PathBuf>, |
| 74 | pub sdp_dump_dir: Option<PathBuf>, |
| 75 | pub trace: bool, |
| 76 | } |
| 77 | |
| 78 | impl Default for CallOptions { |
| 79 | fn default() -> Self { |
| 80 | CallOptions { |
| 81 | hold_after_connected: None, |
| 82 | hard_limit: None, |
| 83 | reconnect_window: RECONNECT_WINDOW, |
| 84 | audio: AudioMode::from_env(), |
| 85 | video: VideoMode::from_env(), |
| 86 | camera: DeviceChoice::SystemDefault, |
| 87 | tone_hz: 440.0, |
| 88 | input: DeviceChoice::SystemDefault, |
| 89 | output: DeviceChoice::SystemDefault, |
| 90 | relay_host: DEFAULT_RELAY_HOST.to_owned(), |
| 91 | routing: TenantRouting::default(), |
| 92 | record_remote: false, |
| 93 | wav_path: None, |
| 94 | sdp_dump_dir: None, |
| 95 | trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(), |
| 96 | } |
| 97 | } |
| 98 | } |
| 99 | |
| 100 | #[derive(Debug, Clone, Default)] |
| 101 | pub struct AudioSecond { |
| 102 | pub second: u32, |
| 103 | pub packets: u64, |
| 104 | pub bytes: u64, |
| 105 | pub audio_level: f64, |
| 106 | pub decoded_rms: f32, |
| 107 | pub tone_ratio: f32, |
| 108 | } |
| 109 | |
| 110 | #[derive(Debug, Clone, Default, PartialEq)] |
| 111 | pub struct VideoReport { |
| 112 | pub inbound_packets: u64, |
| 113 | pub inbound_frames_decoded: u64, |
| 114 | pub inbound_width: u32, |
| 115 | pub inbound_height: u32, |
| 116 | pub frames_received: u64, |
| 117 | pub frames_published: u64, |
| 118 | pub outbound_packets: u64, |
| 119 | pub outbound_frames_encoded: u64, |
| 120 | pub outbound_width: u32, |
| 121 | pub outbound_height: u32, |
| 122 | pub remote_reports: u64, |
| 123 | pub remote_round_trip_ms: f64, |
| 124 | } |
| 125 | |
| 126 | #[derive(Debug, Clone, Default)] |
| 127 | pub struct CallReport { |
| 128 | pub timeline: Vec<TimelineEntry>, |
| 129 | pub ice_connected_ms: Option<u128>, |
| 130 | pub peer_connected_ms: Option<u128>, |
| 131 | pub selected_pair: Option<String>, |
| 132 | pub tls_version: String, |
| 133 | pub dtls_cipher: String, |
| 134 | pub srtp_cipher: String, |
| 135 | pub inbound_packets: u64, |
| 136 | pub inbound_bytes: u64, |
| 137 | pub outbound_packets: u64, |
| 138 | pub video: VideoReport, |
| 139 | pub own_streams: Vec<String>, |
| 140 | pub seconds_with_inbound_audio: u32, |
| 141 | pub seconds: Vec<AudioSecond>, |
| 142 | pub end: Option<CallEnd>, |
| 143 | pub left_cleanly: bool, |
| 144 | pub recorded_samples: usize, |
| 145 | } |
| 146 | |
| 147 | #[derive(Debug, Clone)] |
| 148 | pub enum CallSpec { |
| 149 | Echo, |
| 150 | People { callees: Vec<Callee>, thread_id: String }, |
| 151 | Meeting(MeetingTarget), |
| 152 | } |
| 153 | |
| 154 | impl CallSpec { |
| 155 | fn target(&self) -> InviteTarget { |
| 156 | match self { |
| 157 | CallSpec::Echo => InviteTarget::Echo, |
| 158 | CallSpec::People { callees, thread_id } => InviteTarget::People { |
| 159 | callees: callees.clone(), |
| 160 | thread_id: thread_id.clone(), |
| 161 | }, |
| 162 | CallSpec::Meeting(meeting) => InviteTarget::Meeting(meeting.clone()), |
| 163 | } |
| 164 | } |
| 165 | |
| 166 | fn is_meeting(&self) -> bool { |
| 167 | matches!(self, CallSpec::Meeting(_)) |
| 168 | } |
| 169 | |
| 170 | fn is_people(&self) -> bool { |
| 171 | matches!(self, CallSpec::People { .. }) |
| 172 | } |
| 173 | } |
| 174 | |
| 175 | pub(crate) struct IncomingCall { |
| 176 | pub notification: CallNotification, |
| 177 | pub attached: Attached, |
| 178 | pub links: CallbackLinks, |
| 179 | pub participant: Participant, |
| 180 | pub callbacks: mpsc::UnboundedReceiver<TrouterCallback>, |
| 181 | } |
| 182 | |
| 183 | pub(crate) enum Plan { |
| 184 | Outgoing(CallSpec), |
| 185 | Incoming(Box<IncomingCall>), |
| 186 | } |
| 187 | |
| 188 | pub fn keep_alive_period(seconds: Option<u64>) -> Duration { |
| 189 | let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS); |
| 190 | Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION) |
| 191 | } |
| 192 | |
| 193 | fn random_u32() -> u32 { |
| 194 | let bytes = uuid::Uuid::new_v4().into_bytes(); |
| 195 | u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff |
| 196 | } |
| 197 | |
| 198 | #[derive(Default)] |
| 199 | struct Recording { |
| 200 | samples: Vec<i16>, |
| 201 | current_second: Vec<i16>, |
| 202 | per_second: Vec<(f32, f32)>, |
| 203 | } |
| 204 | |
| 205 | enum PeerEvent { |
| 206 | Ice(IceConnectionState), |
| 207 | Connection(PeerConnectionState), |
| 208 | Track(RtcAudioTrack), |
| 209 | VideoTrack { mid: String, track: RtcVideoTrack }, |
| 210 | } |
| 211 | |
| 212 | struct PeerSession { |
| 213 | peer: PeerConnection, |
| 214 | events: mpsc::UnboundedReceiver<PeerEvent>, |
| 215 | } |
| 216 | |
| 217 | struct OfferedMedia { |
| 218 | browser_offer: String, |
| 219 | signaled: SignaledOffer, |
| 220 | video: VideoLines, |
| 221 | } |
| 222 | |
| 223 | struct NextPeer { |
| 224 | session: PeerSession, |
| 225 | offered: Option<OfferedMedia>, |
| 226 | } |
| 227 | |
| 228 | struct AnsweredMedia { |
| 229 | remote: RemoteOffer, |
| 230 | answer_sdp: String, |
| 231 | } |
| 232 | |
| 233 | #[derive(Clone)] |
| 234 | struct RemoteCall { |
| 235 | signaling: Arc<Signaling>, |
| 236 | conversation: Conversation, |
| 237 | participant: Participant, |
| 238 | } |
| 239 | |
| 240 | #[derive(Default)] |
| 241 | struct Live { |
| 242 | peers: Vec<PeerConnection>, |
| 243 | audio: Option<AudioSetup>, |
| 244 | remote: Option<RemoteCall>, |
| 245 | broker: Option<JoinHandle<()>>, |
| 246 | broker_running: Arc<AtomicBool>, |
| 247 | callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>, |
| 248 | route_id: Option<String>, |
| 249 | skip_leave: bool, |
| 250 | cancel_leave: bool, |
| 251 | video_tasks: Vec<JoinHandle<()>>, |
| 252 | video_counters: Arc<VideoCounters>, |
| 253 | } |
| 254 | |
| 255 | fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool { |
| 256 | let next = state.next(signal, std::time::Instant::now()); |
| 257 | if next == *state { |
| 258 | return false; |
| 259 | } |
| 260 | *state = next.clone(); |
| 261 | control.send(CallUpdate::State(next)); |
| 262 | true |
| 263 | } |
| 264 | |
| 265 | /// Places the Echo test call on its own non-ringable Trouter instance; the app uses a shared engine instead. |
| 266 | pub async fn run_test_call( |
| 267 | session: &Session, |
| 268 | poll_session: &Session, |
| 269 | options: CallOptions, |
| 270 | control: CallControl, |
| 271 | ) -> Result<CallReport> { |
| 272 | let config = EngineConfig { |
| 273 | ringable: false, |
| 274 | routing: options.routing.clone(), |
| 275 | relay_host: options.relay_host.clone(), |
| 276 | trace: options.trace, |
| 277 | instance: chatsvc::InstanceNames { |
| 278 | global: "__testCallTrouter".into(), |
| 279 | binding: "__testCallRealtime".into(), |
| 280 | endpoint_storage_key: "__testCallEpid".into(), |
| 281 | }, |
| 282 | }; |
| 283 | let (engine, _events) = CallEngine::start(session.clone(), poll_session.clone(), config).await?; |
| 284 | let report = engine.run(Plan::Outgoing(CallSpec::Echo), options, control).await; |
| 285 | engine.stop().await; |
| 286 | report |
| 287 | } |
| 288 | |
| 289 | impl CallEngine { |
| 290 | pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> { |
| 291 | let inner = self.inner.as_ref(); |
| 292 | let _one_call_at_a_time = inner.gate.lock().await; |
| 293 | let timeline = Timeline::new(options.trace); |
| 294 | let mut report = CallReport::default(); |
| 295 | let mut state = CallState::Idle; |
| 296 | advance(&mut state, CallSignal::Dial, &control); |
| 297 | let mut live = Live::default(); |
| 298 | let recording = Arc::new(Mutex::new(Recording::default())); |
| 299 | let outcome = drive( |
| 300 | inner, |
| 301 | &options, |
| 302 | &timeline, |
| 303 | &recording, |
| 304 | plan, |
| 305 | &mut live, |
| 306 | &mut control, |
| 307 | &mut state, |
| 308 | &mut report, |
| 309 | ) |
| 310 | .await; |
| 311 | let failure = match outcome { |
| 312 | Ok(()) => None, |
| 313 | Err(Error::Cancelled) => { |
| 314 | advance(&mut state, CallSignal::LocalLeave, &control); |
| 315 | None |
| 316 | } |
| 317 | Err(error) => { |
| 318 | advance(&mut state, CallSignal::Error(error.to_string()), &control); |
| 319 | Some(error) |
| 320 | } |
| 321 | }; |
| 322 | let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled }); |
| 323 | tear_down(live, inner, &timeline, &mut report, cancelled).await; |
| 324 | let recording = recording.lock().await; |
| 325 | report.recorded_samples = recording.samples.len(); |
| 326 | if let Some(path) = &options.wav_path { |
| 327 | write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?; |
| 328 | } |
| 329 | report.timeline = timeline.entries(); |
| 330 | match failure { |
| 331 | Some(error) => Err(error), |
| 332 | None => Ok(report), |
| 333 | } |
| 334 | } |
| 335 | } |
| 336 | |
| 337 | fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str) -> Result<PeerSession> { |
| 338 | let mut configuration = RtcConfiguration::default(); |
| 339 | configuration.ice_servers = vec![grant.ice_server(relay_host)]; |
| 340 | let peer = factory |
| 341 | .create_peer_connection(configuration) |
| 342 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 343 | let (sender, events) = mpsc::unbounded_channel(); |
| 344 | let ice_sender = sender.clone(); |
| 345 | peer.on_ice_connection_state_change(Some(Box::new(move |state| { |
| 346 | let _ = ice_sender.send(PeerEvent::Ice(state)); |
| 347 | }))); |
| 348 | let connection_sender = sender.clone(); |
| 349 | peer.on_connection_state_change(Some(Box::new(move |state| { |
| 350 | let _ = connection_sender.send(PeerEvent::Connection(state)); |
| 351 | }))); |
| 352 | peer.on_track(Some(Box::new(move |event| match event.track { |
| 353 | MediaStreamTrack::Audio(track) => { |
| 354 | let _ = sender.send(PeerEvent::Track(track)); |
| 355 | } |
| 356 | MediaStreamTrack::Video(track) => { |
| 357 | let mid = event.transceiver.mid().unwrap_or_default(); |
| 358 | let _ = sender.send(PeerEvent::VideoTrack { mid, track }); |
| 359 | } |
| 360 | }))); |
| 361 | Ok(PeerSession { peer, events }) |
| 362 | } |
| 363 | |
| 364 | async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack) -> Result<OfferedMedia> { |
| 365 | let transceiver_init = RtpTransceiverInit { |
| 366 | direction: RtpTransceiverDirection::SendRecv, |
| 367 | stream_ids: vec![MIC_STREAM.into()], |
| 368 | send_encodings: Vec::new(), |
| 369 | }; |
| 370 | peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init) |
| 371 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 372 | let video = add_video_lines(peer, factory)?; |
| 373 | let offer = peer |
| 374 | .create_offer(OfferOptions { |
| 375 | offer_to_receive_audio: true, |
| 376 | offer_to_receive_video: true, |
| 377 | ..OfferOptions::default() |
| 378 | }) |
| 379 | .await |
| 380 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 381 | peer.set_local_description(offer.clone()) |
| 382 | .await |
| 383 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 384 | let browser_offer = offer.to_string(); |
| 385 | let mut numbers = random_u32; |
| 386 | let signaled = to_teams_offer(&browser_offer, &offer_plan(), &mut numbers)?; |
| 387 | Ok(OfferedMedia { browser_offer, signaled, video }) |
| 388 | } |
| 389 | |
| 390 | /// Video lines of a Teams offer are stopped so the answer rejects them; audio is all this client does. |
| 391 | async fn answer_offer( |
| 392 | peer: &PeerConnection, |
| 393 | track: Option<&RtcAudioTrack>, |
| 394 | teams_offer: &str, |
| 395 | ) -> Result<AnsweredMedia> { |
| 396 | let remote = from_teams_offer(teams_offer)?; |
| 397 | let description = |
| 398 | SessionDescription::parse(&remote.browser_sdp, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?; |
| 399 | peer.set_remote_description(description) |
| 400 | .await |
| 401 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 402 | for transceiver in peer.transceivers() { |
| 403 | if matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_))) { |
| 404 | let _ = transceiver.stop(); |
| 405 | } |
| 406 | } |
| 407 | if let Some(track) = track { |
| 408 | peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM]) |
| 409 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 410 | } |
| 411 | let answer = peer |
| 412 | .create_answer(AnswerOptions::default()) |
| 413 | .await |
| 414 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 415 | peer.set_local_description(answer.clone()) |
| 416 | .await |
| 417 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 418 | let mut numbers = random_u32; |
| 419 | let signaled = to_teams_answer(&answer.to_string(), &remote, &mut numbers)?; |
| 420 | Ok(AnsweredMedia { |
| 421 | remote, |
| 422 | answer_sdp: signaled.sdp, |
| 423 | }) |
| 424 | } |
| 425 | |
| 426 | fn new_media_leg_id() -> String { |
| 427 | uuid::Uuid::new_v4().simple().to_string().to_uppercase() |
| 428 | } |
| 429 | |
| 430 | async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> { |
| 431 | match next { |
| 432 | Some(next) => next.session.events.recv().await, |
| 433 | None => std::future::pending().await, |
| 434 | } |
| 435 | } |
| 436 | |
| 437 | #[allow(clippy::too_many_arguments)] |
| 438 | async fn drive( |
| 439 | inner: &Inner, |
| 440 | options: &CallOptions, |
| 441 | timeline: &Timeline, |
| 442 | recording: &Arc<Mutex<Recording>>, |
| 443 | plan: Plan, |
| 444 | live: &mut Live, |
| 445 | control: &mut CallControl, |
| 446 | state: &mut CallState, |
| 447 | report: &mut CallReport, |
| 448 | ) -> Result<()> { |
| 449 | let own_mri = format!("8:orgid:{}", inner.identity.object_id); |
| 450 | control.send(CallUpdate::OwnIdentity { mri: own_mri.clone() }); |
| 451 | let (spec, incoming) = match plan { |
| 452 | Plan::Outgoing(spec) => (Some(spec), None), |
| 453 | Plan::Incoming(incoming) => (None, Some(*incoming)), |
| 454 | }; |
| 455 | let (links, participant, mut callbacks, incoming_media) = match incoming { |
| 456 | Some(IncomingCall { |
| 457 | notification, |
| 458 | attached, |
| 459 | links, |
| 460 | participant, |
| 461 | callbacks, |
| 462 | }) => (links, participant, callbacks, Some((notification, attached))), |
| 463 | None => { |
| 464 | let links = inner.callback_links(); |
| 465 | let participant = inner.participant(&uuid::Uuid::new_v4().to_string()); |
| 466 | let callbacks = inner.register_route(links.call_id()); |
| 467 | (links, participant, callbacks, None) |
| 468 | } |
| 469 | }; |
| 470 | live.route_id = Some(links.call_id().to_owned()); |
| 471 | timeline.record("Trouter connected", "callback socket ready"); |
| 472 | |
| 473 | let thread_id = if matches!(spec, Some(CallSpec::Echo)) { |
| 474 | let thread_id = control |
| 475 | .until_hangup(find_echo_bot_thread(&inner.session, &inner.identity.object_id)) |
| 476 | .await??; |
| 477 | timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" }); |
| 478 | thread_id |
| 479 | } else { |
| 480 | None |
| 481 | }; |
| 482 | let grant = control.until_hangup(fetch_relay_grant(&inner.session)).await??; |
| 483 | timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds)); |
| 484 | |
| 485 | let factory = devices::shared_factory(); |
| 486 | let mut input = options.input.clone(); |
| 487 | let mut output = options.output.clone(); |
| 488 | let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output); |
| 489 | control.send(CallUpdate::ListenOnly(audio.listen_only)); |
| 490 | control.send(CallUpdate::Devices(devices::list_devices(&factory))); |
| 491 | control.send(CallUpdate::Selected { |
| 492 | input: input.clone(), |
| 493 | output: output.clone(), |
| 494 | }); |
| 495 | let track = audio.track.clone(); |
| 496 | live.audio = Some(audio); |
| 497 | let mut local_video = LocalVideo::new(&factory, options.video, control.video.clone(), control.updates()); |
| 498 | let mut camera_choice = options.camera.clone(); |
| 499 | let mut media_description_request = 1u32; |
| 500 | control.send(CallUpdate::Cameras(camera_devices(options.video).await)); |
| 501 | refresh_share_sources(control.updates(), options.video); |
| 502 | |
| 503 | let mut current = open_peer(&factory, &grant, &options.relay_host)?; |
| 504 | live.peers.push(current.peer.clone()); |
| 505 | |
| 506 | let signaling = Arc::new(inner.signaling(timeline.clone())); |
| 507 | let media_leg_id = new_media_leg_id(); |
| 508 | let call_started = Instant::now(); |
| 509 | let mut offered: Option<OfferedMedia> = None; |
| 510 | let mut negotiator = MediaNegotiator::default(); |
| 511 | let mut remote_set = false; |
| 512 | let mut keep_alive_link: Option<String> = None; |
| 513 | let mut keep_alive_seconds: Option<u64> = None; |
| 514 | let mut keep_alive_at: Option<Instant> = None; |
| 515 | let mut outgoing_deadline: Option<Instant> = None; |
| 516 | let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting); |
| 517 | let is_echo = matches!(spec, Some(CallSpec::Echo)); |
| 518 | |
| 519 | let conversation = match (spec, incoming_media) { |
| 520 | (Some(spec), None) => { |
| 521 | let media = create_offer(¤t.peer, &factory, &track).await?; |
| 522 | timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len())); |
| 523 | dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer); |
| 524 | dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp); |
| 525 | let target = spec.target(); |
| 526 | let invitation = Invitation { |
| 527 | from: &participant, |
| 528 | offer_sdp: &media.signaled.sdp, |
| 529 | media_leg_id: &media_leg_id, |
| 530 | callbacks: &links, |
| 531 | target: &target, |
| 532 | }; |
| 533 | let conversation = match &target { |
| 534 | InviteTarget::Meeting(meeting) => { |
| 535 | let subscribed = control |
| 536 | .until_hangup(signaling.subscribe_meeting(&participant, &links, meeting)) |
| 537 | .await??; |
| 538 | signaling.join_meeting(&subscribed, &invitation).await? |
| 539 | } |
| 540 | _ => signaling.create_conversation(&invitation).await?, |
| 541 | }; |
| 542 | if spec.is_people() { |
| 543 | control.send(CallUpdate::Progress(Progress::Calling)); |
| 544 | outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT); |
| 545 | } |
| 546 | if let Err(error) = local_video.set_lines(media.video.clone()) { |
| 547 | timeline.record("video lines not attached", error.to_string()); |
| 548 | } |
| 549 | offered = Some(media); |
| 550 | live.remote = Some(RemoteCall { |
| 551 | signaling: signaling.clone(), |
| 552 | conversation: conversation.clone(), |
| 553 | participant: participant.clone(), |
| 554 | }); |
| 555 | conversation |
| 556 | } |
| 557 | (None, Some((_notification, attached))) => { |
| 558 | let teams_offer = attached |
| 559 | .offer_sdp |
| 560 | .clone() |
| 561 | .ok_or_else(|| Error::Signaling("attach answer without an offer".into()))?; |
| 562 | let conversation = attached |
| 563 | .conversation |
| 564 | .clone() |
| 565 | .ok_or_else(|| Error::Signaling("attach answer without a conversation".into()))?; |
| 566 | live.remote = Some(RemoteCall { |
| 567 | signaling: signaling.clone(), |
| 568 | conversation: conversation.clone(), |
| 569 | participant: participant.clone(), |
| 570 | }); |
| 571 | let answered = answer_offer(¤t.peer, Some(&track), &teams_offer).await?; |
| 572 | timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len())); |
| 573 | dump_sdp(options, "3-teams-offer.sdp", &teams_offer); |
| 574 | dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp); |
| 575 | let acceptance_url = attached |
| 576 | .links |
| 577 | .get("acceptance") |
| 578 | .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?; |
| 579 | let modalities = vec!["Audio".to_owned()]; |
| 580 | signaling |
| 581 | .accept( |
| 582 | acceptance_url, |
| 583 | &Answer { |
| 584 | from: &participant, |
| 585 | answer_sdp: &answered.answer_sdp, |
| 586 | media_leg_id: &media_leg_id, |
| 587 | callbacks: &links, |
| 588 | modalities: &modalities, |
| 589 | }, |
| 590 | ) |
| 591 | .await?; |
| 592 | negotiator.answered_incoming(attached.from_mixer); |
| 593 | remote_set = true; |
| 594 | keep_alive_link = attached.links.get("callLeg").cloned(); |
| 595 | keep_alive_at = Some(Instant::now() + keep_alive_period(None)); |
| 596 | conversation |
| 597 | } |
| 598 | _ => return Err(Error::Callback("call plan without an offer or an invitation".into())), |
| 599 | }; |
| 600 | let remote = live.remote.clone().expect("remote call set above"); |
| 601 | live.broker_running.store(true, Ordering::SeqCst); |
| 602 | live.broker = Some(tokio::spawn(poll_broker( |
| 603 | signaling.clone(), |
| 604 | conversation.clone(), |
| 605 | live.broker_running.clone(), |
| 606 | ))); |
| 607 | |
| 608 | let initial = MuteEffect::initial(is_meeting); |
| 609 | let mut muted = initial.muted; |
| 610 | live.audio.as_ref().expect("audio set above").track.set_enabled(initial.track_enabled); |
| 611 | if muted { |
| 612 | control.send(CallUpdate::Muted(true)); |
| 613 | } |
| 614 | if let Err(error) = signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted).await { |
| 615 | timeline.record("updateEndpointState failed", error.to_string()); |
| 616 | } |
| 617 | |
| 618 | let replier = inner.replier.clone(); |
| 619 | let mut stats_tick = interval(STATS_PERIOD); |
| 620 | let hard_deadline = options.hard_limit.map(|limit| call_started + limit); |
| 621 | let mut leave_at = hard_deadline; |
| 622 | let mut reconnect_deadline: Option<Instant> = None; |
| 623 | let mut next: Option<NextPeer> = None; |
| 624 | let mut roster = Roster::default(); |
| 625 | let mut lobby = false; |
| 626 | let mut previous_packets = 0u64; |
| 627 | let mut ticks = 0u32; |
| 628 | let mut second = 0u32; |
| 629 | let echo_thread = thread_id; |
| 630 | let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default()); |
| 631 | let mut media_links: BTreeMap<String, String> = BTreeMap::new(); |
| 632 | let mut share_audio: Option<ShareAudio> = None; |
| 633 | let mut share_sound_wanted = false; |
| 634 | let mut remote_audio: Option<RtcAudioTrack> = None; |
| 635 | let mut own_hand: Option<String> = None; |
| 636 | let mut meeting_chat = conversation.chat_thread.clone(); |
| 637 | if let Some(thread) = &meeting_chat { |
| 638 | control.send(CallUpdate::MeetingChat(thread.clone())); |
| 639 | } |
| 640 | loop { |
| 641 | tokio::select! { |
| 642 | Some(callback) = callbacks.recv() => { |
| 643 | let request_id = callback.request_id; |
| 644 | match handle_callback(&callback, timeline) { |
| 645 | Ok(CallEvent::Acceptance(acceptance)) => { |
| 646 | replier.reply(request_id, 200, acceptance_acknowledgement(&links).to_string()); |
| 647 | match negotiator.on_acceptance(acceptance.from_mixer) { |
| 648 | MediaAction::ApplyAnswer => { |
| 649 | let Some(media) = offered.as_ref() else { continue }; |
| 650 | dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp); |
| 651 | if let Ok(answer) = to_browser_answer(&acceptance.sdp, &media.signaled, &media.browser_offer) { |
| 652 | dump_sdp(options, "4-browser-answer.sdp", &answer); |
| 653 | } |
| 654 | apply_answer(¤t.peer, &acceptance.sdp, &media.signaled, &media.browser_offer) |
| 655 | .await |
| 656 | .inspect_err(|error| timeline.record("answer rejected", error.to_string()))?; |
| 657 | remote_set = true; |
| 658 | media_links.extend(acceptance.links.clone()); |
| 659 | negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster); |
| 660 | outgoing_deadline = None; |
| 661 | let directions: Vec<String> = current |
| 662 | .peer |
| 663 | .transceivers() |
| 664 | .iter() |
| 665 | .map(|transceiver| format!("{:?}", transceiver.current_direction())) |
| 666 | .collect(); |
| 667 | timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(","))); |
| 668 | if acceptance.in_lobby() { |
| 669 | lobby = true; |
| 670 | control.send(CallUpdate::Lobby(true)); |
| 671 | } |
| 672 | keep_alive_link = acceptance.links.get("callLeg").cloned(); |
| 673 | keep_alive_seconds = acceptance.keep_alive_seconds; |
| 674 | keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds)); |
| 675 | let remote = remote.clone(); |
| 676 | let links = links.clone(); |
| 677 | let thread_id = echo_thread.clone(); |
| 678 | tokio::spawn(async move { |
| 679 | if is_echo { |
| 680 | let _ = remote.signaling.add_echo_bot(&remote.conversation, &remote.participant, thread_id.as_deref(), &links).await; |
| 681 | } |
| 682 | let _ = remote.signaling.update_endpoint_metadata(&remote.conversation, &remote.participant).await; |
| 683 | }); |
| 684 | } |
| 685 | MediaAction::Escalate => { |
| 686 | match start_escalation(&factory, &grant, options, &track, &remote, &links, &media_leg_id, &acceptance.links).await { |
| 687 | Ok(pending) => { |
| 688 | timeline.record("escalation", "new peer connection, new offer sent"); |
| 689 | live.peers.push(pending.session.peer.clone()); |
| 690 | next = Some(pending); |
| 691 | } |
| 692 | Err(error) => { |
| 693 | negotiator.escalation_failed(); |
| 694 | timeline.record("escalation failed", error.to_string()); |
| 695 | } |
| 696 | } |
| 697 | } |
| 698 | _ => {} |
| 699 | } |
| 700 | } |
| 701 | Ok(CallEvent::MediaAnswer(answer)) => { |
| 702 | replier.reply(request_id, 200, ""); |
| 703 | if negotiator.on_media_answer() == MediaAction::ApplyOnNewPeer { |
| 704 | let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) { |
| 705 | Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await, |
| 706 | None => Err(Error::Webrtc("no pending peer connection for the answer".into())), |
| 707 | }; |
| 708 | match applied { |
| 709 | Ok(()) => { |
| 710 | if let Some(media) = next.as_ref().and_then(|pending| pending.offered.as_ref()) { |
| 711 | media_links.extend(answer.links.clone()); |
| 712 | negotiate_video(&mut video, &signaling, control, timeline, &answer.sdp, media, true, &media_links, &roster); |
| 713 | } |
| 714 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 715 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 716 | } |
| 717 | } |
| 718 | Err(error) => { |
| 719 | negotiator.escalation_failed(); |
| 720 | next = None; |
| 721 | timeline.record("escalation answer rejected", error.to_string()); |
| 722 | } |
| 723 | } |
| 724 | } |
| 725 | } |
| 726 | Ok(CallEvent::MediaRenegotiation(renegotiation)) => { |
| 727 | replier.reply(request_id, 200, ""); |
| 728 | let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation); |
| 729 | let result = match action { |
| 730 | MediaAction::AnswerOnNewPeer => { |
| 731 | match answer_on_new_peer(&factory, &grant, options, &track, &renegotiation.sdp).await { |
| 732 | Ok((session, answered)) => { |
| 733 | live.peers.push(session.peer.clone()); |
| 734 | let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await; |
| 735 | next = Some(NextPeer { session, offered: None }); |
| 736 | sent |
| 737 | } |
| 738 | Err(error) => Err(error), |
| 739 | } |
| 740 | } |
| 741 | MediaAction::AnswerOnSamePeer => { |
| 742 | match answer_offer(¤t.peer, None, &renegotiation.sdp).await { |
| 743 | Ok(answered) => send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await, |
| 744 | Err(error) => Err(error), |
| 745 | } |
| 746 | } |
| 747 | _ => Ok(()), |
| 748 | }; |
| 749 | if let Err(error) = result { |
| 750 | timeline.record("renegotiation failed", error.to_string()); |
| 751 | } |
| 752 | } |
| 753 | Ok(CallEvent::RosterUpdate(body)) => { |
| 754 | replier.reply(request_id, 200, ""); |
| 755 | if roster.apply(&body) { |
| 756 | let entries = roster.entries(); |
| 757 | timeline.record("roster", format!("{} participant(s)", entries.len())); |
| 758 | control.send(CallUpdate::Roster(entries)); |
| 759 | let own_streams = roster.stream_summaries(&own_mri); |
| 760 | if own_streams != report.own_streams { |
| 761 | timeline.record("own media streams", own_streams.join("; ")); |
| 762 | report.own_streams = own_streams; |
| 763 | } |
| 764 | send_receive_change(control, video.reselect(&roster)); |
| 765 | if let Some(in_lobby) = roster.is_in_lobby(&own_mri) |
| 766 | && in_lobby != lobby |
| 767 | { |
| 768 | lobby = in_lobby; |
| 769 | control.send(CallUpdate::Lobby(lobby)); |
| 770 | } |
| 771 | } |
| 772 | } |
| 773 | Ok(CallEvent::ConversationUpdate(body)) => { |
| 774 | replier.reply(request_id, 200, ""); |
| 775 | if let Some(thread) = chat_thread_id(&body) |
| 776 | && meeting_chat.as_ref() != Some(&thread) |
| 777 | { |
| 778 | control.send(CallUpdate::MeetingChat(thread.clone())); |
| 779 | meeting_chat = Some(thread); |
| 780 | } |
| 781 | } |
| 782 | Ok(CallEvent::Reactions(events)) => { |
| 783 | replier.reply(request_id, 200, ""); |
| 784 | for event in events { |
| 785 | control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction }); |
| 786 | } |
| 787 | } |
| 788 | Ok(CallEvent::Progress(status)) => { |
| 789 | replier.reply(request_id, 200, ""); |
| 790 | if status == ProgressStatus::Ringing { |
| 791 | control.send(CallUpdate::Progress(Progress::Ringing)); |
| 792 | } |
| 793 | } |
| 794 | Ok(CallEvent::Speakers(sources)) => { |
| 795 | replier.reply(request_id, 200, ""); |
| 796 | let speakers = roster.mris_for_sources(&sources); |
| 797 | if video.note_speakers(&speakers) { |
| 798 | send_receive_change(control, video.reselect(&roster)); |
| 799 | } |
| 800 | control.send(CallUpdate::Speakers(speakers)); |
| 801 | } |
| 802 | Ok(CallEvent::End(end)) => { |
| 803 | replier.reply(request_id, 200, ""); |
| 804 | let kind = end.kind(); |
| 805 | report.end = Some(end); |
| 806 | advance(state, CallSignal::RemoteEnd(kind), control); |
| 807 | break; |
| 808 | } |
| 809 | Ok(_) => replier.reply(request_id, 200, ""), |
| 810 | Err(error) => { |
| 811 | replier.reply(request_id, 200, ""); |
| 812 | timeline.record("callback not understood", error.to_string()); |
| 813 | } |
| 814 | } |
| 815 | } |
| 816 | Some(event) = current.events.recv() => match event { |
| 817 | PeerEvent::Ice(ice_state) => { |
| 818 | timeline.record("ICE state", format!("{ice_state:?}")); |
| 819 | if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() { |
| 820 | report.ice_connected_ms = Some(timeline.elapsed_ms()); |
| 821 | } |
| 822 | } |
| 823 | PeerEvent::Connection(connection) => { |
| 824 | timeline.record("PeerConnection state", format!("{connection:?}")); |
| 825 | match connection { |
| 826 | PeerConnectionState::Connected => { |
| 827 | reconnect_deadline = None; |
| 828 | advance(state, CallSignal::MediaConnected, control); |
| 829 | if report.peer_connected_ms.is_none() { |
| 830 | report.peer_connected_ms = Some(timeline.elapsed_ms()); |
| 831 | if let Some(hold) = options.hold_after_connected { |
| 832 | let hold_until = Instant::now() + hold; |
| 833 | leave_at = Some(hard_deadline.map_or(hold_until, |deadline| deadline.min(hold_until))); |
| 834 | } |
| 835 | } |
| 836 | } |
| 837 | PeerConnectionState::Disconnected => { |
| 838 | if advance(state, CallSignal::MediaDisconnected, control) { |
| 839 | reconnect_deadline = Some(Instant::now() + options.reconnect_window); |
| 840 | } |
| 841 | } |
| 842 | PeerConnectionState::Failed => { |
| 843 | advance(state, CallSignal::MediaFailed, control); |
| 844 | break; |
| 845 | } |
| 846 | _ => {} |
| 847 | } |
| 848 | } |
| 849 | PeerEvent::Track(remote_track) => { |
| 850 | timeline.record("remote audio track", "receiving"); |
| 851 | remote_audio = Some(remote_track.clone()); |
| 852 | if options.record_remote { |
| 853 | tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz)); |
| 854 | } |
| 855 | } |
| 856 | PeerEvent::VideoTrack { mid, track } => { |
| 857 | timeline.record("remote video track", format!("mid {mid}")); |
| 858 | live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone())); |
| 859 | } |
| 860 | }, |
| 861 | Some(event) = next_peer_event(&mut next) => match event { |
| 862 | PeerEvent::Connection(PeerConnectionState::Connected) => { |
| 863 | if let Some(pending) = next.take() { |
| 864 | timeline.record("escalation", "new peer connection connected, old one dropped"); |
| 865 | let old = std::mem::replace(&mut current, pending.session); |
| 866 | old.peer.close(); |
| 867 | if let Some(audio) = &share_audio |
| 868 | && let Err(error) = swap_audio_track(¤t.peer, &audio.track) |
| 869 | { |
| 870 | timeline.record("computer sound not carried over", error.to_string()); |
| 871 | } |
| 872 | offered = pending.offered; |
| 873 | if let Some(media) = &offered |
| 874 | && let Err(error) = local_video.set_lines(media.video.clone()) |
| 875 | { |
| 876 | timeline.record("video lines not attached", error.to_string()); |
| 877 | } |
| 878 | remote_set = true; |
| 879 | } |
| 880 | } |
| 881 | PeerEvent::VideoTrack { mid, track } => { |
| 882 | timeline.record("remote video track", format!("mid {mid} (new peer)")); |
| 883 | live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone())); |
| 884 | } |
| 885 | PeerEvent::Connection(PeerConnectionState::Failed) => { |
| 886 | negotiator.escalation_failed(); |
| 887 | if let Some(pending) = next.take() { |
| 888 | pending.session.peer.close(); |
| 889 | } |
| 890 | timeline.record("escalation failed", "new peer connection failed, staying on the old one"); |
| 891 | } |
| 892 | _ => {} |
| 893 | }, |
| 894 | command = control.recv() => match command { |
| 895 | Some(CallCommand::Mute(mute)) => { |
| 896 | muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), share_audio.as_ref(), &remote, control); |
| 897 | } |
| 898 | Some(CallCommand::SelectInput(choice)) => { |
| 899 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 900 | timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice))); |
| 901 | } |
| 902 | input = choice; |
| 903 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 904 | } |
| 905 | Some(CallCommand::SelectOutput(choice)) => { |
| 906 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 907 | timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice))); |
| 908 | } |
| 909 | output = choice; |
| 910 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 911 | } |
| 912 | Some(CallCommand::RefreshDevices) => { |
| 913 | control.send(CallUpdate::Devices(devices::list_devices(&factory))); |
| 914 | } |
| 915 | Some(CallCommand::SetCamera(on)) => { |
| 916 | if !remote_set { |
| 917 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 918 | } else if on { |
| 919 | match local_video.start_camera(&camera_choice) { |
| 920 | Ok(()) => { |
| 921 | control.send(CallUpdate::Camera(true)); |
| 922 | tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline); |
| 923 | } |
| 924 | Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))), |
| 925 | } |
| 926 | } else { |
| 927 | local_video.stop_camera(); |
| 928 | control.send(CallUpdate::Camera(false)); |
| 929 | tell_media_descriptions(&remote, &media_links, MediaDescription::camera(false), &mut media_description_request, timeline); |
| 930 | } |
| 931 | } |
| 932 | Some(CallCommand::SelectCamera(choice)) => { |
| 933 | camera_choice = choice; |
| 934 | if local_video.camera_on() |
| 935 | && let Err(error) = local_video.start_camera(&camera_choice) |
| 936 | { |
| 937 | control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))); |
| 938 | } |
| 939 | } |
| 940 | Some(CallCommand::StartShare(source)) => { |
| 941 | if !remote_set { |
| 942 | control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into())); |
| 943 | } else { |
| 944 | match local_video.start_share(&source) { |
| 945 | Ok(()) => { |
| 946 | control.send(CallUpdate::LocalShare(Some(source.label()))); |
| 947 | tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline); |
| 948 | if share_sound_wanted && share_audio.is_none() { |
| 949 | share_audio = engage_share_sound(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, control, timeline); |
| 950 | } |
| 951 | } |
| 952 | Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))), |
| 953 | } |
| 954 | } |
| 955 | } |
| 956 | Some(CallCommand::StopShare) => { |
| 957 | if local_video.sharing() { |
| 958 | local_video.stop_share(); |
| 959 | release_share_sound(¤t.peer, &track, &mut share_audio, control, timeline); |
| 960 | control.send(CallUpdate::LocalShare(None)); |
| 961 | tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline); |
| 962 | } |
| 963 | } |
| 964 | Some(CallCommand::SetShareSound(on)) => { |
| 965 | share_sound_wanted = on; |
| 966 | if local_video.sharing() { |
| 967 | if on && share_audio.is_none() { |
| 968 | share_audio = engage_share_sound(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, control, timeline); |
| 969 | } else if !on { |
| 970 | release_share_sound(¤t.peer, &track, &mut share_audio, control, timeline); |
| 971 | } |
| 972 | } |
| 973 | } |
| 974 | Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video), |
| 975 | Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await { |
| 976 | Ok(state_id) => own_hand = state_id, |
| 977 | Err(error) => { |
| 978 | timeline.record("raise hand failed", error.to_string()); |
| 979 | control.send(CallUpdate::Notice("Could not raise your hand".into())); |
| 980 | } |
| 981 | }, |
| 982 | Some(CallCommand::SetHand(false)) => { |
| 983 | let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect(); |
| 984 | own_hand = None; |
| 985 | if !state_ids.is_empty() |
| 986 | && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await |
| 987 | { |
| 988 | timeline.record("lower hand failed", error.to_string()); |
| 989 | control.send(CallUpdate::Notice("Could not lower your hand".into())); |
| 990 | } |
| 991 | } |
| 992 | Some(CallCommand::LowerHand { mri }) => { |
| 993 | let state_ids: Vec<String> = roster.hand_of(&mri).map(|hand| hand.state_id.clone()).into_iter().collect(); |
| 994 | if !state_ids.is_empty() |
| 995 | && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await |
| 996 | { |
| 997 | timeline.record("lower hand failed", error.to_string()); |
| 998 | control.send(CallUpdate::Notice("Could not lower that hand".into())); |
| 999 | } |
| 1000 | } |
| 1001 | Some(CallCommand::LowerAllHands) => { |
| 1002 | if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await { |
| 1003 | timeline.record("lower all hands failed", error.to_string()); |
| 1004 | control.send(CallUpdate::Notice("Could not lower all hands".into())); |
| 1005 | } |
| 1006 | } |
| 1007 | Some(CallCommand::SendReaction(reaction)) => { |
| 1008 | if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await { |
| 1009 | timeline.record("reaction failed", error.to_string()); |
| 1010 | control.send(CallUpdate::Notice("Could not send the reaction".into())); |
| 1011 | } |
| 1012 | } |
| 1013 | Some(CallCommand::EndMeeting) => { |
| 1014 | if is_meeting { |
| 1015 | match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await { |
| 1016 | Ok(()) => { |
| 1017 | live.skip_leave = true; |
| 1018 | report.left_cleanly = true; |
| 1019 | } |
| 1020 | Err(error) => timeline.record("end meeting failed", error.to_string()), |
| 1021 | } |
| 1022 | } |
| 1023 | advance(state, CallSignal::LocalLeave, control); |
| 1024 | break; |
| 1025 | } |
| 1026 | Some(CallCommand::Hangup) | None => { |
| 1027 | advance(state, CallSignal::LocalLeave, control); |
| 1028 | break; |
| 1029 | } |
| 1030 | }, |
| 1031 | _ = stats_tick.tick(), if remote_set => { |
| 1032 | let snapshot = collect_stats(¤t.peer).await; |
| 1033 | ticks += 1; |
| 1034 | let local_level = if muted && share_audio.is_none() { 0.0 } else { snapshot.local_level as f32 }; |
| 1035 | control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 }); |
| 1036 | if snapshot.selected_pair.is_some() { |
| 1037 | report.selected_pair = snapshot.selected_pair.clone(); |
| 1038 | report.tls_version = snapshot.tls_version.clone(); |
| 1039 | report.dtls_cipher = snapshot.dtls_cipher.clone(); |
| 1040 | report.srtp_cipher = snapshot.srtp_cipher.clone(); |
| 1041 | } |
| 1042 | report.inbound_packets = snapshot.inbound_packets; |
| 1043 | report.inbound_bytes = snapshot.inbound_bytes; |
| 1044 | report.outbound_packets = snapshot.outbound_packets; |
| 1045 | report.video = VideoReport { |
| 1046 | frames_received: live.video_counters.received.load(Ordering::Relaxed), |
| 1047 | frames_published: live.video_counters.published.load(Ordering::Relaxed), |
| 1048 | ..snapshot.video.clone() |
| 1049 | }; |
| 1050 | if ticks.is_multiple_of(TICKS_PER_SECOND) { |
| 1051 | second += 1; |
| 1052 | let (decoded_rms, ratio) = { |
| 1053 | let recording = recording.lock().await; |
| 1054 | recording.per_second.last().copied().unwrap_or_default() |
| 1055 | }; |
| 1056 | if snapshot.inbound_packets > previous_packets { |
| 1057 | report.seconds_with_inbound_audio += 1; |
| 1058 | } |
| 1059 | previous_packets = snapshot.inbound_packets; |
| 1060 | report.seconds.push(AudioSecond { |
| 1061 | second, |
| 1062 | packets: snapshot.inbound_packets, |
| 1063 | bytes: snapshot.inbound_bytes, |
| 1064 | audio_level: snapshot.audio_level, |
| 1065 | decoded_rms, |
| 1066 | tone_ratio: ratio, |
| 1067 | }); |
| 1068 | control.send(CallUpdate::Stats { |
| 1069 | inbound_packets: snapshot.inbound_packets, |
| 1070 | outbound_packets: snapshot.outbound_packets, |
| 1071 | }); |
| 1072 | timeline.record( |
| 1073 | "stats", |
| 1074 | format!( |
| 1075 | "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)", |
| 1076 | snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state, |
| 1077 | snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height, |
| 1078 | snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height, |
| 1079 | snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms |
| 1080 | ), |
| 1081 | ); |
| 1082 | } |
| 1083 | } |
| 1084 | _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => { |
| 1085 | advance(state, CallSignal::ReconnectTimedOut, control); |
| 1086 | break; |
| 1087 | } |
| 1088 | _ = sleep_until(leave_at.unwrap_or_else(far_future)), if leave_at.is_some() => { |
| 1089 | advance(state, CallSignal::LocalLeave, control); |
| 1090 | break; |
| 1091 | } |
| 1092 | _ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => { |
| 1093 | timeline.record("no answer", "outgoing call timed out"); |
| 1094 | live.cancel_leave = true; |
| 1095 | advance(state, CallSignal::RemoteEnd(EndKind::NoAnswer), control); |
| 1096 | break; |
| 1097 | } |
| 1098 | _ = sleep_until(keep_alive_at.unwrap_or_else(far_future)), if keep_alive_at.is_some() => { |
| 1099 | keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds)); |
| 1100 | let remote = remote.clone(); |
| 1101 | let links = links.clone(); |
| 1102 | let call_leg = keep_alive_link.clone(); |
| 1103 | tokio::spawn(async move { |
| 1104 | if let Some(url) = call_leg { |
| 1105 | let _ = remote.signaling.keep_call_alive(&url).await; |
| 1106 | } |
| 1107 | let _ = remote.signaling.keep_conversation_alive(&remote.conversation, &remote.participant, &links).await; |
| 1108 | }); |
| 1109 | } |
| 1110 | } |
| 1111 | } |
| 1112 | live.callbacks = Some(callbacks); |
| 1113 | Ok(()) |
| 1114 | } |
| 1115 | |
| 1116 | #[allow(clippy::too_many_arguments)] |
| 1117 | async fn start_escalation( |
| 1118 | factory: &PeerConnectionFactory, |
| 1119 | grant: &RelayGrant, |
| 1120 | options: &CallOptions, |
| 1121 | track: &RtcAudioTrack, |
| 1122 | remote: &RemoteCall, |
| 1123 | links: &CallbackLinks, |
| 1124 | media_leg_id: &str, |
| 1125 | acceptance_links: &BTreeMap<String, String>, |
| 1126 | ) -> Result<NextPeer> { |
| 1127 | let url = acceptance_links |
| 1128 | .get("mediaRenegotiation") |
| 1129 | .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?; |
| 1130 | let session = open_peer(factory, grant, &options.relay_host)?; |
| 1131 | let media = create_offer(&session.peer, factory, track).await?; |
| 1132 | let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id); |
| 1133 | remote.signaling.post_json("POST mediaRenegotiation", url, body).await?; |
| 1134 | Ok(NextPeer { |
| 1135 | session, |
| 1136 | offered: Some(media), |
| 1137 | }) |
| 1138 | } |
| 1139 | |
| 1140 | async fn answer_on_new_peer( |
| 1141 | factory: &PeerConnectionFactory, |
| 1142 | grant: &RelayGrant, |
| 1143 | options: &CallOptions, |
| 1144 | track: &RtcAudioTrack, |
| 1145 | teams_offer: &str, |
| 1146 | ) -> Result<(PeerSession, AnsweredMedia)> { |
| 1147 | let session = open_peer(factory, grant, &options.relay_host)?; |
| 1148 | let answered = answer_offer(&session.peer, Some(track), teams_offer).await?; |
| 1149 | Ok((session, answered)) |
| 1150 | } |
| 1151 | |
| 1152 | async fn send_media_answer( |
| 1153 | remote: &RemoteCall, |
| 1154 | links: &CallbackLinks, |
| 1155 | reply_links: &BTreeMap<String, String>, |
| 1156 | answered: &AnsweredMedia, |
| 1157 | media_leg_id: &str, |
| 1158 | ) -> Result<()> { |
| 1159 | let url = reply_links |
| 1160 | .get("mediaAnswer") |
| 1161 | .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?; |
| 1162 | let body = escalation_answer_body(&remote.participant, links, &answered.answer_sdp, media_leg_id); |
| 1163 | remote.signaling.post_json("POST mediaAnswer", url, body).await |
| 1164 | } |
| 1165 | |
| 1166 | #[allow(clippy::too_many_arguments)] |
| 1167 | fn negotiate_video( |
| 1168 | video: &mut VideoReceive, |
| 1169 | signaling: &Arc<Signaling>, |
| 1170 | control: &CallControl, |
| 1171 | timeline: &Timeline, |
| 1172 | answer_sdp: &str, |
| 1173 | media: &OfferedMedia, |
| 1174 | from_mixer: bool, |
| 1175 | links: &BTreeMap<String, String>, |
| 1176 | roster: &Roster, |
| 1177 | ) { |
| 1178 | let streams = match stream_lines(answer_sdp, &media.signaled.lines) { |
| 1179 | Ok(streams) => streams, |
| 1180 | Err(error) => { |
| 1181 | timeline.record("video slots unknown", error.to_string()); |
| 1182 | return; |
| 1183 | } |
| 1184 | }; |
| 1185 | let table = SlotTable::from_streams(&streams); |
| 1186 | let link = links.get("applyChannelParameters").or_else(|| links.get("controlVideoStreaming")); |
| 1187 | timeline.record( |
| 1188 | "video slots", |
| 1189 | format!( |
| 1190 | "{} receive slot(s), screen {}, fromMixer={from_mixer}, request link {}", |
| 1191 | table.people.len(), |
| 1192 | table.screen.is_some(), |
| 1193 | link.is_some() |
| 1194 | ), |
| 1195 | ); |
| 1196 | let requester = link |
| 1197 | .filter(|_| from_mixer) |
| 1198 | .map(|url| SourceRequester::start(signaling.clone(), url.clone(), video.router().clone(), control.video.clone(), timeline.clone())); |
| 1199 | video.negotiated(table, requester); |
| 1200 | send_receive_change(control, video.reselect(roster)); |
| 1201 | } |
| 1202 | |
| 1203 | const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected"; |
| 1204 | |
| 1205 | async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> { |
| 1206 | match mode { |
| 1207 | VideoMode::Pattern => vec![CameraDevice { key: "pattern".into(), name: "Test pattern".into() }], |
| 1208 | VideoMode::Off => Vec::new(), |
| 1209 | VideoMode::Platform => tokio::task::spawn_blocking(list_cameras).await.unwrap_or_default(), |
| 1210 | } |
| 1211 | } |
| 1212 | |
| 1213 | fn refresh_share_sources(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode) { |
| 1214 | tokio::spawn(async move { |
| 1215 | let sources = match mode { |
| 1216 | VideoMode::Pattern => vec![ |
| 1217 | ShareSource { id: 1, kind: ShareKind::Screen, title: "Test screen".into() }, |
| 1218 | ShareSource { id: 2, kind: ShareKind::Window, title: "Test window".into() }, |
| 1219 | ], |
| 1220 | VideoMode::Off => Vec::new(), |
| 1221 | VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources).await.unwrap_or_default(), |
| 1222 | }; |
| 1223 | let _ = updates.send(CallUpdate::ShareSources(sources)); |
| 1224 | }); |
| 1225 | } |
| 1226 | |
| 1227 | fn tell_media_descriptions( |
| 1228 | remote: &RemoteCall, |
| 1229 | links: &BTreeMap<String, String>, |
| 1230 | description: MediaDescription, |
| 1231 | request_id: &mut u32, |
| 1232 | timeline: &Timeline, |
| 1233 | ) { |
| 1234 | let Some(url) = links.get("updateMediaDescriptions").cloned() else { |
| 1235 | timeline.record("updateMediaDescriptions skipped", "no link from the mixer"); |
| 1236 | return; |
| 1237 | }; |
| 1238 | *request_id += 1; |
| 1239 | let request_id = *request_id; |
| 1240 | let signaling = remote.signaling.clone(); |
| 1241 | let timeline = timeline.clone(); |
| 1242 | tokio::spawn(async move { |
| 1243 | let sent = format!("{} {} request {request_id}", description.mid, description.direction); |
| 1244 | if let Err(error) = signaling.update_media_descriptions(&url, &[description], request_id).await { |
| 1245 | timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}")); |
| 1246 | } |
| 1247 | }); |
| 1248 | } |
| 1249 | |
| 1250 | fn send_receive_change(control: &CallControl, change: ReceiveChange) { |
| 1251 | if let Some(sharer) = change.screen_sharer { |
| 1252 | control.send(CallUpdate::ScreenShare(sharer)); |
| 1253 | } |
| 1254 | } |
| 1255 | |
| 1256 | fn far_future() -> Instant { |
| 1257 | Instant::now() + FAR_FUTURE |
| 1258 | } |
| 1259 | |
| 1260 | fn apply_mute( |
| 1261 | command: MuteCommand, |
| 1262 | currently_muted: bool, |
| 1263 | audio: &AudioSetup, |
| 1264 | share_audio: Option<&ShareAudio>, |
| 1265 | remote: &RemoteCall, |
| 1266 | control: &CallControl, |
| 1267 | ) -> bool { |
| 1268 | let effect = MuteEffect::for_muted(command.target(currently_muted)); |
| 1269 | audio.track.set_enabled(effect.track_enabled); |
| 1270 | if let Some(share_audio) = share_audio { |
| 1271 | share_audio.set_microphone_muted(effect.muted); |
| 1272 | } |
| 1273 | control.send(CallUpdate::Muted(effect.muted)); |
| 1274 | let remote = remote.clone(); |
| 1275 | tokio::spawn(async move { |
| 1276 | let _ = remote |
| 1277 | .signaling |
| 1278 | .update_endpoint_state(&remote.conversation, &remote.participant, effect.endpoint_is_muted) |
| 1279 | .await; |
| 1280 | }); |
| 1281 | effect.muted |
| 1282 | } |
| 1283 | |
| 1284 | fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> { |
| 1285 | let sender = peer |
| 1286 | .senders() |
| 1287 | .into_iter() |
| 1288 | .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_)))) |
| 1289 | .ok_or_else(|| Error::Webrtc("no audio sender".into()))?; |
| 1290 | sender |
| 1291 | .set_track(Some(MediaStreamTrack::Audio(track.clone()))) |
| 1292 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 1293 | } |
| 1294 | |
| 1295 | #[allow(clippy::too_many_arguments)] |
| 1296 | fn engage_share_sound( |
| 1297 | factory: &PeerConnectionFactory, |
| 1298 | options: &CallOptions, |
| 1299 | input: &DeviceChoice, |
| 1300 | muted: bool, |
| 1301 | remote_audio: Option<RtcAudioTrack>, |
| 1302 | peer: &PeerConnection, |
| 1303 | control: &CallControl, |
| 1304 | timeline: &Timeline, |
| 1305 | ) -> Option<ShareAudio> { |
| 1306 | let started = ShareAudio::start(factory, options.audio, options.tone_hz, input, muted, remote_audio) |
| 1307 | .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio)); |
| 1308 | match started { |
| 1309 | Ok(audio) => { |
| 1310 | timeline.record("computer sound", format!("{:?}, own playback excluded: {}", audio.loopback, audio.loopback.excludes_own_playback())); |
| 1311 | if let Some(warning) = &audio.warning { |
| 1312 | timeline.record("computer sound warning", warning.clone()); |
| 1313 | } |
| 1314 | control.send(CallUpdate::ShareSound(true)); |
| 1315 | Some(audio) |
| 1316 | } |
| 1317 | Err(error) => { |
| 1318 | timeline.record("computer sound failed", error.to_string()); |
| 1319 | control.send(CallUpdate::Notice("Computer sound could not start, sharing without it".into())); |
| 1320 | None |
| 1321 | } |
| 1322 | } |
| 1323 | } |
| 1324 | |
| 1325 | fn release_share_sound( |
| 1326 | peer: &PeerConnection, |
| 1327 | device_track: &RtcAudioTrack, |
| 1328 | share_audio: &mut Option<ShareAudio>, |
| 1329 | control: &CallControl, |
| 1330 | timeline: &Timeline, |
| 1331 | ) { |
| 1332 | if share_audio.take().is_none() { |
| 1333 | return; |
| 1334 | } |
| 1335 | if let Err(error) = swap_audio_track(peer, device_track) { |
| 1336 | timeline.record("microphone track not restored", error.to_string()); |
| 1337 | } |
| 1338 | control.send(CallUpdate::ShareSound(false)); |
| 1339 | } |
| 1340 | |
| 1341 | async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) { |
| 1342 | if let Some(audio) = &live.audio { |
| 1343 | audio.track.set_enabled(false); |
| 1344 | } |
| 1345 | live.broker_running.store(false, Ordering::SeqCst); |
| 1346 | if !live.skip_leave |
| 1347 | && let Some(remote) = &live.remote |
| 1348 | { |
| 1349 | let reason = if cancelled { LeaveReason::Cancel } else { LeaveReason::Hangup }; |
| 1350 | match remote.signaling.leave(&remote.conversation, &remote.participant, reason).await { |
| 1351 | Ok(()) => report.left_cleanly = true, |
| 1352 | Err(error) => timeline.record("leave failed", error.to_string()), |
| 1353 | } |
| 1354 | } |
| 1355 | if report.end.is_none() |
| 1356 | && let Some(callbacks) = live.callbacks.as_mut() |
| 1357 | && live.remote.is_some() |
| 1358 | { |
| 1359 | let waited = timeout(END_CALLBACK_WAIT, async { |
| 1360 | while let Some(callback) = callbacks.recv().await { |
| 1361 | let request_id = callback.request_id; |
| 1362 | let event = handle_callback(&callback, timeline); |
| 1363 | inner.replier.reply(request_id, 200, ""); |
| 1364 | if let Ok(CallEvent::End(end)) = event { |
| 1365 | return Some(end); |
| 1366 | } |
| 1367 | } |
| 1368 | None |
| 1369 | }) |
| 1370 | .await; |
| 1371 | report.end = waited.ok().flatten(); |
| 1372 | } |
| 1373 | for peer in &live.peers { |
| 1374 | peer.close(); |
| 1375 | } |
| 1376 | if let Some(audio) = live.audio.take() { |
| 1377 | audio.stop().await; |
| 1378 | } |
| 1379 | if let Some(broker) = live.broker.take() { |
| 1380 | broker.abort(); |
| 1381 | } |
| 1382 | for task in live.video_tasks.drain(..) { |
| 1383 | task.abort(); |
| 1384 | } |
| 1385 | if let Some(route_id) = &live.route_id { |
| 1386 | inner.unregister_route(route_id); |
| 1387 | } |
| 1388 | timeline.record("closed", "peer closed, call route removed"); |
| 1389 | } |
| 1390 | |
| 1391 | fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> { |
| 1392 | let body = decode_body(callback)?; |
| 1393 | let (_, event) = classify(&callback.path, body)?; |
| 1394 | let detail = match &event { |
| 1395 | CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer), |
| 1396 | CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase), |
| 1397 | CallEvent::Progress(status) => format!("{status:?}"), |
| 1398 | _ => String::new(), |
| 1399 | }; |
| 1400 | timeline.record(format!("Trouter {}", event.name()), detail); |
| 1401 | Ok(event) |
| 1402 | } |
| 1403 | |
| 1404 | |
| 1405 | async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> { |
| 1406 | let answer = to_browser_answer(teams_answer, signaled, browser_offer)?; |
| 1407 | let description = |
| 1408 | SessionDescription::parse(&answer, SdpType::Answer).map_err(|error| Error::Sdp(error.description))?; |
| 1409 | peer.set_remote_description(description) |
| 1410 | .await |
| 1411 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 1412 | } |
| 1413 | |
| 1414 | /// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect. |
| 1415 | fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) { |
| 1416 | let Some(directory) = &options.sdp_dump_dir else { |
| 1417 | return; |
| 1418 | }; |
| 1419 | let masked: Vec<String> = sdp |
| 1420 | .lines() |
| 1421 | .map(|line| { |
| 1422 | for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:"] { |
| 1423 | if line.starts_with(prefix) { |
| 1424 | return format!("{prefix}<masked>"); |
| 1425 | } |
| 1426 | } |
| 1427 | line.split(' ').map(mask_address).collect::<Vec<_>>().join(" ") |
| 1428 | }) |
| 1429 | .collect(); |
| 1430 | let _ = std::fs::create_dir_all(directory); |
| 1431 | let _ = std::fs::write(directory.join(name), masked.join("\n")); |
| 1432 | } |
| 1433 | |
| 1434 | fn mask_address(token: &str) -> String { |
| 1435 | let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok()); |
| 1436 | let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:"); |
| 1437 | if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1") || colon_address { |
| 1438 | "<addr>".to_owned() |
| 1439 | } else { |
| 1440 | token.to_owned() |
| 1441 | } |
| 1442 | } |
| 1443 | |
| 1444 | async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, tone_hz: f32) { |
| 1445 | let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1); |
| 1446 | while let Some(frame) = stream.next().await { |
| 1447 | let mut recording = recording.lock().await; |
| 1448 | recording.samples.extend_from_slice(&frame.data); |
| 1449 | recording.current_second.extend_from_slice(&frame.data); |
| 1450 | if recording.current_second.len() >= SAMPLE_RATE as usize { |
| 1451 | let second: Vec<i16> = std::mem::take(&mut recording.current_second); |
| 1452 | let summary = (rms(&second), tone_ratio(&second, tone_hz)); |
| 1453 | recording.per_second.push(summary); |
| 1454 | } |
| 1455 | } |
| 1456 | } |
| 1457 | |
| 1458 | async fn poll_broker(signaling: Arc<Signaling>, conversation: Conversation, running: Arc<AtomicBool>) { |
| 1459 | let Ok(first) = conversation.link("subscribe") else { |
| 1460 | return; |
| 1461 | }; |
| 1462 | let mut url = first.to_owned(); |
| 1463 | while running.load(Ordering::SeqCst) { |
| 1464 | match signaling.poll_broker(&url).await { |
| 1465 | Ok(Some(next)) => url = next, |
| 1466 | Ok(None) => {} |
| 1467 | Err(_) => return, |
| 1468 | } |
| 1469 | } |
| 1470 | } |
| 1471 | |
| 1472 | #[derive(Debug, Default)] |
| 1473 | struct StatsSnapshot { |
| 1474 | inbound_packets: u64, |
| 1475 | inbound_bytes: u64, |
| 1476 | outbound_packets: u64, |
| 1477 | audio_level: f64, |
| 1478 | local_level: f64, |
| 1479 | echo_return_loss_enhancement: f64, |
| 1480 | video: VideoReport, |
| 1481 | dtls_state: String, |
| 1482 | tls_version: String, |
| 1483 | dtls_cipher: String, |
| 1484 | srtp_cipher: String, |
| 1485 | selected_pair: Option<String>, |
| 1486 | } |
| 1487 | |
| 1488 | async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot { |
| 1489 | let Ok(stats) = peer.get_stats().await else { |
| 1490 | return StatsSnapshot::default(); |
| 1491 | }; |
| 1492 | let mut snapshot = StatsSnapshot::default(); |
| 1493 | let mut selected_pair_id = None; |
| 1494 | for entry in &stats { |
| 1495 | match entry { |
| 1496 | RtcStats::InboundRtp(inbound) if inbound.stream.kind == "audio" => { |
| 1497 | snapshot.inbound_packets += inbound.received.packets_received; |
| 1498 | snapshot.inbound_bytes += inbound.inbound.bytes_received; |
| 1499 | snapshot.audio_level = snapshot.audio_level.max(inbound.inbound.audio_level); |
| 1500 | } |
| 1501 | RtcStats::MediaSource(source) if source.source.kind == "audio" => { |
| 1502 | snapshot.local_level = snapshot.local_level.max(source.audio.audio_level); |
| 1503 | snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement; |
| 1504 | } |
| 1505 | RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => { |
| 1506 | snapshot.outbound_packets += outbound.sent.packets_sent; |
| 1507 | } |
| 1508 | RtcStats::InboundRtp(inbound) if inbound.stream.kind == "video" => { |
| 1509 | snapshot.video.inbound_packets += inbound.received.packets_received; |
| 1510 | snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded); |
| 1511 | snapshot.video.inbound_width = snapshot.video.inbound_width.max(inbound.inbound.frame_width); |
| 1512 | snapshot.video.inbound_height = snapshot.video.inbound_height.max(inbound.inbound.frame_height); |
| 1513 | } |
| 1514 | RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => { |
| 1515 | snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements; |
| 1516 | snapshot.video.remote_round_trip_ms = snapshot.video.remote_round_trip_ms.max(remote.remote_inbound.round_trip_time * 1000.0); |
| 1517 | } |
| 1518 | RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => { |
| 1519 | snapshot.video.outbound_packets += outbound.sent.packets_sent; |
| 1520 | snapshot.video.outbound_frames_encoded += u64::from(outbound.outbound.frames_encoded); |
| 1521 | snapshot.video.outbound_width = snapshot.video.outbound_width.max(outbound.outbound.frame_width); |
| 1522 | snapshot.video.outbound_height = snapshot.video.outbound_height.max(outbound.outbound.frame_height); |
| 1523 | } |
| 1524 | RtcStats::Transport(transport) => { |
| 1525 | snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state); |
| 1526 | snapshot.tls_version = transport.transport.tls_version.clone(); |
| 1527 | snapshot.dtls_cipher = transport.transport.dtls_cipher.clone(); |
| 1528 | snapshot.srtp_cipher = transport.transport.srtp_cipher.clone(); |
| 1529 | if !transport.transport.selected_candidate_pair_id.is_empty() { |
| 1530 | selected_pair_id = Some(transport.transport.selected_candidate_pair_id.clone()); |
| 1531 | } |
| 1532 | } |
| 1533 | _ => {} |
| 1534 | } |
| 1535 | } |
| 1536 | if let Some(pair_id) = selected_pair_id { |
| 1537 | let pair = stats.iter().find_map(|entry| match entry { |
| 1538 | RtcStats::CandidatePair(pair) if pair.rtc.id == pair_id => Some(pair), |
| 1539 | _ => None, |
| 1540 | }); |
| 1541 | if let Some(pair) = pair { |
| 1542 | let describe = |candidate_id: &str| { |
| 1543 | stats |
| 1544 | .iter() |
| 1545 | .find_map(|entry| match entry { |
| 1546 | RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => Some(&local.local_candidate), |
| 1547 | RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => Some(&remote.remote_candidate), |
| 1548 | _ => None, |
| 1549 | }) |
| 1550 | .map(|candidate| { |
| 1551 | let kind = candidate.candidate_type.map(|kind| format!("{kind:?}")).unwrap_or_default(); |
| 1552 | let relay = candidate.relay_protocol.map(|relay| format!(" via {relay:?}")).unwrap_or_default(); |
| 1553 | format!("{kind}/{}{relay}", candidate.protocol) |
| 1554 | }) |
| 1555 | .unwrap_or_else(|| "?".into()) |
| 1556 | }; |
| 1557 | snapshot.selected_pair = Some(format!( |
| 1558 | "local {} <-> remote {}", |
| 1559 | describe(&pair.candidate_pair.local_candidate_id), |
| 1560 | describe(&pair.candidate_pair.remote_candidate_id) |
| 1561 | )); |
| 1562 | } |
| 1563 | } |
| 1564 | snapshot |
| 1565 | } |
| 1566 | |
| 1567 | #[cfg(test)] |
| 1568 | mod tests { |
| 1569 | use super::*; |
| 1570 | |
| 1571 | #[test] |
| 1572 | fn keep_alive_fires_at_ninety_percent_of_the_interval() { |
| 1573 | assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430)); |
| 1574 | assert_eq!(keep_alive_period(None), Duration::from_secs(2430)); |
| 1575 | assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54)); |
| 1576 | } |
| 1577 | |
| 1578 | #[test] |
| 1579 | fn specs_map_to_invitation_targets() { |
| 1580 | assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo); |
| 1581 | let people = CallSpec::People { |
| 1582 | callees: vec![Callee { mri: "8:orgid:b".into(), display_name: "Bea".into() }], |
| 1583 | thread_id: "19:t@thread.v2".into(), |
| 1584 | }; |
| 1585 | assert!(people.is_people() && !people.is_meeting()); |
| 1586 | assert!(matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2")); |
| 1587 | let meeting = CallSpec::Meeting(MeetingTarget { |
| 1588 | thread_id: "19:meeting@thread.v2".into(), |
| 1589 | tenant_id: "t".into(), |
| 1590 | organizer_id: "o".into(), |
| 1591 | meeting_data: None, |
| 1592 | }); |
| 1593 | assert!(meeting.is_meeting() && !meeting.is_people()); |
| 1594 | } |
| 1595 | } |