BlueGit

ict rusty-teams

Files

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

call.rs

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