| 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::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant}; |
| 29 | use crate::renegotiation::{MediaAction, MediaNegotiator}; |
| 30 | use crate::roster::Roster; |
| 31 | use crate::sdp::{OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, to_browser_answer, to_teams_answer, to_teams_offer}; |
| 32 | use crate::signaling::{ |
| 33 | Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling, |
| 34 | TenantRouting, find_echo_bot_thread, escalation_answer_body, renegotiation_body, |
| 35 | }; |
| 36 | use crate::state::{CallSignal, CallState}; |
| 37 | use crate::timeline::{Timeline, TimelineEntry}; |
| 38 | use crate::trouter_events::{ |
| 39 | CallEnd, CallEvent, CallbackLinks, ProgressStatus, acceptance_acknowledgement, classify, decode_body, |
| 40 | }; |
| 41 | |
| 42 | const END_CALLBACK_WAIT: Duration = Duration::from_secs(4); |
| 43 | const STATS_PERIOD: Duration = Duration::from_millis(200); |
| 44 | const TICKS_PER_SECOND: u32 = 5; |
| 45 | const RECONNECT_WINDOW: Duration = Duration::from_secs(30); |
| 46 | const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90); |
| 47 | const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365); |
| 48 | const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700; |
| 49 | const MIN_KEEP_ALIVE_SECONDS: u64 = 60; |
| 50 | const KEEP_ALIVE_FRACTION: f64 = 0.9; |
| 51 | const MIC_STREAM: &str = "microphone"; |
| 52 | |
| 53 | #[derive(Debug, Clone)] |
| 54 | pub struct CallOptions { |
| 55 | pub hold_after_connected: Option<Duration>, |
| 56 | pub hard_limit: Option<Duration>, |
| 57 | pub reconnect_window: Duration, |
| 58 | pub audio: AudioMode, |
| 59 | pub tone_hz: f32, |
| 60 | pub input: DeviceChoice, |
| 61 | pub output: DeviceChoice, |
| 62 | pub relay_host: String, |
| 63 | pub routing: TenantRouting, |
| 64 | pub record_remote: bool, |
| 65 | pub wav_path: Option<PathBuf>, |
| 66 | pub sdp_dump_dir: Option<PathBuf>, |
| 67 | pub trace: bool, |
| 68 | } |
| 69 | |
| 70 | impl Default for CallOptions { |
| 71 | fn default() -> Self { |
| 72 | CallOptions { |
| 73 | hold_after_connected: None, |
| 74 | hard_limit: None, |
| 75 | reconnect_window: RECONNECT_WINDOW, |
| 76 | audio: AudioMode::from_env(), |
| 77 | tone_hz: 440.0, |
| 78 | input: DeviceChoice::SystemDefault, |
| 79 | output: DeviceChoice::SystemDefault, |
| 80 | relay_host: DEFAULT_RELAY_HOST.to_owned(), |
| 81 | routing: TenantRouting::default(), |
| 82 | record_remote: false, |
| 83 | wav_path: None, |
| 84 | sdp_dump_dir: None, |
| 85 | trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(), |
| 86 | } |
| 87 | } |
| 88 | } |
| 89 | |
| 90 | #[derive(Debug, Clone, Default)] |
| 91 | pub struct AudioSecond { |
| 92 | pub second: u32, |
| 93 | pub packets: u64, |
| 94 | pub bytes: u64, |
| 95 | pub audio_level: f64, |
| 96 | pub decoded_rms: f32, |
| 97 | pub tone_ratio: f32, |
| 98 | } |
| 99 | |
| 100 | #[derive(Debug, Clone, Default)] |
| 101 | pub struct CallReport { |
| 102 | pub timeline: Vec<TimelineEntry>, |
| 103 | pub ice_connected_ms: Option<u128>, |
| 104 | pub peer_connected_ms: Option<u128>, |
| 105 | pub selected_pair: Option<String>, |
| 106 | pub tls_version: String, |
| 107 | pub dtls_cipher: String, |
| 108 | pub srtp_cipher: String, |
| 109 | pub inbound_packets: u64, |
| 110 | pub inbound_bytes: u64, |
| 111 | pub outbound_packets: u64, |
| 112 | pub seconds_with_inbound_audio: u32, |
| 113 | pub seconds: Vec<AudioSecond>, |
| 114 | pub end: Option<CallEnd>, |
| 115 | pub left_cleanly: bool, |
| 116 | pub recorded_samples: usize, |
| 117 | } |
| 118 | |
| 119 | #[derive(Debug, Clone)] |
| 120 | pub enum CallSpec { |
| 121 | Echo, |
| 122 | People { callees: Vec<Callee>, thread_id: String }, |
| 123 | Meeting(MeetingTarget), |
| 124 | } |
| 125 | |
| 126 | impl CallSpec { |
| 127 | fn target(&self) -> InviteTarget { |
| 128 | match self { |
| 129 | CallSpec::Echo => InviteTarget::Echo, |
| 130 | CallSpec::People { callees, thread_id } => InviteTarget::People { |
| 131 | callees: callees.clone(), |
| 132 | thread_id: thread_id.clone(), |
| 133 | }, |
| 134 | CallSpec::Meeting(meeting) => InviteTarget::Meeting(meeting.clone()), |
| 135 | } |
| 136 | } |
| 137 | |
| 138 | fn is_meeting(&self) -> bool { |
| 139 | matches!(self, CallSpec::Meeting(_)) |
| 140 | } |
| 141 | |
| 142 | fn is_people(&self) -> bool { |
| 143 | matches!(self, CallSpec::People { .. }) |
| 144 | } |
| 145 | } |
| 146 | |
| 147 | pub(crate) struct IncomingCall { |
| 148 | pub notification: CallNotification, |
| 149 | pub attached: Attached, |
| 150 | pub links: CallbackLinks, |
| 151 | pub participant: Participant, |
| 152 | pub callbacks: mpsc::UnboundedReceiver<TrouterCallback>, |
| 153 | } |
| 154 | |
| 155 | pub(crate) enum Plan { |
| 156 | Outgoing(CallSpec), |
| 157 | Incoming(Box<IncomingCall>), |
| 158 | } |
| 159 | |
| 160 | pub fn keep_alive_period(seconds: Option<u64>) -> Duration { |
| 161 | let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS); |
| 162 | Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION) |
| 163 | } |
| 164 | |
| 165 | fn random_u32() -> u32 { |
| 166 | let bytes = uuid::Uuid::new_v4().into_bytes(); |
| 167 | u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff |
| 168 | } |
| 169 | |
| 170 | #[derive(Default)] |
| 171 | struct Recording { |
| 172 | samples: Vec<i16>, |
| 173 | current_second: Vec<i16>, |
| 174 | per_second: Vec<(f32, f32)>, |
| 175 | } |
| 176 | |
| 177 | enum PeerEvent { |
| 178 | Ice(IceConnectionState), |
| 179 | Connection(PeerConnectionState), |
| 180 | Track(RtcAudioTrack), |
| 181 | } |
| 182 | |
| 183 | struct PeerSession { |
| 184 | peer: PeerConnection, |
| 185 | events: mpsc::UnboundedReceiver<PeerEvent>, |
| 186 | } |
| 187 | |
| 188 | struct OfferedMedia { |
| 189 | browser_offer: String, |
| 190 | signaled: SignaledOffer, |
| 191 | } |
| 192 | |
| 193 | struct NextPeer { |
| 194 | session: PeerSession, |
| 195 | offered: Option<OfferedMedia>, |
| 196 | } |
| 197 | |
| 198 | struct AnsweredMedia { |
| 199 | remote: RemoteOffer, |
| 200 | answer_sdp: String, |
| 201 | } |
| 202 | |
| 203 | #[derive(Clone)] |
| 204 | struct RemoteCall { |
| 205 | signaling: Arc<Signaling>, |
| 206 | conversation: Conversation, |
| 207 | participant: Participant, |
| 208 | } |
| 209 | |
| 210 | #[derive(Default)] |
| 211 | struct Live { |
| 212 | peers: Vec<PeerConnection>, |
| 213 | audio: Option<AudioSetup>, |
| 214 | remote: Option<RemoteCall>, |
| 215 | broker: Option<JoinHandle<()>>, |
| 216 | broker_running: Arc<AtomicBool>, |
| 217 | callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>, |
| 218 | route_id: Option<String>, |
| 219 | skip_leave: bool, |
| 220 | cancel_leave: bool, |
| 221 | } |
| 222 | |
| 223 | fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool { |
| 224 | let next = state.next(signal, std::time::Instant::now()); |
| 225 | if next == *state { |
| 226 | return false; |
| 227 | } |
| 228 | *state = next.clone(); |
| 229 | control.send(CallUpdate::State(next)); |
| 230 | true |
| 231 | } |
| 232 | |
| 233 | /// Places the Echo test call on its own non-ringable Trouter instance; the app uses a shared engine instead. |
| 234 | pub async fn run_test_call( |
| 235 | session: &Session, |
| 236 | poll_session: &Session, |
| 237 | options: CallOptions, |
| 238 | control: CallControl, |
| 239 | ) -> Result<CallReport> { |
| 240 | let config = EngineConfig { |
| 241 | ringable: false, |
| 242 | routing: options.routing.clone(), |
| 243 | relay_host: options.relay_host.clone(), |
| 244 | trace: options.trace, |
| 245 | instance: chatsvc::InstanceNames { |
| 246 | global: "__testCallTrouter".into(), |
| 247 | binding: "__testCallRealtime".into(), |
| 248 | endpoint_storage_key: "__testCallEpid".into(), |
| 249 | }, |
| 250 | }; |
| 251 | let (engine, _events) = CallEngine::start(session.clone(), poll_session.clone(), config).await?; |
| 252 | let report = engine.run(Plan::Outgoing(CallSpec::Echo), options, control).await; |
| 253 | engine.stop().await; |
| 254 | report |
| 255 | } |
| 256 | |
| 257 | impl CallEngine { |
| 258 | pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> { |
| 259 | let inner = self.inner.as_ref(); |
| 260 | let _one_call_at_a_time = inner.gate.lock().await; |
| 261 | let timeline = Timeline::new(options.trace); |
| 262 | let mut report = CallReport::default(); |
| 263 | let mut state = CallState::Idle; |
| 264 | advance(&mut state, CallSignal::Dial, &control); |
| 265 | let mut live = Live::default(); |
| 266 | let recording = Arc::new(Mutex::new(Recording::default())); |
| 267 | let outcome = drive( |
| 268 | inner, |
| 269 | &options, |
| 270 | &timeline, |
| 271 | &recording, |
| 272 | plan, |
| 273 | &mut live, |
| 274 | &mut control, |
| 275 | &mut state, |
| 276 | &mut report, |
| 277 | ) |
| 278 | .await; |
| 279 | let failure = match outcome { |
| 280 | Ok(()) => None, |
| 281 | Err(Error::Cancelled) => { |
| 282 | advance(&mut state, CallSignal::LocalLeave, &control); |
| 283 | None |
| 284 | } |
| 285 | Err(error) => { |
| 286 | advance(&mut state, CallSignal::Error(error.to_string()), &control); |
| 287 | Some(error) |
| 288 | } |
| 289 | }; |
| 290 | let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled }); |
| 291 | tear_down(live, inner, &timeline, &mut report, cancelled).await; |
| 292 | let recording = recording.lock().await; |
| 293 | report.recorded_samples = recording.samples.len(); |
| 294 | if let Some(path) = &options.wav_path { |
| 295 | write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?; |
| 296 | } |
| 297 | report.timeline = timeline.entries(); |
| 298 | match failure { |
| 299 | Some(error) => Err(error), |
| 300 | None => Ok(report), |
| 301 | } |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str) -> Result<PeerSession> { |
| 306 | let mut configuration = RtcConfiguration::default(); |
| 307 | configuration.ice_servers = vec![grant.ice_server(relay_host)]; |
| 308 | let peer = factory |
| 309 | .create_peer_connection(configuration) |
| 310 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 311 | let (sender, events) = mpsc::unbounded_channel(); |
| 312 | let ice_sender = sender.clone(); |
| 313 | peer.on_ice_connection_state_change(Some(Box::new(move |state| { |
| 314 | let _ = ice_sender.send(PeerEvent::Ice(state)); |
| 315 | }))); |
| 316 | let connection_sender = sender.clone(); |
| 317 | peer.on_connection_state_change(Some(Box::new(move |state| { |
| 318 | let _ = connection_sender.send(PeerEvent::Connection(state)); |
| 319 | }))); |
| 320 | peer.on_track(Some(Box::new(move |event| { |
| 321 | if let MediaStreamTrack::Audio(track) = event.track { |
| 322 | let _ = sender.send(PeerEvent::Track(track)); |
| 323 | } |
| 324 | }))); |
| 325 | Ok(PeerSession { peer, events }) |
| 326 | } |
| 327 | |
| 328 | async fn create_offer(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<OfferedMedia> { |
| 329 | let transceiver_init = RtpTransceiverInit { |
| 330 | direction: RtpTransceiverDirection::SendRecv, |
| 331 | stream_ids: vec![MIC_STREAM.into()], |
| 332 | send_encodings: Vec::new(), |
| 333 | }; |
| 334 | peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init) |
| 335 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 336 | let offer = peer |
| 337 | .create_offer(OfferOptions { |
| 338 | offer_to_receive_audio: true, |
| 339 | ..OfferOptions::default() |
| 340 | }) |
| 341 | .await |
| 342 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 343 | peer.set_local_description(offer.clone()) |
| 344 | .await |
| 345 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 346 | let browser_offer = offer.to_string(); |
| 347 | let mut numbers = random_u32; |
| 348 | let signaled = to_teams_offer(&browser_offer, &OfferPlan::default(), &mut numbers)?; |
| 349 | Ok(OfferedMedia { browser_offer, signaled }) |
| 350 | } |
| 351 | |
| 352 | /// Video lines of a Teams offer are stopped so the answer rejects them; audio is all this client does. |
| 353 | async fn answer_offer( |
| 354 | peer: &PeerConnection, |
| 355 | track: Option<&RtcAudioTrack>, |
| 356 | teams_offer: &str, |
| 357 | ) -> Result<AnsweredMedia> { |
| 358 | let remote = from_teams_offer(teams_offer)?; |
| 359 | let description = |
| 360 | SessionDescription::parse(&remote.browser_sdp, SdpType::Offer).map_err(|error| Error::Sdp(error.description))?; |
| 361 | peer.set_remote_description(description) |
| 362 | .await |
| 363 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 364 | for transceiver in peer.transceivers() { |
| 365 | if matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_))) { |
| 366 | let _ = transceiver.stop(); |
| 367 | } |
| 368 | } |
| 369 | if let Some(track) = track { |
| 370 | peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM]) |
| 371 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 372 | } |
| 373 | let answer = peer |
| 374 | .create_answer(AnswerOptions::default()) |
| 375 | .await |
| 376 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 377 | peer.set_local_description(answer.clone()) |
| 378 | .await |
| 379 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 380 | let mut numbers = random_u32; |
| 381 | let signaled = to_teams_answer(&answer.to_string(), &remote, &mut numbers)?; |
| 382 | Ok(AnsweredMedia { |
| 383 | remote, |
| 384 | answer_sdp: signaled.sdp, |
| 385 | }) |
| 386 | } |
| 387 | |
| 388 | fn new_media_leg_id() -> String { |
| 389 | uuid::Uuid::new_v4().simple().to_string().to_uppercase() |
| 390 | } |
| 391 | |
| 392 | async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> { |
| 393 | match next { |
| 394 | Some(next) => next.session.events.recv().await, |
| 395 | None => std::future::pending().await, |
| 396 | } |
| 397 | } |
| 398 | |
| 399 | #[allow(clippy::too_many_arguments)] |
| 400 | async fn drive( |
| 401 | inner: &Inner, |
| 402 | options: &CallOptions, |
| 403 | timeline: &Timeline, |
| 404 | recording: &Arc<Mutex<Recording>>, |
| 405 | plan: Plan, |
| 406 | live: &mut Live, |
| 407 | control: &mut CallControl, |
| 408 | state: &mut CallState, |
| 409 | report: &mut CallReport, |
| 410 | ) -> Result<()> { |
| 411 | let own_mri = format!("8:orgid:{}", inner.identity.object_id); |
| 412 | control.send(CallUpdate::OwnIdentity { mri: own_mri.clone() }); |
| 413 | let (spec, incoming) = match plan { |
| 414 | Plan::Outgoing(spec) => (Some(spec), None), |
| 415 | Plan::Incoming(incoming) => (None, Some(*incoming)), |
| 416 | }; |
| 417 | let (links, participant, mut callbacks, incoming_media) = match incoming { |
| 418 | Some(IncomingCall { |
| 419 | notification, |
| 420 | attached, |
| 421 | links, |
| 422 | participant, |
| 423 | callbacks, |
| 424 | }) => (links, participant, callbacks, Some((notification, attached))), |
| 425 | None => { |
| 426 | let links = inner.callback_links(); |
| 427 | let participant = inner.participant(&uuid::Uuid::new_v4().to_string()); |
| 428 | let callbacks = inner.register_route(links.call_id()); |
| 429 | (links, participant, callbacks, None) |
| 430 | } |
| 431 | }; |
| 432 | live.route_id = Some(links.call_id().to_owned()); |
| 433 | timeline.record("Trouter connected", "callback socket ready"); |
| 434 | |
| 435 | let thread_id = if matches!(spec, Some(CallSpec::Echo)) { |
| 436 | let thread_id = control |
| 437 | .until_hangup(find_echo_bot_thread(&inner.session, &inner.identity.object_id)) |
| 438 | .await??; |
| 439 | timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" }); |
| 440 | thread_id |
| 441 | } else { |
| 442 | None |
| 443 | }; |
| 444 | let grant = control.until_hangup(fetch_relay_grant(&inner.session)).await??; |
| 445 | timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds)); |
| 446 | |
| 447 | let factory = devices::shared_factory(); |
| 448 | let mut input = options.input.clone(); |
| 449 | let mut output = options.output.clone(); |
| 450 | let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output); |
| 451 | control.send(CallUpdate::ListenOnly(audio.listen_only)); |
| 452 | control.send(CallUpdate::Devices(devices::list_devices(&factory))); |
| 453 | control.send(CallUpdate::Selected { |
| 454 | input: input.clone(), |
| 455 | output: output.clone(), |
| 456 | }); |
| 457 | let track = audio.track.clone(); |
| 458 | live.audio = Some(audio); |
| 459 | |
| 460 | let mut current = open_peer(&factory, &grant, &options.relay_host)?; |
| 461 | live.peers.push(current.peer.clone()); |
| 462 | |
| 463 | let signaling = Arc::new(inner.signaling(timeline.clone())); |
| 464 | let media_leg_id = new_media_leg_id(); |
| 465 | let call_started = Instant::now(); |
| 466 | let mut offered: Option<OfferedMedia> = None; |
| 467 | let mut negotiator = MediaNegotiator::default(); |
| 468 | let mut remote_set = false; |
| 469 | let mut keep_alive_link: Option<String> = None; |
| 470 | let mut keep_alive_seconds: Option<u64> = None; |
| 471 | let mut keep_alive_at: Option<Instant> = None; |
| 472 | let mut outgoing_deadline: Option<Instant> = None; |
| 473 | let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting); |
| 474 | let is_echo = matches!(spec, Some(CallSpec::Echo)); |
| 475 | |
| 476 | let conversation = match (spec, incoming_media) { |
| 477 | (Some(spec), None) => { |
| 478 | let media = create_offer(¤t.peer, &track).await?; |
| 479 | timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len())); |
| 480 | dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer); |
| 481 | dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp); |
| 482 | let target = spec.target(); |
| 483 | let invitation = Invitation { |
| 484 | from: &participant, |
| 485 | offer_sdp: &media.signaled.sdp, |
| 486 | media_leg_id: &media_leg_id, |
| 487 | callbacks: &links, |
| 488 | target: &target, |
| 489 | }; |
| 490 | let conversation = match &target { |
| 491 | InviteTarget::Meeting(meeting) => { |
| 492 | let subscribed = control |
| 493 | .until_hangup(signaling.subscribe_meeting(&participant, &links, meeting)) |
| 494 | .await??; |
| 495 | signaling.join_meeting(&subscribed, &invitation).await? |
| 496 | } |
| 497 | _ => signaling.create_conversation(&invitation).await?, |
| 498 | }; |
| 499 | if spec.is_people() { |
| 500 | control.send(CallUpdate::Progress(Progress::Calling)); |
| 501 | outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT); |
| 502 | } |
| 503 | offered = Some(media); |
| 504 | live.remote = Some(RemoteCall { |
| 505 | signaling: signaling.clone(), |
| 506 | conversation: conversation.clone(), |
| 507 | participant: participant.clone(), |
| 508 | }); |
| 509 | conversation |
| 510 | } |
| 511 | (None, Some((_notification, attached))) => { |
| 512 | let teams_offer = attached |
| 513 | .offer_sdp |
| 514 | .clone() |
| 515 | .ok_or_else(|| Error::Signaling("attach answer without an offer".into()))?; |
| 516 | let conversation = attached |
| 517 | .conversation |
| 518 | .clone() |
| 519 | .ok_or_else(|| Error::Signaling("attach answer without a conversation".into()))?; |
| 520 | live.remote = Some(RemoteCall { |
| 521 | signaling: signaling.clone(), |
| 522 | conversation: conversation.clone(), |
| 523 | participant: participant.clone(), |
| 524 | }); |
| 525 | let answered = answer_offer(¤t.peer, Some(&track), &teams_offer).await?; |
| 526 | timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len())); |
| 527 | dump_sdp(options, "3-teams-offer.sdp", &teams_offer); |
| 528 | dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp); |
| 529 | let acceptance_url = attached |
| 530 | .links |
| 531 | .get("acceptance") |
| 532 | .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?; |
| 533 | let modalities = vec!["Audio".to_owned()]; |
| 534 | signaling |
| 535 | .accept( |
| 536 | acceptance_url, |
| 537 | &Answer { |
| 538 | from: &participant, |
| 539 | answer_sdp: &answered.answer_sdp, |
| 540 | media_leg_id: &media_leg_id, |
| 541 | callbacks: &links, |
| 542 | modalities: &modalities, |
| 543 | }, |
| 544 | ) |
| 545 | .await?; |
| 546 | negotiator.answered_incoming(attached.from_mixer); |
| 547 | remote_set = true; |
| 548 | keep_alive_link = attached.links.get("callLeg").cloned(); |
| 549 | keep_alive_at = Some(Instant::now() + keep_alive_period(None)); |
| 550 | conversation |
| 551 | } |
| 552 | _ => return Err(Error::Callback("call plan without an offer or an invitation".into())), |
| 553 | }; |
| 554 | let remote = live.remote.clone().expect("remote call set above"); |
| 555 | live.broker_running.store(true, Ordering::SeqCst); |
| 556 | live.broker = Some(tokio::spawn(poll_broker( |
| 557 | signaling.clone(), |
| 558 | conversation.clone(), |
| 559 | live.broker_running.clone(), |
| 560 | ))); |
| 561 | |
| 562 | let initial = MuteEffect::initial(is_meeting); |
| 563 | let mut muted = initial.muted; |
| 564 | live.audio.as_ref().expect("audio set above").track.set_enabled(initial.track_enabled); |
| 565 | if muted { |
| 566 | control.send(CallUpdate::Muted(true)); |
| 567 | } |
| 568 | if let Err(error) = signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted).await { |
| 569 | timeline.record("updateEndpointState failed", error.to_string()); |
| 570 | } |
| 571 | |
| 572 | let replier = inner.replier.clone(); |
| 573 | let mut stats_tick = interval(STATS_PERIOD); |
| 574 | let hard_deadline = options.hard_limit.map(|limit| call_started + limit); |
| 575 | let mut leave_at = hard_deadline; |
| 576 | let mut reconnect_deadline: Option<Instant> = None; |
| 577 | let mut next: Option<NextPeer> = None; |
| 578 | let mut roster = Roster::default(); |
| 579 | let mut lobby = false; |
| 580 | let mut previous_packets = 0u64; |
| 581 | let mut ticks = 0u32; |
| 582 | let mut second = 0u32; |
| 583 | let echo_thread = thread_id; |
| 584 | loop { |
| 585 | tokio::select! { |
| 586 | Some(callback) = callbacks.recv() => { |
| 587 | let request_id = callback.request_id; |
| 588 | match handle_callback(&callback, timeline) { |
| 589 | Ok(CallEvent::Acceptance(acceptance)) => { |
| 590 | replier.reply(request_id, 200, acceptance_acknowledgement(&links).to_string()); |
| 591 | match negotiator.on_acceptance(acceptance.from_mixer) { |
| 592 | MediaAction::ApplyAnswer => { |
| 593 | let Some(media) = offered.as_ref() else { continue }; |
| 594 | dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp); |
| 595 | if let Ok(answer) = to_browser_answer(&acceptance.sdp, &media.signaled, &media.browser_offer) { |
| 596 | dump_sdp(options, "4-browser-answer.sdp", &answer); |
| 597 | } |
| 598 | apply_answer(¤t.peer, &acceptance.sdp, &media.signaled, &media.browser_offer) |
| 599 | .await |
| 600 | .inspect_err(|error| timeline.record("answer rejected", error.to_string()))?; |
| 601 | remote_set = true; |
| 602 | outgoing_deadline = None; |
| 603 | let directions: Vec<String> = current |
| 604 | .peer |
| 605 | .transceivers() |
| 606 | .iter() |
| 607 | .map(|transceiver| format!("{:?}", transceiver.current_direction())) |
| 608 | .collect(); |
| 609 | timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(","))); |
| 610 | if acceptance.in_lobby() { |
| 611 | lobby = true; |
| 612 | control.send(CallUpdate::Lobby(true)); |
| 613 | } |
| 614 | keep_alive_link = acceptance.links.get("callLeg").cloned(); |
| 615 | keep_alive_seconds = acceptance.keep_alive_seconds; |
| 616 | keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds)); |
| 617 | let remote = remote.clone(); |
| 618 | let links = links.clone(); |
| 619 | let thread_id = echo_thread.clone(); |
| 620 | tokio::spawn(async move { |
| 621 | if is_echo { |
| 622 | let _ = remote.signaling.add_echo_bot(&remote.conversation, &remote.participant, thread_id.as_deref(), &links).await; |
| 623 | } |
| 624 | let _ = remote.signaling.update_endpoint_metadata(&remote.conversation, &remote.participant).await; |
| 625 | }); |
| 626 | } |
| 627 | MediaAction::Escalate => { |
| 628 | match start_escalation(&factory, &grant, options, &track, &remote, &links, &media_leg_id, &acceptance.links).await { |
| 629 | Ok(pending) => { |
| 630 | timeline.record("escalation", "new peer connection, new offer sent"); |
| 631 | live.peers.push(pending.session.peer.clone()); |
| 632 | next = Some(pending); |
| 633 | } |
| 634 | Err(error) => { |
| 635 | negotiator.escalation_failed(); |
| 636 | timeline.record("escalation failed", error.to_string()); |
| 637 | } |
| 638 | } |
| 639 | } |
| 640 | _ => {} |
| 641 | } |
| 642 | } |
| 643 | Ok(CallEvent::MediaAnswer(answer)) => { |
| 644 | replier.reply(request_id, 200, ""); |
| 645 | if negotiator.on_media_answer() == MediaAction::ApplyOnNewPeer { |
| 646 | let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) { |
| 647 | Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await, |
| 648 | None => Err(Error::Webrtc("no pending peer connection for the answer".into())), |
| 649 | }; |
| 650 | match applied { |
| 651 | Ok(()) => { |
| 652 | if let Some(url) = answer.links.get("mediaAcknowledgement") { |
| 653 | let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await; |
| 654 | } |
| 655 | } |
| 656 | Err(error) => { |
| 657 | negotiator.escalation_failed(); |
| 658 | next = None; |
| 659 | timeline.record("escalation answer rejected", error.to_string()); |
| 660 | } |
| 661 | } |
| 662 | } |
| 663 | } |
| 664 | Ok(CallEvent::MediaRenegotiation(renegotiation)) => { |
| 665 | replier.reply(request_id, 200, ""); |
| 666 | let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation); |
| 667 | let result = match action { |
| 668 | MediaAction::AnswerOnNewPeer => { |
| 669 | match answer_on_new_peer(&factory, &grant, options, &track, &renegotiation.sdp).await { |
| 670 | Ok((session, answered)) => { |
| 671 | live.peers.push(session.peer.clone()); |
| 672 | let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await; |
| 673 | next = Some(NextPeer { session, offered: None }); |
| 674 | sent |
| 675 | } |
| 676 | Err(error) => Err(error), |
| 677 | } |
| 678 | } |
| 679 | MediaAction::AnswerOnSamePeer => { |
| 680 | match answer_offer(¤t.peer, None, &renegotiation.sdp).await { |
| 681 | Ok(answered) => send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await, |
| 682 | Err(error) => Err(error), |
| 683 | } |
| 684 | } |
| 685 | _ => Ok(()), |
| 686 | }; |
| 687 | if let Err(error) = result { |
| 688 | timeline.record("renegotiation failed", error.to_string()); |
| 689 | } |
| 690 | } |
| 691 | Ok(CallEvent::RosterUpdate(body)) => { |
| 692 | replier.reply(request_id, 200, ""); |
| 693 | if roster.apply(&body) { |
| 694 | let entries = roster.entries(); |
| 695 | timeline.record("roster", format!("{} participant(s)", entries.len())); |
| 696 | control.send(CallUpdate::Roster(entries)); |
| 697 | if let Some(in_lobby) = roster.is_in_lobby(&own_mri) |
| 698 | && in_lobby != lobby |
| 699 | { |
| 700 | lobby = in_lobby; |
| 701 | control.send(CallUpdate::Lobby(lobby)); |
| 702 | } |
| 703 | } |
| 704 | } |
| 705 | Ok(CallEvent::Progress(status)) => { |
| 706 | replier.reply(request_id, 200, ""); |
| 707 | if status == ProgressStatus::Ringing { |
| 708 | control.send(CallUpdate::Progress(Progress::Ringing)); |
| 709 | } |
| 710 | } |
| 711 | Ok(CallEvent::Speakers(sources)) => { |
| 712 | replier.reply(request_id, 200, ""); |
| 713 | control.send(CallUpdate::Speakers(roster.mris_for_sources(&sources))); |
| 714 | } |
| 715 | Ok(CallEvent::End(end)) => { |
| 716 | replier.reply(request_id, 200, ""); |
| 717 | let kind = end.kind(); |
| 718 | report.end = Some(end); |
| 719 | advance(state, CallSignal::RemoteEnd(kind), control); |
| 720 | break; |
| 721 | } |
| 722 | Ok(_) => replier.reply(request_id, 200, ""), |
| 723 | Err(error) => { |
| 724 | replier.reply(request_id, 200, ""); |
| 725 | timeline.record("callback not understood", error.to_string()); |
| 726 | } |
| 727 | } |
| 728 | } |
| 729 | Some(event) = current.events.recv() => match event { |
| 730 | PeerEvent::Ice(ice_state) => { |
| 731 | timeline.record("ICE state", format!("{ice_state:?}")); |
| 732 | if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() { |
| 733 | report.ice_connected_ms = Some(timeline.elapsed_ms()); |
| 734 | } |
| 735 | } |
| 736 | PeerEvent::Connection(connection) => { |
| 737 | timeline.record("PeerConnection state", format!("{connection:?}")); |
| 738 | match connection { |
| 739 | PeerConnectionState::Connected => { |
| 740 | reconnect_deadline = None; |
| 741 | advance(state, CallSignal::MediaConnected, control); |
| 742 | if report.peer_connected_ms.is_none() { |
| 743 | report.peer_connected_ms = Some(timeline.elapsed_ms()); |
| 744 | if let Some(hold) = options.hold_after_connected { |
| 745 | let hold_until = Instant::now() + hold; |
| 746 | leave_at = Some(hard_deadline.map_or(hold_until, |deadline| deadline.min(hold_until))); |
| 747 | } |
| 748 | } |
| 749 | } |
| 750 | PeerConnectionState::Disconnected => { |
| 751 | if advance(state, CallSignal::MediaDisconnected, control) { |
| 752 | reconnect_deadline = Some(Instant::now() + options.reconnect_window); |
| 753 | } |
| 754 | } |
| 755 | PeerConnectionState::Failed => { |
| 756 | advance(state, CallSignal::MediaFailed, control); |
| 757 | break; |
| 758 | } |
| 759 | _ => {} |
| 760 | } |
| 761 | } |
| 762 | PeerEvent::Track(remote_track) => { |
| 763 | timeline.record("remote audio track", "receiving"); |
| 764 | if options.record_remote { |
| 765 | tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz)); |
| 766 | } |
| 767 | } |
| 768 | }, |
| 769 | Some(event) = next_peer_event(&mut next) => match event { |
| 770 | PeerEvent::Connection(PeerConnectionState::Connected) => { |
| 771 | if let Some(pending) = next.take() { |
| 772 | timeline.record("escalation", "new peer connection connected, old one dropped"); |
| 773 | let old = std::mem::replace(&mut current, pending.session); |
| 774 | old.peer.close(); |
| 775 | offered = pending.offered; |
| 776 | remote_set = true; |
| 777 | } |
| 778 | } |
| 779 | PeerEvent::Connection(PeerConnectionState::Failed) => { |
| 780 | negotiator.escalation_failed(); |
| 781 | if let Some(pending) = next.take() { |
| 782 | pending.session.peer.close(); |
| 783 | } |
| 784 | timeline.record("escalation failed", "new peer connection failed, staying on the old one"); |
| 785 | } |
| 786 | _ => {} |
| 787 | }, |
| 788 | command = control.recv() => match command { |
| 789 | Some(CallCommand::Mute(mute)) => { |
| 790 | muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), &remote, control); |
| 791 | } |
| 792 | Some(CallCommand::SelectInput(choice)) => { |
| 793 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 794 | timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice))); |
| 795 | } |
| 796 | input = choice; |
| 797 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 798 | } |
| 799 | Some(CallCommand::SelectOutput(choice)) => { |
| 800 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 801 | timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice))); |
| 802 | } |
| 803 | output = choice; |
| 804 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 805 | } |
| 806 | Some(CallCommand::RefreshDevices) => { |
| 807 | control.send(CallUpdate::Devices(devices::list_devices(&factory))); |
| 808 | } |
| 809 | Some(CallCommand::EndMeeting) => { |
| 810 | if is_meeting { |
| 811 | match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await { |
| 812 | Ok(()) => { |
| 813 | live.skip_leave = true; |
| 814 | report.left_cleanly = true; |
| 815 | } |
| 816 | Err(error) => timeline.record("end meeting failed", error.to_string()), |
| 817 | } |
| 818 | } |
| 819 | advance(state, CallSignal::LocalLeave, control); |
| 820 | break; |
| 821 | } |
| 822 | Some(CallCommand::Hangup) | None => { |
| 823 | advance(state, CallSignal::LocalLeave, control); |
| 824 | break; |
| 825 | } |
| 826 | }, |
| 827 | _ = stats_tick.tick(), if remote_set => { |
| 828 | let snapshot = collect_stats(¤t.peer).await; |
| 829 | ticks += 1; |
| 830 | let local_level = if muted { 0.0 } else { snapshot.local_level as f32 }; |
| 831 | control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 }); |
| 832 | if snapshot.selected_pair.is_some() { |
| 833 | report.selected_pair = snapshot.selected_pair.clone(); |
| 834 | report.tls_version = snapshot.tls_version.clone(); |
| 835 | report.dtls_cipher = snapshot.dtls_cipher.clone(); |
| 836 | report.srtp_cipher = snapshot.srtp_cipher.clone(); |
| 837 | } |
| 838 | report.inbound_packets = snapshot.inbound_packets; |
| 839 | report.inbound_bytes = snapshot.inbound_bytes; |
| 840 | report.outbound_packets = snapshot.outbound_packets; |
| 841 | if ticks.is_multiple_of(TICKS_PER_SECOND) { |
| 842 | second += 1; |
| 843 | let (decoded_rms, ratio) = { |
| 844 | let recording = recording.lock().await; |
| 845 | recording.per_second.last().copied().unwrap_or_default() |
| 846 | }; |
| 847 | if snapshot.inbound_packets > previous_packets { |
| 848 | report.seconds_with_inbound_audio += 1; |
| 849 | } |
| 850 | previous_packets = snapshot.inbound_packets; |
| 851 | report.seconds.push(AudioSecond { |
| 852 | second, |
| 853 | packets: snapshot.inbound_packets, |
| 854 | bytes: snapshot.inbound_bytes, |
| 855 | audio_level: snapshot.audio_level, |
| 856 | decoded_rms, |
| 857 | tone_ratio: ratio, |
| 858 | }); |
| 859 | control.send(CallUpdate::Stats { |
| 860 | inbound_packets: snapshot.inbound_packets, |
| 861 | outbound_packets: snapshot.outbound_packets, |
| 862 | }); |
| 863 | timeline.record( |
| 864 | "stats", |
| 865 | format!( |
| 866 | "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={}", |
| 867 | snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state |
| 868 | ), |
| 869 | ); |
| 870 | } |
| 871 | } |
| 872 | _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => { |
| 873 | advance(state, CallSignal::ReconnectTimedOut, control); |
| 874 | break; |
| 875 | } |
| 876 | _ = sleep_until(leave_at.unwrap_or_else(far_future)), if leave_at.is_some() => { |
| 877 | advance(state, CallSignal::LocalLeave, control); |
| 878 | break; |
| 879 | } |
| 880 | _ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => { |
| 881 | timeline.record("no answer", "outgoing call timed out"); |
| 882 | live.cancel_leave = true; |
| 883 | advance(state, CallSignal::RemoteEnd(EndKind::NoAnswer), control); |
| 884 | break; |
| 885 | } |
| 886 | _ = sleep_until(keep_alive_at.unwrap_or_else(far_future)), if keep_alive_at.is_some() => { |
| 887 | keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds)); |
| 888 | let remote = remote.clone(); |
| 889 | let links = links.clone(); |
| 890 | let call_leg = keep_alive_link.clone(); |
| 891 | tokio::spawn(async move { |
| 892 | if let Some(url) = call_leg { |
| 893 | let _ = remote.signaling.keep_call_alive(&url).await; |
| 894 | } |
| 895 | let _ = remote.signaling.keep_conversation_alive(&remote.conversation, &remote.participant, &links).await; |
| 896 | }); |
| 897 | } |
| 898 | } |
| 899 | } |
| 900 | live.callbacks = Some(callbacks); |
| 901 | Ok(()) |
| 902 | } |
| 903 | |
| 904 | #[allow(clippy::too_many_arguments)] |
| 905 | async fn start_escalation( |
| 906 | factory: &PeerConnectionFactory, |
| 907 | grant: &RelayGrant, |
| 908 | options: &CallOptions, |
| 909 | track: &RtcAudioTrack, |
| 910 | remote: &RemoteCall, |
| 911 | links: &CallbackLinks, |
| 912 | media_leg_id: &str, |
| 913 | acceptance_links: &BTreeMap<String, String>, |
| 914 | ) -> Result<NextPeer> { |
| 915 | let url = acceptance_links |
| 916 | .get("mediaRenegotiation") |
| 917 | .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?; |
| 918 | let session = open_peer(factory, grant, &options.relay_host)?; |
| 919 | let media = create_offer(&session.peer, track).await?; |
| 920 | let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id); |
| 921 | remote.signaling.post_json("POST mediaRenegotiation", url, body).await?; |
| 922 | Ok(NextPeer { |
| 923 | session, |
| 924 | offered: Some(media), |
| 925 | }) |
| 926 | } |
| 927 | |
| 928 | async fn answer_on_new_peer( |
| 929 | factory: &PeerConnectionFactory, |
| 930 | grant: &RelayGrant, |
| 931 | options: &CallOptions, |
| 932 | track: &RtcAudioTrack, |
| 933 | teams_offer: &str, |
| 934 | ) -> Result<(PeerSession, AnsweredMedia)> { |
| 935 | let session = open_peer(factory, grant, &options.relay_host)?; |
| 936 | let answered = answer_offer(&session.peer, Some(track), teams_offer).await?; |
| 937 | Ok((session, answered)) |
| 938 | } |
| 939 | |
| 940 | async fn send_media_answer( |
| 941 | remote: &RemoteCall, |
| 942 | links: &CallbackLinks, |
| 943 | reply_links: &BTreeMap<String, String>, |
| 944 | answered: &AnsweredMedia, |
| 945 | media_leg_id: &str, |
| 946 | ) -> Result<()> { |
| 947 | let url = reply_links |
| 948 | .get("mediaAnswer") |
| 949 | .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?; |
| 950 | let body = escalation_answer_body(&remote.participant, links, &answered.answer_sdp, media_leg_id); |
| 951 | remote.signaling.post_json("POST mediaAnswer", url, body).await |
| 952 | } |
| 953 | |
| 954 | fn far_future() -> Instant { |
| 955 | Instant::now() + FAR_FUTURE |
| 956 | } |
| 957 | |
| 958 | fn apply_mute(command: MuteCommand, currently_muted: bool, audio: &AudioSetup, remote: &RemoteCall, control: &CallControl) -> bool { |
| 959 | let effect = MuteEffect::for_muted(command.target(currently_muted)); |
| 960 | audio.track.set_enabled(effect.track_enabled); |
| 961 | control.send(CallUpdate::Muted(effect.muted)); |
| 962 | let remote = remote.clone(); |
| 963 | tokio::spawn(async move { |
| 964 | let _ = remote |
| 965 | .signaling |
| 966 | .update_endpoint_state(&remote.conversation, &remote.participant, effect.endpoint_is_muted) |
| 967 | .await; |
| 968 | }); |
| 969 | effect.muted |
| 970 | } |
| 971 | |
| 972 | async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) { |
| 973 | if let Some(audio) = &live.audio { |
| 974 | audio.track.set_enabled(false); |
| 975 | } |
| 976 | live.broker_running.store(false, Ordering::SeqCst); |
| 977 | if !live.skip_leave |
| 978 | && let Some(remote) = &live.remote |
| 979 | { |
| 980 | let reason = if cancelled { LeaveReason::Cancel } else { LeaveReason::Hangup }; |
| 981 | match remote.signaling.leave(&remote.conversation, &remote.participant, reason).await { |
| 982 | Ok(()) => report.left_cleanly = true, |
| 983 | Err(error) => timeline.record("leave failed", error.to_string()), |
| 984 | } |
| 985 | } |
| 986 | if report.end.is_none() |
| 987 | && let Some(callbacks) = live.callbacks.as_mut() |
| 988 | && live.remote.is_some() |
| 989 | { |
| 990 | let waited = timeout(END_CALLBACK_WAIT, async { |
| 991 | while let Some(callback) = callbacks.recv().await { |
| 992 | let request_id = callback.request_id; |
| 993 | let event = handle_callback(&callback, timeline); |
| 994 | inner.replier.reply(request_id, 200, ""); |
| 995 | if let Ok(CallEvent::End(end)) = event { |
| 996 | return Some(end); |
| 997 | } |
| 998 | } |
| 999 | None |
| 1000 | }) |
| 1001 | .await; |
| 1002 | report.end = waited.ok().flatten(); |
| 1003 | } |
| 1004 | for peer in &live.peers { |
| 1005 | peer.close(); |
| 1006 | } |
| 1007 | if let Some(audio) = live.audio.take() { |
| 1008 | audio.stop().await; |
| 1009 | } |
| 1010 | if let Some(broker) = live.broker.take() { |
| 1011 | broker.abort(); |
| 1012 | } |
| 1013 | if let Some(route_id) = &live.route_id { |
| 1014 | inner.unregister_route(route_id); |
| 1015 | } |
| 1016 | timeline.record("closed", "peer closed, call route removed"); |
| 1017 | } |
| 1018 | |
| 1019 | fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> { |
| 1020 | let body = decode_body(callback)?; |
| 1021 | let (_, event) = classify(&callback.path, body)?; |
| 1022 | let detail = match &event { |
| 1023 | CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer), |
| 1024 | CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase), |
| 1025 | CallEvent::Progress(status) => format!("{status:?}"), |
| 1026 | _ => String::new(), |
| 1027 | }; |
| 1028 | timeline.record(format!("Trouter {}", event.name()), detail); |
| 1029 | Ok(event) |
| 1030 | } |
| 1031 | |
| 1032 | |
| 1033 | async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> { |
| 1034 | let answer = to_browser_answer(teams_answer, signaled, browser_offer)?; |
| 1035 | let description = |
| 1036 | SessionDescription::parse(&answer, SdpType::Answer).map_err(|error| Error::Sdp(error.description))?; |
| 1037 | peer.set_remote_description(description) |
| 1038 | .await |
| 1039 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 1040 | } |
| 1041 | |
| 1042 | /// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect. |
| 1043 | fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) { |
| 1044 | let Some(directory) = &options.sdp_dump_dir else { |
| 1045 | return; |
| 1046 | }; |
| 1047 | let masked: Vec<String> = sdp |
| 1048 | .lines() |
| 1049 | .map(|line| { |
| 1050 | for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:"] { |
| 1051 | if line.starts_with(prefix) { |
| 1052 | return format!("{prefix}<masked>"); |
| 1053 | } |
| 1054 | } |
| 1055 | line.split(' ').map(mask_address).collect::<Vec<_>>().join(" ") |
| 1056 | }) |
| 1057 | .collect(); |
| 1058 | let _ = std::fs::create_dir_all(directory); |
| 1059 | let _ = std::fs::write(directory.join(name), masked.join("\n")); |
| 1060 | } |
| 1061 | |
| 1062 | fn mask_address(token: &str) -> String { |
| 1063 | let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok()); |
| 1064 | let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:"); |
| 1065 | if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1") || colon_address { |
| 1066 | "<addr>".to_owned() |
| 1067 | } else { |
| 1068 | token.to_owned() |
| 1069 | } |
| 1070 | } |
| 1071 | |
| 1072 | async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, tone_hz: f32) { |
| 1073 | let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1); |
| 1074 | while let Some(frame) = stream.next().await { |
| 1075 | let mut recording = recording.lock().await; |
| 1076 | recording.samples.extend_from_slice(&frame.data); |
| 1077 | recording.current_second.extend_from_slice(&frame.data); |
| 1078 | if recording.current_second.len() >= SAMPLE_RATE as usize { |
| 1079 | let second: Vec<i16> = std::mem::take(&mut recording.current_second); |
| 1080 | let summary = (rms(&second), tone_ratio(&second, tone_hz)); |
| 1081 | recording.per_second.push(summary); |
| 1082 | } |
| 1083 | } |
| 1084 | } |
| 1085 | |
| 1086 | async fn poll_broker(signaling: Arc<Signaling>, conversation: Conversation, running: Arc<AtomicBool>) { |
| 1087 | let Ok(first) = conversation.link("subscribe") else { |
| 1088 | return; |
| 1089 | }; |
| 1090 | let mut url = first.to_owned(); |
| 1091 | while running.load(Ordering::SeqCst) { |
| 1092 | match signaling.poll_broker(&url).await { |
| 1093 | Ok(Some(next)) => url = next, |
| 1094 | Ok(None) => {} |
| 1095 | Err(_) => return, |
| 1096 | } |
| 1097 | } |
| 1098 | } |
| 1099 | |
| 1100 | #[derive(Debug, Default)] |
| 1101 | struct StatsSnapshot { |
| 1102 | inbound_packets: u64, |
| 1103 | inbound_bytes: u64, |
| 1104 | outbound_packets: u64, |
| 1105 | audio_level: f64, |
| 1106 | local_level: f64, |
| 1107 | echo_return_loss_enhancement: f64, |
| 1108 | dtls_state: String, |
| 1109 | tls_version: String, |
| 1110 | dtls_cipher: String, |
| 1111 | srtp_cipher: String, |
| 1112 | selected_pair: Option<String>, |
| 1113 | } |
| 1114 | |
| 1115 | async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot { |
| 1116 | let Ok(stats) = peer.get_stats().await else { |
| 1117 | return StatsSnapshot::default(); |
| 1118 | }; |
| 1119 | let mut snapshot = StatsSnapshot::default(); |
| 1120 | let mut selected_pair_id = None; |
| 1121 | for entry in &stats { |
| 1122 | match entry { |
| 1123 | RtcStats::InboundRtp(inbound) if inbound.stream.kind == "audio" => { |
| 1124 | snapshot.inbound_packets += inbound.received.packets_received; |
| 1125 | snapshot.inbound_bytes += inbound.inbound.bytes_received; |
| 1126 | snapshot.audio_level = snapshot.audio_level.max(inbound.inbound.audio_level); |
| 1127 | } |
| 1128 | RtcStats::MediaSource(source) if source.source.kind == "audio" => { |
| 1129 | snapshot.local_level = snapshot.local_level.max(source.audio.audio_level); |
| 1130 | snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement; |
| 1131 | } |
| 1132 | RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => { |
| 1133 | snapshot.outbound_packets += outbound.sent.packets_sent; |
| 1134 | } |
| 1135 | RtcStats::Transport(transport) => { |
| 1136 | snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state); |
| 1137 | snapshot.tls_version = transport.transport.tls_version.clone(); |
| 1138 | snapshot.dtls_cipher = transport.transport.dtls_cipher.clone(); |
| 1139 | snapshot.srtp_cipher = transport.transport.srtp_cipher.clone(); |
| 1140 | if !transport.transport.selected_candidate_pair_id.is_empty() { |
| 1141 | selected_pair_id = Some(transport.transport.selected_candidate_pair_id.clone()); |
| 1142 | } |
| 1143 | } |
| 1144 | _ => {} |
| 1145 | } |
| 1146 | } |
| 1147 | if let Some(pair_id) = selected_pair_id { |
| 1148 | let pair = stats.iter().find_map(|entry| match entry { |
| 1149 | RtcStats::CandidatePair(pair) if pair.rtc.id == pair_id => Some(pair), |
| 1150 | _ => None, |
| 1151 | }); |
| 1152 | if let Some(pair) = pair { |
| 1153 | let describe = |candidate_id: &str| { |
| 1154 | stats |
| 1155 | .iter() |
| 1156 | .find_map(|entry| match entry { |
| 1157 | RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => Some(&local.local_candidate), |
| 1158 | RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => Some(&remote.remote_candidate), |
| 1159 | _ => None, |
| 1160 | }) |
| 1161 | .map(|candidate| { |
| 1162 | let kind = candidate.candidate_type.map(|kind| format!("{kind:?}")).unwrap_or_default(); |
| 1163 | let relay = candidate.relay_protocol.map(|relay| format!(" via {relay:?}")).unwrap_or_default(); |
| 1164 | format!("{kind}/{}{relay}", candidate.protocol) |
| 1165 | }) |
| 1166 | .unwrap_or_else(|| "?".into()) |
| 1167 | }; |
| 1168 | snapshot.selected_pair = Some(format!( |
| 1169 | "local {} <-> remote {}", |
| 1170 | describe(&pair.candidate_pair.local_candidate_id), |
| 1171 | describe(&pair.candidate_pair.remote_candidate_id) |
| 1172 | )); |
| 1173 | } |
| 1174 | } |
| 1175 | snapshot |
| 1176 | } |
| 1177 | |
| 1178 | #[cfg(test)] |
| 1179 | mod tests { |
| 1180 | use super::*; |
| 1181 | |
| 1182 | #[test] |
| 1183 | fn keep_alive_fires_at_ninety_percent_of_the_interval() { |
| 1184 | assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430)); |
| 1185 | assert_eq!(keep_alive_period(None), Duration::from_secs(2430)); |
| 1186 | assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54)); |
| 1187 | } |
| 1188 | |
| 1189 | #[test] |
| 1190 | fn specs_map_to_invitation_targets() { |
| 1191 | assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo); |
| 1192 | let people = CallSpec::People { |
| 1193 | callees: vec![Callee { mri: "8:orgid:b".into(), display_name: "Bea".into() }], |
| 1194 | thread_id: "19:t@thread.v2".into(), |
| 1195 | }; |
| 1196 | assert!(people.is_people() && !people.is_meeting()); |
| 1197 | assert!(matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2")); |
| 1198 | let meeting = CallSpec::Meeting(MeetingTarget { |
| 1199 | thread_id: "19:meeting@thread.v2".into(), |
| 1200 | tenant_id: "t".into(), |
| 1201 | organizer_id: "o".into(), |
| 1202 | meeting_data: None, |
| 1203 | }); |
| 1204 | assert!(meeting.is_meeting() && !meeting.is_people()); |
| 1205 | } |
| 1206 | } |