| 1 | use std::path::PathBuf; |
| 2 | use std::sync::Arc; |
| 3 | use std::sync::atomic::{AtomicBool, Ordering}; |
| 4 | use std::time::Duration; |
| 5 | |
| 6 | use chatsvc::{CallbackReplier, InstanceNames, Realtime, RealtimeConfig, RealtimeEvent, TrouterCallback}; |
| 7 | use futures_util::StreamExt; |
| 8 | use libwebrtc::audio_stream::native::NativeAudioStream; |
| 9 | use libwebrtc::prelude::*; |
| 10 | use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit}; |
| 11 | use libwebrtc::session_description::{SdpType, SessionDescription}; |
| 12 | use libwebrtc::stats::RtcStats; |
| 13 | use session::Session; |
| 14 | use tokio::sync::{Mutex, mpsc}; |
| 15 | use tokio::task::JoinHandle; |
| 16 | use tokio::time::{Instant, interval, sleep_until, timeout}; |
| 17 | |
| 18 | use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav}; |
| 19 | use crate::audio_io::{AudioMode, AudioSetup}; |
| 20 | use crate::control::{CallCommand, CallControl, CallUpdate}; |
| 21 | use crate::devices::{self, DeviceChoice}; |
| 22 | use crate::error::{Error, Result}; |
| 23 | use crate::mute::{MuteCommand, MuteEffect}; |
| 24 | use crate::relay::{DEFAULT_RELAY_HOST, fetch_relay_grant}; |
| 25 | use crate::sdp::{OfferPlan, SignaledOffer, to_browser_answer, to_teams_offer}; |
| 26 | use crate::signaling::{ |
| 27 | Conversation, EchoInvitation, Participant, Signaling, TenantRouting, fetch_self, find_echo_bot_thread, |
| 28 | }; |
| 29 | use crate::state::{CallSignal, CallState}; |
| 30 | use crate::timeline::{Timeline, TimelineEntry}; |
| 31 | use crate::trouter_events::{CallEnd, CallEvent, CallbackLinks, acceptance_acknowledgement, classify, decode_body}; |
| 32 | |
| 33 | const ENDPOINT_WAIT: Duration = Duration::from_secs(30); |
| 34 | const END_CALLBACK_WAIT: Duration = Duration::from_secs(4); |
| 35 | const STATS_PERIOD: Duration = Duration::from_millis(200); |
| 36 | const TICKS_PER_SECOND: u32 = 5; |
| 37 | const RECONNECT_WINDOW: Duration = Duration::from_secs(30); |
| 38 | const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365); |
| 39 | const PRESENCE_SUFFIX: &str = "unifiedPresenceService"; |
| 40 | pub const TRACE_ENV: &str = "CALLING_TRACE"; |
| 41 | |
| 42 | #[derive(Debug, Clone)] |
| 43 | pub struct TestCallOptions { |
| 44 | pub hold_after_connected: Option<Duration>, |
| 45 | pub hard_limit: Option<Duration>, |
| 46 | pub reconnect_window: Duration, |
| 47 | pub audio: AudioMode, |
| 48 | pub tone_hz: f32, |
| 49 | pub input: DeviceChoice, |
| 50 | pub output: DeviceChoice, |
| 51 | pub relay_host: String, |
| 52 | pub routing: TenantRouting, |
| 53 | pub record_remote: bool, |
| 54 | pub wav_path: Option<PathBuf>, |
| 55 | pub sdp_dump_dir: Option<PathBuf>, |
| 56 | pub trace: bool, |
| 57 | } |
| 58 | |
| 59 | impl Default for TestCallOptions { |
| 60 | fn default() -> Self { |
| 61 | TestCallOptions { |
| 62 | hold_after_connected: None, |
| 63 | hard_limit: None, |
| 64 | reconnect_window: RECONNECT_WINDOW, |
| 65 | audio: AudioMode::from_env(), |
| 66 | tone_hz: 440.0, |
| 67 | input: DeviceChoice::SystemDefault, |
| 68 | output: DeviceChoice::SystemDefault, |
| 69 | relay_host: DEFAULT_RELAY_HOST.to_owned(), |
| 70 | routing: TenantRouting::default(), |
| 71 | record_remote: false, |
| 72 | wav_path: None, |
| 73 | sdp_dump_dir: None, |
| 74 | trace: std::env::var_os(TRACE_ENV).is_some(), |
| 75 | } |
| 76 | } |
| 77 | } |
| 78 | |
| 79 | #[derive(Debug, Clone, Default)] |
| 80 | pub struct AudioSecond { |
| 81 | pub second: u32, |
| 82 | pub packets: u64, |
| 83 | pub bytes: u64, |
| 84 | pub audio_level: f64, |
| 85 | pub decoded_rms: f32, |
| 86 | pub tone_ratio: f32, |
| 87 | } |
| 88 | |
| 89 | #[derive(Debug, Clone, Default)] |
| 90 | pub struct TestCallReport { |
| 91 | pub timeline: Vec<TimelineEntry>, |
| 92 | pub ice_connected_ms: Option<u128>, |
| 93 | pub peer_connected_ms: Option<u128>, |
| 94 | pub selected_pair: Option<String>, |
| 95 | pub tls_version: String, |
| 96 | pub dtls_cipher: String, |
| 97 | pub srtp_cipher: String, |
| 98 | pub inbound_packets: u64, |
| 99 | pub inbound_bytes: u64, |
| 100 | pub outbound_packets: u64, |
| 101 | pub seconds_with_inbound_audio: u32, |
| 102 | pub seconds: Vec<AudioSecond>, |
| 103 | pub end: Option<CallEnd>, |
| 104 | pub left_cleanly: bool, |
| 105 | pub recorded_samples: usize, |
| 106 | } |
| 107 | |
| 108 | pub fn calling_realtime_config() -> RealtimeConfig { |
| 109 | RealtimeConfig { |
| 110 | instance: InstanceNames { |
| 111 | global: "__callingTrouter".into(), |
| 112 | binding: "__callingRealtime".into(), |
| 113 | endpoint_storage_key: "__callingEpid".into(), |
| 114 | }, |
| 115 | forward_callbacks: true, |
| 116 | ..RealtimeConfig::default() |
| 117 | } |
| 118 | } |
| 119 | |
| 120 | fn random_u32() -> u32 { |
| 121 | let bytes = uuid::Uuid::new_v4().into_bytes(); |
| 122 | u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff |
| 123 | } |
| 124 | |
| 125 | fn callback_base(trouter_uri: &str) -> String { |
| 126 | let trimmed = trouter_uri.strip_suffix(PRESENCE_SUFFIX).unwrap_or(trouter_uri).trim_end_matches('/'); |
| 127 | format!("{trimmed}/") |
| 128 | } |
| 129 | |
| 130 | #[derive(Default)] |
| 131 | struct Recording { |
| 132 | samples: Vec<i16>, |
| 133 | current_second: Vec<i16>, |
| 134 | per_second: Vec<(f32, f32)>, |
| 135 | } |
| 136 | |
| 137 | enum PeerEvent { |
| 138 | Ice(IceConnectionState), |
| 139 | Connection(PeerConnectionState), |
| 140 | Track(RtcAudioTrack), |
| 141 | } |
| 142 | |
| 143 | #[derive(Clone)] |
| 144 | struct RemoteCall { |
| 145 | signaling: Arc<Signaling>, |
| 146 | conversation: Conversation, |
| 147 | participant: Participant, |
| 148 | } |
| 149 | |
| 150 | #[derive(Default)] |
| 151 | struct Live { |
| 152 | realtime: Option<Realtime>, |
| 153 | callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>, |
| 154 | replier: Option<CallbackReplier>, |
| 155 | peer: Option<PeerConnection>, |
| 156 | audio: Option<AudioSetup>, |
| 157 | remote: Option<RemoteCall>, |
| 158 | broker: Option<JoinHandle<()>>, |
| 159 | broker_running: Arc<AtomicBool>, |
| 160 | } |
| 161 | |
| 162 | fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool { |
| 163 | let next = state.next(signal, std::time::Instant::now()); |
| 164 | if next == *state { |
| 165 | return false; |
| 166 | } |
| 167 | *state = next.clone(); |
| 168 | control.send(CallUpdate::State(next)); |
| 169 | true |
| 170 | } |
| 171 | |
| 172 | pub async fn run_test_call( |
| 173 | session: &Session, |
| 174 | poll_session: &Session, |
| 175 | options: TestCallOptions, |
| 176 | mut control: CallControl, |
| 177 | ) -> Result<TestCallReport> { |
| 178 | let timeline = Timeline::new(options.trace); |
| 179 | let mut report = TestCallReport::default(); |
| 180 | let mut state = CallState::Idle; |
| 181 | advance(&mut state, CallSignal::Dial, &control); |
| 182 | let mut live = Live::default(); |
| 183 | let recording = Arc::new(Mutex::new(Recording::default())); |
| 184 | let setup = CallSetup { |
| 185 | session, |
| 186 | poll_session, |
| 187 | options: &options, |
| 188 | timeline: &timeline, |
| 189 | recording: &recording, |
| 190 | }; |
| 191 | let outcome = drive(&mut live, &setup, &mut control, &mut state, &mut report).await; |
| 192 | let failure = match outcome { |
| 193 | Ok(()) => None, |
| 194 | Err(Error::Cancelled) => { |
| 195 | advance(&mut state, CallSignal::LocalLeave, &control); |
| 196 | None |
| 197 | } |
| 198 | Err(error) => { |
| 199 | advance(&mut state, CallSignal::Error(error.to_string()), &control); |
| 200 | Some(error) |
| 201 | } |
| 202 | }; |
| 203 | tear_down(live, &timeline, &mut report).await; |
| 204 | let recording = recording.lock().await; |
| 205 | report.recorded_samples = recording.samples.len(); |
| 206 | if let Some(path) = &options.wav_path { |
| 207 | write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?; |
| 208 | } |
| 209 | report.timeline = timeline.entries(); |
| 210 | match failure { |
| 211 | Some(error) => Err(error), |
| 212 | None => Ok(report), |
| 213 | } |
| 214 | } |
| 215 | |
| 216 | struct CallSetup<'a> { |
| 217 | session: &'a Session, |
| 218 | poll_session: &'a Session, |
| 219 | options: &'a TestCallOptions, |
| 220 | timeline: &'a Timeline, |
| 221 | recording: &'a Arc<Mutex<Recording>>, |
| 222 | } |
| 223 | |
| 224 | async fn drive( |
| 225 | live: &mut Live, |
| 226 | setup: &CallSetup<'_>, |
| 227 | control: &mut CallControl, |
| 228 | state: &mut CallState, |
| 229 | report: &mut TestCallReport, |
| 230 | ) -> Result<()> { |
| 231 | let CallSetup { |
| 232 | session, |
| 233 | poll_session, |
| 234 | options, |
| 235 | timeline, |
| 236 | recording, |
| 237 | } = *setup; |
| 238 | let mut realtime = Realtime::start_with(session, calling_realtime_config()).await?; |
| 239 | live.callbacks = Some( |
| 240 | realtime |
| 241 | .take_callbacks() |
| 242 | .ok_or_else(|| Error::Callback("callback stream already taken".into()))?, |
| 243 | ); |
| 244 | live.replier = Some(realtime.callback_replier()); |
| 245 | let endpoint = control |
| 246 | .until_hangup(timeout(ENDPOINT_WAIT, async { |
| 247 | while let Some(event) = realtime.recv().await { |
| 248 | if let RealtimeEvent::Endpoint(endpoint) = event { |
| 249 | return Some(endpoint); |
| 250 | } |
| 251 | } |
| 252 | None |
| 253 | })) |
| 254 | .await; |
| 255 | live.realtime = Some(realtime); |
| 256 | let endpoint = endpoint? |
| 257 | .ok() |
| 258 | .flatten() |
| 259 | .ok_or_else(|| Error::Callback("Trouter socket never announced its endpoint".into()))?; |
| 260 | timeline.record("Trouter connected", "callback socket ready"); |
| 261 | |
| 262 | let identity = control.until_hangup(fetch_self(session)).await??; |
| 263 | let thread_id = control |
| 264 | .until_hangup(find_echo_bot_thread(session, &identity.object_id)) |
| 265 | .await??; |
| 266 | timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" }); |
| 267 | let grant = control.until_hangup(fetch_relay_grant(session)).await??; |
| 268 | timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds)); |
| 269 | |
| 270 | let factory = devices::shared_factory(); |
| 271 | let mut input = options.input.clone(); |
| 272 | let mut output = options.output.clone(); |
| 273 | let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output); |
| 274 | control.send(CallUpdate::ListenOnly(audio.listen_only)); |
| 275 | control.send(CallUpdate::Devices(devices::list_devices(&factory))); |
| 276 | control.send(CallUpdate::Selected { |
| 277 | input: input.clone(), |
| 278 | output: output.clone(), |
| 279 | }); |
| 280 | let track = audio.track.clone(); |
| 281 | live.audio = Some(audio); |
| 282 | |
| 283 | let mut configuration = RtcConfiguration::default(); |
| 284 | configuration.ice_servers = vec![grant.ice_server(&options.relay_host)]; |
| 285 | let peer = factory |
| 286 | .create_peer_connection(configuration) |
| 287 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 288 | live.peer = Some(peer.clone()); |
| 289 | let (peer_events, mut peer_receiver) = mpsc::unbounded_channel(); |
| 290 | let ice_sender = peer_events.clone(); |
| 291 | peer.on_ice_connection_state_change(Some(Box::new(move |state| { |
| 292 | let _ = ice_sender.send(PeerEvent::Ice(state)); |
| 293 | }))); |
| 294 | let connection_sender = peer_events.clone(); |
| 295 | peer.on_connection_state_change(Some(Box::new(move |state| { |
| 296 | let _ = connection_sender.send(PeerEvent::Connection(state)); |
| 297 | }))); |
| 298 | let track_sender = peer_events; |
| 299 | peer.on_track(Some(Box::new(move |event| { |
| 300 | if let MediaStreamTrack::Audio(track) = event.track { |
| 301 | let _ = track_sender.send(PeerEvent::Track(track)); |
| 302 | } |
| 303 | }))); |
| 304 | |
| 305 | let transceiver_init = RtpTransceiverInit { |
| 306 | direction: RtpTransceiverDirection::SendRecv, |
| 307 | stream_ids: vec!["microphone".into()], |
| 308 | send_encodings: Vec::new(), |
| 309 | }; |
| 310 | peer.add_transceiver(MediaStreamTrack::Audio(track), transceiver_init) |
| 311 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 312 | |
| 313 | let offer = peer |
| 314 | .create_offer(OfferOptions { |
| 315 | offer_to_receive_audio: true, |
| 316 | ..OfferOptions::default() |
| 317 | }) |
| 318 | .await |
| 319 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 320 | peer.set_local_description(offer.clone()) |
| 321 | .await |
| 322 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 323 | let browser_offer = offer.to_string(); |
| 324 | let mut numbers = random_u32; |
| 325 | let signaled = to_teams_offer(&browser_offer, &OfferPlan::default(), &mut numbers)?; |
| 326 | timeline.record("setLocalDescription", format!("{} m-line(s) signaled", signaled.lines.len())); |
| 327 | dump_sdp(options, "1-browser-offer.sdp", &browser_offer); |
| 328 | dump_sdp(options, "2-teams-offer.sdp", &signaled.sdp); |
| 329 | |
| 330 | let participant = Participant { |
| 331 | mri: format!("8:orgid:{}", identity.object_id), |
| 332 | display_name: identity.display_name.clone(), |
| 333 | endpoint_id: endpoint.endpoint_id.clone(), |
| 334 | participant_id: uuid::Uuid::new_v4().to_string(), |
| 335 | language_id: "en-gb".into(), |
| 336 | }; |
| 337 | let links = CallbackLinks::new(&callback_base(&endpoint.trouter_uri), &uuid::Uuid::new_v4().to_string()); |
| 338 | let media_leg_id = uuid::Uuid::new_v4().simple().to_string().to_uppercase(); |
| 339 | let signaling = Arc::new(Signaling::new( |
| 340 | session.clone(), |
| 341 | poll_session.clone(), |
| 342 | options.routing.clone(), |
| 343 | timeline.clone(), |
| 344 | )); |
| 345 | let call_started = Instant::now(); |
| 346 | let conversation = control |
| 347 | .until_hangup(signaling.create_conversation(&EchoInvitation { |
| 348 | from: &participant, |
| 349 | offer_sdp: &signaled.sdp, |
| 350 | media_leg_id: &media_leg_id, |
| 351 | callbacks: &links, |
| 352 | })) |
| 353 | .await??; |
| 354 | let remote = RemoteCall { |
| 355 | signaling: signaling.clone(), |
| 356 | conversation: conversation.clone(), |
| 357 | participant: participant.clone(), |
| 358 | }; |
| 359 | live.remote = Some(remote.clone()); |
| 360 | live.broker_running.store(true, Ordering::SeqCst); |
| 361 | live.broker = Some(tokio::spawn(poll_broker( |
| 362 | signaling.clone(), |
| 363 | conversation.clone(), |
| 364 | live.broker_running.clone(), |
| 365 | ))); |
| 366 | |
| 367 | let mut muted = false; |
| 368 | if let Err(error) = signaling.update_endpoint_state(&conversation, &participant, muted).await { |
| 369 | timeline.record("updateEndpointState failed", error.to_string()); |
| 370 | } |
| 371 | |
| 372 | let callbacks = live.callbacks.as_mut().expect("callbacks set above"); |
| 373 | let replier = live.replier.clone().expect("replier set above"); |
| 374 | let mut stats_tick = interval(STATS_PERIOD); |
| 375 | let hard_deadline = options.hard_limit.map(|limit| call_started + limit); |
| 376 | let mut leave_at = hard_deadline; |
| 377 | let mut reconnect_deadline: Option<Instant> = None; |
| 378 | let mut remote_set = false; |
| 379 | let mut previous_packets = 0u64; |
| 380 | let mut ticks = 0u32; |
| 381 | let mut second = 0u32; |
| 382 | loop { |
| 383 | tokio::select! { |
| 384 | Some(callback) = callbacks.recv() => { |
| 385 | let request_id = callback.request_id; |
| 386 | match handle_callback(&callback, timeline) { |
| 387 | Ok(CallEvent::Acceptance(acceptance)) => { |
| 388 | replier.reply(request_id, 200, acceptance_acknowledgement(&links).to_string()); |
| 389 | dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp); |
| 390 | if let Ok(answer) = to_browser_answer(&acceptance.sdp, &signaled, &browser_offer) { |
| 391 | dump_sdp(options, "4-browser-answer.sdp", &answer); |
| 392 | } |
| 393 | apply_answer(&peer, &acceptance.sdp, &signaled, &browser_offer).await.inspect_err(|error| { |
| 394 | timeline.record("answer rejected", error.to_string()); |
| 395 | })?; |
| 396 | remote_set = true; |
| 397 | let directions: Vec<String> = peer |
| 398 | .transceivers() |
| 399 | .iter() |
| 400 | .map(|transceiver| format!("{:?}", transceiver.current_direction())) |
| 401 | .collect(); |
| 402 | timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(","))); |
| 403 | let signaling = signaling.clone(); |
| 404 | let conversation = conversation.clone(); |
| 405 | let participant = participant.clone(); |
| 406 | let links = links.clone(); |
| 407 | let thread_id = thread_id.clone(); |
| 408 | tokio::spawn(async move { |
| 409 | let _ = signaling.add_echo_bot(&conversation, &participant, thread_id.as_deref(), &links).await; |
| 410 | let _ = signaling.update_endpoint_metadata(&conversation, &participant).await; |
| 411 | }); |
| 412 | } |
| 413 | Ok(CallEvent::End(end)) => { |
| 414 | replier.reply(request_id, 200, ""); |
| 415 | report.end = Some(end); |
| 416 | advance(state, CallSignal::RemoteEnd, control); |
| 417 | break; |
| 418 | } |
| 419 | Ok(_) => replier.reply(request_id, 200, ""), |
| 420 | Err(error) => { |
| 421 | replier.reply(request_id, 200, ""); |
| 422 | timeline.record("callback not understood", error.to_string()); |
| 423 | } |
| 424 | } |
| 425 | } |
| 426 | Some(event) = peer_receiver.recv() => match event { |
| 427 | PeerEvent::Ice(ice_state) => { |
| 428 | timeline.record("ICE state", format!("{ice_state:?}")); |
| 429 | if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() { |
| 430 | report.ice_connected_ms = Some(timeline.elapsed_ms()); |
| 431 | } |
| 432 | } |
| 433 | PeerEvent::Connection(connection) => { |
| 434 | timeline.record("PeerConnection state", format!("{connection:?}")); |
| 435 | match connection { |
| 436 | PeerConnectionState::Connected => { |
| 437 | reconnect_deadline = None; |
| 438 | advance(state, CallSignal::MediaConnected, control); |
| 439 | if report.peer_connected_ms.is_none() { |
| 440 | report.peer_connected_ms = Some(timeline.elapsed_ms()); |
| 441 | if let Some(hold) = options.hold_after_connected { |
| 442 | let hold_until = Instant::now() + hold; |
| 443 | leave_at = Some(hard_deadline.map_or(hold_until, |deadline| deadline.min(hold_until))); |
| 444 | } |
| 445 | } |
| 446 | } |
| 447 | PeerConnectionState::Disconnected => { |
| 448 | if advance(state, CallSignal::MediaDisconnected, control) { |
| 449 | reconnect_deadline = Some(Instant::now() + options.reconnect_window); |
| 450 | } |
| 451 | } |
| 452 | PeerConnectionState::Failed => { |
| 453 | advance(state, CallSignal::MediaFailed, control); |
| 454 | break; |
| 455 | } |
| 456 | _ => {} |
| 457 | } |
| 458 | } |
| 459 | PeerEvent::Track(track) => { |
| 460 | timeline.record("remote audio track", "receiving"); |
| 461 | if options.record_remote { |
| 462 | tokio::spawn(record_track(track, recording.clone(), options.tone_hz)); |
| 463 | } |
| 464 | } |
| 465 | }, |
| 466 | command = control.recv() => match command { |
| 467 | Some(CallCommand::Mute(mute)) => { |
| 468 | muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), &remote, control); |
| 469 | } |
| 470 | Some(CallCommand::SelectInput(choice)) => { |
| 471 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 472 | timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice))); |
| 473 | } |
| 474 | input = choice; |
| 475 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 476 | } |
| 477 | Some(CallCommand::SelectOutput(choice)) => { |
| 478 | if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) { |
| 479 | timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice))); |
| 480 | } |
| 481 | output = choice; |
| 482 | control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() }); |
| 483 | } |
| 484 | Some(CallCommand::RefreshDevices) => { |
| 485 | control.send(CallUpdate::Devices(devices::list_devices(&factory))); |
| 486 | } |
| 487 | Some(CallCommand::Hangup) | None => { |
| 488 | advance(state, CallSignal::LocalLeave, control); |
| 489 | break; |
| 490 | } |
| 491 | }, |
| 492 | _ = stats_tick.tick(), if remote_set => { |
| 493 | let snapshot = collect_stats(&peer).await; |
| 494 | ticks += 1; |
| 495 | let local_level = if muted { 0.0 } else { snapshot.local_level as f32 }; |
| 496 | control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 }); |
| 497 | if snapshot.selected_pair.is_some() { |
| 498 | report.selected_pair = snapshot.selected_pair.clone(); |
| 499 | report.tls_version = snapshot.tls_version.clone(); |
| 500 | report.dtls_cipher = snapshot.dtls_cipher.clone(); |
| 501 | report.srtp_cipher = snapshot.srtp_cipher.clone(); |
| 502 | } |
| 503 | report.inbound_packets = snapshot.inbound_packets; |
| 504 | report.inbound_bytes = snapshot.inbound_bytes; |
| 505 | report.outbound_packets = snapshot.outbound_packets; |
| 506 | if ticks.is_multiple_of(TICKS_PER_SECOND) { |
| 507 | second += 1; |
| 508 | let (decoded_rms, ratio) = { |
| 509 | let recording = recording.lock().await; |
| 510 | recording.per_second.last().copied().unwrap_or_default() |
| 511 | }; |
| 512 | if snapshot.inbound_packets > previous_packets { |
| 513 | report.seconds_with_inbound_audio += 1; |
| 514 | } |
| 515 | previous_packets = snapshot.inbound_packets; |
| 516 | report.seconds.push(AudioSecond { |
| 517 | second, |
| 518 | packets: snapshot.inbound_packets, |
| 519 | bytes: snapshot.inbound_bytes, |
| 520 | audio_level: snapshot.audio_level, |
| 521 | decoded_rms, |
| 522 | tone_ratio: ratio, |
| 523 | }); |
| 524 | control.send(CallUpdate::Stats { |
| 525 | inbound_packets: snapshot.inbound_packets, |
| 526 | outbound_packets: snapshot.outbound_packets, |
| 527 | }); |
| 528 | timeline.record( |
| 529 | "stats", |
| 530 | format!( |
| 531 | "in packets={} bytes={} level={:.3} rms={decoded_rms:.3} tone={ratio:.2} out packets={} mic={:.3} erle={:.1} dtls={}", |
| 532 | snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state |
| 533 | ), |
| 534 | ); |
| 535 | } |
| 536 | } |
| 537 | _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => { |
| 538 | advance(state, CallSignal::ReconnectTimedOut, control); |
| 539 | break; |
| 540 | } |
| 541 | _ = sleep_until(leave_at.unwrap_or_else(far_future)), if leave_at.is_some() => { |
| 542 | advance(state, CallSignal::LocalLeave, control); |
| 543 | break; |
| 544 | } |
| 545 | } |
| 546 | } |
| 547 | Ok(()) |
| 548 | } |
| 549 | |
| 550 | fn far_future() -> Instant { |
| 551 | Instant::now() + FAR_FUTURE |
| 552 | } |
| 553 | |
| 554 | fn apply_mute(command: MuteCommand, currently_muted: bool, audio: &AudioSetup, remote: &RemoteCall, control: &CallControl) -> bool { |
| 555 | let effect = MuteEffect::for_muted(command.target(currently_muted)); |
| 556 | audio.track.set_enabled(effect.track_enabled); |
| 557 | control.send(CallUpdate::Muted(effect.muted)); |
| 558 | let remote = remote.clone(); |
| 559 | tokio::spawn(async move { |
| 560 | let _ = remote |
| 561 | .signaling |
| 562 | .update_endpoint_state(&remote.conversation, &remote.participant, effect.endpoint_is_muted) |
| 563 | .await; |
| 564 | }); |
| 565 | effect.muted |
| 566 | } |
| 567 | |
| 568 | async fn tear_down(mut live: Live, timeline: &Timeline, report: &mut TestCallReport) { |
| 569 | if let Some(audio) = &live.audio { |
| 570 | audio.track.set_enabled(false); |
| 571 | } |
| 572 | live.broker_running.store(false, Ordering::SeqCst); |
| 573 | if let Some(remote) = &live.remote { |
| 574 | match remote.signaling.leave(&remote.conversation, &remote.participant).await { |
| 575 | Ok(()) => report.left_cleanly = true, |
| 576 | Err(error) => timeline.record("leave failed", error.to_string()), |
| 577 | } |
| 578 | } |
| 579 | if report.end.is_none() |
| 580 | && let (Some(callbacks), Some(replier)) = (live.callbacks.as_mut(), live.replier.as_ref()) |
| 581 | && live.remote.is_some() |
| 582 | { |
| 583 | let waited = timeout(END_CALLBACK_WAIT, async { |
| 584 | while let Some(callback) = callbacks.recv().await { |
| 585 | let request_id = callback.request_id; |
| 586 | let event = handle_callback(&callback, timeline); |
| 587 | replier.reply(request_id, 200, ""); |
| 588 | if let Ok(CallEvent::End(end)) = event { |
| 589 | return Some(end); |
| 590 | } |
| 591 | } |
| 592 | None |
| 593 | }) |
| 594 | .await; |
| 595 | report.end = waited.ok().flatten(); |
| 596 | } |
| 597 | if let Some(peer) = &live.peer { |
| 598 | peer.close(); |
| 599 | } |
| 600 | if let Some(audio) = live.audio.take() { |
| 601 | audio.stop().await; |
| 602 | } |
| 603 | if let Some(broker) = live.broker.take() { |
| 604 | broker.abort(); |
| 605 | } |
| 606 | if let Some(realtime) = live.realtime.take() { |
| 607 | realtime.stop().await; |
| 608 | } |
| 609 | timeline.record("closed", "peer closed, Trouter registration removed"); |
| 610 | } |
| 611 | |
| 612 | async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> { |
| 613 | let answer = to_browser_answer(teams_answer, signaled, browser_offer)?; |
| 614 | let description = |
| 615 | SessionDescription::parse(&answer, SdpType::Answer).map_err(|error| Error::Sdp(error.description))?; |
| 616 | peer.set_remote_description(description) |
| 617 | .await |
| 618 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 619 | } |
| 620 | |
| 621 | /// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect. |
| 622 | fn dump_sdp(options: &TestCallOptions, name: &str, sdp: &str) { |
| 623 | let Some(directory) = &options.sdp_dump_dir else { |
| 624 | return; |
| 625 | }; |
| 626 | let masked: Vec<String> = sdp |
| 627 | .lines() |
| 628 | .map(|line| { |
| 629 | for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:"] { |
| 630 | if line.starts_with(prefix) { |
| 631 | return format!("{prefix}<masked>"); |
| 632 | } |
| 633 | } |
| 634 | line.split(' ').map(mask_address).collect::<Vec<_>>().join(" ") |
| 635 | }) |
| 636 | .collect(); |
| 637 | let _ = std::fs::create_dir_all(directory); |
| 638 | let _ = std::fs::write(directory.join(name), masked.join("\n")); |
| 639 | } |
| 640 | |
| 641 | fn mask_address(token: &str) -> String { |
| 642 | let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok()); |
| 643 | let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:"); |
| 644 | if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1") || colon_address { |
| 645 | "<addr>".to_owned() |
| 646 | } else { |
| 647 | token.to_owned() |
| 648 | } |
| 649 | } |
| 650 | |
| 651 | fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> { |
| 652 | let body = decode_body(callback)?; |
| 653 | let (_, event) = classify(&callback.path, body)?; |
| 654 | let detail = match &event { |
| 655 | CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer), |
| 656 | CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase), |
| 657 | _ => String::new(), |
| 658 | }; |
| 659 | timeline.record(format!("Trouter {}", event.name()), detail); |
| 660 | Ok(event) |
| 661 | } |
| 662 | |
| 663 | async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, tone_hz: f32) { |
| 664 | let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1); |
| 665 | while let Some(frame) = stream.next().await { |
| 666 | let mut recording = recording.lock().await; |
| 667 | recording.samples.extend_from_slice(&frame.data); |
| 668 | recording.current_second.extend_from_slice(&frame.data); |
| 669 | if recording.current_second.len() >= SAMPLE_RATE as usize { |
| 670 | let second: Vec<i16> = std::mem::take(&mut recording.current_second); |
| 671 | let summary = (rms(&second), tone_ratio(&second, tone_hz)); |
| 672 | recording.per_second.push(summary); |
| 673 | } |
| 674 | } |
| 675 | } |
| 676 | |
| 677 | async fn poll_broker(signaling: Arc<Signaling>, conversation: Conversation, running: Arc<AtomicBool>) { |
| 678 | let Ok(first) = conversation.link("subscribe") else { |
| 679 | return; |
| 680 | }; |
| 681 | let mut url = first.to_owned(); |
| 682 | while running.load(Ordering::SeqCst) { |
| 683 | match signaling.poll_broker(&url).await { |
| 684 | Ok(Some(next)) => url = next, |
| 685 | Ok(None) => {} |
| 686 | Err(_) => return, |
| 687 | } |
| 688 | } |
| 689 | } |
| 690 | |
| 691 | #[derive(Debug, Default)] |
| 692 | struct StatsSnapshot { |
| 693 | inbound_packets: u64, |
| 694 | inbound_bytes: u64, |
| 695 | outbound_packets: u64, |
| 696 | audio_level: f64, |
| 697 | local_level: f64, |
| 698 | echo_return_loss_enhancement: f64, |
| 699 | dtls_state: String, |
| 700 | tls_version: String, |
| 701 | dtls_cipher: String, |
| 702 | srtp_cipher: String, |
| 703 | selected_pair: Option<String>, |
| 704 | } |
| 705 | |
| 706 | async fn collect_stats(peer: &PeerConnection) -> StatsSnapshot { |
| 707 | let Ok(stats) = peer.get_stats().await else { |
| 708 | return StatsSnapshot::default(); |
| 709 | }; |
| 710 | let mut snapshot = StatsSnapshot::default(); |
| 711 | let mut selected_pair_id = None; |
| 712 | for entry in &stats { |
| 713 | match entry { |
| 714 | RtcStats::InboundRtp(inbound) if inbound.stream.kind == "audio" => { |
| 715 | snapshot.inbound_packets += inbound.received.packets_received; |
| 716 | snapshot.inbound_bytes += inbound.inbound.bytes_received; |
| 717 | snapshot.audio_level = snapshot.audio_level.max(inbound.inbound.audio_level); |
| 718 | } |
| 719 | RtcStats::MediaSource(source) if source.source.kind == "audio" => { |
| 720 | snapshot.local_level = snapshot.local_level.max(source.audio.audio_level); |
| 721 | snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement; |
| 722 | } |
| 723 | RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => { |
| 724 | snapshot.outbound_packets += outbound.sent.packets_sent; |
| 725 | } |
| 726 | RtcStats::Transport(transport) => { |
| 727 | snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state); |
| 728 | snapshot.tls_version = transport.transport.tls_version.clone(); |
| 729 | snapshot.dtls_cipher = transport.transport.dtls_cipher.clone(); |
| 730 | snapshot.srtp_cipher = transport.transport.srtp_cipher.clone(); |
| 731 | if !transport.transport.selected_candidate_pair_id.is_empty() { |
| 732 | selected_pair_id = Some(transport.transport.selected_candidate_pair_id.clone()); |
| 733 | } |
| 734 | } |
| 735 | _ => {} |
| 736 | } |
| 737 | } |
| 738 | if let Some(pair_id) = selected_pair_id { |
| 739 | let pair = stats.iter().find_map(|entry| match entry { |
| 740 | RtcStats::CandidatePair(pair) if pair.rtc.id == pair_id => Some(pair), |
| 741 | _ => None, |
| 742 | }); |
| 743 | if let Some(pair) = pair { |
| 744 | let describe = |candidate_id: &str| { |
| 745 | stats |
| 746 | .iter() |
| 747 | .find_map(|entry| match entry { |
| 748 | RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => Some(&local.local_candidate), |
| 749 | RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => Some(&remote.remote_candidate), |
| 750 | _ => None, |
| 751 | }) |
| 752 | .map(|candidate| { |
| 753 | let kind = candidate.candidate_type.map(|kind| format!("{kind:?}")).unwrap_or_default(); |
| 754 | let relay = candidate.relay_protocol.map(|relay| format!(" via {relay:?}")).unwrap_or_default(); |
| 755 | format!("{kind}/{}{relay}", candidate.protocol) |
| 756 | }) |
| 757 | .unwrap_or_else(|| "?".into()) |
| 758 | }; |
| 759 | snapshot.selected_pair = Some(format!( |
| 760 | "local {} <-> remote {}", |
| 761 | describe(&pair.candidate_pair.local_candidate_id), |
| 762 | describe(&pair.candidate_pair.remote_candidate_id) |
| 763 | )); |
| 764 | } |
| 765 | } |
| 766 | snapshot |
| 767 | } |
| 768 | |
| 769 | #[cfg(test)] |
| 770 | mod tests { |
| 771 | use super::*; |
| 772 | |
| 773 | #[test] |
| 774 | fn callback_base_comes_from_the_presence_uri() { |
| 775 | assert_eq!( |
| 776 | callback_base("https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc//unifiedPresenceService"), |
| 777 | "https://pub-ent-euwe-02-f.trouter.teams.microsoft.com:3443/v4/f/abc/" |
| 778 | ); |
| 779 | assert_eq!(callback_base("https://h/v4/f/abc/unifiedPresenceService"), "https://h/v4/f/abc/"); |
| 780 | } |
| 781 | } |