BlueGit

ict rusty-teams

Files

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

call.rs

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