BlueGit

ict rusty-teams

Files

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

call.rs

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