BlueGit

ict rusty-teams

Files

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

call.rs

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