BlueGit

ict rusty-teams

Files

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

mod.rs

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