BlueGit

ict rusty-teams

Files

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

call.rs

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