BlueGit

ict rusty-teams

Files

rusty-teams / crates / calling / src / call.rs

call.rs

call.rs 194.0 KiB Download Raw
1use std::collections::BTreeMap;
2use std::path::PathBuf;
3use std::sync::Arc;
4use std::sync::atomic::{AtomicBool, Ordering};
5use std::time::Duration;
6
7use chatsvc::TrouterCallback;
8use futures_util::StreamExt;
9use libwebrtc::audio_stream::native::NativeAudioStream;
10use libwebrtc::data_channel::{DataChannel, DataChannelInit};
11use libwebrtc::prelude::*;
12use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection, RtpTransceiverInit};
13use libwebrtc::session_description::{SdpType, SessionDescription};
14use libwebrtc::stats::RtcStats;
15use session::Session;
16use tokio::sync::{Mutex, mpsc};
17use tokio::task::JoinHandle;
18use tokio::time::{Instant, interval, sleep_until, timeout};
19
20use crate::audio::{SAMPLE_RATE, rms, tone_ratio, write_wav};
21use crate::audio_io::{AudioMode, AudioSetup};
22use crate::background::{BackgroundChoice, BackgroundPicture};
23use crate::breakout::{self, RoomWatcher};
24use crate::callee_gate::{CalleeGate, EchoWatch, roster_has_callee};
25use crate::camera::{CameraDevice, list_cameras};
26use crate::captions::{
27 BotAction, CAPTIONS_DATA_ID, CaptionEntry, CaptionFlow, CaptionState, CaptionStep,
28 parse_caption_message,
29};
30use crate::control::{CallCommand, CallControl, CallUpdate, Progress};
31use crate::diagnostics::{CallDiagnostics, StatsSample};
32use crate::data_channel::Depacketizer;
33use crate::device_watch::{self, Debounce};
34use crate::devices::{self, AppliedDevice, AudioDevice, DeviceChoice, Flow, Reselect};
35use crate::end::EndKind;
36use crate::engine::{CallEngine, EngineConfig, Inner};
37use crate::error::{Error, Result};
38use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
39use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, offer_modalities, is_hold, keep_media_running, rewrite_directions, stop_sending_on};
40use crate::mic_processing::MicSettings;
41use crate::mute::{MuteCommand, MuteEffect};
42use crate::push::CallNotification;
43use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
44use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
45use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
46use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
47use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
48use crate::meeting_options::{self, OptionWrite};
49use crate::recording::{Consent, RecordingPlan, RecordingStatus};
50use crate::roster::{Roster, direct_roster};
51use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
52use crate::signaling::{
53 Answer, Attached, Callee, one_to_one_thread, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, NegotiationFailure, Participant, Signaling,
54 TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
55};
56use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
57use crate::state::{CallSignal, CallState};
58use crate::timeline::{Timeline, TimelineEntry};
59use crate::transfer::{Replacement, TransferEvent, TransferTarget};
60use crate::video_frame::{VideoKey, VideoPicture};
61use crate::video_layout::{
62 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines, offer_plan, one_to_one_plan,
63};
64use crate::send_control::{RequestFilter, parse_request};
65use crate::video_send::{LocalVideo, SendSource, VideoMode};
66use crate::screen::{ShareKind, ShareSource, list_share_sources, share_thumbnail};
67use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
68use crate::trouter_events::{
69 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
70};
71use crate::whiteboard;
72
73const END_CALLBACK_WAIT: Duration = Duration::from_secs(4);
74const STATS_PERIOD: Duration = Duration::from_millis(200);
75const TICKS_PER_SECOND: u32 = 5;
76const RECONNECT_WINDOW: Duration = Duration::from_secs(30);
77const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90);
78const SETUP_STEP_TIMEOUT: Duration = Duration::from_secs(30);
79const DIRECT_OUTGOING_TIMEOUT: Duration = Duration::from_secs(185);
80const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365);
81const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700;
82const MIN_KEEP_ALIVE_SECONDS: u64 = 60;
83const KEEP_ALIVE_FRACTION: f64 = 0.9;
84const MIC_STREAM: &str = "microphone";
85const DATA_CHANNEL_LABEL: &str = "main-channel";
86pub const DATA_CHANNEL_ENV: &str = "CALLING_DATA_CHANNEL";
87const CAPTION_START_LIMIT: Duration = Duration::from_secs(40);
88const SEND_CAPABILITIES_LABEL: &str = "POST applyChannelParameters";
89const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
90const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
91const BOT_PREFIX: &str = "28:";
92const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
93const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
94const GATHERING_LIMIT: Duration = Duration::from_secs(5);
95const GATHERING_QUIET: Duration = Duration::from_millis(500);
96const GATHERING_POLL: Duration = Duration::from_millis(50);
97const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
98const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
99const GLARE_CODE: i64 = 491;
100const RETARGET_WAIT: Duration = Duration::from_secs(20);
101const CAMERA_STREAM: &str = "camera";
102const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
103
104#[derive(Debug, Clone)]
105pub struct CallOptions {
106 pub hold_after_connected: Option<Duration>,
107 pub hard_limit: Option<Duration>,
108 pub reconnect_window: Duration,
109 pub audio: AudioMode,
110 pub video: VideoMode,
111 pub camera: DeviceChoice,
112 pub tone_hz: f32,
113 pub input: DeviceChoice,
114 pub output: DeviceChoice,
115 pub relay_host: String,
116 pub routing: TenantRouting,
117 pub record_remote: bool,
118 pub wav_path: Option<PathBuf>,
119 pub sdp_dump_dir: Option<PathBuf>,
120 pub trace: bool,
121 pub data_channel: bool,
122 pub concurrent: bool,
123 pub start_camera: bool,
124}
125
126impl Default for CallOptions {
127 fn default() -> Self {
128 CallOptions {
129 hold_after_connected: None,
130 hard_limit: None,
131 reconnect_window: RECONNECT_WINDOW,
132 audio: AudioMode::from_env(),
133 video: VideoMode::from_env(),
134 camera: DeviceChoice::SystemDefault,
135 tone_hz: 440.0,
136 input: DeviceChoice::SystemDefault,
137 output: DeviceChoice::SystemDefault,
138 relay_host: DEFAULT_RELAY_HOST.to_owned(),
139 routing: TenantRouting::default(),
140 record_remote: false,
141 wav_path: None,
142 sdp_dump_dir: None,
143 trace: std::env::var_os(crate::engine::TRACE_ENV).is_some(),
144 data_channel: data_channel_from_env(),
145 concurrent: false,
146 start_camera: false,
147 }
148 }
149}
150
151#[derive(Debug, Clone, Default)]
152pub struct AudioSecond {
153 pub second: u32,
154 pub packets: u64,
155 pub bytes: u64,
156 pub audio_level: f64,
157 pub decoded_rms: f32,
158 pub tone_ratio: f32,
159}
160
161#[derive(Debug, Clone, Default, PartialEq)]
162pub struct VideoReport {
163 pub inbound_packets: u64,
164 pub inbound_frames_decoded: u64,
165 pub inbound_width: u32,
166 pub inbound_height: u32,
167 pub frames_received: u64,
168 pub frames_published: u64,
169 pub outbound_packets: u64,
170 pub outbound_frames_encoded: u64,
171 pub outbound_width: u32,
172 pub outbound_height: u32,
173 pub remote_reports: u64,
174 pub remote_round_trip_ms: f64,
175}
176
177#[derive(Debug, Clone, Default)]
178pub struct CallReport {
179 pub timeline: Vec<TimelineEntry>,
180 pub ice_connected_ms: Option<u128>,
181 pub peer_connected_ms: Option<u128>,
182 pub selected_pair: Option<String>,
183 pub tls_version: String,
184 pub dtls_cipher: String,
185 pub srtp_cipher: String,
186 pub inbound_packets: u64,
187 pub inbound_bytes: u64,
188 pub outbound_packets: u64,
189 pub video: VideoReport,
190 pub own_streams: Vec<String>,
191 pub seconds_with_inbound_audio: u32,
192 pub seconds: Vec<AudioSecond>,
193 pub end: Option<CallEnd>,
194 pub left_cleanly: bool,
195 pub recorded_samples: usize,
196}
197
198#[derive(Debug, Clone)]
199pub enum CallSpec {
200 Echo,
201 People { callees: Vec<Callee>, thread_id: String },
202 Meeting(MeetingTarget),
203}
204
205impl CallSpec {
206 fn target(&self) -> InviteTarget {
207 match self {
208 CallSpec::Echo => InviteTarget::Echo,
209 CallSpec::People { callees, thread_id } => InviteTarget::People {
210 callees: callees.clone(),
211 thread_id: thread_id.clone(),
212 },
213 CallSpec::Meeting(meeting) => InviteTarget::Meeting(meeting.clone()),
214 }
215 }
216
217 fn is_meeting(&self) -> bool {
218 matches!(self, CallSpec::Meeting(_))
219 }
220
221 fn is_people(&self) -> bool {
222 matches!(self, CallSpec::People { .. })
223 }
224
225 fn callee_count(&self) -> usize {
226 match self {
227 CallSpec::People { callees, .. } => callees.len(),
228 CallSpec::Echo => 1,
229 CallSpec::Meeting(_) => 0,
230 }
231 }
232}
233
234pub(crate) struct IncomingCall {
235 pub accept: AcceptMode,
236 pub notification: CallNotification,
237 pub attached: Attached,
238 pub links: CallbackLinks,
239 pub participant: Participant,
240 pub callbacks: mpsc::UnboundedReceiver<TrouterCallback>,
241}
242
243pub(crate) enum Plan {
244 Outgoing(CallSpec),
245 Incoming(Box<IncomingCall>),
246}
247
248fn data_channel_from_env() -> bool {
249 !matches!(std::env::var(DATA_CHANNEL_ENV).ok().as_deref(), Some("0" | "off"))
250}
251
252pub fn keep_alive_period(seconds: Option<u64>) -> Duration {
253 let seconds = seconds.unwrap_or(DEFAULT_KEEP_ALIVE_SECONDS).max(MIN_KEEP_ALIVE_SECONDS);
254 Duration::from_secs_f64(seconds as f64 * KEEP_ALIVE_FRACTION)
255}
256
257fn random_u32() -> u32 {
258 let bytes = uuid::Uuid::new_v4().into_bytes();
259 u32::from_le_bytes([bytes[0], bytes[1], bytes[2], bytes[3]]) & 0x7fff_ffff
260}
261
262#[derive(Default)]
263struct Recording {
264 samples: Vec<i16>,
265 current_second: Vec<i16>,
266 per_second: Vec<(f32, f32)>,
267}
268
269enum PeerEvent {
270 Ice(IceConnectionState),
271 Connection(PeerConnectionState),
272 Track(RtcAudioTrack),
273 VideoTrack { mid: String, track: RtcVideoTrack },
274 Data(Vec<u8>),
275}
276
277struct PeerSession {
278 peer: PeerConnection,
279 events: mpsc::UnboundedReceiver<PeerEvent>,
280 _data_channel: Option<DataChannel>,
281 gathered: Gathered,
282}
283
284#[derive(Clone, Default)]
285struct Gathered {
286 candidates: Arc<std::sync::Mutex<Vec<String>>>,
287 complete: Arc<AtomicBool>,
288 relay_seen: Arc<AtomicBool>,
289 last_candidate: Arc<std::sync::Mutex<Option<Instant>>>,
290}
291
292impl Gathered {
293 /// libwebrtc gathers continually here, so "done" is a relay candidate followed by a quiet spell.
294 fn settled(&self) -> bool {
295 let quiet = self
296 .last_candidate
297 .lock()
298 .expect("candidate time lock")
299 .is_some_and(|at| at.elapsed() >= GATHERING_QUIET);
300 self.complete.load(Ordering::SeqCst) || (self.relay_seen.load(Ordering::SeqCst) && quiet)
301 }
302
303 async fn candidates(&self) -> Vec<String> {
304 let waited = Instant::now();
305 while !self.settled() && waited.elapsed() < GATHERING_LIMIT {
306 tokio::time::sleep(GATHERING_POLL).await;
307 }
308 self.complete.store(true, Ordering::SeqCst);
309 self.candidates.lock().expect("candidates lock").clone()
310 }
311}
312
313async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
314 match gathered {
315 Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind),
316 None => Ok(teams_sdp.to_owned()),
317 }
318}
319
320struct OfferedMedia {
321 browser_offer: String,
322 signaled: SignaledOffer,
323 video: VideoLines,
324 plan: OfferPlan,
325 modalities: Vec<String>,
326}
327
328#[derive(Debug, Clone, Copy, PartialEq, Eq)]
329enum Layout {
330 Conference,
331 OneToOne,
332}
333
334#[derive(Debug, Clone, Copy, PartialEq, Eq)]
335pub enum AcceptMode {
336 Audio,
337 Video,
338}
339
340#[derive(Clone, Copy)]
341enum AnswerVideo<'a> {
342 Reject,
343 Receive,
344 Send(&'a RtcVideoTrack),
345}
346
347#[derive(Debug, Clone, Copy, PartialEq, Eq)]
348enum Change {
349 Hold(bool),
350 Camera(bool),
351 Share(bool),
352}
353
354struct SamePeerOffer {
355 browser_offer: String,
356 signaled: SignaledOffer,
357 change: Change,
358 reply_tags: Vec<String>,
359}
360
361struct GlareResend {
362 change: Change,
363 reply_tags: Vec<String>,
364 at: Instant,
365}
366
367struct NextPeer {
368 session: PeerSession,
369 offered: Option<OfferedMedia>,
370 reply_tags: Vec<String>,
371 deadline: Option<Instant>,
372 connected: bool,
373 retargeted: bool,
374}
375
376fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
377 match callback_tag(callback_path) {
378 Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag),
379 _ => true,
380 }
381}
382
383#[derive(Clone)]
384struct RemoteCall {
385 signaling: Arc<Signaling>,
386 conversation: Conversation,
387 participant: Participant,
388 threadless: bool,
389}
390
391#[derive(Default)]
392struct Live {
393 peers: Vec<PeerConnection>,
394 audio: Option<AudioSetup>,
395 remote: Option<RemoteCall>,
396 broker: Option<JoinHandle<()>>,
397 broker_running: Arc<AtomicBool>,
398 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
399 route_id: Option<String>,
400 skip_leave: bool,
401 cancel_leave: bool,
402 video_tasks: Vec<JoinHandle<()>>,
403 video_counters: Arc<VideoCounters>,
404}
405
406fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool {
407 let next = state.next(signal, std::time::Instant::now());
408 if next == *state {
409 return false;
410 }
411 *state = next.clone();
412 control.send(CallUpdate::State(next));
413 true
414}
415
416/// Places the Echo test call on its own non-ringable Trouter instance; the app uses a shared engine instead.
417pub async fn run_test_call(
418 session: &Session,
419 poll_session: &Session,
420 options: CallOptions,
421 control: CallControl,
422) -> Result<CallReport> {
423 let config = EngineConfig {
424 ringable: false,
425 routing: options.routing.clone(),
426 relay_host: options.relay_host.clone(),
427 trace: options.trace,
428 dump_dir: None,
429 instance: chatsvc::InstanceNames {
430 global: "__testCallTrouter".into(),
431 binding: "__testCallRealtime".into(),
432 endpoint_storage_key: "__testCallEpid".into(),
433 },
434 };
435 let (engine, _events) = CallEngine::start(session.clone(), poll_session.clone(), config).await?;
436 let report = engine.run(Plan::Outgoing(CallSpec::Echo), options, control).await;
437 engine.stop().await;
438 report
439}
440
441impl CallEngine {
442 pub(crate) async fn run(&self, plan: Plan, options: CallOptions, mut control: CallControl) -> Result<CallReport> {
443 let inner = self.inner.as_ref();
444 let _one_call_at_a_time = if options.concurrent {
445 None
446 } else {
447 match control.until_hangup(inner.gate.lock()).await {
448 Ok(guard) => Some(guard),
449 Err(_) => {
450 let mut state = CallState::Idle;
451 advance(&mut state, CallSignal::Dial, &control);
452 advance(&mut state, CallSignal::LocalLeave, &control);
453 return Ok(CallReport::default());
454 }
455 }
456 };
457 let _trouter_tab_stays = inner.session.hold_tab(session::App::Teams);
458 let timeline = Timeline::new(options.trace);
459 let mut report = CallReport::default();
460 let mut state = CallState::Idle;
461 advance(&mut state, CallSignal::Dial, &control);
462 let mut live = Live::default();
463 let recording = Arc::new(Mutex::new(Recording::default()));
464 let outcome = drive(
465 inner,
466 &options,
467 &timeline,
468 &recording,
469 plan,
470 &mut live,
471 &mut control,
472 &mut state,
473 &mut report,
474 )
475 .await;
476 let failure = match outcome {
477 Ok(()) => None,
478 Err(Error::Cancelled) => {
479 advance(&mut state, CallSignal::LocalLeave, &control);
480 None
481 }
482 Err(error) => {
483 advance(&mut state, CallSignal::Error(error.to_string()), &control);
484 Some(error)
485 }
486 };
487 dump_timeline(&options, &timeline, failure.as_ref());
488 let cancelled = live.cancel_leave || matches!(&state, CallState::Ended { reason: crate::state::EndReason::Cancelled });
489 tear_down(live, inner, &timeline, &mut report, cancelled).await;
490 let recording = recording.lock().await;
491 report.recorded_samples = recording.samples.len();
492 report.timeline = timeline.entries();
493 control.send(CallUpdate::Diagnostics(Box::new(CallDiagnostics::new(&report, timeline.sdp_summaries()))));
494 if let Some(path) = &options.wav_path {
495 write_wav(path, &recording.samples).map_err(|error| Error::Webrtc(format!("wav: {error}")))?;
496 }
497 match failure {
498 Some(error) => Err(error),
499 None => Ok(report),
500 }
501 }
502}
503
504fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &str, with_data_channel: bool) -> Result<PeerSession> {
505 let mut configuration = RtcConfiguration::default();
506 configuration.ice_servers = vec![grant.ice_server(relay_host)];
507 let peer = factory
508 .create_peer_connection(configuration)
509 .map_err(|error| Error::Webrtc(error.to_string()))?;
510 let (sender, events) = mpsc::unbounded_channel();
511 let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;
512 let gathered = Gathered::default();
513 let candidate_sink = gathered.candidates.clone();
514 let relay_seen = gathered.relay_seen.clone();
515 let last_candidate = gathered.last_candidate.clone();
516 peer.on_ice_candidate(Some(Box::new(move |candidate| {
517 if candidate.sdp_mline_index() == 0 {
518 let text = candidate.candidate();
519 if is_udp_relay(&text) {
520 relay_seen.store(true, Ordering::SeqCst);
521 }
522 *last_candidate.lock().expect("candidate time lock") = Some(Instant::now());
523 candidate_sink.lock().expect("candidates lock").push(text);
524 }
525 })));
526 let gathering_done = gathered.complete.clone();
527 peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state {
528 IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst),
529 IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst),
530 IceGatheringState::New => {}
531 })));
532 let ice_sender = sender.clone();
533 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
534 let _ = ice_sender.send(PeerEvent::Ice(state));
535 })));
536 let connection_sender = sender.clone();
537 peer.on_connection_state_change(Some(Box::new(move |state| {
538 let _ = connection_sender.send(PeerEvent::Connection(state));
539 })));
540 peer.on_track(Some(Box::new(move |event| match event.track {
541 MediaStreamTrack::Audio(track) => {
542 let _ = sender.send(PeerEvent::Track(track));
543 }
544 MediaStreamTrack::Video(track) => {
545 let mid = event.transceiver.mid().unwrap_or_default();
546 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
547 }
548 })));
549 Ok(PeerSession { peer, events, _data_channel: data_channel, gathered })
550}
551
552fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {
553 let channel = peer
554 .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default())
555 .map_err(|error| Error::Webrtc(error.to_string()))?;
556 channel.on_message(Some(Box::new(move |buffer| {
557 let _ = sender.send(PeerEvent::Data(buffer.data.to_vec()));
558 })));
559 Ok(channel)
560}
561
562fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str, share_mid: Option<&'a str>, remote_shares: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
563 move |line| match line.kind {
564 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
565 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
566 (true, true) => "sendrecv",
567 (true, false) => "sendonly",
568 (false, true) => "recvonly",
569 (false, false) => INACTIVE,
570 }),
571 _ => None,
572 }
573}
574
575fn share_mid_in(offer_text: &str) -> Option<String> {
576 let mut mid = None;
577 for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) {
578 if line.starts_with("m=") {
579 mid = None;
580 } else if let Some(value) = line.strip_prefix("a=mid:") {
581 mid = Some(value.to_owned());
582 } else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() {
583 return mid;
584 }
585 }
586 None
587}
588
589#[allow(clippy::too_many_arguments)]
590fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, share_mid: Option<&str>, remote_shares: bool, text: &str) -> String {
591 match (hold, layout) {
592 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
593 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares)),
594 (false, Layout::Conference) => text.to_owned(),
595 }
596}
597
598async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout, gathered: Option<&Gathered>) -> Result<OfferedMedia> {
599 let transceiver_init = RtpTransceiverInit {
600 direction: RtpTransceiverDirection::SendRecv,
601 stream_ids: vec![MIC_STREAM.into()],
602 send_encodings: Vec::new(),
603 };
604 peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init)
605 .map_err(|error| Error::Webrtc(error.to_string()))?;
606 let (video, plan) = match layout {
607 Layout::Conference => (add_video_lines(peer, factory)?, offer_plan()),
608 Layout::OneToOne => (add_one_to_one_lines(peer, factory)?, one_to_one_plan()),
609 };
610 let offer = peer
611 .create_offer(OfferOptions {
612 offer_to_receive_audio: true,
613 offer_to_receive_video: true,
614 ..OfferOptions::default()
615 })
616 .await
617 .map_err(|error| Error::Webrtc(error.to_string()))?;
618 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, &offer.to_string());
619 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
620 peer.set_local_description(description)
621 .await
622 .map_err(|error| Error::Webrtc(error.to_string()))?;
623 let mut numbers = random_u32;
624 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
625 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
626 Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })
627}
628
629struct AnsweredMedia {
630 remote: RemoteOffer,
631 answer_sdp: String,
632 camera_mid: Option<String>,
633 receiving_share_mid: Option<String>,
634}
635
636fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
637 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
638}
639
640fn share_mids(remote: &RemoteOffer) -> Vec<String> {
641 remote.lines.iter().filter(|line| line.role == LineRole::ScreenShare).filter_map(|line| line.browser_mids.first().cloned()).collect()
642}
643
644async fn answer_offer(
645 peer: &PeerConnection,
646 track: Option<&RtcAudioTrack>,
647 teams_offer: &str,
648 video: AnswerVideo<'_>,
649 sending_share_mid: Option<String>,
650 camera_on: bool,
651 gathered: Option<&Gathered>,
652) -> Result<AnsweredMedia> {
653 let remote = from_teams_offer(teams_offer)?;
654 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
655 peer.set_remote_description(description).await.map_err(|error| {
656 let lines: Vec<String> = remote.lines.iter().map(|line| format!("{:?}{:?}", line.role, line.browser_mids)).collect();
657 Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" ")))
658 })?;
659 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
660 let kept_share_mids = if matches!(video, AnswerVideo::Reject) { Vec::new() } else { share_mids(&remote) };
661 for transceiver in peer.transceivers() {
662 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
663 let unused = transceiver
664 .mid()
665 .is_some_and(|mid| Some(&mid) != camera_mid.as_ref() && !kept_share_mids.contains(&mid) && Some(&mid) != sending_share_mid.as_ref());
666 if is_video && unused {
667 let _ = transceiver.stop();
668 }
669 }
670 if let Some(track) = track {
671 peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
672 .map_err(|error| Error::Webrtc(error.to_string()))?;
673 }
674 if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {
675 peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM])
676 .map_err(|error| Error::Webrtc(error.to_string()))?;
677 }
678 let answer = peer
679 .create_answer(AnswerOptions::default())
680 .await
681 .map_err(|error| Error::Webrtc(error.to_string()))?;
682 let mut answer_text = answer.to_string();
683 for mid in kept_share_mids.iter().filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) {
684 answer_text = stop_sending_on(&answer_text, mid);
685 }
686 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
687 if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
688 answer_text = stop_sending_on(&answer_text, mid);
689 }
690 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
691 .await
692 .map_err(|error| Error::Webrtc(error.to_string()))?;
693 let receiving_share_mid = kept_share_mids
694 .into_iter()
695 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
696 .find(|mid| matches!(direction_of(&answer_text, mid).as_deref(), Some("recvonly" | "sendrecv")));
697 let mut numbers = random_u32;
698 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
699 Ok(AnsweredMedia {
700 remote,
701 answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
702 camera_mid,
703 receiving_share_mid,
704 })
705}
706
707fn new_media_leg_id() -> String {
708 uuid::Uuid::new_v4().simple().to_string().to_uppercase()
709}
710
711async fn setup_step<T, E>(control: &mut CallControl, step: impl std::future::Future<Output = std::result::Result<T, E>>) -> Result<T>
712where
713 Error: From<E>,
714{
715 setup_step_within(control, SETUP_STEP_TIMEOUT, step).await
716}
717
718async fn setup_step_within<T, E>(
719 control: &mut CallControl,
720 limit: Duration,
721 step: impl std::future::Future<Output = std::result::Result<T, E>>,
722) -> Result<T>
723where
724 Error: From<E>,
725{
726 match control.until_hangup(timeout(limit, step)).await? {
727 Ok(result) => Ok(result?),
728 Err(_) => Err(Error::Signaling("Teams did not answer in time".into())),
729 }
730}
731
732async fn next_peer_event(next: &mut Option<NextPeer>) -> Option<PeerEvent> {
733 match next {
734 Some(next) => next.session.events.recv().await,
735 None => std::future::pending().await,
736 }
737}
738
739fn video_possible(remote_set: bool, layout: Layout, path: MediaPath) -> bool {
740 remote_set && !(layout == Layout::OneToOne && path == MediaPath::Mixer)
741}
742
743#[allow(clippy::too_many_arguments)]
744async fn drive(
745 inner: &Inner,
746 options: &CallOptions,
747 timeline: &Timeline,
748 recording: &Arc<Mutex<Recording>>,
749 plan: Plan,
750 live: &mut Live,
751 control: &mut CallControl,
752 state: &mut CallState,
753 report: &mut CallReport,
754) -> Result<()> {
755 let own_mri = format!("8:orgid:{}", inner.identity.object_id);
756 control.send(CallUpdate::OwnIdentity { mri: own_mri.clone() });
757 let (spec, incoming) = match plan {
758 Plan::Outgoing(spec) => (Some(spec), None),
759 Plan::Incoming(incoming) => (None, Some(*incoming)),
760 };
761 let accept_mode = incoming.as_ref().map_or(AcceptMode::Audio, |incoming| incoming.accept);
762 let (links, participant, mut callbacks, incoming_media) = match incoming {
763 Some(IncomingCall {
764 accept: _,
765 notification,
766 attached,
767 links,
768 participant,
769 callbacks,
770 }) => (links, participant, callbacks, Some((notification, attached))),
771 None => {
772 let links = inner.callback_links();
773 let participant = inner.participant(&uuid::Uuid::new_v4().to_string());
774 let callbacks = inner.register_route(&links);
775 (links, participant, callbacks, None)
776 }
777 };
778 live.route_id = Some(links.call_id().to_owned());
779 timeline.record("Trouter connected", "callback socket ready");
780
781 let thread_id = if matches!(spec, Some(CallSpec::Echo)) {
782 let thread_id = control
783 .until_hangup(find_echo_bot_thread(&inner.session, &inner.identity.object_id))
784 .await??;
785 timeline.record("echo bot chat", if thread_id.is_some() { "found" } else { "none" });
786 thread_id
787 } else {
788 None
789 };
790 let grant = control.until_hangup(fetch_relay_grant(&inner.session)).await??;
791 timeline.record("GET trap/tokens", format!("relay grant, expires in {} s", grant.expires_in_seconds));
792
793 let factory = devices::shared_factory();
794 let mut input = options.input.clone();
795 let mut output = options.output.clone();
796 let audio = AudioSetup::start(&factory, options.audio, options.tone_hz, &input, &output);
797 control.send(CallUpdate::ListenOnly(audio.listen_only));
798 let mut device_lists = devices::list_devices(&factory);
799 let mut applied_input = devices::applied_device(&device_lists.inputs, &input, devices::system_default_id(Flow::Capture).as_deref());
800 let mut applied_output = devices::applied_device(&device_lists.outputs, &output, devices::system_default_id(Flow::Render).as_deref());
801 let (_device_watcher, mut device_changes) = device_watch::watch();
802 let mut device_debounce = Debounce::default();
803 timeline.record(
804 "audio setup",
805 format!("listen only {}, {} input(s), {} output(s); {}", audio.listen_only, device_lists.inputs.len(), device_lists.outputs.len(), audio.adm_state),
806 );
807 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
808 control.send(CallUpdate::Devices(device_lists.clone()));
809 control.send(CallUpdate::Selected {
810 input: input.clone(),
811 output: output.clone(),
812 });
813 let track = audio.track.clone();
814 live.audio = Some(audio);
815 let mut local_video = LocalVideo::new(&factory, options.video, control.video.clone(), control.updates());
816 let mut camera_choice = options.camera.clone();
817 if options.start_camera {
818 match local_video.preview_camera(&camera_choice) {
819 Ok(()) => control.send(CallUpdate::Camera(true)),
820 Err(error) => timeline.record("camera preview failed", error.to_string()),
821 }
822 }
823 let mut media_description_request = 1u32;
824 refresh_cameras(control.updates(), options.video, timeline.clone());
825 refresh_share_sources(control.updates(), options.video, false);
826
827 let wants_data_channel = options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
828 let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?;
829 live.peers.push(current.peer.clone());
830
831 let signaling = Arc::new(inner.signaling(timeline.clone()));
832 let media_leg_id = new_media_leg_id();
833 let call_started = Instant::now();
834 let mut offered: Option<OfferedMedia> = None;
835 let mut negotiator = MediaNegotiator::default();
836 let mut remote_set = false;
837 let mut keep_alive_link: Option<String> = None;
838 let mut keep_alive_seconds: Option<u64> = None;
839 let mut keep_alive_at: Option<Instant> = None;
840 let mut outgoing_deadline: Option<Instant> = None;
841 let mut outgoing_limit = OUTGOING_TIMEOUT;
842 let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
843 let is_echo = matches!(spec, Some(CallSpec::Echo));
844 let mut echo_watch = EchoWatch::default();
845 let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count));
846 let meeting_target = match &spec {
847 Some(CallSpec::Meeting(target)) => Some(target.clone()),
848 _ => None,
849 };
850 let people_thread = match &spec {
851 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),
852 _ => incoming_media
853 .as_ref()
854 .filter(|(notification, _)| !notification.is_multi_party)
855 .and_then(|(notification, _)| {
856 notification
857 .thread_id
858 .clone()
859 .filter(|thread| *thread != notification.caller.mri)
860 .or_else(|| one_to_one_thread(&inner.identity.object_id, &notification.caller.mri))
861 }),
862 };
863 let mut layout = match &spec {
864 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne,
865 _ => Layout::Conference,
866 };
867 let peer_mri = match &spec {
868 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Some(callees[0].mri.clone()),
869 _ => incoming_media.as_ref().map(|(notification, _)| notification.caller.mri.clone()),
870 };
871 let mut layout_plan: OfferPlan;
872 let mut direct_video_mid: Option<String> = None;
873 let mut sending_camera = false;
874 let mut media_links: BTreeMap<String, String> = BTreeMap::new();
875
876 let conversation = match (spec, incoming_media) {
877 (Some(spec), None) => {
878 let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
879 let offer_started = Instant::now();
880 let media = control
881 .until_hangup(create_offer(&current.peer, &factory, &track, layout, direct_invite.then_some(&current.gathered)))
882 .await??;
883 timeline.record("offer created", format!("{} ms", offer_started.elapsed().as_millis()));
884 layout_plan = media.plan.clone();
885 if layout == Layout::OneToOne {
886 direct_video_mid = Some(CAMERA_MID.to_owned());
887 }
888 timeline.record("setLocalDescription", format!("{} m-line(s) signaled", media.signaled.lines.len()));
889 timeline.record_sdp("local offer", &media.signaled.sdp);
890 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
891 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
892 let target = spec.target();
893 let invitation = Invitation {
894 from: &participant,
895 offer_sdp: &media.signaled.sdp,
896 media_leg_id: &media_leg_id,
897 callbacks: &links,
898 target: &target,
899 modalities: &media.modalities,
900 direct: !options.concurrent,
901 };
902 let threadless = invitation.is_direct();
903 let conversation = match &target {
904 InviteTarget::Meeting(meeting) => {
905 let subscribed = control
906 .until_hangup(signaling.subscribe_meeting(&participant, &links, meeting))
907 .await??;
908 setup_step(control, signaling.join_meeting(&subscribed, &invitation)).await?
909 }
910 _ => setup_step(control, signaling.create_conversation(&invitation)).await?,
911 };
912 if spec.is_people() {
913 control.send(CallUpdate::Progress(Progress::Calling));
914 if threadless {
915 outgoing_limit = DIRECT_OUTGOING_TIMEOUT;
916 }
917 outgoing_deadline = Some(Instant::now() + outgoing_limit);
918 }
919 if let Err(error) = local_video.set_lines(media.video.clone()) {
920 timeline.record("video lines not attached", error.to_string());
921 }
922 offered = Some(media);
923 live.remote = Some(RemoteCall {
924 signaling: signaling.clone(),
925 conversation: conversation.clone(),
926 participant: participant.clone(),
927 threadless,
928 });
929 conversation
930 }
931 (None, Some((notification, attached))) => {
932 let teams_offer = attached
933 .offer_sdp
934 .clone()
935 .ok_or_else(|| Error::Signaling("attach answer without an offer".into()))?;
936 let conversation = attached
937 .conversation
938 .clone()
939 .ok_or_else(|| Error::Signaling("attach answer without a conversation".into()))?;
940 live.remote = Some(RemoteCall {
941 signaling: signaling.clone(),
942 conversation: conversation.clone(),
943 participant: participant.clone(),
944 threadless: notification.thread_id.is_none(),
945 });
946 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
947 layout = if one_to_one { Layout::OneToOne } else { Layout::Conference };
948 let camera_track = local_video.camera_track();
949 let video_answer = match accept_mode {
950 _ if !one_to_one => AnswerVideo::Reject,
951 AcceptMode::Video if local_video.is_available() => AnswerVideo::Send(&camera_track),
952 _ => AnswerVideo::Receive,
953 };
954 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
955 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, None, false, one_to_one.then_some(&current.gathered)).await?;
956 layout_plan = answered.remote.plan();
957 direct_video_mid = answered.camera_mid.clone();
958 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
959 timeline.record_sdp("remote offer", &teams_offer);
960 timeline.record_sdp("local answer", &answered.answer_sdp);
961 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
962 let acceptance_url = attached
963 .links
964 .get("acceptance")
965 .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
966 let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some());
967 let acknowledged = signaling
968 .accept(
969 acceptance_url,
970 &Answer {
971 from: &participant,
972 answer_sdp: &answered.answer_sdp,
973 media_leg_id: &media_leg_id,
974 callbacks: &links,
975 modalities: &modalities,
976 },
977 )
978 .await?;
979 negotiator.answered_incoming(attached.from_mixer);
980 remote_set = true;
981 media_links.extend(attached.links.clone());
982 media_links.extend(acknowledged);
983 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
984 let camera = peer_transceiver(&current.peer, mid);
985 match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) {
986 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
987 Ok(()) => sending_camera = true,
988 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
989 },
990 Some(Err(error)) => timeline.record("video lines not attached", error.to_string()),
991 None => timeline.record("video lines not attached", "no transceiver for the camera line"),
992 }
993 }
994 keep_alive_link = media_links.get("callLeg").cloned();
995 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
996 conversation
997 }
998 _ => return Err(Error::Callback("call plan without an offer or an invitation".into())),
999 };
1000 let remote = live.remote.clone().expect("remote call set above");
1001 live.broker_running.store(true, Ordering::SeqCst);
1002 live.broker = Some(tokio::spawn(poll_broker(
1003 signaling.clone(),
1004 conversation.clone(),
1005 live.broker_running.clone(),
1006 )));
1007
1008 let initial = MuteEffect::initial(is_meeting);
1009 let mut muted = initial.muted;
1010 live.audio.as_ref().expect("audio set above").track.set_enabled(initial.track_enabled);
1011 if muted {
1012 control.send(CallUpdate::Muted(true));
1013 }
1014 match setup_step(control, signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted)).await {
1015 Err(Error::Cancelled) => return Err(Error::Cancelled),
1016 Err(error) => timeline.record("updateEndpointState failed", error.to_string()),
1017 Ok(()) => {}
1018 }
1019
1020 let mut stats_tick = interval(STATS_PERIOD);
1021 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
1022 let mut leave_at = hard_deadline;
1023 let mut reconnect_deadline: Option<Instant> = None;
1024 let mut next: Option<NextPeer> = None;
1025 let mut roster = Roster::default();
1026 if let Some(snapshot) = &conversation.roster
1027 && roster.apply_snapshot(snapshot)
1028 {
1029 let entries = roster.entries();
1030 timeline.record("roster", format!("{} participant(s) from the conversation answer", entries.len()));
1031 control.send(CallUpdate::Roster(entries));
1032 }
1033 let mut lobby = false;
1034 let mut capability = MeetingCapability::default();
1035 let mut previous_packets = 0u64;
1036 let mut ticks = 0u32;
1037 let mut segmentation_model: Option<&'static str> = None;
1038 let mut health_sampler = HealthSampler::default();
1039 let mut quality_tracker = QualityTracker::default();
1040 let mut second = 0u32;
1041 let echo_thread = thread_id;
1042 let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());
1043 if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) {
1044 video.router().set(mid, Some(VideoKey::Person(mri.clone())));
1045 }
1046 if sending_camera {
1047 control.send(CallUpdate::Camera(true));
1048 }
1049 let mut software_audio: Option<SoftwareAudio> = None;
1050 let mut share_sound_wanted = false;
1051 let mut mic_settings = MicSettings::default();
1052 crate::noise_stage::apply(mic_settings);
1053 let mut audio_disabled = false;
1054 let mut remote_audio: Option<RtcAudioTrack> = None;
1055 sync_software_audio(&factory, options, &input, muted, None, &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1056 let mut own_hand: Option<String> = None;
1057 let mut depacketizer = Depacketizer::default();
1058 let mut caption_flow = CaptionFlow::default();
1059 let mut caption_deadline: Option<Instant> = None;
1060 let mut recording_flow = CaptionFlow::default();
1061 let mut recording_deadline: Option<Instant> = None;
1062 let mut recording_plan = RecordingPlan::default();
1063 let mut recording_audio_only = false;
1064 let mut recording_status = RecordingStatus::default();
1065 let mut bot_pending = false;
1066 let mut consent_pending = false;
1067 let mut room_watcher = RoomWatcher::default();
1068 let mut main_meeting_sent = false;
1069 let mut local_hold = false;
1070 let mut remote_hold = false;
1071 let mut same_peer: Option<SamePeerOffer> = None;
1072 let mut send_requests = RequestFilter::default();
1073 let mut send_capabilities = SendCapabilityReporter::default();
1074 let mut same_peer_deadline: Option<Instant> = None;
1075 let mut meeting_chat = conversation.chat_thread.clone();
1076 if let Some(thread) = &meeting_chat {
1077 control.send(CallUpdate::MeetingChat(thread.clone()));
1078 }
1079 if let Some(target) = &meeting_target {
1080 control.send(CallUpdate::MeetingTenant(target.tenant_id.clone()));
1081 }
1082 if meeting_chat.is_none() {
1083 meeting_chat = people_thread;
1084 }
1085 let mut start_camera_pending = options.start_camera;
1086 let mut share_pending: Option<ShareSource> = None;
1087 let mut glare_resend: Option<GlareResend> = None;
1088 let mut deferred_changes: Vec<Change> = Vec::new();
1089 let mut remote_direct_share: Option<String> = None;
1090 let mut sent_replacement: Option<Replacement> = None;
1091 loop {
1092 if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
1093 start_camera_pending = false;
1094 control.defer(CallCommand::SetCamera(true));
1095 }
1096 if video_possible(remote_set, layout, negotiator.path())
1097 && let Some(source) = share_pending.take()
1098 {
1099 control.defer(CallCommand::StartShare(source));
1100 }
1101 if next.as_ref().is_some_and(|pending| pending.connected && (pending.offered.is_some() || pending.retargeted))
1102 && let Some(pending) = next.take()
1103 {
1104 timeline.record("escalation", "new peer connection connected, old one dropped");
1105 deferred_changes.clear();
1106 negotiator.server_escalation_done();
1107 if let Some(mid) = remote_direct_share.take() {
1108 video.router().set(&mid, None);
1109 control.send(CallUpdate::ScreenShare(None));
1110 }
1111 let old = std::mem::replace(&mut current, pending.session);
1112 old.peer.close();
1113 if let Some(audio) = &software_audio
1114 && let Err(error) = swap_audio_track(&current.peer, &audio.track)
1115 {
1116 timeline.record("computer sound not carried over", error.to_string());
1117 }
1118 offered = pending.offered;
1119 if let Some(mid) = direct_video_mid.take() {
1120 video.router().set(&mid, None);
1121 }
1122 if let Some(media) = &offered {
1123 layout = Layout::Conference;
1124 layout_plan = media.plan.clone();
1125 if let Err(error) = local_video.set_lines(media.video.clone()) {
1126 timeline.record("video lines not attached", error.to_string());
1127 }
1128 if local_video.camera_on() {
1129 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1130 }
1131 if local_video.sharing() {
1132 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1133 }
1134 }
1135 remote_set = true;
1136 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1137 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
1138 if pending.is_none() {
1139 drop_local_media(&mut local_video, control);
1140 }
1141 next = pending.or(next);
1142 }
1143 }
1144 let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);
1145 let glare_at = glare_resend.as_ref().map(|resend| resend.at);
1146 tokio::select! {
1147 Some(callback) = callbacks.recv() => {
1148 match handle_callback(&callback, timeline) {
1149 Ok(CallEvent::Acceptance(acceptance)) => {
1150 if !acceptance.from_mixer
1151 && let Some(accepted_by) = &acceptance.accepted_by
1152 && roster.apply(&direct_roster(&[(own_mri.as_str(), participant.display_name.as_str()), (accepted_by.mri.as_str(), accepted_by.display_name.as_str())]))
1153 {
1154 control.send(CallUpdate::Roster(roster.entries()));
1155 }
1156 if !acceptance.from_mixer && callee_gate.callee_joined() {
1157 advance(state, CallSignal::MediaConnected, control);
1158 }
1159 let action = negotiator.on_acceptance(acceptance.from_mixer, layout == Layout::OneToOne);
1160 match action {
1161 MediaAction::ApplyAnswer | MediaAction::ApplyAnswerThenEscalate => {
1162 let Some(media) = offered.as_ref() else { continue };
1163 dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp);
1164 if let Ok(answer) = to_browser_answer(&acceptance.sdp, &media.signaled, &media.browser_offer) {
1165 dump_sdp(options, "4-browser-answer.sdp", &answer);
1166 }
1167 apply_answer(&current.peer, &acceptance.sdp, &media.signaled, &media.browser_offer)
1168 .await
1169 .inspect_err(|error| timeline.record("answer rejected", error.to_string()))?;
1170 remote_set = true;
1171 media_links.extend(acceptance.links.clone());
1172 if layout == Layout::Conference {
1173 negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster);
1174 }
1175 if let Some(link) = acceptance.links.get("replacement")
1176 && sent_replacement.as_ref().is_none_or(|sent| sent.participant_id.is_none())
1177 {
1178 let replacement = Replacement::of_call(link.clone());
1179 sent_replacement = Some(replacement.clone());
1180 control.send(CallUpdate::ReplacementLink(replacement));
1181 }
1182 if !callee_gate.is_waiting() {
1183 outgoing_deadline = None;
1184 }
1185 let directions: Vec<String> = current
1186 .peer
1187 .transceivers()
1188 .iter()
1189 .map(|transceiver| format!("{:?}", transceiver.current_direction()))
1190 .collect();
1191 timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(",")));
1192 if acceptance.in_lobby() {
1193 lobby = true;
1194 control.send(CallUpdate::Lobby(true));
1195 }
1196 keep_alive_link = acceptance.links.get("callLeg").cloned();
1197 keep_alive_seconds = acceptance.keep_alive_seconds;
1198 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
1199 if action == MediaAction::ApplyAnswerThenEscalate {
1200 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &acceptance.links, &mut negotiator, live, timeline).await;
1201 next = pending.or(next);
1202 }
1203 let remote = remote.clone();
1204 let links = links.clone();
1205 let thread_id = echo_thread.clone();
1206 tokio::spawn(async move {
1207 if is_echo {
1208 let _ = remote.signaling.add_echo_bot(&remote.conversation, &remote.participant, thread_id.as_deref(), &links).await;
1209 }
1210 let _ = remote.signaling.update_endpoint_metadata(&remote.conversation, &remote.participant).await;
1211 });
1212 }
1213 MediaAction::Escalate => {
1214 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &acceptance.links, &mut negotiator, live, timeline).await;
1215 next = pending.or(next);
1216 }
1217 _ => {}
1218 }
1219 }
1220 Ok(CallEvent::MediaAnswer(answer)) if !remote_set && !answer.from_mixer && same_peer.is_none() && next.is_none() && outgoing_deadline.is_some() => {
1221 timeline.record("provisional answer", if answer.no_ring_back { "no ringback" } else { "ringing" });
1222 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1223 if !answer.no_ring_back {
1224 control.send(CallUpdate::Progress(Progress::Ringing));
1225 }
1226 }
1227 Ok(CallEvent::MediaAnswer(answer))
1228 if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1229 {
1230 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1231 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1232 }
1233 if answer.from_mixer {
1234 negotiator.note_mixer_path();
1235 }
1236 if let Some(resend) = glare_resend.as_mut() {
1237 resend.at = Instant::now();
1238 }
1239 }
1240 Ok(CallEvent::MediaAnswer(answer)) => {
1241 let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1242 || next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags));
1243 if (same_peer.is_some() || next.is_some()) && !belongs {
1244 timeline.record("media answer ignored", "it answers an offer that is no longer pending");
1245 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1246 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1247 }
1248 continue;
1249 }
1250 let action = negotiator.on_media_answer();
1251 if action == MediaAction::Ignore
1252 && let Some(url) = answer.links.get("mediaAcknowledgement")
1253 {
1254 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1255 }
1256 if action == MediaAction::ApplyOnSamePeer
1257 && let Some(pending) = same_peer.take()
1258 {
1259 same_peer_deadline = None;
1260 let applied = match pending.change {
1261 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1262 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1263 };
1264 match applied {
1265 Ok(()) => {
1266 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1267 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1268 }
1269 match pending.change {
1270 Change::Hold(hold) => {
1271 local_hold = hold;
1272 silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref());
1273 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1274 }
1275 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1276 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1277 local_video.stop_share();
1278 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1279 control.send(CallUpdate::LocalShare(None));
1280 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1281 }
1282 Change::Share(_) => {}
1283 }
1284 if answer.from_mixer {
1285 media_links.extend(answer.links.clone());
1286 let wants_video = !local_hold && (local_video.camera_on() || local_video.sharing());
1287 let upgrade = wants_video
1288 && (negotiator.escalate_after_mixer_answer() || (layout == Layout::OneToOne && next.is_none() && negotiator.begin_conference_upgrade()));
1289 if !wants_video {
1290 negotiator.note_mixer_path();
1291 } else if upgrade {
1292 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
1293 if pending.is_none() {
1294 drop_local_media(&mut local_video, control);
1295 }
1296 next = pending.or(next);
1297 }
1298 }
1299 }
1300 Err(error) => {
1301 timeline.record("same-peer answer rejected", error.to_string());
1302 undo_change(pending.change, &mut local_video, control);
1303 }
1304 }
1305 }
1306 if action == MediaAction::ApplyOnNewPeer {
1307 let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) {
1308 Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await,
1309 None => Err(Error::Webrtc("no pending peer connection for the answer".into())),
1310 };
1311 match applied {
1312 Ok(()) => {
1313 if let Some(media) = next.as_ref().and_then(|pending| pending.offered.as_ref()) {
1314 media_links.extend(answer.links.clone());
1315 negotiate_video(&mut video, &signaling, control, timeline, &answer.sdp, media, true, &media_links, &roster);
1316 }
1317 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1318 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1319 }
1320 }
1321 Err(error) => {
1322 negotiator.escalation_failed();
1323 if let Some(pending) = next.take() {
1324 pending.session.peer.close();
1325 }
1326 if layout == Layout::OneToOne {
1327 drop_local_media(&mut local_video, control);
1328 }
1329 timeline.record("escalation answer rejected", error.to_string());
1330 }
1331 }
1332 }
1333 }
1334 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
1335 if !renegotiation.escalation
1336 && !renegotiation.new_offer
1337 && let Some(pending) = same_peer.take()
1338 {
1339 same_peer_deadline = None;
1340 negotiator.same_peer_offer_failed();
1341 rollback_offer(&current.peer).await;
1342 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
1343 glare_resend = Some(GlareResend { change: pending.change, reply_tags: pending.reply_tags, at: Instant::now() + GLARE_RESEND_LIMIT });
1344 }
1345 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1346 let rejection_link = renegotiation.links.get("rejection").cloned();
1347 let result = match action {
1348 MediaAction::AnswerOnNewPeer => {
1349 if let Some(pending) = same_peer.take() {
1350 same_peer_deadline = None;
1351 timeline.record("same-peer offer", "superseded by the escalation offer");
1352 rollback_offer(&current.peer).await;
1353 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
1354 }
1355 if let Some(resend) = glare_resend.take() {
1356 defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control);
1357 }
1358 match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1359 Ok((session, answered)) => {
1360 timeline.record_sdp("local answer", &answered.answer_sdp);
1361 live.peers.push(session.peer.clone());
1362 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1363 if let Some(replaced) = next.take() {
1364 replaced.session.peer.close();
1365 }
1366 next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: Some(Instant::now() + NEXT_PEER_LIMIT), connected: false, retargeted: false });
1367 sent
1368 }
1369 Err(error) => {
1370 if next.is_none() {
1371 negotiator.server_escalation_failed();
1372 }
1373 for change in deferred_changes.drain(..) {
1374 undo_change(change, &mut local_video, control);
1375 }
1376 if let Some(url) = &rejection_link {
1377 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1378 }
1379 Err(error)
1380 }
1381 }
1382 }
1383 MediaAction::AnswerOnSamePeer => {
1384 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
1385 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer, local_video.sharing().then(|| local_video.share_mid()).flatten(), local_video.camera_on(), (layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct).then_some(&current.gathered)).await {
1386 Ok(answered) => {
1387 timeline.record_sdp("local answer", &answered.answer_sdp);
1388 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1389 for mid in answered.remote.plan().screen_share_mids {
1390 if !layout_plan.screen_share_mids.contains(&mid) {
1391 layout_plan.screen_share_mids.push(mid);
1392 }
1393 }
1394 if layout == Layout::OneToOne && answered.receiving_share_mid != remote_direct_share {
1395 if let Some(mid) = &remote_direct_share {
1396 video.router().set(mid, None);
1397 }
1398 if let Some(mid) = &answered.receiving_share_mid {
1399 video.router().set(mid, Some(VideoKey::Screen));
1400 }
1401 remote_direct_share = answered.receiving_share_mid.clone();
1402 control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));
1403 }
1404 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
1405 if held != remote_hold {
1406 remote_hold = held;
1407 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1408 }
1409 sent
1410 }
1411 Err(error) => {
1412 if current.peer.signaling_state() == SignalingState::HaveRemoteOffer {
1413 rollback_remote_offer(&current.peer).await;
1414 }
1415 if let Some(url) = &rejection_link {
1416 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1417 }
1418 Err(error)
1419 }
1420 }
1421 }
1422 MediaAction::RejectGlare => {
1423 if let Some(url) = &rejection_link {
1424 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::InProgress).await;
1425 }
1426 Ok(())
1427 }
1428 _ => Ok(()),
1429 };
1430 if let Err(error) = result {
1431 timeline.record("renegotiation failed", error.to_string());
1432 }
1433 }
1434 Ok(CallEvent::RosterUpdate(body)) => {
1435 if roster.apply(&body) {
1436 let entries = roster.entries();
1437 timeline.record("roster", format!("{} participant(s)", entries.len()));
1438 control.send(CallUpdate::Roster(entries));
1439 if is_echo && echo_watch.bot_left(roster.members().iter().map(|member| member.mri.as_str())) {
1440 timeline.record("echo bot left", "test call ends like in Teams");
1441 advance(state, CallSignal::RemoteEnd(EndKind::Normal), control);
1442 break;
1443 }
1444 if callee_gate.is_waiting() && roster_has_callee(roster.members().iter().map(|member| member.mri.as_str()), &own_mri) {
1445 outgoing_deadline = None;
1446 if callee_gate.callee_joined() {
1447 advance(state, CallSignal::MediaConnected, control);
1448 }
1449 }
1450 let own_streams = roster.stream_summaries(&own_mri);
1451 if own_streams != report.own_streams {
1452 timeline.record("own media streams", own_streams.join("; "));
1453 report.own_streams = own_streams;
1454 }
1455 send_receive_change(control, video.reselect(&roster));
1456 if let Some(replacement) = roster.transfer_replacement(&own_mri)
1457 && sent_replacement.as_ref() != Some(&replacement)
1458 {
1459 sent_replacement = Some(replacement.clone());
1460 control.send(CallUpdate::ReplacementLink(replacement));
1461 }
1462 if let Some(in_lobby) = roster.is_in_lobby(&own_mri)
1463 && in_lobby != lobby
1464 {
1465 lobby = in_lobby;
1466 control.send(CallUpdate::Lobby(lobby));
1467 }
1468 if roster.caption_bot().is_some() {
1469 bot_pending = false;
1470 }
1471 let audio_only = roster.caption_bot().is_some_and(|bot| bot.recording && bot.audio_only);
1472 if audio_only != recording_audio_only {
1473 recording_audio_only = audio_only;
1474 control.send(CallUpdate::RecordingAudioOnly(audio_only));
1475 }
1476 if caption_flow.wanted() {
1477 run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), &RecordingPlan::default(), &mut bot_pending, control, timeline).await;
1478 if caption_flow.on() {
1479 caption_deadline = None;
1480 }
1481 }
1482 if recording_flow.wanted() {
1483 run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await;
1484 }
1485 }
1486 }
1487 Ok(CallEvent::AddParticipantFailure(body)) => {
1488 let bot_add = bot_pending;
1489 bot_pending = false;
1490 if !bot_add && callee_gate.callees_failed(failed_participant_count(&body)) {
1491 let end = embedded_end(&body);
1492 let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind);
1493 report.end = end;
1494 advance(state, CallSignal::RemoteEnd(kind), control);
1495 break;
1496 }
1497 if recording_flow.wanted() && roster.caption_bot().is_none() {
1498 timeline.record("recorder bot failed", "addParticipantFailure");
1499 recording_flow.failed();
1500 recording_deadline = None;
1501 control.send(CallUpdate::RecordingPending(false));
1502 control.send(CallUpdate::Notice("The recording service could not join".into()));
1503 }
1504 if caption_flow.wanted() && roster.caption_bot().is_none() {
1505 timeline.record("caption bot failed", "addParticipantFailure");
1506 caption_flow.failed();
1507 caption_deadline = None;
1508 control.send(CallUpdate::Captions(CaptionState::Failed("The captions service could not join".into())));
1509 }
1510 }
1511 Ok(CallEvent::ConversationUpdate(body)) => {
1512 if let Some(thread) = chat_thread_id(&body)
1513 && meeting_chat.as_ref() != Some(&thread)
1514 {
1515 control.send(CallUpdate::MeetingChat(thread.clone()));
1516 meeting_chat = Some(thread);
1517 }
1518 if capability.apply(&body) {
1519 control.send(CallUpdate::Capability(capability));
1520 }
1521 let change = recording_status.apply(&body);
1522 if let Some(on) = change.recording {
1523 control.send(CallUpdate::Recording(on));
1524 if on {
1525 recording_deadline = None;
1526 control.send(CallUpdate::RecordingPending(false));
1527 }
1528 }
1529 if let Some(on) = change.transcription {
1530 control.send(CallUpdate::Transcribing(on));
1531 if on {
1532 recording_deadline = None;
1533 control.send(CallUpdate::RecordingPending(false));
1534 }
1535 }
1536 if let Some(required) = change.consent_required {
1537 consent_pending = required;
1538 control.send(CallUpdate::ConsentRequired(required));
1539 if required {
1540 withhold_media(&mut muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, &mut local_video, control);
1541 }
1542 }
1543 if !main_meeting_sent
1544 && let Some(main) = breakout::main_meeting_target(&body)
1545 {
1546 main_meeting_sent = true;
1547 control.send(CallUpdate::BreakoutRoom { main });
1548 }
1549 }
1550 Ok(CallEvent::LocalParticipantUpdate(body)) => {
1551 let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1552 if let Some(moved) = moved {
1553 timeline.record("breakout", format!("moved to {}", moved.room_name));
1554 control.send(CallUpdate::BreakoutMove(moved));
1555 }
1556 }
1557 Ok(CallEvent::Replacement(body)) => {
1558 let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1559 if let Some(moved) = invited {
1560 timeline.record("breakout", format!("invited to {}", moved.room_name));
1561 control.send(CallUpdate::BreakoutMove(moved));
1562 }
1563 }
1564 Ok(CallEvent::ContentShareUpdate(body)) => {
1565 if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) {
1566 control.send(CallUpdate::Whiteboard(Some(share)));
1567 }
1568 }
1569 Ok(CallEvent::ContentShareEnd(_)) => {
1570 control.send(CallUpdate::Whiteboard(None));
1571 }
1572 Ok(CallEvent::Transfer(event)) => {
1573 match event {
1574 TransferEvent::Accepted => timeline.record("transfer accepted", "by the target"),
1575 completed if completed.succeeded() => {
1576 timeline.record("transfer", "completed");
1577 control.send(CallUpdate::TransferResult { succeeded: true });
1578 control.send(CallUpdate::Notice("Call transferred".into()));
1579 advance(state, CallSignal::LocalLeave, control);
1580 break;
1581 }
1582 TransferEvent::Completed { code, sub_code } => {
1583 timeline.record("transfer failed", format!("code {code} subCode {sub_code}"));
1584 control.send(CallUpdate::TransferResult { succeeded: false });
1585 control.send(CallUpdate::Notice("The transfer did not go through".into()));
1586 }
1587 }
1588 }
1589 Ok(CallEvent::Reactions(events)) => {
1590 for event in events {
1591 control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction });
1592 }
1593 }
1594 Ok(CallEvent::Progress(status)) => {
1595 if status == ProgressStatus::Ringing {
1596 control.send(CallUpdate::Progress(Progress::Ringing));
1597 if outgoing_deadline.is_some() {
1598 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1599 }
1600 }
1601 }
1602 Ok(CallEvent::ControlVideoStreaming(body)) => {
1603 let Some(request) = parse_request(&body) else { continue };
1604 let Some(limits) = send_requests.admit(&request) else { continue };
1605 let own_screen = roster.screen_source_of(&own_mri).map(i64::from);
1606 let source = if request.source_id.is_some() && request.source_id == own_screen { SendSource::Screen } else { SendSource::Camera };
1607 match local_video.apply_send_limit(source, &limits) {
1608 Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?}")),
1609 Ok(None) => {}
1610 Err(error) => timeline.record("send limits failed", error.to_string()),
1611 }
1612 }
1613 Ok(CallEvent::Speakers(sources)) => {
1614 let speakers = roster.mris_for_sources(&sources);
1615 if video.note_speakers(&speakers) {
1616 send_receive_change(control, video.reselect(&roster));
1617 }
1618 control.send(CallUpdate::Speakers(speakers));
1619 }
1620 Ok(CallEvent::ConversationEnd(body)) if callee_gate.is_waiting() => {
1621 live.skip_leave = true;
1622 let end = embedded_end(&body);
1623 let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind);
1624 report.end = end;
1625 advance(state, CallSignal::RemoteEnd(kind), control);
1626 break;
1627 }
1628 Ok(CallEvent::Rejection(_))
1629 if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1630 {
1631 if let Some(resend) = glare_resend.as_mut() {
1632 resend.at = Instant::now();
1633 }
1634 }
1635 Ok(CallEvent::Rejection(_))
1636 if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1637 && !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) =>
1638 {
1639 timeline.record("rejection ignored", "it names an offer that is no longer pending");
1640 }
1641 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1642 RejectedOffer::SamePeer => {
1643 same_peer_deadline = None;
1644 if let Some(pending) = same_peer.take() {
1645 rollback_offer(&current.peer).await;
1646 if is_glare_rejection(&body) {
1647 timeline.record("glare", "our offer met theirs, it goes out again");
1648 glare_resend = Some(GlareResend { change: pending.change, reply_tags: Vec::new(), at: Instant::now() + GLARE_RESEND_LIMIT });
1649 } else {
1650 undo_change(pending.change, &mut local_video, control);
1651 }
1652 }
1653 }
1654 RejectedOffer::NewPeer => {
1655 if let Some(pending) = next.take() {
1656 pending.session.peer.close();
1657 }
1658 if layout == Layout::OneToOne {
1659 drop_local_media(&mut local_video, control);
1660 }
1661 timeline.record("escalation failed", "offer rejected, staying on the old peer connection");
1662 }
1663 RejectedOffer::None => {}
1664 },
1665 Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => {
1666 if let Some(pending) = next.as_mut() {
1667 pending.retargeted = true;
1668 }
1669 }
1670 Ok(CallEvent::RetargetCompletion(body)) => {
1671 if body["retargetCompleted"]["code"].as_i64().is_some() && let Some(pending) = next.take() {
1672 pending.session.peer.close();
1673 negotiator.escalation_failed();
1674 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
1675 timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");
1676 }
1677 }
1678 Ok(CallEvent::End(end)) => {
1679 let kind = end.kind();
1680 report.end = Some(end);
1681 advance(state, CallSignal::RemoteEnd(kind), control);
1682 break;
1683 }
1684 Ok(_) => {}
1685 Err(error) => {
1686 timeline.record("callback not understood", error.to_string());
1687 }
1688 }
1689 }
1690 Some(event) = current.events.recv() => match event {
1691 PeerEvent::Ice(ice_state) => {
1692 timeline.record("ICE state", format!("{ice_state:?}"));
1693 if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() {
1694 report.ice_connected_ms = Some(timeline.elapsed_ms());
1695 }
1696 }
1697 PeerEvent::Connection(connection) => {
1698 timeline.record("PeerConnection state", format!("{connection:?}"));
1699 match connection {
1700 PeerConnectionState::Connected => {
1701 reconnect_deadline = None;
1702 if callee_gate.media_connected() {
1703 advance(state, CallSignal::MediaConnected, control);
1704 }
1705 if report.peer_connected_ms.is_none() {
1706 report.peer_connected_ms = Some(timeline.elapsed_ms());
1707 if let Some(hold) = options.hold_after_connected {
1708 let hold_until = Instant::now() + hold;
1709 leave_at = Some(hard_deadline.map_or(hold_until, |deadline| deadline.min(hold_until)));
1710 }
1711 }
1712 }
1713 PeerConnectionState::Disconnected => {
1714 if advance(state, CallSignal::MediaDisconnected, control) {
1715 reconnect_deadline = Some(Instant::now() + options.reconnect_window);
1716 }
1717 }
1718 PeerConnectionState::Failed => {
1719 advance(state, CallSignal::MediaFailed, control);
1720 break;
1721 }
1722 _ => {}
1723 }
1724 }
1725 PeerEvent::Track(remote_track) => {
1726 timeline.record("remote audio track", "receiving");
1727 let had_far_end = remote_audio.replace(remote_track.clone()).is_some();
1728 if !had_far_end && software_audio.is_some() {
1729 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline);
1730 }
1731 if options.record_remote {
1732 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
1733 }
1734 }
1735 PeerEvent::VideoTrack { mid, track } => {
1736 timeline.record("remote video track", format!("mid {mid}"));
1737 live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));
1738 }
1739 PeerEvent::Data(frame) => {
1740 if let Some(message) = depacketizer.push(&frame)
1741 && message.data_id == CAPTIONS_DATA_ID
1742 {
1743 for entry in parse_caption_message(&message.payload) {
1744 if caption_flow.text_arrived() {
1745 caption_deadline = None;
1746 control.send(CallUpdate::Captions(CaptionState::On));
1747 }
1748 control.send(CallUpdate::Caption(named_caption(entry, &roster)));
1749 }
1750 }
1751 }
1752 },
1753 Some(event) = next_peer_event(&mut next) => match event {
1754 PeerEvent::Connection(PeerConnectionState::Connected) => {
1755 if let Some(pending) = next.as_mut() {
1756 pending.connected = true;
1757 if pending.offered.is_none() && !pending.retargeted {
1758 pending.deadline = Some(Instant::now() + RETARGET_WAIT);
1759 timeline.record("escalation", "new peer connection up, waiting for retargetCompletion");
1760 }
1761 }
1762 }
1763 PeerEvent::VideoTrack { mid, track } => {
1764 timeline.record("remote video track", format!("mid {mid} (new peer)"));
1765 live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));
1766 }
1767 PeerEvent::Connection(PeerConnectionState::Failed) => {
1768 negotiator.escalation_failed();
1769 if let Some(pending) = next.take() {
1770 pending.session.peer.close();
1771 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
1772 }
1773 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
1774 }
1775 _ => {}
1776 },
1777 command = control.recv() => match command {
1778 Some(CallCommand::Mute(mute)) => {
1779 if consent_pending && !mute.target(muted) {
1780 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
1781 } else {
1782 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control);
1783 silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref());
1784 }
1785 }
1786 Some(CallCommand::DisableAudio) => {
1787 let audio = live.audio.as_ref().expect("audio set above");
1788 muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
1789 audio_disabled = true;
1790 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, None, false, &mut software_audio, control, timeline);
1791 if audio.uses_devices() {
1792 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
1793 factory.set_adm_recording_enabled(false);
1794 factory.set_adm_playout_enabled(false);
1795 }
1796 control.send(CallUpdate::ListenOnly(true));
1797 }
1798 Some(CallCommand::SelectInput(choice)) => {
1799 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1800 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
1801 applied_input = devices::applied_device(&device_lists.inputs, &choice, devices::system_default_id(Flow::Capture).as_deref());
1802 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
1803 }
1804 input = choice;
1805 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
1806 if software_audio.is_some() {
1807 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline);
1808 }
1809 }
1810 Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
1811 mic_settings = settings;
1812 crate::noise_stage::apply(mic_settings);
1813 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1814 }
1815 Some(CallCommand::SetMicSettings(settings)) => {
1816 mic_settings = settings;
1817 crate::noise_stage::apply(mic_settings);
1818 }
1819 Some(CallCommand::SelectOutput(choice)) => {
1820 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
1821 timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice)));
1822 applied_output = devices::applied_device(&device_lists.outputs, &choice, devices::system_default_id(Flow::Render).as_deref());
1823 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
1824 }
1825 output = choice;
1826 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
1827 }
1828 Some(CallCommand::RefreshDevices) => {
1829 device_lists = devices::list_devices(&factory);
1830 control.send(CallUpdate::Devices(device_lists.clone()));
1831 }
1832 Some(CallCommand::SetCamera(false)) if local_video.camera_previewing() => {
1833 start_camera_pending = false;
1834 local_video.stop_camera();
1835 control.send(CallUpdate::Camera(false));
1836 }
1837 Some(CallCommand::SetCamera(on)) => {
1838 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
1839 if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) {
1840 if remote_set && next.is_none() && negotiator.begin_conference_upgrade() {
1841 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
1842 next = pending.or(next);
1843 }
1844 if remote_set && on && next.is_some() {
1845 start_camera_pending = true;
1846 }
1847 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1848 } else if on && consent_pending {
1849 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
1850 } else if local_hold {
1851 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1852 } else if on && direct && (same_peer.is_some() || glare_resend.is_some()) {
1853 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1854 } else if on {
1855 let started = start_camera_line(&mut local_video, &current.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
1856 match started {
1857 Ok(()) if direct => {
1858 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, true, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1859 Ok((browser_offer, signaled, reply_tags)) => {
1860 timeline.record_sdp("local offer", &signaled.sdp);
1861 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
1862 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1863 }
1864 Err(error) => {
1865 timeline.record("camera offer failed", error.to_string());
1866 undo_change(Change::Camera(true), &mut local_video, control);
1867 }
1868 }
1869 }
1870 Ok(()) => {
1871 control.send(CallUpdate::Camera(true));
1872 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1873 }
1874 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1875 }
1876 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1877 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1878 } else if direct {
1879 local_video.stop_camera();
1880 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, false, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1881 Ok((browser_offer, signaled, reply_tags)) => {
1882 timeline.record_sdp("local offer", &signaled.sdp);
1883 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
1884 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1885 }
1886 Err(error) => {
1887 timeline.record("camera offer failed", error.to_string());
1888 control.send(CallUpdate::Camera(false));
1889 }
1890 }
1891 } else {
1892 local_video.stop_camera();
1893 control.send(CallUpdate::Camera(false));
1894 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(false), &mut media_description_request, timeline);
1895 }
1896 }
1897 Some(CallCommand::SelectCamera(choice)) => {
1898 camera_choice = choice;
1899 if local_video.camera_previewing()
1900 && let Err(error) = local_video.preview_camera(&camera_choice)
1901 {
1902 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
1903 } else if local_video.camera_on()
1904 && let Err(error) = local_video.start_camera(&camera_choice)
1905 {
1906 control.send(CallUpdate::Notice(format!("Camera could not start: {error}")));
1907 }
1908 }
1909 Some(CallCommand::StartShare(source)) => {
1910 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1911 if !remote_set {
1912 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1913 } else if local_hold {
1914 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1915 } else if direct && local_video.sharing() {
1916 match local_video.start_share(&source) {
1917 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
1918 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1919 }
1920 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1921 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1922 } else if direct
1923 && !local_video.has_share_line()
1924 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
1925 {
1926 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
1927 } else if direct {
1928 match local_video.start_share(&source) {
1929 Ok(()) => {
1930 control.send(CallUpdate::LocalShare(Some(source.label())));
1931 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1932 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1933 Ok((browser_offer, signaled, reply_tags)) => {
1934 timeline.record_sdp("local offer", &signaled.sdp);
1935 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
1936 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1937 }
1938 Err(error) => {
1939 timeline.record("share offer failed", error.to_string());
1940 undo_change(Change::Share(true), &mut local_video, control);
1941 }
1942 }
1943 }
1944 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1945 }
1946 } else if !video_possible(remote_set, layout, negotiator.path()) {
1947 if next.is_none() && negotiator.begin_conference_upgrade() {
1948 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
1949 next = pending.or(next);
1950 }
1951 if next.is_some() {
1952 share_pending = Some(source);
1953 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
1954 } else {
1955 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1956 }
1957 } else {
1958 match local_video.start_share(&source) {
1959 Ok(()) => {
1960 control.send(CallUpdate::LocalShare(Some(source.label())));
1961 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1962 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1963 }
1964 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1965 }
1966 }
1967 }
1968 Some(CallCommand::StopShare) => {
1969 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1970 share_pending = None;
1971 if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
1972 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1973 } else if direct && local_video.sharing() {
1974 local_video.stop_share();
1975 control.send(CallUpdate::LocalShare(None));
1976 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1977 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1978 Ok((browser_offer, signaled, reply_tags)) => {
1979 timeline.record_sdp("local offer", &signaled.sdp);
1980 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
1981 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1982 }
1983 Err(error) => timeline.record("share offer failed", error.to_string()),
1984 }
1985 } else if local_video.sharing() {
1986 local_video.stop_share();
1987 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1988 control.send(CallUpdate::LocalShare(None));
1989 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
1990 }
1991 }
1992 Some(CallCommand::SetShareSound(on)) => {
1993 share_sound_wanted = on;
1994 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1995 }
1996 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),
1997 Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
1998 Ok(receipt) => {
1999 own_hand = receipt.state_id;
2000 control.send(CallUpdate::OwnHand(Some(receipt.rank)));
2001 }
2002 Err(error) => {
2003 timeline.record("raise hand failed", error.to_string());
2004 control.send(CallUpdate::OwnHand(None));
2005 control.send(CallUpdate::Notice("Could not raise your hand".into()));
2006 }
2007 },
2008 Some(CallCommand::SetHand(false)) => {
2009 let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect();
2010 own_hand = None;
2011 control.send(CallUpdate::OwnHand(None));
2012 if !state_ids.is_empty()
2013 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2014 {
2015 timeline.record("lower hand failed", error.to_string());
2016 control.send(CallUpdate::Notice("Could not lower your hand".into()));
2017 }
2018 }
2019 Some(CallCommand::LowerHand { mri }) => {
2020 let state_ids: Vec<String> = roster.hand_of(&mri).map(|hand| hand.state_id.clone()).into_iter().collect();
2021 if !state_ids.is_empty()
2022 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2023 {
2024 timeline.record("lower hand failed", error.to_string());
2025 control.send(CallUpdate::Notice("Could not lower that hand".into()));
2026 }
2027 }
2028 Some(CallCommand::LowerAllHands) => {
2029 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
2030 timeline.record("lower all hands failed", error.to_string());
2031 control.send(CallUpdate::Notice("Could not lower all hands".into()));
2032 }
2033 }
2034 Some(CallCommand::Admit { mri }) => {
2035 let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2036 report_organizer_result(result, "admit", "Could not admit that person", control, timeline);
2037 }
2038 Some(CallCommand::AdmitAll) => {
2039 let mut result = Ok(202);
2040 for mri in roster.lobby_mris() {
2041 result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2042 if result.is_err() {
2043 break;
2044 }
2045 }
2046 report_organizer_result(result, "admit all", "Could not admit everyone", control, timeline);
2047 }
2048 Some(CallCommand::Deny { mri }) => {
2049 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2050 report_organizer_result(result, "deny", "Could not deny that person", control, timeline);
2051 }
2052 Some(CallCommand::RemoveParticipant { mri }) => {
2053 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2054 report_organizer_result(result, "remove participant", "Could not remove that person", control, timeline);
2055 }
2056 Some(CallCommand::MuteParticipant { mri }) => {
2057 let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;
2058 report_organizer_result(result, "mute participant", "Could not mute that person", control, timeline);
2059 }
2060 Some(CallCommand::MuteAll) => {
2061 let others: Vec<String> = roster
2062 .members()
2063 .iter()
2064 .filter(|member| member.mri != own_mri && !member.in_lobby && !member.mri.starts_with(BOT_PREFIX))
2065 .map(|member| member.mri.clone())
2066 .collect();
2067 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
2068 report_organizer_result(result, "mute all", "Could not mute everyone", control, timeline);
2069 }
2070 Some(CallCommand::SetLock(locked)) => {
2071 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
2072 if result.is_ok() {
2073 capability.locked = locked;
2074 control.send(CallUpdate::Capability(capability));
2075 }
2076 report_organizer_result(result, "lock meeting", "Could not change the meeting lock", control, timeline);
2077 }
2078 Some(CallCommand::SetRole { mri, role }) => {
2079 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
2080 report_organizer_result(result, "change role", "Could not change that role", control, timeline);
2081 }
2082 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
2083 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
2084 let mut result = Ok(200);
2085 for step in modality_steps(modality, allowed, capability, &limits) {
2086 result = match step {
2087 StateStep::Publish(state_type) => remote.signaling.publish_attendee_state(&remote.conversation, &remote.participant, state_type, &mri).await,
2088 StateStep::Remove(state_id) => remote.signaling.lower_hands(&remote.conversation, &remote.participant, &[state_id]).await.map(|()| 200),
2089 };
2090 if result.is_err() {
2091 break;
2092 }
2093 }
2094 let notice = if modality == Modality::Mic { "Could not change that microphone setting" } else { "Could not change that camera setting" };
2095 report_organizer_result(result, "attendee modality", notice, control, timeline);
2096 }
2097 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
2098 let result = match &meeting_target {
2099 Some(target) => meeting_options::write(&inner.session, target, &OptionWrite::restrictions(mic_off, camera_off)).await.map(|()| 200),
2100 None => Err(Error::Signaling("no meeting coordinates for the options".into())),
2101 };
2102 if result.is_ok() {
2103 capability.attendee_mic_off = mic_off;
2104 capability.attendee_camera_off = camera_off;
2105 control.send(CallUpdate::Capability(capability));
2106 }
2107 report_organizer_result(result, "attendee restrictions", "Could not change the attendee settings", control, timeline);
2108 }
2109 Some(CallCommand::Invite { callees, group_thread }) => {
2110 let thread = group_thread.or_else(|| meeting_chat.clone());
2111 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
2112 report_organizer_result(result, "invite", "Could not invite that person", control, timeline);
2113 }
2114 Some(CallCommand::LoadMeetingOptions) => {
2115 let update = match &meeting_target {
2116 Some(target) => meeting_options::fetch(&inner.session, target).await.map_err(|error| error.to_string()),
2117 None => Err("This meeting has no options page".to_owned()),
2118 };
2119 control.send(CallUpdate::MeetingOptions(update));
2120 }
2121 Some(CallCommand::SaveMeetingOptions(writes)) => {
2122 let update = match &meeting_target {
2123 Some(target) => save_meeting_options(&inner.session, target, &writes).await,
2124 None => Err("This meeting has no options page".to_owned()),
2125 };
2126 if let Ok(options) = &update {
2127 let (mic_off, camera_off) = options.attendees_off();
2128 capability.attendee_mic_off = mic_off;
2129 capability.attendee_camera_off = camera_off;
2130 control.send(CallUpdate::Capability(capability));
2131 }
2132 control.send(CallUpdate::MeetingOptionsSaved(update));
2133 }
2134 Some(CallCommand::Spotlight { mri }) => {
2135 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
2136 report_organizer_result(result, "spotlight", "Could not spotlight that person", control, timeline);
2137 }
2138 Some(CallCommand::StopSpotlight { mri }) => {
2139 let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();
2140 if !state_ids.is_empty() {
2141 let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);
2142 report_organizer_result(result, "stop spotlight", "Could not stop the spotlight", control, timeline);
2143 }
2144 }
2145 Some(CallCommand::SetCaptions(on)) => {
2146 caption_flow.want(on);
2147 if on {
2148 caption_deadline = Some(Instant::now() + CAPTION_START_LIMIT);
2149 control.send(CallUpdate::Captions(CaptionState::Starting));
2150 } else {
2151 caption_deadline = None;
2152 control.send(CallUpdate::Captions(CaptionState::Off));
2153 }
2154 run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), &RecordingPlan::default(), &mut bot_pending, control, timeline).await;
2155 if caption_flow.on() {
2156 caption_deadline = None;
2157 }
2158 }
2159 Some(CallCommand::StartRecording { kind, title }) => {
2160 if !is_echo {
2161 recording_plan = RecordingPlan { title, kind, ..RecordingPlan::default() };
2162 recording_flow.want(true);
2163 recording_deadline = Some(Instant::now() + RECORDING_START_LIMIT);
2164 control.send(CallUpdate::RecordingPending(true));
2165 run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await;
2166 }
2167 }
2168 Some(CallCommand::StopRecording { scope }) => {
2169 if !is_echo {
2170 recording_plan.scope = scope;
2171 recording_flow.stop();
2172 recording_deadline = None;
2173 run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await;
2174 }
2175 }
2176 Some(CallCommand::SetCaptionLanguage(language)) => {
2177 if let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone())
2178 && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await
2179 {
2180 timeline.record("caption language failed", error.to_string());
2181 control.send(CallUpdate::Notice("Could not change the spoken language".into()));
2182 }
2183 }
2184 Some(CallCommand::ConsentToRecording) => {
2185 match remote.signaling.consent_to_recording(&remote.conversation, &remote.participant, Consent::Give).await {
2186 Ok(_) => {
2187 consent_pending = false;
2188 control.send(CallUpdate::ConsentRequired(false));
2189 }
2190 Err(error) => {
2191 timeline.record("recording consent failed", error.to_string());
2192 control.send(CallUpdate::Notice("Could not confirm the recording notice".into()));
2193 }
2194 }
2195 }
2196 Some(CallCommand::Hold(hold)) => {
2197 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || glare_resend.is_some() || next.is_some() {
2198 continue;
2199 }
2200 if hold && local_video.camera_on() {
2201 local_video.stop_camera();
2202 control.send(CallUpdate::Camera(false));
2203 }
2204 let camera = !hold && local_video.camera_on();
2205 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), hold, camera, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2206 Ok((browser_offer, signaled, reply_tags)) => {
2207 timeline.record_sdp("local offer", &signaled.sdp);
2208 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2209 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2210 }
2211 Err(error) => {
2212 timeline.record("hold failed", error.to_string());
2213 control.send(CallUpdate::Notice(if hold { "Could not put the call on hold".into() } else { "Could not resume the call".into() }));
2214 }
2215 }
2216 }
2217 Some(CallCommand::Transfer { target, replaces }) => {
2218 let Some(url) = media_links.get("transfer").cloned() else {
2219 control.send(CallUpdate::TransferResult { succeeded: false });
2220 control.send(CallUpdate::Notice("This call cannot be transferred".into()));
2221 continue;
2222 };
2223 let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() };
2224 match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {
2225 Ok(()) => control.send(CallUpdate::Notice(format!("Transferring to {}...", target.display_name))),
2226 Err(error) => {
2227 timeline.record("transfer failed", error.to_string());
2228 control.send(CallUpdate::TransferResult { succeeded: false });
2229 control.send(CallUpdate::Notice("Could not transfer the call".into()));
2230 }
2231 }
2232 }
2233 Some(CallCommand::OpenWhiteboard { title }) => {
2234 let Some(target) = meeting_target.clone() else {
2235 control.send(CallUpdate::Notice("Whiteboards belong to meetings".into()));
2236 continue;
2237 };
2238 let session = inner.session.clone();
2239 let updates = control.updates();
2240 tokio::spawn(async move {
2241 let update = match whiteboard::fetch_board(&session, &target, &title).await {
2242 Ok(url) => CallUpdate::WhiteboardUrl(url),
2243 Err(_) => CallUpdate::Notice("The whiteboard could not be opened".into()),
2244 };
2245 let _ = updates.send(update);
2246 });
2247 }
2248 Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,
2249 Some(CallCommand::SetIncomingVideo(enabled)) => {
2250 video.set_incoming_enabled(enabled);
2251 if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) {
2252 let key = VideoKey::Person(mri.clone());
2253 control.video.forget(&key);
2254 video.router().set(mid, enabled.then_some(key));
2255 }
2256 send_receive_change(control, video.reselect(&roster));
2257 control.send(CallUpdate::IncomingVideo(enabled));
2258 }
2259 Some(CallCommand::SetVideoWants(wants)) => {
2260 if video.set_wants(wants) {
2261 send_receive_change(control, video.reselect(&roster));
2262 }
2263 }
2264 Some(CallCommand::SetShareMotion(on)) => local_video.set_motion(on),
2265 Some(CallCommand::SetShareStandout(on)) => local_video.set_standout(on),
2266 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
2267 Some(CallCommand::SendReaction(reaction)) => {
2268 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
2269 timeline.record("reaction failed", error.to_string());
2270 control.send(CallUpdate::Notice("Could not send the reaction".into()));
2271 }
2272 }
2273 Some(CallCommand::EndMeeting) => {
2274 if is_meeting {
2275 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
2276 Ok(()) => {
2277 live.skip_leave = true;
2278 report.left_cleanly = true;
2279 }
2280 Err(error) => timeline.record("end meeting failed", error.to_string()),
2281 }
2282 }
2283 advance(state, CallSignal::LocalLeave, control);
2284 break;
2285 }
2286 Some(CallCommand::Hangup) | None => {
2287 advance(state, CallSignal::LocalLeave, control);
2288 break;
2289 }
2290 },
2291 _ = stats_tick.tick(), if remote_set => {
2292 let snapshot = collect_stats(&current.peer, &layout_plan.screen_share_mids).await;
2293 ticks += 1;
2294 if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
2295 caption_deadline = None;
2296 caption_flow.failed();
2297 timeline.record("captions", "did not start in time");
2298 control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into())));
2299 }
2300 if recording_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
2301 recording_deadline = None;
2302 recording_flow.failed();
2303 timeline.record("recording", "did not start in time");
2304 control.send(CallUpdate::RecordingPending(false));
2305 control.send(CallUpdate::Notice("The recording did not start".into()));
2306 }
2307 if layout == Layout::Conference
2308 && let Some(size) = local_video.camera_size()
2309 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2310 && let Some(body) = send_capabilities.body_for(size)
2311 {
2312 let signaling = signaling.clone();
2313 let timeline = timeline.clone();
2314 tokio::spawn(async move {
2315 match signaling.post_json(SEND_CAPABILITIES_LABEL, &url, body).await {
2316 Ok(()) => timeline.record("send capabilities", format!("{}x{} accepted", size.0, size.1)),
2317 Err(error) => timeline.record("send capabilities failed", error.to_string()),
2318 }
2319 });
2320 }
2321 for (source, refreshed) in local_video.refresh_send_limits() {
2322 match refreshed {
2323 Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?} after a frame size change")),
2324 Ok(None) => {}
2325 Err(error) => timeline.record("send limits failed", error.to_string()),
2326 }
2327 }
2328 if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)
2329 && let Some(average_ms) = local_video.blur_average_ms()
2330 {
2331 control.send(CallUpdate::BlurTiming(average_ms));
2332 if let Some(model) = local_video.blur_model().filter(|model| Some(*model) != segmentation_model) {
2333 timeline.record("segmentation model", format!("{model}, effects {average_ms:.1} ms per frame"));
2334 segmentation_model = Some(model);
2335 }
2336 }
2337 if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {
2338 control.send(CallUpdate::Sample(StatsSample {
2339 audio_in_packets: snapshot.inbound_packets,
2340 audio_out_packets: snapshot.outbound_packets,
2341 audio_in_level: snapshot.audio_level,
2342 audio_out_level: snapshot.local_level,
2343 video: VideoReport {
2344 frames_received: live.video_counters.received.load(Ordering::Relaxed),
2345 frames_published: live.video_counters.published.load(Ordering::Relaxed),
2346 ..snapshot.video.clone()
2347 },
2348 share_in_packets: snapshot.share_inbound_packets,
2349 share_out_packets: snapshot.share_outbound_packets,
2350 }));
2351 }
2352 if ticks.is_multiple_of(HEALTH_EVERY_TICKS)
2353 && snapshot.selected_pair.is_some()
2354 && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)
2355 {
2356 let quality = quality_tracker.observe(std::time::Instant::now(), &sample);
2357 control.send(CallUpdate::Health(CallHealth {
2358 level: quality.level,
2359 cpu_limited: quality.cpu_limited,
2360 sample,
2361 transport: snapshot.transport.clone(),
2362 path: negotiator.path(),
2363 }));
2364 }
2365 let local_level = if muted && software_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };
2366 control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
2367 if snapshot.selected_pair.is_some() {
2368 report.selected_pair = snapshot.selected_pair.clone();
2369 report.tls_version = snapshot.tls_version.clone();
2370 report.dtls_cipher = snapshot.dtls_cipher.clone();
2371 report.srtp_cipher = snapshot.srtp_cipher.clone();
2372 }
2373 report.inbound_packets = snapshot.inbound_packets;
2374 report.inbound_bytes = snapshot.inbound_bytes;
2375 report.outbound_packets = snapshot.outbound_packets;
2376 report.video = VideoReport {
2377 frames_received: live.video_counters.received.load(Ordering::Relaxed),
2378 frames_published: live.video_counters.published.load(Ordering::Relaxed),
2379 ..snapshot.video.clone()
2380 };
2381 if ticks.is_multiple_of(TICKS_PER_SECOND) {
2382 second += 1;
2383 let (decoded_rms, ratio) = {
2384 let recording = recording.lock().await;
2385 recording.per_second.last().copied().unwrap_or_default()
2386 };
2387 if snapshot.inbound_packets > previous_packets {
2388 report.seconds_with_inbound_audio += 1;
2389 }
2390 previous_packets = snapshot.inbound_packets;
2391 report.seconds.push(AudioSecond {
2392 second,
2393 packets: snapshot.inbound_packets,
2394 bytes: snapshot.inbound_bytes,
2395 audio_level: snapshot.audio_level,
2396 decoded_rms,
2397 tone_ratio: ratio,
2398 });
2399 control.send(CallUpdate::Stats {
2400 inbound_packets: snapshot.inbound_packets,
2401 outbound_packets: snapshot.outbound_packets,
2402 });
2403 timeline.record(
2404 "stats",
2405 format!(
2406 "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) out bytes={} sources={:?} video senders={:?}{}",
2407 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2408 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2409 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2410 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2411 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default()
2412 ),
2413 );
2414 }
2415 }
2416 Some(()) = device_changes.recv() => {
2417 device_debounce.signal(Instant::now());
2418 }
2419 _ = sleep_until(device_debounce.deadline().unwrap_or_else(far_future)), if device_debounce.deadline().is_some() => {
2420 if device_debounce.take_due(Instant::now()) {
2421 let previous = std::mem::replace(&mut device_lists, devices::list_devices(&factory));
2422 control.send(CallUpdate::Devices(device_lists.clone()));
2423 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2424 let input_changed = follow_device_change(Flow::Capture, (&previous.inputs, &device_lists.inputs), &input, &mut applied_input, |index| devices::select_input_index(&factory, index), timeline, control);
2425 let output_changed = follow_device_change(Flow::Render, (&previous.outputs, &device_lists.outputs), &output, &mut applied_output, |index| devices::select_output_index(&factory, index), timeline, control);
2426 if input_changed || output_changed {
2427 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2428 }
2429 if input_changed && software_audio.is_some() {
2430 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), true, &mut software_audio, control, timeline);
2431 }
2432 }
2433 }
2434 }
2435 _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => {
2436 advance(state, CallSignal::ReconnectTimedOut, control);
2437 break;
2438 }
2439 _ = sleep_until(leave_at.unwrap_or_else(far_future)), if leave_at.is_some() => {
2440 advance(state, CallSignal::LocalLeave, control);
2441 break;
2442 }
2443 _ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {
2444 if let Some(pending) = next.as_mut().filter(|pending| pending.connected && pending.offered.is_none()) {
2445 pending.retargeted = true;
2446 timeline.record("escalation", "no retargetCompletion, switching anyway");
2447 } else if let Some(pending) = next.take() {
2448 pending.session.peer.close();
2449 negotiator.escalation_failed();
2450 start_camera_pending = false;
2451 if local_video.camera_previewing() {
2452 local_video.stop_camera();
2453 control.send(CallUpdate::Camera(false));
2454 }
2455 share_pending = None;
2456 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2457 timeline.record("escalation failed", "no answer for the new peer connection in time");
2458 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2459 }
2460 }
2461 _ = sleep_until(glare_at.unwrap_or_else(far_future)), if glare_at.is_some() => {
2462 let resend = glare_resend.take();
2463 if let Some(resend) = resend.as_ref().filter(|_| same_peer.is_some() || next.is_some()) {
2464 timeline.record("glare", "another change took over, ours is dropped");
2465 undo_change(resend.change, &mut local_video, control);
2466 } else if let Some(resend) = resend.as_ref().filter(|resend| layout == Layout::OneToOne && negotiator.path() == MediaPath::Mixer && !matches!(resend.change, Change::Hold(_))) {
2467 if negotiator.begin_conference_upgrade() {
2468 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2469 if pending.is_none() {
2470 drop_local_media(&mut local_video, control);
2471 }
2472 next = pending.or(next);
2473 } else {
2474 undo_change(resend.change, &mut local_video, control);
2475 }
2476 } else if let Some(resend) = resend {
2477 let (hold, camera, share) = match resend.change {
2478 Change::Hold(hold) => (hold, !hold && local_video.camera_on(), local_video.sharing()),
2479 _ => (local_hold, local_video.camera_on(), local_video.sharing()),
2480 };
2481 match offer_same_peer(&current.peer, &current.gathered, local_video.share_mid(), &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), hold, camera, share, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
2482 Ok((browser_offer, signaled, reply_tags)) => {
2483 timeline.record_sdp("local offer", &signaled.sdp);
2484 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2485 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2486 }
2487 Err(error) => {
2488 timeline.record("offer after glare failed", error.to_string());
2489 undo_change(resend.change, &mut local_video, control);
2490 }
2491 }
2492 }
2493 }
2494 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2495 same_peer_deadline = None;
2496 if let Some(pending) = same_peer.take() {
2497 timeline.record("same-peer offer", "no answer in time");
2498 negotiator.same_peer_offer_failed();
2499 rollback_offer(&current.peer).await;
2500 undo_change(pending.change, &mut local_video, control);
2501 }
2502 }
2503 _ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => {
2504 timeline.record("no answer", "outgoing call timed out");
2505 live.cancel_leave = true;
2506 advance(state, CallSignal::RemoteEnd(EndKind::NoAnswer), control);
2507 break;
2508 }
2509 _ = sleep_until(keep_alive_at.unwrap_or_else(far_future)), if keep_alive_at.is_some() => {
2510 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
2511 let remote = remote.clone();
2512 let links = links.clone();
2513 let call_leg = keep_alive_link.clone();
2514 tokio::spawn(async move {
2515 if let Some(url) = call_leg {
2516 let _ = remote.signaling.keep_call_alive(&url).await;
2517 }
2518 let _ = remote.signaling.keep_conversation_alive(&remote.conversation, &remote.participant, &links).await;
2519 });
2520 }
2521 }
2522 }
2523 live.callbacks = Some(callbacks);
2524 Ok(())
2525}
2526
2527#[allow(clippy::too_many_arguments)]
2528async fn start_escalation(
2529 factory: &PeerConnectionFactory,
2530 grant: &RelayGrant,
2531 options: &CallOptions,
2532 track: &RtcAudioTrack,
2533 remote: &RemoteCall,
2534 links: &CallbackLinks,
2535 media_leg_id: &str,
2536 acceptance_links: &BTreeMap<String, String>,
2537) -> Result<NextPeer> {
2538 let url = acceptance_links
2539 .get("mediaRenegotiation")
2540 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2541 let session = open_peer(factory, grant, &options.relay_host, false)?;
2542 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
2543 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);
2544 let reply_tags = offer_reply_tags(&body);
2545 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
2546 Ok(NextPeer {
2547 session,
2548 offered: Some(media),
2549 reply_tags,
2550 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
2551 connected: false,
2552 retargeted: false,
2553 })
2554}
2555
2556#[allow(clippy::too_many_arguments)]
2557async fn escalate(
2558 factory: &PeerConnectionFactory,
2559 grant: &RelayGrant,
2560 options: &CallOptions,
2561 track: &RtcAudioTrack,
2562 remote: &RemoteCall,
2563 links: &CallbackLinks,
2564 media_leg_id: &str,
2565 acceptance_links: &BTreeMap<String, String>,
2566 negotiator: &mut MediaNegotiator,
2567 live: &mut Live,
2568 timeline: &Timeline,
2569) -> Option<NextPeer> {
2570 match start_escalation(
2571 factory,
2572 grant,
2573 options,
2574 track,
2575 remote,
2576 links,
2577 media_leg_id,
2578 acceptance_links,
2579 )
2580 .await
2581 {
2582 Ok(pending) => {
2583 timeline.record("escalation", "new peer connection, new offer sent");
2584 if let Some(media) = &pending.offered {
2585 timeline.record_sdp("local offer", &media.signaled.sdp);
2586 }
2587 live.peers.push(pending.session.peer.clone());
2588 Some(pending)
2589 }
2590 Err(error) => {
2591 negotiator.escalation_failed();
2592 timeline.record("escalation failed", error.to_string());
2593 None
2594 }
2595 }
2596}
2597
2598async fn answer_on_new_peer(
2599 factory: &PeerConnectionFactory,
2600 grant: &RelayGrant,
2601 options: &CallOptions,
2602 track: &RtcAudioTrack,
2603 teams_offer: &str,
2604) -> Result<(PeerSession, AnsweredMedia)> {
2605 let session = open_peer(factory, grant, &options.relay_host, false)?;
2606 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, None, false, None).await?;
2607 Ok((session, answered))
2608}
2609
2610async fn send_media_answer(
2611 remote: &RemoteCall,
2612 links: &CallbackLinks,
2613 reply_links: &BTreeMap<String, String>,
2614 answered: &AnsweredMedia,
2615 media_leg_id: &str,
2616) -> Result<()> {
2617 let url = reply_links
2618 .get("mediaAnswer")
2619 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
2620 let body = escalation_answer_body(&remote.participant, links, &answered.answer_sdp, media_leg_id);
2621 remote.signaling.post_json("POST mediaAnswer", url, body).await
2622}
2623
2624#[allow(clippy::too_many_arguments)]
2625fn negotiate_video(
2626 video: &mut VideoReceive,
2627 signaling: &Arc<Signaling>,
2628 control: &CallControl,
2629 timeline: &Timeline,
2630 answer_sdp: &str,
2631 media: &OfferedMedia,
2632 from_mixer: bool,
2633 links: &BTreeMap<String, String>,
2634 roster: &Roster,
2635) {
2636 let streams = match stream_lines(answer_sdp, &media.signaled.lines) {
2637 Ok(streams) => streams,
2638 Err(error) => {
2639 timeline.record("video slots unknown", error.to_string());
2640 return;
2641 }
2642 };
2643 let table = SlotTable::from_streams(&streams);
2644 let link = links.get("applyChannelParameters").or_else(|| links.get("controlVideoStreaming"));
2645 timeline.record(
2646 "video slots",
2647 format!(
2648 "{} receive slot(s), screen {}, fromMixer={from_mixer}, request link {}",
2649 table.people.len(),
2650 table.screen.is_some(),
2651 link.is_some()
2652 ),
2653 );
2654 let requester = link
2655 .filter(|_| from_mixer)
2656 .map(|url| SourceRequester::start(signaling.clone(), url.clone(), video.router().clone(), control.video.clone(), timeline.clone()));
2657 video.negotiated(table, requester);
2658 send_receive_change(control, video.reselect(roster));
2659}
2660
2661const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";
2662const ON_HOLD_NOTICE: &str = "Resume the call first";
2663const CHANGE_RUNNING_NOTICE: &str = "Another change is still running, try again in a moment";
2664const VIDEO_FAILED_NOTICE: &str = "Video could not start, the call stays audio only";
2665const SHARE_QUEUED_NOTICE: &str = "Sharing starts in a moment";
2666const SHARE_REFUSED_NOTICE: &str = "The other side did not accept the screen share";
2667
2668async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
2669 match mode {
2670 VideoMode::Pattern => vec![CameraDevice { key: "pattern".into(), name: "Test pattern".into() }],
2671 VideoMode::Off => Vec::new(),
2672 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras).await.unwrap_or_default(),
2673 }
2674}
2675
2676fn refresh_cameras(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode, timeline: Timeline) {
2677 tokio::spawn(async move {
2678 let started = Instant::now();
2679 let cameras = camera_devices(mode).await;
2680 timeline.record("camera list", format!("{} camera(s) in {} ms", cameras.len(), started.elapsed().as_millis()));
2681 let _ = updates.send(CallUpdate::Cameras(cameras));
2682 });
2683}
2684
2685const SHARE_THUMBNAIL_WINDOWS: usize = 12;
2686const SHARE_THUMBNAIL_WIDTH: u32 = 320;
2687const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
2688
2689fn refresh_share_sources(updates: mpsc::UnboundedSender<CallUpdate>, mode: VideoMode, with_thumbnails: bool) {
2690 tokio::spawn(async move {
2691 let sources = match mode {
2692 VideoMode::Pattern => vec![
2693 ShareSource { id: 1, kind: ShareKind::Screen, title: "Test screen".into() },
2694 ShareSource { id: 2, kind: ShareKind::Window, title: "Test window".into() },
2695 ],
2696 VideoMode::Off => Vec::new(),
2697 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources).await.unwrap_or_default(),
2698 };
2699 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
2700 if !with_thumbnails {
2701 return;
2702 }
2703 let wanted: Vec<ShareSource> = sources
2704 .iter()
2705 .filter(|source| source.kind == ShareKind::Screen)
2706 .chain(sources.iter().filter(|source| source.kind == ShareKind::Window).take(SHARE_THUMBNAIL_WINDOWS))
2707 .cloned()
2708 .collect();
2709 for source in wanted {
2710 let picture = match mode {
2711 VideoMode::Platform => {
2712 let wanted = source.clone();
2713 tokio::task::spawn_blocking(move || share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)).await.ok().flatten()
2714 }
2715 VideoMode::Pattern => Some(VideoPicture::solid(SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT, 120, 80, 40)),
2716 VideoMode::Off => None,
2717 };
2718 if let Some(picture) = picture
2719 && updates.send(CallUpdate::ShareThumbnail { source, picture: Arc::new(picture) }).is_err()
2720 {
2721 return;
2722 }
2723 }
2724 });
2725}
2726
2727fn tell_media_descriptions(
2728 remote: &RemoteCall,
2729 links: &BTreeMap<String, String>,
2730 description: MediaDescription,
2731 request_id: &mut u32,
2732 timeline: &Timeline,
2733) {
2734 let Some(url) = links.get("updateMediaDescriptions").cloned() else {
2735 timeline.record("updateMediaDescriptions skipped", "no link from the mixer");
2736 return;
2737 };
2738 *request_id += 1;
2739 let request_id = *request_id;
2740 let signaling = remote.signaling.clone();
2741 let timeline = timeline.clone();
2742 tokio::spawn(async move {
2743 let sent = format!("{} {} request {request_id}", description.mid, description.direction);
2744 if let Err(error) = signaling.update_media_descriptions(&url, &[description], request_id).await {
2745 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
2746 }
2747 });
2748}
2749
2750fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
2751 own.is_some_and(|own| own.thread_id == target.thread_id)
2752}
2753
2754fn attach_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory, local_video: &mut LocalVideo, camera_mid: Option<&str>) -> Result<()> {
2755 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
2756 if !local_video.has_lines() && camera.is_none() {
2757 return Err(Error::Webrtc("no video line negotiated".into()));
2758 }
2759 let share = add_share_line(peer, factory)?;
2760 local_video.add_share_line(share.clone(), camera).inspect_err(|_| {
2761 let _ = share.stop();
2762 })
2763}
2764
2765fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
2766 peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid))
2767}
2768
2769fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct_mid: Option<&str>, choice: &DeviceChoice) -> Result<()> {
2770 if !local_video.has_lines() {
2771 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
2772 let camera = peer_transceiver(peer, mid).ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
2773 if !matches!(camera.direction(), RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly) {
2774 peer.add_track(MediaStreamTrack::Video(local_video.camera_track()), &[CAMERA_STREAM])
2775 .map_err(|error| Error::Webrtc(error.to_string()))?;
2776 }
2777 local_video.set_lines(VideoLines { camera, share: None })?;
2778 }
2779 local_video.start_camera(choice)
2780}
2781
2782#[allow(clippy::too_many_arguments)]
2783async fn offer_same_peer(
2784 peer: &PeerConnection,
2785 gathered: &Gathered,
2786 own_share_mid: Option<String>,
2787 plan: &OfferPlan,
2788 layout: Layout,
2789 camera_mid: &str,
2790 hold: bool,
2791 camera: bool,
2792 share: bool,
2793 remote: &RemoteCall,
2794 links: &CallbackLinks,
2795 media_leg_id: &str,
2796 media_links: &BTreeMap<String, String>,
2797 negotiator: &mut MediaNegotiator,
2798) -> Result<(String, SignaledOffer, Vec<String>)> {
2799 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2800 let url = media_links
2801 .get("mediaRenegotiation")
2802 .cloned()
2803 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
2804 if !negotiator.begin_same_peer_offer() {
2805 return Err(Error::Signaling("another media negotiation is running".into()));
2806 }
2807 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid, own_share_mid, direct.then_some(gathered)).await;
2808 let (text, signaled) = match offered {
2809 Ok(offered) => offered,
2810 Err(error) => {
2811 negotiator.same_peer_offer_failed();
2812 return Err(error);
2813 }
2814 };
2815 let modalities = offer_modalities(layout == Layout::OneToOne && camera && !hold, share && !hold);
2816 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
2817 let reply_tags = offer_reply_tags(&body);
2818 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
2819 negotiator.same_peer_offer_failed();
2820 rollback_offer(peer).await;
2821 return Err(error);
2822 }
2823 Ok((text, signaled, reply_tags))
2824}
2825
2826#[allow(clippy::too_many_arguments)]
2827async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, own_share_mid: Option<String>, gathered: Option<&Gathered>) -> Result<(String, SignaledOffer)> {
2828 let offer = peer
2829 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
2830 .await
2831 .map_err(|error| Error::Webrtc(error.to_string()))?;
2832 let offer_text = offer.to_string();
2833 let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text));
2834 let remote_shares = share_mid.as_deref().is_some_and(|mid| {
2835 peer.current_remote_description()
2836 .and_then(|remote| direction_of(&remote.to_string(), mid))
2837 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
2838 });
2839 let text = directions_for(layout, false, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &offer_text);
2840 let description = parse_sdp(&text, SdpType::Offer)?;
2841 peer.set_local_description(description)
2842 .await
2843 .map_err(|error| Error::Webrtc(error.to_string()))?;
2844 let mut numbers = random_u32;
2845 let mut plan = plan.clone();
2846 if let Some(mid) = share_mid.as_ref().filter(|mid| !plan.screen_share_mids.contains(mid)) {
2847 plan.screen_share_mids.push(mid.clone());
2848 }
2849 let mut signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &text), &plan, &mut numbers)?;
2850 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
2851 if gathered.is_some()
2852 && let Some(role) = negotiated_setup(
2853 peer.current_local_description().map(|local| local.to_string()).as_deref(),
2854 peer.current_remote_description().map(|remote| remote.to_string()).as_deref(),
2855 )
2856 {
2857 signaled.sdp = signaled.sdp.replace("a=setup:actpass", &format!("a=setup:{role}"));
2858 }
2859 Ok((text, signaled))
2860}
2861
2862/// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging.
2863fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
2864 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
2865 Ok(Ok(description)) => Ok(description),
2866 Ok(Err(error)) => Err(Error::Sdp(format!("{kind:?} rejected: {}", error.description))),
2867 Err(_) => Err(Error::Sdp(format!("{kind:?} rejected, libwebrtc gave no readable reason"))),
2868 }
2869}
2870
2871async fn rollback_offer(peer: &PeerConnection) {
2872 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
2873 let _ = peer.set_local_description(rollback).await;
2874 }
2875}
2876
2877async fn rollback_remote_offer(peer: &PeerConnection) {
2878 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
2879 let _ = peer.set_remote_description(rollback).await;
2880 }
2881}
2882
2883fn is_glare_rejection(body: &serde_json::Value) -> bool {
2884 body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE)
2885}
2886
2887fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2888 let links = &body["mediaNegotiation"]["links"];
2889 ["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
2890}
2891
2892#[cfg(test)]
2893mod reply_tag_tests {
2894 use super::*;
2895
2896 #[test]
2897 fn answers_and_rejections_match_the_offer_by_tag() {
2898 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
2899 assert!(answers_offer("callAgent/c/aaaa1111/call/mediaAnswer/", &tags));
2900 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
2901 assert!(!answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &tags));
2902 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
2903 }
2904
2905 #[test]
2906 fn an_offer_names_both_reply_tags() {
2907 let body = serde_json::json!({"mediaNegotiation": {"links": {
2908 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
2909 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
2910 assert_eq!(offer_reply_tags(&body), vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]);
2911 }
2912}
2913
2914fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
2915 match change {
2916 Change::Camera(true) => {
2917 control.send(CallUpdate::Camera(true));
2918 deferred.push(change);
2919 }
2920 Change::Share(true) => deferred.push(change),
2921 change => undo_change(change, local_video, control),
2922 }
2923}
2924
2925/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
2926fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut MediaNegotiator, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
2927 if server {
2928 negotiator.server_escalation_failed();
2929 for change in deferred.drain(..) {
2930 undo_change(change, local_video, control);
2931 }
2932 } else if layout == Layout::OneToOne {
2933 drop_local_media(local_video, control);
2934 }
2935}
2936
2937fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2938 if local_video.sharing() {
2939 local_video.stop_share();
2940 control.send(CallUpdate::LocalShare(None));
2941 }
2942 if local_video.camera_on() {
2943 local_video.stop_camera();
2944 control.send(CallUpdate::Camera(false));
2945 }
2946}
2947
2948fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {
2949 match change {
2950 Change::Camera(true) => {
2951 local_video.stop_camera();
2952 control.send(CallUpdate::Camera(false));
2953 }
2954 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
2955 Change::Share(true) => {
2956 local_video.stop_share();
2957 control.send(CallUpdate::LocalShare(None));
2958 control.send(CallUpdate::Notice("Sharing could not start".into()));
2959 }
2960 Change::Share(false) => {}
2961 Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())),
2962 }
2963}
2964
2965fn withhold_media(
2966 muted: &mut bool,
2967 audio: &AudioSetup,
2968 software_audio: Option<&SoftwareAudio>,
2969 remote: &RemoteCall,
2970 local_video: &mut LocalVideo,
2971 control: &CallControl,
2972) {
2973 *muted = apply_mute(MuteCommand::Mute, *muted, audio, software_audio, remote, control);
2974 if local_video.camera_on() {
2975 local_video.stop_camera();
2976 control.send(CallUpdate::Camera(false));
2977 }
2978}
2979
2980async fn apply_background(choice: BackgroundChoice, local_video: &LocalVideo, control: &CallControl, timeline: &Timeline) {
2981 match choice {
2982 BackgroundChoice::None => local_video.set_background(false, None),
2983 BackgroundChoice::Blur => local_video.set_background(true, None),
2984 BackgroundChoice::Image(path) => match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
2985 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
2986 Ok(Err(error)) => {
2987 timeline.record("background image failed", error.to_string());
2988 control.send(CallUpdate::Notice("That background image could not be used".into()));
2989 }
2990 Err(_) => {}
2991 },
2992 }
2993}
2994
2995async fn save_meeting_options(session: &session::Session, target: &MeetingTarget, writes: &[OptionWrite]) -> std::result::Result<meeting_options::MeetingOptions, String> {
2996 for change in writes {
2997 meeting_options::write(session, target, change).await.map_err(|error| error.to_string())?;
2998 }
2999 meeting_options::fetch(session, target).await.map_err(|error| error.to_string())
3000}
3001
3002fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
3003 let display_name = roster.members().iter().find(|member| member.mri == mri).map_or("", |member| member.display_name.as_str());
3004 Target { mri, display_name }
3005}
3006
3007const RECORDING_STOP_RETRIES: usize = 6;
3008const RECORDING_STOP_RETRY_WAIT: Duration = Duration::from_secs(5);
3009
3010/// The recorder answers 409 to a stop sent while its start is still settling.
3011fn recorder_busy(error: &Error) -> bool {
3012 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
3013}
3014
3015fn report_organizer_result(result: Result<u16>, label: &str, notice: &str, control: &CallControl, timeline: &Timeline) {
3016 if let Err(error) = &result {
3017 timeline.record(format!("{label} failed"), error.to_string());
3018 control.send(CallUpdate::Notice(notice.into()));
3019 }
3020 control.send(CallUpdate::Organizer { action: label.to_owned(), outcome: result.map_err(|error| error.to_string()) });
3021}
3022
3023fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
3024 if entry.display_name.is_empty() {
3025 entry.display_name = roster.name_of(&entry.user_id).unwrap_or_default().to_owned();
3026 }
3027 entry
3028}
3029
3030#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3031enum BotJob {
3032 Captions,
3033 Recording,
3034}
3035
3036#[allow(clippy::too_many_arguments)]
3037async fn run_bot_steps(
3038 job: BotJob,
3039 flow: &mut CaptionFlow,
3040 roster: &Roster,
3041 remote: &RemoteCall,
3042 links: &CallbackLinks,
3043 meeting_chat: Option<&str>,
3044 plan: &RecordingPlan,
3045 bot_pending: &mut bool,
3046 control: &CallControl,
3047 timeline: &Timeline,
3048) {
3049 let is_active: fn(&crate::roster::CaptionBot) -> bool = match job {
3050 BotJob::Captions => |bot| bot.active,
3051 BotJob::Recording => |bot| bot.recording,
3052 };
3053 let fail = |flow: &mut CaptionFlow, reason: &str| {
3054 flow.failed();
3055 control.send(match job {
3056 BotJob::Captions => CallUpdate::Captions(CaptionState::Failed(reason.to_owned())),
3057 BotJob::Recording => CallUpdate::Notice(reason.to_owned()),
3058 });
3059 if job == BotJob::Recording {
3060 control.send(CallUpdate::RecordingPending(false));
3061 }
3062 };
3063 let (join_failure, start_failure) = match job {
3064 BotJob::Captions => ("The captions service could not join", "Captions could not start"),
3065 BotJob::Recording => ("The recording service could not join", "The recording could not start"),
3066 };
3067 loop {
3068 match flow.next_for(roster.caption_bot(), is_active) {
3069 CaptionStep::Wait => return,
3070 CaptionStep::AddBot => {
3071 if *bot_pending {
3072 continue;
3073 }
3074 let Some(thread) = meeting_chat else {
3075 return fail(flow, "This call has no chat for the captions and the recording");
3076 };
3077 *bot_pending = true;
3078 let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links, remote.threadless).await;
3079 if job == BotJob::Recording {
3080 report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline);
3081 }
3082 if let Err(error) = added {
3083 timeline.record("bot invitation failed", error.to_string());
3084 *bot_pending = false;
3085 return fail(flow, join_failure);
3086 }
3087 }
3088 CaptionStep::Start => {
3089 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { return };
3090 match job {
3091 BotJob::Captions => {
3092 if let Err(error) = remote.signaling.caption_command(&url, BotAction::Start, &remote.participant).await {
3093 timeline.record("caption start failed", error.to_string());
3094 return fail(flow, start_failure);
3095 }
3096 if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, true).await {
3097 timeline.record("caption preference failed", error.to_string());
3098 }
3099 }
3100 BotJob::Recording => {
3101 let started = remote.signaling.recording_command(&url, plan.start(), &remote.participant, &plan.title).await;
3102 let failed = started.is_err();
3103 report_organizer_result(started, "recording start", start_failure, control, timeline);
3104 if failed {
3105 return fail(flow, start_failure);
3106 }
3107 }
3108 }
3109 }
3110 CaptionStep::Stop => {
3111 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else { continue };
3112 match job {
3113 BotJob::Captions => {
3114 if let Err(error) = remote.signaling.caption_command(&url, BotAction::Stop, &remote.participant).await {
3115 timeline.record("caption stop failed", error.to_string());
3116 }
3117 if let Err(error) = remote.signaling.set_caption_preference(&remote.conversation, &remote.participant, false).await {
3118 timeline.record("caption preference failed", error.to_string());
3119 }
3120 }
3121 BotJob::Recording => {
3122 let remote = remote.clone();
3123 let updates = control.updates();
3124 let (command, title) = (plan.stop(), plan.title.clone());
3125 tokio::spawn(async move {
3126 let mut stopped = remote.signaling.recording_command(&url, command, &remote.participant, &title).await;
3127 for _ in 0..RECORDING_STOP_RETRIES {
3128 if !stopped.as_ref().is_err_and(recorder_busy) {
3129 break;
3130 }
3131 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
3132 stopped = remote.signaling.recording_command(&url, command, &remote.participant, &title).await;
3133 }
3134 if stopped.is_err() {
3135 let _ = updates.send(CallUpdate::Notice("The recording could not be stopped".into()));
3136 }
3137 let _ = updates.send(CallUpdate::Organizer { action: "recording stop".into(), outcome: stopped.map_err(|error| error.to_string()) });
3138 });
3139 }
3140 }
3141 }
3142 CaptionStep::ReportOn => {
3143 if job == BotJob::Captions {
3144 control.send(CallUpdate::Captions(CaptionState::On));
3145 }
3146 }
3147 }
3148 }
3149}
3150
3151fn send_receive_change(control: &CallControl, change: ReceiveChange) {
3152 if let Some(sharer) = change.screen_sharer {
3153 control.send(CallUpdate::ScreenShare(sharer));
3154 }
3155}
3156
3157fn record_audio_devices(timeline: &Timeline, lists: &devices::DeviceLists, input: Option<&AppliedDevice>, output: Option<&AppliedDevice>) {
3158 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
3159 applied
3160 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
3161 .map_or("none", |device| device.name.as_str())
3162 .to_owned()
3163 };
3164 timeline.record(
3165 "audio devices",
3166 format!("input={} output={}", name(&lists.inputs, input), name(&lists.outputs, output)),
3167 );
3168}
3169
3170fn follow_device_change(
3171 flow: Flow,
3172 (previous, current): (&[AudioDevice], &[AudioDevice]),
3173 choice: &DeviceChoice,
3174 applied: &mut Option<AppliedDevice>,
3175 select: impl Fn(u16) -> bool,
3176 timeline: &Timeline,
3177 control: &CallControl,
3178) -> bool {
3179 let system_default = devices::system_default_id(flow);
3180 let (index, fell_back) = match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
3181 Reselect::Keep => return false,
3182 Reselect::Select(index) => (index, false),
3183 Reselect::FallBack(index) => (index, true),
3184 };
3185 let selected = select(index);
3186 timeline.record("device change", format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"));
3187 if selected {
3188 *applied = current.iter().find(|device| device.index == index).map(|device| AppliedDevice { index, key: device.key() });
3189 }
3190 if fell_back {
3191 let fallback = current.iter().find(|device| device.index == index);
3192 control.send(CallUpdate::Notice(devices::disconnect_notice(previous, choice, fallback)));
3193 }
3194 selected
3195}
3196
3197fn far_future() -> Instant {
3198 Instant::now() + FAR_FUTURE
3199}
3200
3201fn apply_mute(
3202 command: MuteCommand,
3203 currently_muted: bool,
3204 audio: &AudioSetup,
3205 software_audio: Option<&SoftwareAudio>,
3206 remote: &RemoteCall,
3207 control: &CallControl,
3208) -> bool {
3209 let effect = MuteEffect::for_muted(command.target(currently_muted));
3210 audio.track.set_enabled(effect.track_enabled);
3211 if let Some(software_audio) = software_audio {
3212 software_audio.set_microphone_muted(effect.muted);
3213 }
3214 control.send(CallUpdate::Muted(effect.muted));
3215 let remote = remote.clone();
3216 tokio::spawn(async move {
3217 let _ = remote
3218 .signaling
3219 .update_endpoint_state(&remote.conversation, &remote.participant, effect.endpoint_is_muted)
3220 .await;
3221 });
3222 effect.muted
3223}
3224
3225fn silence_for_hold(on_hold: bool, muted: bool, audio: Option<&AudioSetup>, software_audio: Option<&SoftwareAudio>) {
3226 let silent = on_hold || muted;
3227 if let Some(audio) = audio {
3228 audio.track.set_enabled(MuteEffect::for_muted(silent).track_enabled);
3229 }
3230 if let Some(software_audio) = software_audio {
3231 software_audio.set_microphone_muted(silent);
3232 }
3233}
3234
3235fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {
3236 let sender = peer
3237 .senders()
3238 .into_iter()
3239 .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_))))
3240 .ok_or_else(|| Error::Webrtc("no audio sender".into()))?;
3241 sender
3242 .set_track(Some(MediaStreamTrack::Audio(track.clone())))
3243 .map_err(|error| Error::Webrtc(error.to_string()))
3244}
3245
3246fn outgoing_track<'a>(software_audio: Option<&'a SoftwareAudio>, device_track: &'a RtcAudioTrack) -> &'a RtcAudioTrack {
3247 pick_track(software_audio.map(|audio| &audio.track), device_track)
3248}
3249
3250fn pick_track<'a, T>(software: Option<&'a T>, device: &'a T) -> &'a T {
3251 software.unwrap_or(device)
3252}
3253
3254fn software_wanted(
3255 mic_settings: MicSettings,
3256 share_sound_wanted: bool,
3257 local_video: &LocalVideo,
3258 audio: Option<&AudioSetup>,
3259) -> Option<SoftwareAudioPlan> {
3260 let sharing_sound = share_sound_wanted && local_video.sharing();
3261 SoftwareAudioPlan::wanted(mic_settings, sharing_sound, audio.is_some_and(AudioSetup::uses_devices))
3262}
3263
3264fn restore_device_track(factory: &PeerConnectionFactory, input: &DeviceChoice, peer: &PeerConnection, device_track: &RtcAudioTrack, timeline: &Timeline) {
3265 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3266 if cfg!(windows) && !factory.adm_recording_enabled() {
3267 factory.set_adm_recording_enabled(true);
3268 devices::select_input(factory, input);
3269 }
3270 if let Err(error) = swap_audio_track(peer, device_track) {
3271 timeline.record("microphone track not restored", error.to_string());
3272 }
3273}
3274
3275#[allow(clippy::too_many_arguments)]
3276fn sync_software_audio(
3277 factory: &PeerConnectionFactory,
3278 options: &CallOptions,
3279 input: &DeviceChoice,
3280 muted: bool,
3281 remote_audio: Option<RtcAudioTrack>,
3282 peer: &PeerConnection,
3283 device_track: &RtcAudioTrack,
3284 wanted: Option<SoftwareAudioPlan>,
3285 restart: bool,
3286 software_audio: &mut Option<SoftwareAudio>,
3287 control: &CallControl,
3288 timeline: &Timeline,
3289) {
3290 let running = software_audio.as_ref().map(|audio| audio.plan);
3291 if running == wanted && !restart {
3292 return;
3293 }
3294 *software_audio = None;
3295 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
3296 let Some(plan) = wanted else {
3297 restore_device_track(factory, input, peer, device_track, timeline);
3298 control.send(CallUpdate::ShareSound(false));
3299 return;
3300 };
3301 let started = SoftwareAudio::start(factory, options.audio, options.tone_hz, input, plan, muted, remote_audio)
3302 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
3303 match started {
3304 Ok(audio) => {
3305 timeline.record("software audio", format!("{:?}, computer sound {:?}", plan.processing, audio.loopback));
3306 if let Some(source) = &audio.microphone_source {
3307 timeline.record("mic capture", source.clone());
3308 }
3309 if cfg!(windows) && audio.microphone_source.is_some() {
3310 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3311 factory.set_adm_recording_enabled(false);
3312 }
3313 if let Some(warning) = &audio.warning {
3314 timeline.record("computer sound warning", warning.clone());
3315 }
3316 control.send(CallUpdate::ShareSound(plan.computer_sound));
3317 *software_audio = Some(audio);
3318 }
3319 Err(error) => {
3320 timeline.record("software audio failed", error.to_string());
3321 restore_device_track(factory, input, peer, device_track, timeline);
3322 if was_sharing_sound || plan.computer_sound {
3323 control.send(CallUpdate::ShareSound(false));
3324 }
3325 let notice = if plan.computer_sound {
3326 "Computer sound could not start, sharing without it"
3327 } else {
3328 "Microphone processing could not start, using the standard microphone"
3329 };
3330 control.send(CallUpdate::Notice(notice.into()));
3331 }
3332 }
3333}
3334
3335async fn tear_down(mut live: Live, inner: &Inner, timeline: &Timeline, report: &mut CallReport, cancelled: bool) {
3336 if let Some(audio) = &live.audio {
3337 audio.track.set_enabled(false);
3338 }
3339 live.broker_running.store(false, Ordering::SeqCst);
3340 if !live.skip_leave
3341 && let Some(remote) = &live.remote
3342 {
3343 let reason = if cancelled { LeaveReason::Cancel } else { LeaveReason::Hangup };
3344 match remote.signaling.leave(&remote.conversation, &remote.participant, reason).await {
3345 Ok(()) => report.left_cleanly = true,
3346 Err(error) => timeline.record("leave failed", error.to_string()),
3347 }
3348 }
3349 if report.end.is_none()
3350 && let Some(callbacks) = live.callbacks.as_mut()
3351 && live.remote.is_some()
3352 {
3353 let waited = timeout(END_CALLBACK_WAIT, async {
3354 while let Some(callback) = callbacks.recv().await {
3355 let event = handle_callback(&callback, timeline);
3356 if let Ok(CallEvent::End(end)) = event {
3357 return Some(end);
3358 }
3359 }
3360 None
3361 })
3362 .await;
3363 report.end = waited.ok().flatten();
3364 }
3365 for peer in &live.peers {
3366 peer.close();
3367 }
3368 if let Some(audio) = live.audio.take() {
3369 audio.stop().await;
3370 }
3371 if let Some(broker) = live.broker.take() {
3372 broker.abort();
3373 }
3374 for task in live.video_tasks.drain(..) {
3375 task.abort();
3376 }
3377 if let Some(route_id) = &live.route_id {
3378 inner.unregister_route(route_id);
3379 }
3380 timeline.record("closed", "peer closed, call route removed");
3381}
3382
3383fn setup_end_kind(end: &CallEnd) -> EndKind {
3384 match end.kind() {
3385 EndKind::Normal | EndKind::Other => EndKind::Unavailable,
3386 kind => kind,
3387 }
3388}
3389
3390fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
3391 let body = decode_body(callback)?;
3392 let (_, event) = classify(&callback.path, body)?;
3393 let detail = match &event {
3394 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
3395 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
3396 CallEvent::Progress(status) => format!("{status:?}"),
3397 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) | CallEvent::RetargetCompletion(body) => outcome_summary(body),
3398 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
3399 _ => String::new(),
3400 };
3401 timeline.record(format!("Trouter {}", event.name()), detail);
3402 match &event {
3403 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
3404 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
3405 CallEvent::MediaRenegotiation(renegotiation) => timeline.record_sdp("remote offer", &renegotiation.sdp),
3406 _ => {}
3407 }
3408 Ok(event)
3409}
3410
3411
3412async fn apply_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
3413 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
3414 set_browser_answer(peer, &answer).await
3415}
3416
3417/// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
3418async fn apply_hold_answer(peer: &PeerConnection, teams_answer: &str, signaled: &SignaledOffer, browser_offer: &str) -> Result<()> {
3419 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
3420 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
3421}
3422
3423async fn set_browser_answer(peer: &PeerConnection, answer: &str) -> Result<()> {
3424 let description = parse_sdp(answer, SdpType::Answer)?;
3425 peer.set_remote_description(description)
3426 .await
3427 .map_err(|error| Error::Webrtc(error.to_string()))
3428}
3429
3430/// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect.
3431fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) {
3432 let Some(directory) = &options.sdp_dump_dir else {
3433 return;
3434 };
3435 let masked: Vec<String> = sdp
3436 .lines()
3437 .map(|line| {
3438 for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:", "a=crypto:"] {
3439 if line.starts_with(prefix) {
3440 return format!("{prefix}<masked>");
3441 }
3442 }
3443 line.split(' ').map(mask_address).collect::<Vec<_>>().join(" ")
3444 })
3445 .collect();
3446 let _ = std::fs::create_dir_all(directory);
3447 let _ = std::fs::write(directory.join(name), masked.join("\n"));
3448}
3449
3450fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Error>) {
3451 let Some(directory) = &options.sdp_dump_dir else {
3452 return;
3453 };
3454 let mut lines: Vec<String> =
3455 timeline.entries().iter().map(|entry| format!("{:>6} ms {} {}", entry.elapsed_ms, entry.label, entry.detail)).collect();
3456 lines.push(match failure {
3457 Some(error) => format!("failed: {error}"),
3458 None => "ended without error".to_owned(),
3459 });
3460 let _ = std::fs::create_dir_all(directory);
3461 let _ = std::fs::write(directory.join("timeline.txt"), lines.join("\n"));
3462}
3463
3464fn mask_address(token: &str) -> String {
3465 let dotted_quad = token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok());
3466 let colon_address = token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:");
3467 if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1") || colon_address {
3468 "<addr>".to_owned()
3469 } else {
3470 token.to_owned()
3471 }
3472}
3473
3474async fn record_track(track: RtcAudioTrack, recording: Arc<Mutex<Recording>>, tone_hz: f32) {
3475 let mut stream = NativeAudioStream::new(track, SAMPLE_RATE as i32, 1);
3476 while let Some(frame) = stream.next().await {
3477 let mut recording = recording.lock().await;
3478 recording.samples.extend_from_slice(&frame.data);
3479 recording.current_second.extend_from_slice(&frame.data);
3480 if recording.current_second.len() >= SAMPLE_RATE as usize {
3481 let second: Vec<i16> = std::mem::take(&mut recording.current_second);
3482 let summary = (rms(&second), tone_ratio(&second, tone_hz));
3483 recording.per_second.push(summary);
3484 }
3485 }
3486}
3487
3488async fn poll_broker(signaling: Arc<Signaling>, conversation: Conversation, running: Arc<AtomicBool>) {
3489 let Ok(first) = conversation.link("subscribe") else {
3490 return;
3491 };
3492 let mut url = first.to_owned();
3493 while running.load(Ordering::SeqCst) {
3494 match signaling.poll_broker(&url).await {
3495 Ok(Some(next)) => url = next,
3496 Ok(None) => {}
3497 Err(_) => return,
3498 }
3499 }
3500}
3501
3502#[derive(Debug, Default)]
3503struct StatsSnapshot {
3504 inbound_packets: u64,
3505 inbound_bytes: u64,
3506 outbound_packets: u64,
3507 outbound_bytes: u64,
3508 source_levels: Vec<String>,
3509 video_senders: Vec<String>,
3510 audio_level: f64,
3511 local_level: f64,
3512 echo_return_loss_enhancement: f64,
3513 video: VideoReport,
3514 share_inbound_packets: u64,
3515 share_outbound_packets: u64,
3516 share_receive: Option<ShareReceive>,
3517 dtls_state: String,
3518 tls_version: String,
3519 dtls_cipher: String,
3520 srtp_cipher: String,
3521 selected_pair: Option<String>,
3522 health: HealthCounters,
3523 transport: TransportDetails,
3524}
3525
3526#[derive(Debug, Default)]
3527struct ShareReceive {
3528 frames_decoded: u32,
3529 key_frames_decoded: u32,
3530 width: u32,
3531 height: u32,
3532 frames_per_second: f64,
3533 pli_count: u32,
3534 fir_count: u32,
3535 freeze_count: u32,
3536}
3537
3538impl ShareReceive {
3539 fn summary(&self) -> String {
3540 format!(
3541 " share in decoded={} keyframes={} {}x{} fps={:.0} pli={} fir={} freezes={}",
3542 self.frames_decoded, self.key_frames_decoded, self.width, self.height, self.frames_per_second, self.pli_count, self.fir_count, self.freeze_count
3543 )
3544 }
3545}
3546
3547async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSnapshot {
3548 let Ok(stats) = peer.get_stats().await else {
3549 return StatsSnapshot::default();
3550 };
3551 let mut snapshot = StatsSnapshot::default();
3552 (snapshot.health, snapshot.transport) = health_from_stats(&stats);
3553 let mut selected_pair_id = None;
3554 for entry in &stats {
3555 match entry {
3556 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "audio" => {
3557 snapshot.inbound_packets += inbound.received.packets_received;
3558 snapshot.inbound_bytes += inbound.inbound.bytes_received;
3559 snapshot.audio_level = snapshot.audio_level.max(inbound.inbound.audio_level);
3560 }
3561 RtcStats::MediaSource(source) if source.source.kind == "audio" => {
3562 snapshot.local_level = snapshot.local_level.max(source.audio.audio_level);
3563 snapshot.source_levels.push(format!("{}={:.3}", source.source.track_identifier, source.audio.audio_level));
3564 snapshot.echo_return_loss_enhancement = source.audio.echo_return_loss_enhancement;
3565 }
3566 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "audio" => {
3567 snapshot.outbound_packets += outbound.sent.packets_sent;
3568 snapshot.outbound_bytes += outbound.sent.bytes_sent;
3569 }
3570 RtcStats::InboundRtp(inbound) if inbound.stream.kind == "video" => {
3571 snapshot.video.inbound_packets += inbound.received.packets_received;
3572 if share_mids.contains(&inbound.inbound.mid) {
3573 snapshot.share_inbound_packets += inbound.received.packets_received;
3574 snapshot.share_receive = Some(ShareReceive {
3575 frames_decoded: inbound.inbound.frames_decoded,
3576 key_frames_decoded: inbound.inbound.key_frames_decoded,
3577 width: inbound.inbound.frame_width,
3578 height: inbound.inbound.frame_height,
3579 frames_per_second: inbound.inbound.frames_per_second,
3580 pli_count: inbound.inbound.pli_count,
3581 fir_count: inbound.inbound.fir_count,
3582 freeze_count: inbound.inbound.freeze_count,
3583 });
3584 }
3585 snapshot.video.inbound_frames_decoded += u64::from(inbound.inbound.frames_decoded);
3586 snapshot.video.inbound_width = snapshot.video.inbound_width.max(inbound.inbound.frame_width);
3587 snapshot.video.inbound_height = snapshot.video.inbound_height.max(inbound.inbound.frame_height);
3588 }
3589 RtcStats::RemoteInboundRtp(remote) if remote.stream.kind == "video" => {
3590 snapshot.video.remote_reports += remote.remote_inbound.round_trip_time_measurements;
3591 snapshot.video.remote_round_trip_ms = snapshot.video.remote_round_trip_ms.max(remote.remote_inbound.round_trip_time * 1000.0);
3592 }
3593 RtcStats::OutboundRtp(outbound) if outbound.stream.kind == "video" => {
3594 snapshot.video.outbound_packets += outbound.sent.packets_sent;
3595 if share_mids.contains(&outbound.outbound.mid) {
3596 snapshot.share_outbound_packets += outbound.sent.packets_sent;
3597 }
3598 snapshot.video.outbound_frames_encoded += u64::from(outbound.outbound.frames_encoded);
3599 snapshot.video_senders.push(format!(
3600 "mid {} packets={} key={} pli={} fir={} nack={} target={:.0}kbps limit={:?} active={}",
3601 outbound.outbound.mid,
3602 outbound.sent.packets_sent,
3603 outbound.outbound.key_frames_encoded,
3604 outbound.outbound.pli_count,
3605 outbound.outbound.fir_count,
3606 outbound.outbound.nack_count,
3607 outbound.outbound.target_bitrate / 1000.0,
3608 outbound.outbound.quality_limitation_reason,
3609 outbound.outbound.active
3610 ));
3611 snapshot.video.outbound_width = snapshot.video.outbound_width.max(outbound.outbound.frame_width);
3612 snapshot.video.outbound_height = snapshot.video.outbound_height.max(outbound.outbound.frame_height);
3613 }
3614 RtcStats::Transport(transport) => {
3615 snapshot.dtls_state = format!("{:?}", transport.transport.dtls_state);
3616 snapshot.tls_version = transport.transport.tls_version.clone();
3617 snapshot.dtls_cipher = transport.transport.dtls_cipher.clone();
3618 snapshot.srtp_cipher = transport.transport.srtp_cipher.clone();
3619 if !transport.transport.selected_candidate_pair_id.is_empty() {
3620 selected_pair_id = Some(transport.transport.selected_candidate_pair_id.clone());
3621 }
3622 }
3623 _ => {}
3624 }
3625 }
3626 if let Some(pair_id) = selected_pair_id {
3627 let pair = stats.iter().find_map(|entry| match entry {
3628 RtcStats::CandidatePair(pair) if pair.rtc.id == pair_id => Some(pair),
3629 _ => None,
3630 });
3631 if let Some(pair) = pair {
3632 let describe = |candidate_id: &str| {
3633 stats
3634 .iter()
3635 .find_map(|entry| match entry {
3636 RtcStats::LocalCandidate(local) if local.rtc.id == candidate_id => Some(&local.local_candidate),
3637 RtcStats::RemoteCandidate(remote) if remote.rtc.id == candidate_id => Some(&remote.remote_candidate),
3638 _ => None,
3639 })
3640 .map(|candidate| {
3641 let kind = candidate.candidate_type.map(|kind| format!("{kind:?}")).unwrap_or_default();
3642 let relay = candidate.relay_protocol.map(|relay| format!(" via {relay:?}")).unwrap_or_default();
3643 format!("{kind}/{}{relay}", candidate.protocol)
3644 })
3645 .unwrap_or_else(|| "?".into())
3646 };
3647 snapshot.selected_pair = Some(format!(
3648 "local {} <-> remote {}",
3649 describe(&pair.candidate_pair.local_candidate_id),
3650 describe(&pair.candidate_pair.remote_candidate_id)
3651 ));
3652 }
3653 }
3654 snapshot
3655}
3656
3657#[cfg(test)]
3658mod tests {
3659 #[tokio::test]
3660 async fn a_hanging_setup_step_ends_on_cancel_or_after_the_step_timeout() {
3661 let (handle, mut control) = crate::control::call_channel();
3662 handle.commands.send(CallCommand::Hangup).unwrap();
3663 let limit = Duration::from_millis(20);
3664 let cancelled = setup_step_within(&mut control, limit, std::future::pending::<std::result::Result<(), Error>>()).await;
3665 assert!(matches!(cancelled, Err(Error::Cancelled)));
3666 let timed_out = setup_step_within(&mut control, limit, std::future::pending::<std::result::Result<(), Error>>()).await;
3667 assert!(matches!(timed_out, Err(Error::Signaling(_))));
3668 }
3669
3670 use super::*;
3671
3672 #[test]
3673 fn an_echo_call_waits_for_the_echo_bot_before_it_counts_as_connected() {
3674 let mut gate = CalleeGate::new(CallSpec::Echo.callee_count());
3675 assert!(!gate.media_connected());
3676 assert!(gate.callee_joined());
3677 }
3678
3679 #[test]
3680 fn only_a_conflict_answer_retries_a_recording_stop() {
3681 assert!(recorder_busy(&Error::Signaling("recording command answered HTTP 409 no answer".into())));
3682 assert!(!recorder_busy(&Error::Signaling("recording command answered HTTP 500 no answer".into())));
3683 assert!(!recorder_busy(&Error::Cancelled));
3684 }
3685
3686 #[test]
3687 fn escalation_keeps_the_software_track_when_it_runs() {
3688 assert_eq!(*pick_track(Some(&1), &0), 1);
3689 assert_eq!(*pick_track(None, &0), 0);
3690 }
3691
3692 #[test]
3693 fn video_is_possible_once_connected_and_not_waiting_on_a_mixer_escalation() {
3694 assert!(video_possible(true, Layout::OneToOne, MediaPath::Direct));
3695 assert!(video_possible(true, Layout::Conference, MediaPath::Mixer));
3696 assert!(!video_possible(true, Layout::OneToOne, MediaPath::Mixer));
3697 assert!(!video_possible(
3698 false,
3699 Layout::Conference,
3700 MediaPath::Direct
3701 ));
3702 }
3703
3704 #[test]
3705 fn keep_alive_fires_at_ninety_percent_of_the_interval() {
3706 assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430));
3707 assert_eq!(keep_alive_period(None), Duration::from_secs(2430));
3708 assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54));
3709 }
3710
3711 const BROWSER_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\na=mid:0\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:1\r\na=sendrecv\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\na=mid:2\r\na=recvonly\r\n";
3712
3713 fn directions(sdp: &str) -> Vec<String> {
3714 crate::sdp::parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()
3715 }
3716
3717 async fn local_offer(layout: Layout) -> Result<OfferedMedia> {
3718 use libwebrtc::audio_source::native::NativeAudioSource;
3719 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3720 let factory = devices::shared_factory();
3721 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
3722 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3723 let track = factory.create_audio_track("microphone", source);
3724 let offer = create_offer(&peer, &factory, &track, layout, None).await;
3725 peer.close();
3726 offer
3727 }
3728
3729 #[tokio::test]
3730 async fn libwebrtc_accepts_its_own_offer_after_the_direction_rewrite() {
3731 for layout in [Layout::OneToOne, Layout::Conference] {
3732 if let Err(error) = local_offer(layout).await {
3733 panic!("{layout:?}: {error}");
3734 }
3735 }
3736 }
3737
3738 #[tokio::test]
3739 async fn a_peer_to_peer_offer_from_the_teams_client_gets_an_answer() {
3740 use libwebrtc::audio_source::native::NativeAudioSource;
3741 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3742 let factory = devices::shared_factory();
3743 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
3744 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3745 let track = factory.create_audio_track("microphone", source);
3746 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3747 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, None, false, None).await;
3748 peer.close();
3749 if let Err(error) = answered {
3750 panic!("{error}");
3751 }
3752 }
3753
3754 #[test]
3755 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3756 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3757 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
3758 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);
3759 }
3760
3761 #[test]
3762 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3763 for layout in [Layout::OneToOne, Layout::Conference] {
3764 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, None, false, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3765 }
3766 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, None, false, BROWSER_OFFER), BROWSER_OFFER);
3767 }
3768
3769 #[test]
3770 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3771 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, None, false, BROWSER_OFFER);
3772 let mut numbers = || 7;
3773 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
3774 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
3775 assert_eq!(signaled.matches("a=candidate:").count(), 1);
3776 }
3777
3778 #[test]
3779 fn a_move_into_the_meeting_you_are_already_in_is_ignored() {
3780 let target = |thread: &str| MeetingTarget { thread_id: thread.into(), tenant_id: "t".into(), organizer_id: "o".into(), meeting_data: None };
3781 assert!(is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_a@thread.v2")));
3782 assert!(!is_own_meeting(Some(&target("19:meeting_a@thread.v2")), &target("19:meeting_b@thread.v2")));
3783 assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2")));
3784 }
3785
3786 #[test]
3787 fn a_video_call_names_the_video_modality_only_when_the_camera_sends() {
3788 assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]);
3789 assert_eq!(accepted_modalities(true), vec!["Audio".to_owned(), "Video".to_owned()]);
3790 }
3791
3792 #[test]
3793 fn specs_map_to_invitation_targets() {
3794 assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
3795 let people = CallSpec::People {
3796 callees: vec![Callee { mri: "8:orgid:b".into(), display_name: "Bea".into() }],
3797 thread_id: "19:t@thread.v2".into(),
3798 };
3799 assert!(people.is_people() && !people.is_meeting());
3800 assert!(matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2"));
3801 let meeting = CallSpec::Meeting(MeetingTarget {
3802 thread_id: "19:meeting@thread.v2".into(),
3803 tenant_id: "t".into(),
3804 organizer_id: "o".into(),
3805 meeting_data: None,
3806 });
3807 assert!(meeting.is_meeting() && !meeting.is_people());
3808 }
3809}