BlueGit

ict rusty-teams

Files

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

call.rs

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