BlueGit

ict rusty-teams

Files

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

call.rs

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