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