BlueGit

ict rusty-teams

Files

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

mod.rs

mod.rs 174.4 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 segmentation_model: Option<&'static str> = None;
925 let mut health_sampler = HealthSampler::default();
926 let mut quality_tracker = QualityTracker::default();
927 let mut second = 0u32;
928 let echo_thread = thread_id;
929 let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());
930 if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) {
931 video.router().set(mid, Some(VideoKey::Person(mri.clone())));
932 }
933 if let Some(mid) = &initial_share_mid {
934 video.router().set(mid, Some(VideoKey::Screen));
935 control.send(CallUpdate::ScreenShare(peer_mri.clone()));
936 }
937 if sending_camera {
938 control.send(CallUpdate::Camera(true));
939 }
940 let mut software_audio: Option<SoftwareAudio> = None;
941 let mut share_sound_wanted = false;
942 let mut audio_disabled = false;
943 let mut remote_audio: Option<RtcAudioTrack> = None;
944 sync_software_audio(
945 &factory,
946 options,
947 &input,
948 muted,
949 None,
950 &current.peer,
951 &track,
952 software_wanted(
953 mic_settings,
954 share_sound_wanted,
955 &local_video,
956 live.audio.as_ref(),
957 ),
958 false,
959 &mut software_audio,
960 mic_settings,
961 control,
962 timeline,
963 );
964 let mut own_hand: Option<String> = None;
965 let mut depacketizer = Depacketizer::default();
966 let mut caption_flow = CaptionFlow::default();
967 let mut caption_deadline: Option<Instant> = None;
968 let mut recording_flow = CaptionFlow::default();
969 let mut recording_deadline: Option<Instant> = None;
970 let mut recording_plan = RecordingPlan::default();
971 let mut recording_audio_only = false;
972 let mut recording_status = RecordingStatus::default();
973 let mut bot_pending = false;
974 let mut consent_pending = false;
975 let mut room_watcher = RoomWatcher::default();
976 let mut main_meeting_sent = false;
977 let mut local_hold = false;
978 let mut remote_hold = false;
979 let mut same_peer: Option<SamePeerOffer> = None;
980 let mut send_requests = RequestFilter::default();
981 let mut send_capabilities = SendCapabilityReporter::default();
982 let mut bitrate_governor = BitrateGovernor::default();
983 let mut same_peer_deadline: Option<Instant> = None;
984 let mut same_peer_grace_until: Option<Instant> = None;
985 let mut meeting_chat = conversation.chat_thread.clone();
986 if let Some(thread) = &meeting_chat {
987 control.send(CallUpdate::MeetingChat(thread.clone()));
988 }
989 if let Some(target) = &meeting_target {
990 control.send(CallUpdate::MeetingTenant(target.tenant_id.clone()));
991 }
992 if meeting_chat.is_none() {
993 meeting_chat = people_thread;
994 }
995 let mut start_camera_pending = options.start_camera;
996 let mut share_pending: Option<ShareSource> = None;
997 let mut portal_pending: Option<ShareKind> = None;
998 let mut glare_resend: Option<GlareResend> = None;
999 let mut deferred_changes: Vec<Change> = Vec::new();
1000 let mut remote_direct_share: Option<String> = initial_share_mid.clone();
1001 let mut sent_replacement: Option<Replacement> = None;
1002 let (echo_add_tx, mut echo_add_rx) = mpsc::unbounded_channel::<Result<()>>();
1003 let mut echo_add_pending = false;
1004 loop {
1005 let possible = video_possible(remote_set, layout, negotiator.path());
1006 if camera_may_start(start_camera_pending, next.is_some(), possible) {
1007 start_camera_pending = false;
1008 control.defer(CallCommand::SetCamera(true));
1009 }
1010 if camera_may_start(share_pending.is_some(), next.is_some(), possible)
1011 && let Some(source) = share_pending.take()
1012 {
1013 control.defer(CallCommand::StartShare(source));
1014 }
1015 if camera_may_start(portal_pending.is_some(), next.is_some(), possible)
1016 && let Some(kind) = portal_pending.take()
1017 {
1018 control.defer(CallCommand::StartPortalShare(kind));
1019 }
1020 if next.as_ref().is_some_and(|pending| {
1021 pending.connected && (pending.offered.is_some() || pending.retargeted)
1022 }) && let Some(pending) = next.take()
1023 {
1024 timeline.record(
1025 "escalation",
1026 "new peer connection connected, old one dropped",
1027 );
1028 deferred_changes.clear();
1029 negotiator.server_escalation_done();
1030 // New mixer leg starts sequence numbers from 1 and has not heard our send capabilities yet.
1031 send_requests = RequestFilter::default();
1032 send_capabilities = SendCapabilityReporter::default();
1033 if let Some(mid) = remote_direct_share.take() {
1034 video.router().set(&mid, None);
1035 control.send(CallUpdate::ScreenShare(None));
1036 }
1037 // Detach local senders before closing: otherwise peer.close can hang
1038 // while the camera/share capture threads still feed the old track.
1039 local_video.clear_lines();
1040 replace_leg_media_links(&mut media_links, &pending.leg_links);
1041 let leg_names = pending
1042 .leg_links
1043 .keys()
1044 .cloned()
1045 .collect::<Vec<_>>()
1046 .join(",");
1047 timeline.record(
1048 "leg links",
1049 if leg_names.is_empty() {
1050 "none".to_owned()
1051 } else {
1052 leg_names
1053 },
1054 );
1055 if let Some(url) = media_links.get("callLeg").cloned()
1056 && keep_alive_link.as_deref() != Some(url.as_str())
1057 {
1058 keep_alive_link = Some(url.clone());
1059 remember_call_leg(live, Some(&url));
1060 }
1061 if let Some(track) = pending.remote_audio {
1062 remote_audio = Some(track.clone());
1063 if options.record_remote {
1064 tokio::spawn(record_track(track, recording.clone(), options.tone_hz));
1065 }
1066 }
1067 let old = std::mem::replace(&mut current, pending.session);
1068 old.peer.close();
1069 reconnect_deadline = None;
1070 if callee_gate.media_connected() {
1071 advance(state, CallSignal::MediaConnected, control);
1072 }
1073 if let Some(audio) = &software_audio
1074 && let Err(error) = swap_audio_track(&current.peer, &audio.track)
1075 {
1076 timeline.record("computer sound not carried over", error.to_string());
1077 }
1078 if remote_audio.is_some() {
1079 sync_software_audio(
1080 &factory,
1081 options,
1082 &input,
1083 muted,
1084 remote_audio.clone(),
1085 &current.peer,
1086 &track,
1087 software_wanted(
1088 mic_settings,
1089 share_sound_wanted,
1090 &local_video,
1091 live.audio.as_ref(),
1092 ),
1093 true,
1094 &mut software_audio,
1095 mic_settings,
1096 control,
1097 timeline,
1098 );
1099 }
1100 offered = pending.offered;
1101 let answered = pending.answered;
1102 if let Some(mid) = direct_video_mid.take() {
1103 video.router().set(&mid, None);
1104 }
1105 if let Some(media) = &offered {
1106 layout = Layout::Conference;
1107 layout_plan = media.plan.clone();
1108 if let Err(error) = local_video.set_lines(media.video.clone()) {
1109 timeline.record("video lines not attached", error.to_string());
1110 }
1111 tell_bound_camera(
1112 &remote,
1113 &media_links,
1114 &local_video,
1115 &mut media_description_request,
1116 timeline,
1117 );
1118 tell_bound_share(
1119 &remote,
1120 &media_links,
1121 &local_video,
1122 &mut media_description_request,
1123 timeline,
1124 );
1125 } else if let Some(answered) = answered {
1126 // Server escalation answered on a new peer: drop the old peer's
1127 // senders and bind the camera/share lines that stayed alive there.
1128 layout = Layout::Conference;
1129 layout_plan = answered.remote.plan();
1130 match video_lines_from_answer(&current.peer, &answered) {
1131 Some(lines) => {
1132 if let Err(error) = local_video.set_lines(lines) {
1133 timeline.record("video lines not attached", error.to_string());
1134 }
1135 }
1136 None => {
1137 local_video.clear_lines();
1138 timeline.record(
1139 "video lines not attached",
1140 "no transceiver for the answered camera line",
1141 );
1142 }
1143 }
1144 negotiate_video_lines(
1145 &mut video,
1146 &signaling,
1147 control,
1148 timeline,
1149 &answered.offer_sdp,
1150 &answered.remote.lines,
1151 true,
1152 &media_links,
1153 &roster,
1154 );
1155 tell_bound_camera(
1156 &remote,
1157 &media_links,
1158 &local_video,
1159 &mut media_description_request,
1160 timeline,
1161 );
1162 tell_bound_share(
1163 &remote,
1164 &media_links,
1165 &local_video,
1166 &mut media_description_request,
1167 timeline,
1168 );
1169 } else {
1170 local_video.clear_lines();
1171 }
1172 remote_set = true;
1173 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1174 let pending = escalate(
1175 &factory,
1176 &grant,
1177 options,
1178 outgoing_track(software_audio.as_ref(), &track),
1179 &remote,
1180 &links,
1181 &media_leg_id,
1182 &media_links,
1183 &mut negotiator,
1184 live,
1185 timeline,
1186 )
1187 .await;
1188 if pending.is_none() {
1189 drop_local_media(&mut local_video, control);
1190 }
1191 next = pending.or(next);
1192 }
1193 }
1194 let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);
1195 let glare_at = glare_resend.as_ref().map(|resend| resend.at);
1196 tokio::select! {
1197 Some(callback) = callbacks.recv() => {
1198 match handle_callback(&callback, timeline) {
1199 Ok(CallEvent::Acceptance(acceptance)) => {
1200 if !acceptance.from_mixer
1201 && let Some(accepted_by) = &acceptance.accepted_by
1202 && roster.apply(&direct_roster(&[(own_mri.as_str(), participant.display_name.as_str()), (accepted_by.mri.as_str(), accepted_by.display_name.as_str())]))
1203 {
1204 control.send(CallUpdate::Roster(roster.entries()));
1205 }
1206 if !acceptance.from_mixer && callee_gate.callee_joined() {
1207 advance(state, CallSignal::MediaConnected, control);
1208 }
1209 let action = negotiator.on_acceptance(acceptance.from_mixer, layout == Layout::OneToOne);
1210 match action {
1211 MediaAction::ApplyAnswer | MediaAction::ApplyAnswerThenEscalate => {
1212 let Some(media) = offered.as_ref() else { continue };
1213 dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp);
1214 if let Ok(answer) = to_browser_answer(&acceptance.sdp, &media.signaled, &media.browser_offer) {
1215 dump_sdp(options, "4-browser-answer.sdp", &answer);
1216 }
1217 apply_answer(&current.peer, &acceptance.sdp, &media.signaled, &media.browser_offer)
1218 .await
1219 .inspect_err(|error| timeline.record("answer rejected", error.to_string()))?;
1220 remote_set = true;
1221 media_links.extend(acceptance.links.clone());
1222 if layout == Layout::Conference {
1223 negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster);
1224 }
1225 if let Some(link) = acceptance.links.get("replacement")
1226 && sent_replacement.as_ref().is_none_or(|sent| sent.participant_id.is_none())
1227 {
1228 let replacement = Replacement::of_call(link.clone());
1229 sent_replacement = Some(replacement.clone());
1230 control.send(CallUpdate::ReplacementLink(replacement));
1231 }
1232 if !callee_gate.is_waiting() {
1233 outgoing_deadline = None;
1234 }
1235 let directions: Vec<String> = current
1236 .peer
1237 .transceivers()
1238 .iter()
1239 .map(|transceiver| format!("{:?}", transceiver.current_direction()))
1240 .collect();
1241 timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(",")));
1242 if acceptance.in_lobby() {
1243 lobby = true;
1244 control.send(CallUpdate::Lobby(true));
1245 }
1246 keep_alive_link = acceptance.links.get("callLeg").cloned();
1247 remember_call_leg(live, keep_alive_link.as_deref());
1248 keep_alive_seconds = acceptance.keep_alive_seconds;
1249 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
1250 if action == MediaAction::ApplyAnswerThenEscalate {
1251 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;
1252 next = pending.or(next);
1253 }
1254 let remote = remote.clone();
1255 let links = links.clone();
1256 let thread_id = echo_thread.clone();
1257 let echo_add_tx = echo_add_tx.clone();
1258 if is_echo {
1259 echo_add_pending = true;
1260 }
1261 tokio::spawn(async move {
1262 if is_echo {
1263 let result = remote
1264 .signaling
1265 .add_echo_bot(
1266 &remote.conversation,
1267 &remote.participant,
1268 thread_id.as_deref(),
1269 &links,
1270 )
1271 .await;
1272 let ok = result.is_ok();
1273 let _ = echo_add_tx.send(result);
1274 if !ok {
1275 return;
1276 }
1277 }
1278 let _ = remote
1279 .signaling
1280 .update_endpoint_metadata(
1281 &remote.conversation,
1282 &remote.participant,
1283 )
1284 .await;
1285 });
1286 }
1287 MediaAction::Escalate => {
1288 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;
1289 next = pending.or(next);
1290 }
1291 _ => {}
1292 }
1293 }
1294 Ok(CallEvent::MediaAnswer(answer)) if !remote_set && !answer.from_mixer && same_peer.is_none() && next.is_none() && outgoing_deadline.is_some() => {
1295 timeline.record("provisional answer", if answer.no_ring_back { "no ringback" } else { "ringing" });
1296 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1297 if !answer.no_ring_back {
1298 control.send(CallUpdate::Progress(Progress::Ringing));
1299 }
1300 }
1301 Ok(CallEvent::MediaAnswer(answer))
1302 if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1303 {
1304 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1305 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1306 }
1307 if answer.from_mixer {
1308 negotiator.note_mixer_path();
1309 }
1310 if let Some(resend) = glare_resend.as_mut() {
1311 resend.at = Instant::now();
1312 }
1313 }
1314 Ok(CallEvent::MediaAnswer(answer)) => {
1315 let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1316 || next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags));
1317 if (same_peer.is_some() || next.is_some()) && !belongs {
1318 timeline.record("media answer ignored", "it answers an offer that is no longer pending");
1319 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1320 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1321 }
1322 continue;
1323 }
1324 let action = negotiator.on_media_answer();
1325 if action == MediaAction::Ignore
1326 && let Some(url) = answer.links.get("mediaAcknowledgement")
1327 {
1328 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1329 }
1330 if action == MediaAction::ApplyOnSamePeer
1331 && let Some(pending) = same_peer.take()
1332 {
1333 same_peer_deadline = None;
1334 same_peer_grace_until = None;
1335 let applied = match pending.change {
1336 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1337 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1338 };
1339 match applied {
1340 Ok(()) => {
1341 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1342 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1343 }
1344 match pending.change {
1345 Change::Hold(hold) => {
1346 local_hold = hold;
1347 silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref());
1348 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1349 }
1350 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1351 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1352 local_video.stop_share();
1353 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);
1354 clear_share(control);
1355 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1356 }
1357 Change::Share(_) => {}
1358 }
1359 if answer.from_mixer {
1360 media_links.extend(answer.links.clone());
1361 let wants_video = !local_hold && (local_video.camera_on() || local_video.sharing());
1362 let upgrade = wants_video
1363 && (negotiator.escalate_after_mixer_answer() || (layout == Layout::OneToOne && next.is_none() && negotiator.begin_conference_upgrade()));
1364 if !wants_video {
1365 negotiator.note_mixer_path();
1366 } else if upgrade {
1367 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;
1368 if pending.is_none() {
1369 drop_local_media(&mut local_video, control);
1370 }
1371 next = pending.or(next);
1372 }
1373 }
1374 }
1375 Err(error) => {
1376 timeline.record("same-peer answer rejected", error.to_string());
1377 undo_change(pending.change, &mut local_video, control);
1378 }
1379 }
1380 }
1381 if action == MediaAction::ApplyOnNewPeer {
1382 let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) {
1383 Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await,
1384 None => Err(Error::Webrtc("no pending peer connection for the answer".into())),
1385 };
1386 match applied {
1387 Ok(()) => {
1388 if let Some(pending) = next.as_mut() {
1389 pending.leg_links.extend(answer.links.clone());
1390 }
1391 if let Some(media) = next.as_ref().and_then(|pending| pending.offered.as_ref()) {
1392 media_links.extend(answer.links.clone());
1393 negotiate_video(&mut video, &signaling, control, timeline, &answer.sdp, media, true, &media_links, &roster);
1394 }
1395 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1396 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1397 }
1398 }
1399 Err(error) => {
1400 negotiator.escalation_failed();
1401 if let Some(pending) = next.take() {
1402 pending.session.peer.close();
1403 }
1404 if layout == Layout::OneToOne {
1405 drop_local_media(&mut local_video, control);
1406 }
1407 timeline.record("escalation answer rejected", error.to_string());
1408 }
1409 }
1410 }
1411 }
1412 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
1413 if !renegotiation.escalation
1414 && !renegotiation.new_offer
1415 && let Some(pending) = same_peer.take()
1416 {
1417 same_peer_deadline = None;
1418 same_peer_grace_until = None;
1419 negotiator.same_peer_offer_failed();
1420 rollback_offer(&current.peer).await;
1421 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
1422 glare_resend = Some(GlareResend { change: pending.change, reply_tags: pending.reply_tags, at: Instant::now() + GLARE_RESEND_LIMIT });
1423 }
1424 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1425 let rejection_link = renegotiation.links.get("rejection").cloned();
1426 let result = match action {
1427 MediaAction::AnswerOnNewPeer => {
1428 if let Some(pending) = same_peer.take() {
1429 same_peer_deadline = None;
1430 same_peer_grace_until = None;
1431 timeline.record("same-peer offer", "superseded by the escalation offer");
1432 rollback_offer(&current.peer).await;
1433 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
1434 }
1435 if let Some(resend) = glare_resend.take() {
1436 defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control);
1437 }
1438 let camera_track = local_video.camera_track();
1439 let share_track = local_video.share_track();
1440 match answer_on_new_peer(
1441 &factory,
1442 &grant,
1443 options,
1444 outgoing_track(software_audio.as_ref(), &track),
1445 &renegotiation.sdp,
1446 local_video.camera_on(),
1447 local_video.camera_on().then_some(&camera_track),
1448 local_video.sharing().then_some(&share_track),
1449 )
1450 .await
1451 {
1452 Ok((session, answered)) => {
1453 timeline.record_sdp("local answer", &answered.answer_sdp);
1454 live.peers.push(session.peer.clone());
1455 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1456 if let Some(replaced) = next.take() {
1457 replaced.session.peer.close();
1458 }
1459 let mut leg_links = renegotiation.links.clone();
1460 if let Ok((extra, keys)) = &sent {
1461 absorb_answered_links(&mut leg_links, extra, timeline, keys);
1462 }
1463 next = Some(NextPeer {
1464 session,
1465 offered: None,
1466 answered: Some(answered),
1467 leg_links,
1468 remote_audio: None,
1469 reply_tags: Vec::new(),
1470 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
1471 connected: false,
1472 retargeted: false,
1473 });
1474 sent.map(|_| ())
1475 }
1476 Err(error) => {
1477 if next.is_none() {
1478 negotiator.server_escalation_failed();
1479 }
1480 for change in deferred_changes.drain(..) {
1481 undo_change(change, &mut local_video, control);
1482 }
1483 if let Some(url) = &rejection_link {
1484 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1485 }
1486 Err(error)
1487 }
1488 }
1489 }
1490 MediaAction::AnswerOnSamePeer => {
1491 // After a server escalation the follow-up offer matches the
1492 // pending peer's m-line order: never answer it on the old peer.
1493 let on_pending = next.as_ref().is_some_and(|pending| pending.answered.is_some());
1494 let peer = if on_pending {
1495 &next.as_ref().unwrap().session.peer
1496 } else {
1497 &current.peer
1498 };
1499 let camera_track = local_video.camera_track();
1500 let share_track = local_video.share_track();
1501 let video_answer = if local_video.camera_on() {
1502 AnswerVideo::Send(&camera_track)
1503 } else {
1504 AnswerVideo::Receive
1505 };
1506 let keep_slots = on_pending || layout == Layout::Conference;
1507 let gathered = (!on_pending
1508 && layout == Layout::OneToOne
1509 && negotiator.path() == MediaPath::Direct)
1510 .then_some(&current.gathered);
1511 match answer_offer_with(
1512 peer,
1513 None,
1514 &renegotiation.sdp,
1515 video_answer,
1516 local_video.sharing().then(|| local_video.share_mid()).flatten(),
1517 local_video.sharing().then_some(&share_track),
1518 local_video.camera_on(),
1519 gathered,
1520 keep_slots,
1521 keep_slots,
1522 )
1523 .await
1524 {
1525 Ok(answered) => {
1526 timeline.record_sdp("local answer", &answered.answer_sdp);
1527 if on_pending {
1528 if let Some(pending) = next.as_mut() {
1529 pending.leg_links.extend(renegotiation.links.clone());
1530 }
1531 } else {
1532 media_links.extend(renegotiation.links.clone());
1533 }
1534 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1535 if let Ok((extra, keys)) = &sent {
1536 if on_pending {
1537 if let Some(pending) = next.as_mut() {
1538 absorb_answered_links(&mut pending.leg_links, extra, timeline, keys);
1539 }
1540 } else {
1541 absorb_answered_links(&mut media_links, extra, timeline, keys);
1542 }
1543 }
1544 for mid in answered.remote.plan().screen_share_mids {
1545 if !layout_plan.screen_share_mids.contains(&mid) {
1546 layout_plan.screen_share_mids.push(mid);
1547 }
1548 }
1549 if on_pending {
1550 if let Some(pending) = next.as_mut() {
1551 pending.answered = Some(answered);
1552 }
1553 } else if layout == Layout::Conference {
1554 negotiate_video_lines(
1555 &mut video,
1556 &signaling,
1557 control,
1558 timeline,
1559 &answered.offer_sdp,
1560 &answered.remote.lines,
1561 true,
1562 &media_links,
1563 &roster,
1564 );
1565 } else if layout == Layout::OneToOne {
1566 if answered.receiving_share_mid != remote_direct_share {
1567 if let Some(mid) = &remote_direct_share {
1568 video.router().set(mid, None);
1569 }
1570 if let Some(mid) = &answered.receiving_share_mid {
1571 video.router().set(mid, Some(VideoKey::Screen));
1572 }
1573 remote_direct_share = answered.receiving_share_mid.clone();
1574 control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));
1575 }
1576 if !offer_sends_video(&renegotiation.sdp)
1577 && let Some(key) = main_video_mid(&answered.remote).and_then(|mid| video.router().key_for(&mid))
1578 {
1579 control.video.forget(&key);
1580 control.send(CallUpdate::VideoStopped(key));
1581 }
1582 }
1583 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
1584 if held != remote_hold {
1585 remote_hold = held;
1586 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1587 }
1588 sent.map(|_| ())
1589 }
1590 Err(error) => {
1591 if on_pending {
1592 if let Some(pending) = next.as_ref()
1593 && pending.session.peer.signaling_state()
1594 == SignalingState::HaveRemoteOffer
1595 {
1596 rollback_remote_offer(&pending.session.peer).await;
1597 }
1598 } else if current.peer.signaling_state()
1599 == SignalingState::HaveRemoteOffer
1600 {
1601 rollback_remote_offer(&current.peer).await;
1602 }
1603 if let Some(url) = &rejection_link {
1604 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1605 }
1606 Err(error)
1607 }
1608 }
1609 }
1610 MediaAction::RejectGlare => {
1611 if let Some(url) = &rejection_link {
1612 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::InProgress).await;
1613 }
1614 Ok(())
1615 }
1616 _ => Ok(()),
1617 };
1618 if let Err(error) = result {
1619 timeline.record("renegotiation failed", error.to_string());
1620 }
1621 }
1622 Ok(CallEvent::RosterUpdate(body)) => {
1623 if roster.apply(&body) {
1624 let entries = roster.entries();
1625 timeline.record("roster", format!("{} participant(s)", entries.len()));
1626 control.send(CallUpdate::Roster(entries));
1627 let own_server_muted = roster
1628 .members()
1629 .iter()
1630 .any(|member| member.mri == own_mri && member.server_muted);
1631 let decision = sync_server_mute(own_server_muted, muted, server_mute_cleared);
1632 server_mute_cleared = decision.cleared;
1633 if decision.silence_without_signal
1634 && let Some(audio) = live.audio.as_ref()
1635 {
1636 silence_for_server_mute(audio, software_audio.as_ref(), control);
1637 muted = true;
1638 }
1639 if is_echo && echo_watch.bot_left(roster.members().iter().map(|member| member.mri.as_str())) {
1640 timeline.record("echo bot left", "test call ends like in Teams");
1641 advance(state, CallSignal::RemoteEnd(EndKind::Normal), control);
1642 break;
1643 }
1644 if callee_gate.is_waiting() && roster_has_callee(roster.members().iter().map(|member| member.mri.as_str()), &own_mri) {
1645 outgoing_deadline = None;
1646 if callee_gate.callee_joined() {
1647 advance(state, CallSignal::MediaConnected, control);
1648 }
1649 }
1650 let own_streams = roster.stream_summaries(&own_mri);
1651 if own_streams != report.own_streams {
1652 timeline.record("own media streams", own_streams.join("; "));
1653 report.own_streams = own_streams;
1654 }
1655 send_receive_change(control, video.reselect(&roster));
1656 if let Some(replacement) = roster.transfer_replacement(&own_mri)
1657 && sent_replacement.as_ref() != Some(&replacement)
1658 {
1659 sent_replacement = Some(replacement.clone());
1660 control.send(CallUpdate::ReplacementLink(replacement));
1661 }
1662 if let Some(in_lobby) = roster.is_in_lobby(&own_mri)
1663 && in_lobby != lobby
1664 {
1665 lobby = in_lobby;
1666 control.send(CallUpdate::Lobby(lobby));
1667 }
1668 if roster.caption_bot().is_some() {
1669 bot_pending = false;
1670 }
1671 let audio_only = roster.caption_bot().is_some_and(|bot| bot.recording && bot.audio_only);
1672 if audio_only != recording_audio_only {
1673 recording_audio_only = audio_only;
1674 control.send(CallUpdate::RecordingAudioOnly(audio_only));
1675 }
1676 if caption_flow.wanted() {
1677 run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), &RecordingPlan::default(), &mut bot_pending, control, timeline).await;
1678 if caption_flow.on() {
1679 caption_deadline = None;
1680 }
1681 }
1682 if recording_flow.wanted() {
1683 run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await;
1684 }
1685 }
1686 }
1687 Ok(CallEvent::AddParticipantFailure(body)) => {
1688 let bot_add = bot_pending;
1689 bot_pending = false;
1690 if !bot_add && callee_gate.callees_failed(failed_participant_count(&body)) {
1691 let end = embedded_end(&body);
1692 let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind);
1693 report.end = end;
1694 advance(state, CallSignal::RemoteEnd(kind), control);
1695 break;
1696 }
1697 if recording_flow.wanted() && roster.caption_bot().is_none() {
1698 timeline.record("recorder bot failed", "addParticipantFailure");
1699 recording_flow.failed();
1700 recording_deadline = None;
1701 control.send(CallUpdate::RecordingPending(false));
1702 control.send(CallUpdate::Notice(RECORDING_JOIN_FAILED_NOTICE.into()));
1703 }
1704 if caption_flow.wanted() && roster.caption_bot().is_none() {
1705 timeline.record("caption bot failed", "addParticipantFailure");
1706 caption_flow.failed();
1707 caption_deadline = None;
1708 control.send(CallUpdate::Captions(CaptionState::Failed(
1709 CAPTIONS_JOIN_FAILED_NOTICE.into(),
1710 )));
1711 }
1712 }
1713 Ok(CallEvent::ConversationUpdate(body)) => {
1714 if let Some(thread) = chat_thread_id(&body)
1715 && meeting_chat.as_ref() != Some(&thread)
1716 {
1717 control.send(CallUpdate::MeetingChat(thread.clone()));
1718 meeting_chat = Some(thread);
1719 }
1720 if capability.apply(&body) {
1721 control.send(CallUpdate::Capability(capability));
1722 }
1723 let change = recording_status.apply(&body);
1724 if let Some(on) = change.recording {
1725 control.send(CallUpdate::Recording(on));
1726 if on {
1727 recording_deadline = None;
1728 control.send(CallUpdate::RecordingPending(false));
1729 }
1730 }
1731 if let Some(on) = change.transcription {
1732 control.send(CallUpdate::Transcribing(on));
1733 if on {
1734 recording_deadline = None;
1735 control.send(CallUpdate::RecordingPending(false));
1736 }
1737 }
1738 if let Some(required) = change.consent_required {
1739 consent_pending = required;
1740 control.send(CallUpdate::ConsentRequired(required));
1741 if required {
1742 withhold_media(&mut muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, &mut local_video, control);
1743 }
1744 }
1745 if !main_meeting_sent
1746 && let Some(main) = breakout::main_meeting_target(&body)
1747 {
1748 main_meeting_sent = true;
1749 control.send(CallUpdate::BreakoutRoom { main });
1750 }
1751 }
1752 Ok(CallEvent::LocalParticipantUpdate(body)) => {
1753 let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1754 if let Some(moved) = moved {
1755 timeline.record("breakout", format!("moved to {}", moved.room_name));
1756 control.send(CallUpdate::BreakoutMove(moved));
1757 }
1758 }
1759 Ok(CallEvent::Replacement(body)) => {
1760 let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1761 if let Some(moved) = invited {
1762 timeline.record("breakout", format!("invited to {}", moved.room_name));
1763 control.send(CallUpdate::BreakoutMove(moved));
1764 }
1765 }
1766 Ok(CallEvent::ContentShareUpdate(body)) => {
1767 if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) {
1768 control.send(CallUpdate::Whiteboard(Some(share)));
1769 }
1770 }
1771 Ok(CallEvent::ContentShareEnd(_)) => {
1772 control.send(CallUpdate::Whiteboard(None));
1773 }
1774 Ok(CallEvent::Transfer(event)) => {
1775 match event {
1776 TransferEvent::Accepted => timeline.record("transfer accepted", "by the target"),
1777 completed if completed.succeeded() => {
1778 timeline.record("transfer", "completed");
1779 control.send(CallUpdate::TransferResult { succeeded: true });
1780 control.send(CallUpdate::Notice(CALL_TRANSFERRED_NOTICE.into()));
1781 advance(state, CallSignal::LocalLeave, control);
1782 break;
1783 }
1784 TransferEvent::Completed { code, sub_code } => {
1785 timeline.record("transfer failed", format!("code {code} subCode {sub_code}"));
1786 control.send(CallUpdate::TransferResult { succeeded: false });
1787 control.send(CallUpdate::Notice(TRANSFER_FAILED_NOTICE.into()));
1788 }
1789 }
1790 }
1791 Ok(CallEvent::Reactions(events)) => {
1792 for event in events {
1793 control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction });
1794 }
1795 }
1796 Ok(CallEvent::Progress(status)) => {
1797 if status == ProgressStatus::Ringing {
1798 control.send(CallUpdate::Progress(Progress::Ringing));
1799 if outgoing_deadline.is_some() {
1800 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1801 }
1802 }
1803 }
1804 Ok(CallEvent::ControlVideoStreaming(body)) => {
1805 let Some(request) = parse_request(&body) else { continue };
1806 let Some(limits) = send_requests.admit(&request) else { continue };
1807 let own_screen = roster.screen_source_of(&own_mri).map(i64::from);
1808 let source = if request.source_id.is_some() && request.source_id == own_screen { SendSource::Screen } else { SendSource::Camera };
1809 match local_video.apply_send_limit(source, &limits) {
1810 Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?}")),
1811 Ok(None) => {}
1812 Err(error) => timeline.record("send limits failed", error.to_string()),
1813 }
1814 }
1815 Ok(CallEvent::Speakers(sources)) => {
1816 let speakers = roster.mris_for_sources(&sources);
1817 if video.note_speakers(&speakers) {
1818 send_receive_change(control, video.reselect(&roster));
1819 }
1820 control.send(CallUpdate::Speakers(speakers));
1821 }
1822 Ok(CallEvent::ConversationEnd(body)) if callee_gate.is_waiting() => {
1823 live.skip_leave = true;
1824 let end = embedded_end(&body);
1825 let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind);
1826 report.end = end;
1827 advance(state, CallSignal::RemoteEnd(kind), control);
1828 break;
1829 }
1830 Ok(CallEvent::Rejection(_))
1831 if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1832 {
1833 if let Some(resend) = glare_resend.as_mut() {
1834 resend.at = Instant::now();
1835 }
1836 }
1837 Ok(CallEvent::Rejection(_))
1838 if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1839 && !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) =>
1840 {
1841 timeline.record("rejection ignored", "it names an offer that is no longer pending");
1842 }
1843 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1844 RejectedOffer::SamePeer => {
1845 same_peer_deadline = None;
1846 same_peer_grace_until = None;
1847 if let Some(pending) = same_peer.take() {
1848 rollback_offer(&current.peer).await;
1849 if is_glare_rejection(&body) {
1850 timeline.record("glare", "our offer met theirs, it goes out again");
1851 glare_resend = Some(GlareResend { change: pending.change, reply_tags: Vec::new(), at: Instant::now() + GLARE_RESEND_LIMIT });
1852 } else {
1853 undo_change(pending.change, &mut local_video, control);
1854 }
1855 }
1856 }
1857 RejectedOffer::NewPeer => {
1858 if let Some(pending) = next.take() {
1859 pending.session.peer.close();
1860 }
1861 if layout == Layout::OneToOne {
1862 drop_local_media(&mut local_video, control);
1863 }
1864 timeline.record("escalation failed", "offer rejected, staying on the old peer connection");
1865 }
1866 RejectedOffer::None => {}
1867 },
1868 Ok(CallEvent::MediaAcknowledgement(ack)) => {
1869 if let Some(pending) = next.as_mut() {
1870 pending.leg_links.extend(ack.links);
1871 if pending.answered.is_some() {
1872 // Server-initiated mixer leg switch sends mediaAcknowledgement
1873 // instead of retargetCompletion; switch as soon as ICE connects.
1874 pending.retargeted = true;
1875 }
1876 } else if !ack.links.is_empty() {
1877 let old_request = media_links
1878 .get("applyChannelParameters")
1879 .or_else(|| media_links.get("controlVideoStreaming"))
1880 .cloned();
1881 let old_update = media_links.get("updateMediaDescriptions").cloned();
1882 replace_leg_media_links(&mut media_links, &ack.links);
1883 if let Some(url) = media_links.get("callLeg").cloned()
1884 && keep_alive_link.as_deref() != Some(url.as_str())
1885 {
1886 keep_alive_link = Some(url.clone());
1887 remember_call_leg(live, Some(&url));
1888 }
1889 let new_request = media_links
1890 .get("applyChannelParameters")
1891 .or_else(|| media_links.get("controlVideoStreaming"))
1892 .cloned();
1893 if layout == Layout::Conference
1894 && new_request != old_request
1895 && let Some(url) = new_request
1896 {
1897 video.replace_requester(SourceRequester::start(
1898 signaling.clone(),
1899 url,
1900 video.router().clone(),
1901 control.video.clone(),
1902 timeline.clone(),
1903 ));
1904 send_receive_change(control, video.reselect(&roster));
1905 }
1906 if layout == Layout::Conference
1907 && media_links.get("updateMediaDescriptions") != old_update.as_ref()
1908 && local_video.has_lines()
1909 {
1910 send_capabilities = SendCapabilityReporter::default();
1911 if local_video.camera_on() {
1912 tell_bound_camera(
1913 &remote,
1914 &media_links,
1915 &local_video,
1916 &mut media_description_request,
1917 timeline,
1918 );
1919 }
1920 if local_video.sharing() {
1921 tell_bound_share(
1922 &remote,
1923 &media_links,
1924 &local_video,
1925 &mut media_description_request,
1926 timeline,
1927 );
1928 }
1929 }
1930 }
1931 }
1932 Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => {
1933 if let Some(pending) = next.as_mut() {
1934 pending.retargeted = true;
1935 }
1936 }
1937 Ok(CallEvent::RetargetCompletion(body)) => {
1938 if body["retargetCompleted"]["code"].as_i64().is_some() && let Some(pending) = next.take() {
1939 pending.session.peer.close();
1940 negotiator.escalation_failed();
1941 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
1942 timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");
1943 }
1944 }
1945 Ok(CallEvent::End(end)) => {
1946 let kind = end.kind();
1947 report.end = Some(end);
1948 advance(state, CallSignal::RemoteEnd(kind), control);
1949 break;
1950 }
1951 Ok(_) => {}
1952 Err(error) => {
1953 timeline.record("callback not understood", error.to_string());
1954 }
1955 }
1956 }
1957 Some(result) = echo_add_rx.recv(), if echo_add_pending => {
1958 echo_add_pending = false;
1959 if let Err(error) = result {
1960 timeline.record("echo bot add failed", error.to_string());
1961 control.send(CallUpdate::Notice(ECHO_TEST_FAILED_NOTICE.into()));
1962 live.cancel_leave = true;
1963 advance(state, CallSignal::RemoteEnd(EndKind::Unavailable), control);
1964 break;
1965 }
1966 }
1967 Some(event) = current.events.recv() => match event {
1968 PeerEvent::Ice(ice_state) => {
1969 timeline.record("ICE state", format!("{ice_state:?}"));
1970 if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() {
1971 report.ice_connected_ms = Some(timeline.elapsed_ms());
1972 }
1973 }
1974 PeerEvent::Connection(connection) => {
1975 timeline.record("PeerConnection state", format!("{connection:?}"));
1976 match connection {
1977 PeerConnectionState::Connected => {
1978 reconnect_deadline = None;
1979 if callee_gate.media_connected() {
1980 advance(state, CallSignal::MediaConnected, control);
1981 }
1982 if report.peer_connected_ms.is_none() {
1983 report.peer_connected_ms = Some(timeline.elapsed_ms());
1984 if let Some(hold) = options.hold_after_connected {
1985 let hold_until = Instant::now() + hold;
1986 leave_at = Some(hard_deadline.map_or(hold_until, |deadline| deadline.min(hold_until)));
1987 }
1988 }
1989 }
1990 // Planned mixer escalation: ignore old-peer death while the new peer is pending.
1991 PeerConnectionState::Disconnected | PeerConnectionState::Failed
1992 if next.is_some() => {}
1993 PeerConnectionState::Disconnected => {
1994 if advance(state, CallSignal::MediaDisconnected, control) {
1995 reconnect_deadline = Some(Instant::now() + options.reconnect_window);
1996 }
1997 }
1998 PeerConnectionState::Failed => {
1999 advance(state, CallSignal::MediaFailed, control);
2000 break;
2001 }
2002 _ => {}
2003 }
2004 }
2005 PeerEvent::Track(remote_track) => {
2006 timeline.record("remote audio track", "receiving");
2007 let had_far_end = remote_audio.replace(remote_track.clone()).is_some();
2008 if !had_far_end && software_audio.is_some() {
2009 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);
2010 }
2011 if options.record_remote {
2012 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
2013 }
2014 }
2015 PeerEvent::VideoTrack { mid, track } => {
2016 timeline.record("remote video track", format!("mid {mid}"));
2017 live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));
2018 }
2019 PeerEvent::Data(frame) => {
2020 if let Some(message) = depacketizer.push(&frame)
2021 && message.data_id == CAPTIONS_DATA_ID
2022 {
2023 for entry in parse_caption_message(&message.payload) {
2024 if caption_flow.text_arrived() {
2025 caption_deadline = None;
2026 control.send(CallUpdate::Captions(CaptionState::On));
2027 }
2028 control.send(CallUpdate::Caption(named_caption(entry, &roster)));
2029 }
2030 }
2031 }
2032 },
2033 Some(event) = next_peer_event(&mut next) => match event {
2034 PeerEvent::Connection(PeerConnectionState::Connected) => {
2035 if let Some(pending) = next.as_mut() {
2036 pending.connected = true;
2037 if pending.offered.is_none() && !pending.retargeted {
2038 pending.deadline = Some(Instant::now() + RETARGET_WAIT);
2039 timeline.record("escalation", "new peer connection up, waiting for retargetCompletion");
2040 }
2041 }
2042 }
2043 PeerEvent::VideoTrack { mid, track } => {
2044 timeline.record("remote video track", format!("mid {mid} (new peer)"));
2045 live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));
2046 }
2047 PeerEvent::Track(remote_track) => {
2048 timeline.record("remote audio track", "receiving (new peer)");
2049 if let Some(pending) = next.as_mut() {
2050 pending.remote_audio = Some(remote_track);
2051 }
2052 }
2053 PeerEvent::Connection(PeerConnectionState::Failed) => {
2054 negotiator.escalation_failed();
2055 if let Some(pending) = next.take() {
2056 pending.session.peer.close();
2057 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2058 }
2059 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
2060 }
2061 _ => {}
2062 },
2063 command = control.recv() => match command {
2064 Some(CallCommand::Mute(mute)) => {
2065 let own_server_muted = roster
2066 .members()
2067 .iter()
2068 .any(|member| member.mri == own_mri && member.server_muted);
2069 if !mute.target(muted) && own_server_muted {
2070 server_mute_cleared = true;
2071 }
2072 if consent_pending && !mute.target(muted) {
2073 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
2074 } else {
2075 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control);
2076 silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref());
2077 }
2078 }
2079 Some(CallCommand::DisableAudio) => {
2080 let audio = live.audio.as_ref().expect("audio set above");
2081 muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
2082 audio_disabled = true;
2083 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, None, false, &mut software_audio, mic_settings, control, timeline);
2084 if audio.uses_devices() {
2085 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
2086 factory.set_adm_recording_enabled(false);
2087 factory.set_adm_playout_enabled(false);
2088 }
2089 control.send(CallUpdate::ListenOnly(true));
2090 }
2091 Some(CallCommand::SelectInput(choice)) => {
2092 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2093 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
2094 applied_input = devices::applied_device(&device_lists.inputs, &choice, devices::system_default_id(Flow::Capture).as_deref());
2095 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2096 }
2097 input = choice;
2098 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
2099 if software_audio.is_some() {
2100 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);
2101 }
2102 }
2103 Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
2104 let device_ns_changed =
2105 mic_settings.ml_noise_suppression() != settings.ml_noise_suppression();
2106 mic_settings = settings;
2107 if let Some(audio) = live.audio.as_ref() {
2108 track = audio.device_track(mic_settings).clone();
2109 }
2110 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);
2111 }
2112 Some(CallCommand::SetMicSettings(settings)) => {
2113 mic_settings = settings;
2114 crate::noise_stage::apply_for_outgoing(mic_settings, false);
2115 }
2116 Some(CallCommand::SelectOutput(choice)) => {
2117 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2118 timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice)));
2119 applied_output = devices::applied_device(&device_lists.outputs, &choice, devices::system_default_id(Flow::Render).as_deref());
2120 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2121 }
2122 output = choice;
2123 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
2124 }
2125 Some(CallCommand::RefreshDevices) => {
2126 device_lists = devices::list_devices(&factory);
2127 control.send(CallUpdate::Devices(device_lists.clone()));
2128 }
2129 Some(CallCommand::SetCamera(false)) if local_video.camera_previewing() => {
2130 start_camera_pending = false;
2131 local_video.stop_camera();
2132 control.send(CallUpdate::Camera(false));
2133 }
2134 Some(CallCommand::SetCamera(on)) => {
2135 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
2136 if on && next.is_some() {
2137 let first = !start_camera_pending;
2138 start_camera_pending = true;
2139 if local_video.is_available()
2140 && !local_video.camera_on()
2141 && !local_video.camera_previewing()
2142 && let Err(error) = local_video.preview_camera(&camera_choice)
2143 {
2144 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2145 }
2146 if first {
2147 control.send(CallUpdate::Camera(true));
2148 }
2149 } else if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) {
2150 if remote_set && next.is_none() && negotiator.begin_conference_upgrade() {
2151 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;
2152 next = pending.or(next);
2153 }
2154 if remote_set && on && next.is_some() {
2155 start_camera_pending = true;
2156 }
2157 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2158 } else if on && consent_pending {
2159 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
2160 } else if local_hold {
2161 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2162 } else if on && direct && (same_peer.is_some() || glare_resend.is_some()) {
2163 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2164 } else if on {
2165 let started = start_camera_line(&mut local_video, &current.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
2166 match started {
2167 Ok(()) if direct => {
2168 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 {
2169 Ok((browser_offer, signaled, reply_tags)) => {
2170 timeline.record_sdp("local offer", &signaled.sdp);
2171 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
2172 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2173 same_peer_grace_until = None;
2174 }
2175 Err(error) => {
2176 timeline.record("camera offer failed", error.to_string());
2177 undo_change(Change::Camera(true), &mut local_video, control);
2178 }
2179 }
2180 }
2181 Ok(()) => {
2182 control.send(CallUpdate::Camera(true));
2183 tell_media_descriptions(
2184 &remote,
2185 &media_links,
2186 MediaDescription::camera_line(
2187 local_video.camera_mid().unwrap_or_else(|| CAMERA_MID.to_owned()),
2188 true,
2189 ),
2190 &mut media_description_request,
2191 timeline,
2192 );
2193 }
2194 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))),
2195 }
2196 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2197 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2198 } else if direct {
2199 local_video.stop_camera();
2200 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 {
2201 Ok((browser_offer, signaled, reply_tags)) => {
2202 timeline.record_sdp("local offer", &signaled.sdp);
2203 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
2204 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2205 same_peer_grace_until = None;
2206 }
2207 Err(error) => {
2208 timeline.record("camera offer failed", error.to_string());
2209 control.send(CallUpdate::Camera(false));
2210 }
2211 }
2212 } else {
2213 local_video.stop_camera();
2214 control.send(CallUpdate::Camera(false));
2215 tell_media_descriptions(
2216 &remote,
2217 &media_links,
2218 MediaDescription::camera_line(
2219 local_video.camera_mid().unwrap_or_else(|| CAMERA_MID.to_owned()),
2220 false,
2221 ),
2222 &mut media_description_request,
2223 timeline,
2224 );
2225 }
2226 }
2227 Some(CallCommand::SelectCamera(choice)) => {
2228 camera_choice = choice;
2229 if local_video.camera_previewing()
2230 && let Err(error) = local_video.preview_camera(&camera_choice)
2231 {
2232 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2233 } else if local_video.camera_on()
2234 && let Err(error) = local_video.start_camera(&camera_choice)
2235 {
2236 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2237 }
2238 }
2239 Some(CallCommand::SetVideoQuality(quality)) => {
2240 local_video.set_video_quality(quality);
2241 if let Err(error) = local_video.refresh_camera_capture(&camera_choice) {
2242 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_RESTART_NOTICE, error)));
2243 }
2244 if video.set_video_quality(quality) {
2245 send_receive_change(control, video.reselect(&roster));
2246 }
2247 }
2248 Some(CallCommand::StartPortalShare(kind)) => {
2249 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2250 if !remote_set {
2251 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2252 } else if local_hold {
2253 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2254 } else if !local_video.sharing() && next.is_some() {
2255 portal_pending = Some(kind);
2256 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2257 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2258 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2259 } else if direct
2260 && !local_video.sharing()
2261 && !local_video.has_share_line()
2262 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2263 {
2264 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2265 } else if !local_video.sharing()
2266 && (!video_possible(remote_set, layout, negotiator.path())
2267 || !local_video.share_sending())
2268 {
2269 if next.is_none() && negotiator.begin_conference_upgrade() {
2270 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;
2271 next = pending.or(next);
2272 }
2273 if next.is_some() {
2274 portal_pending = Some(kind);
2275 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2276 } else {
2277 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2278 }
2279 } else if let Err(error) = local_video.open_portal(kind, control.command_sender()) {
2280 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2281 }
2282 }
2283 Some(CallCommand::FinishPortalShare { source, generation }) => {
2284 if local_video.accept_portal(generation) {
2285 control.defer(CallCommand::StartShare(source));
2286 }
2287 }
2288 Some(CallCommand::AbandonPortalShare) => {
2289 if local_video.portal_is_open() {
2290 local_video.stop_share();
2291 }
2292 }
2293 Some(CallCommand::StartShare(source)) => {
2294 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2295 if !remote_set {
2296 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2297 } else if local_hold {
2298 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2299 } else if next.is_some() {
2300 share_pending = Some(source);
2301 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2302 } else if direct && local_video.share_sending() {
2303 match local_video.start_share(&source) {
2304 Ok(()) => announce_share(control, &source),
2305 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2306 }
2307 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2308 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2309 } else if direct
2310 && !local_video.has_share_line()
2311 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2312 {
2313 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2314 } else if direct {
2315 match local_video.start_share(&source) {
2316 Ok(()) => {
2317 announce_share(control, &source);
2318 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);
2319 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 {
2320 Ok((browser_offer, signaled, reply_tags)) => {
2321 timeline.record_sdp("local offer", &signaled.sdp);
2322 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
2323 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2324 same_peer_grace_until = None;
2325 }
2326 Err(error) => {
2327 timeline.record("share offer failed", error.to_string());
2328 undo_change(Change::Share(true), &mut local_video, control);
2329 }
2330 }
2331 }
2332 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2333 }
2334 } else if !video_possible(remote_set, layout, negotiator.path())
2335 || !local_video.share_sending()
2336 {
2337 if next.is_none() && negotiator.begin_conference_upgrade() {
2338 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;
2339 next = pending.or(next);
2340 }
2341 if next.is_some() {
2342 share_pending = Some(source);
2343 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2344 } else {
2345 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2346 }
2347 } else {
2348 match local_video.start_share(&source) {
2349 Ok(()) => {
2350 announce_share(control, &source);
2351 tell_media_descriptions(
2352 &remote,
2353 &media_links,
2354 MediaDescription::share_line(
2355 local_video.share_mid().unwrap_or_else(|| SHARE_MID.to_owned()),
2356 true,
2357 ),
2358 &mut media_description_request,
2359 timeline,
2360 );
2361 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);
2362 }
2363 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2364 }
2365 }
2366 }
2367 Some(CallCommand::StopShare) => {
2368 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2369 share_pending = None;
2370 portal_pending = None;
2371 if local_video.portal_is_open() {
2372 local_video.stop_share();
2373 } else if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2374 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2375 } else if direct && local_video.sharing() {
2376 local_video.stop_share();
2377 clear_share(control);
2378 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);
2379 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 {
2380 Ok((browser_offer, signaled, reply_tags)) => {
2381 timeline.record_sdp("local offer", &signaled.sdp);
2382 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
2383 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2384 same_peer_grace_until = None;
2385 }
2386 Err(error) => timeline.record("share offer failed", error.to_string()),
2387 }
2388 } else if local_video.sharing() {
2389 local_video.stop_share();
2390 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);
2391 clear_share(control);
2392 tell_media_descriptions(
2393 &remote,
2394 &media_links,
2395 MediaDescription::share_line(
2396 local_video.share_mid().unwrap_or_else(|| SHARE_MID.to_owned()),
2397 false,
2398 ),
2399 &mut media_description_request,
2400 timeline,
2401 );
2402 }
2403 }
2404 Some(CallCommand::SetShareSound(on)) => {
2405 share_sound_wanted = on;
2406 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);
2407 }
2408 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),
2409 Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
2410 Ok(receipt) => {
2411 own_hand = receipt.state_id;
2412 control.send(CallUpdate::OwnHand(Some(receipt.rank)));
2413 }
2414 Err(error) => {
2415 timeline.record("raise hand failed", error.to_string());
2416 control.send(CallUpdate::OwnHand(None));
2417 control.send(CallUpdate::Notice(RAISE_HAND_FAILED_NOTICE.into()));
2418 }
2419 },
2420 Some(CallCommand::SetHand(false)) => {
2421 let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect();
2422 own_hand = None;
2423 control.send(CallUpdate::OwnHand(None));
2424 if !state_ids.is_empty()
2425 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2426 {
2427 timeline.record("lower hand failed", error.to_string());
2428 control.send(CallUpdate::Notice(LOWER_HAND_FAILED_NOTICE.into()));
2429 }
2430 }
2431 Some(CallCommand::LowerHand { mri }) => {
2432 let state_ids: Vec<String> = roster.hand_of(&mri).map(|hand| hand.state_id.clone()).into_iter().collect();
2433 if !state_ids.is_empty()
2434 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2435 {
2436 timeline.record("lower hand failed", error.to_string());
2437 control.send(CallUpdate::Notice(LOWER_THAT_HAND_FAILED_NOTICE.into()));
2438 }
2439 }
2440 Some(CallCommand::LowerAllHands) => {
2441 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
2442 timeline.record("lower all hands failed", error.to_string());
2443 control.send(CallUpdate::Notice(LOWER_ALL_HANDS_FAILED_NOTICE.into()));
2444 }
2445 }
2446 Some(CallCommand::Admit { mri }) => {
2447 let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2448 report_organizer_result(result, "admit", ADMIT_FAILED_NOTICE, control, timeline);
2449 }
2450 Some(CallCommand::AdmitAll) => {
2451 let mut result = Ok(202);
2452 for mri in roster.lobby_mris() {
2453 result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2454 if result.is_err() {
2455 break;
2456 }
2457 }
2458 report_organizer_result(result, "admit all", ADMIT_ALL_FAILED_NOTICE, control, timeline);
2459 }
2460 Some(CallCommand::Deny { mri }) => {
2461 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2462 report_organizer_result(result, "deny", DENY_FAILED_NOTICE, control, timeline);
2463 }
2464 Some(CallCommand::RemoveParticipant { mri }) => {
2465 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2466 report_organizer_result(result, "remove participant", REMOVE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2467 }
2468 Some(CallCommand::MuteParticipant { mri }) => {
2469 let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;
2470 report_organizer_result(result, "mute participant", MUTE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2471 }
2472 Some(CallCommand::MuteAll) => {
2473 let others: Vec<String> = roster
2474 .members()
2475 .iter()
2476 .filter(|member| member.mri != own_mri && !member.in_lobby && !member.mri.starts_with(BOT_PREFIX))
2477 .map(|member| member.mri.clone())
2478 .collect();
2479 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
2480 report_organizer_result(result, "mute all", MUTE_ALL_FAILED_NOTICE, control, timeline);
2481 }
2482 Some(CallCommand::SetLock(locked)) => {
2483 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
2484 if result.is_ok() {
2485 capability.locked = locked;
2486 control.send(CallUpdate::Capability(capability));
2487 }
2488 report_organizer_result(result, "lock meeting", MEETING_LOCK_FAILED_NOTICE, control, timeline);
2489 }
2490 Some(CallCommand::SetRole { mri, role }) => {
2491 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
2492 report_organizer_result(result, "change role", CHANGE_ROLE_FAILED_NOTICE, control, timeline);
2493 }
2494 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
2495 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
2496 let mut result = Ok(200);
2497 for step in modality_steps(modality, allowed, capability, &limits) {
2498 result = match step {
2499 StateStep::Publish(state_type) => remote.signaling.publish_attendee_state(&remote.conversation, &remote.participant, state_type, &mri).await,
2500 StateStep::Remove(state_id) => remote.signaling.lower_hands(&remote.conversation, &remote.participant, &[state_id]).await.map(|()| 200),
2501 };
2502 if result.is_err() {
2503 break;
2504 }
2505 }
2506 let notice = if modality == Modality::Mic {
2507 MIC_SETTING_FAILED_NOTICE
2508 } else {
2509 CAMERA_SETTING_FAILED_NOTICE
2510 };
2511 report_organizer_result(result, "attendee modality", notice, control, timeline);
2512 }
2513 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
2514 let result = match &meeting_target {
2515 Some(target) => meeting_options::write(&inner.session, target, &OptionWrite::restrictions(mic_off, camera_off)).await.map(|()| 200),
2516 None => Err(Error::Signaling("no meeting coordinates for the options".into())),
2517 };
2518 if result.is_ok() {
2519 capability.attendee_mic_off = mic_off;
2520 capability.attendee_camera_off = camera_off;
2521 control.send(CallUpdate::Capability(capability));
2522 }
2523 report_organizer_result(result, "attendee restrictions", ATTENDEE_SETTINGS_FAILED_NOTICE, control, timeline);
2524 }
2525 Some(CallCommand::Invite { callees, group_thread }) => {
2526 let thread = group_thread.or_else(|| meeting_chat.clone());
2527 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
2528 report_organizer_result(result, "invite", INVITE_PERSON_FAILED_NOTICE, control, timeline);
2529 }
2530 Some(CallCommand::LoadMeetingOptions) => {
2531 let update = match &meeting_target {
2532 Some(target) => meeting_options::fetch(&inner.session, target).await.map_err(|error| error.to_string()),
2533 None => Err("This meeting has no options page".to_owned()),
2534 };
2535 control.send(CallUpdate::MeetingOptions(update));
2536 }
2537 Some(CallCommand::SaveMeetingOptions(writes)) => {
2538 let update = match &meeting_target {
2539 Some(target) => save_meeting_options(&inner.session, target, &writes).await,
2540 None => Err("This meeting has no options page".to_owned()),
2541 };
2542 if let Ok(options) = &update {
2543 let (mic_off, camera_off) = options.attendees_off();
2544 capability.attendee_mic_off = mic_off;
2545 capability.attendee_camera_off = camera_off;
2546 control.send(CallUpdate::Capability(capability));
2547 }
2548 control.send(CallUpdate::MeetingOptionsSaved(update));
2549 }
2550 Some(CallCommand::Spotlight { mri }) => {
2551 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
2552 report_organizer_result(result, "spotlight", SPOTLIGHT_FAILED_NOTICE, control, timeline);
2553 }
2554 Some(CallCommand::StopSpotlight { mri }) => {
2555 let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();
2556 if !state_ids.is_empty() {
2557 let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);
2558 report_organizer_result(result, "stop spotlight", STOP_SPOTLIGHT_FAILED_NOTICE, control, timeline);
2559 }
2560 }
2561 Some(CallCommand::SetCaptions(on)) => {
2562 caption_flow.want(on);
2563 if on {
2564 caption_deadline = Some(Instant::now() + CAPTION_START_LIMIT);
2565 control.send(CallUpdate::Captions(CaptionState::Starting));
2566 } else {
2567 caption_deadline = None;
2568 control.send(CallUpdate::Captions(CaptionState::Off));
2569 }
2570 run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), &RecordingPlan::default(), &mut bot_pending, control, timeline).await;
2571 if caption_flow.on() {
2572 caption_deadline = None;
2573 }
2574 }
2575 Some(CallCommand::StartRecording { kind, title }) => {
2576 if !is_echo {
2577 recording_plan = RecordingPlan { title, kind, ..RecordingPlan::default() };
2578 recording_flow.want(true);
2579 recording_deadline = Some(Instant::now() + RECORDING_START_LIMIT);
2580 control.send(CallUpdate::RecordingPending(true));
2581 run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await;
2582 }
2583 }
2584 Some(CallCommand::StopRecording { scope }) => {
2585 if !is_echo {
2586 recording_plan.scope = scope;
2587 recording_flow.stop();
2588 recording_deadline = None;
2589 run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await;
2590 }
2591 }
2592 Some(CallCommand::SetCaptionLanguage(language)) => {
2593 if let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone())
2594 && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await
2595 {
2596 timeline.record("caption language failed", error.to_string());
2597 control.send(CallUpdate::Notice(CAPTION_LANGUAGE_FAILED_NOTICE.into()));
2598 }
2599 }
2600 Some(CallCommand::ConsentToRecording) => {
2601 match remote.signaling.consent_to_recording(&remote.conversation, &remote.participant, Consent::Give).await {
2602 Ok(_) => {
2603 consent_pending = false;
2604 control.send(CallUpdate::ConsentRequired(false));
2605 }
2606 Err(error) => {
2607 timeline.record("recording consent failed", error.to_string());
2608 control.send(CallUpdate::Notice(CONFIRM_RECORDING_FAILED_NOTICE.into()));
2609 }
2610 }
2611 }
2612 Some(CallCommand::Hold(hold)) => {
2613 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || glare_resend.is_some() || next.is_some() {
2614 continue;
2615 }
2616 if hold && local_video.camera_on() {
2617 local_video.stop_camera();
2618 control.send(CallUpdate::Camera(false));
2619 }
2620 let camera = !hold && local_video.camera_on();
2621 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 {
2622 Ok((browser_offer, signaled, reply_tags)) => {
2623 timeline.record_sdp("local offer", &signaled.sdp);
2624 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2625 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2626 same_peer_grace_until = None;
2627 }
2628 Err(error) => {
2629 timeline.record("hold failed", error.to_string());
2630 control.send(CallUpdate::Notice(if hold {
2631 HOLD_FAILED_NOTICE.into()
2632 } else {
2633 RESUME_FAILED_NOTICE.into()
2634 }));
2635 }
2636 }
2637 }
2638 Some(CallCommand::Transfer { target, replaces }) => {
2639 let Some(url) = media_links.get("transfer").cloned() else {
2640 control.send(CallUpdate::TransferResult { succeeded: false });
2641 control.send(CallUpdate::Notice(TRANSFER_NOT_ALLOWED_NOTICE.into()));
2642 continue;
2643 };
2644 let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() };
2645 match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {
2646 Ok(()) => control.send(CallUpdate::Notice(notice_with_detail(
2647 TRANSFERRING_NOTICE,
2648 target.display_name,
2649 ))),
2650 Err(error) => {
2651 timeline.record("transfer failed", error.to_string());
2652 control.send(CallUpdate::TransferResult { succeeded: false });
2653 control.send(CallUpdate::Notice(TRANSFER_CALL_FAILED_NOTICE.into()));
2654 }
2655 }
2656 }
2657 Some(CallCommand::OpenWhiteboard { title }) => {
2658 let Some(target) = meeting_target.clone() else {
2659 control.send(CallUpdate::Notice(WHITEBOARDS_MEETINGS_ONLY_NOTICE.into()));
2660 continue;
2661 };
2662 let session = inner.session.clone();
2663 let updates = control.updates();
2664 tokio::spawn(async move {
2665 let update = match whiteboard::fetch_board(&session, &target, &title).await {
2666 Ok(url) => CallUpdate::WhiteboardUrl(url),
2667 Err(_) => CallUpdate::Notice(WHITEBOARD_OPEN_FAILED_NOTICE.into()),
2668 };
2669 let _ = updates.send(update);
2670 });
2671 }
2672 Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,
2673 Some(CallCommand::SetIncomingVideo(enabled)) => {
2674 video.set_incoming_enabled(enabled);
2675 if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) {
2676 let key = VideoKey::Person(mri.clone());
2677 control.video.forget(&key);
2678 video.router().set(mid, enabled.then_some(key));
2679 }
2680 send_receive_change(control, video.reselect(&roster));
2681 control.send(CallUpdate::IncomingVideo(enabled));
2682 }
2683 Some(CallCommand::SetVideoWants(wants)) => {
2684 if video.set_wants(wants) {
2685 send_receive_change(control, video.reselect(&roster));
2686 }
2687 }
2688 Some(CallCommand::SetShareMotion(on)) => local_video.set_motion(on),
2689 Some(CallCommand::SetShareStandout(on)) => local_video.set_standout(on),
2690 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
2691 Some(CallCommand::SendReaction(reaction)) => {
2692 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
2693 timeline.record("reaction failed", error.to_string());
2694 control.send(CallUpdate::Notice(REACTION_FAILED_NOTICE.into()));
2695 }
2696 }
2697 Some(CallCommand::EndMeeting) => {
2698 stop_local_publish(
2699 &mut local_video,
2700 &remote,
2701 &media_links,
2702 &mut media_description_request,
2703 control,
2704 timeline,
2705 )
2706 .await;
2707 if is_meeting {
2708 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
2709 Ok(()) => {
2710 live.skip_leave = true;
2711 report.left_cleanly = true;
2712 }
2713 Err(error) => timeline.record("end meeting failed", error.to_string()),
2714 }
2715 }
2716 advance(state, CallSignal::LocalLeave, control);
2717 break;
2718 }
2719 Some(CallCommand::Hangup) | None => {
2720 // Stop publishing before leave so remotes do not keep a frozen camera tile.
2721 stop_local_publish(
2722 &mut local_video,
2723 &remote,
2724 &media_links,
2725 &mut media_description_request,
2726 control,
2727 timeline,
2728 )
2729 .await;
2730 advance(state, CallSignal::LocalLeave, control);
2731 break;
2732 }
2733 },
2734 _ = stats_tick.tick(), if remote_set => {
2735 if local_video.take_effects_failure() {
2736 timeline.record("camera effects failed", "segmentation model did not load");
2737 control.send(CallUpdate::Notice(CAMERA_EFFECTS_FAILED_NOTICE.into()));
2738 }
2739 let speaking = active_speakers::speaking_sources(&active_speakers::audio_sources(&current.peer));
2740 if speaking != speaking_sources {
2741 if speaking_sources.is_empty() && !speaker_sources_seen {
2742 speaker_sources_seen = true;
2743 timeline.record("active speakers", format!("{} source(s) from RTP", speaking.len()));
2744 }
2745 speaking_sources = speaking;
2746 let mut speakers = roster.mris_for_sources(&speaking_sources);
2747 if speakers.is_empty() && !speaking_sources.is_empty() && layout == Layout::OneToOne {
2748 speakers = roster.entries().into_iter().map(|entry| entry.mri).filter(|mri| *mri != own_mri).collect();
2749 }
2750 if video.note_speakers(&speakers) {
2751 send_receive_change(control, video.reselect(&roster));
2752 }
2753 control.send(CallUpdate::Speakers(speakers));
2754 }
2755 let snapshot = collect_stats(&current.peer, &layout_plan.screen_share_mids).await;
2756 ticks += 1;
2757 if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
2758 caption_deadline = None;
2759 caption_flow.failed();
2760 timeline.record("captions", "did not start in time");
2761 control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into())));
2762 }
2763 if recording_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
2764 recording_deadline = None;
2765 recording_flow.failed();
2766 timeline.record("recording", "did not start in time");
2767 control.send(CallUpdate::RecordingPending(false));
2768 control.send(CallUpdate::Notice(RECORDING_NOT_STARTED_NOTICE.into()));
2769 }
2770 if layout == Layout::Conference
2771 && let Some(size) = local_video.camera_size()
2772 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2773 && let Some(body) = send_capabilities.body_for_mid(
2774 local_video
2775 .camera_mid()
2776 .as_deref()
2777 .unwrap_or(CAMERA_MID),
2778 size,
2779 local_video.video_quality(),
2780 )
2781 {
2782 let signaling = signaling.clone();
2783 let timeline = timeline.clone();
2784 tokio::spawn(async move {
2785 match signaling.post_json(SEND_CAPABILITIES_LABEL, &url, body).await {
2786 Ok(()) => timeline.record("send capabilities", format!("{}x{} accepted", size.0, size.1)),
2787 Err(error) => timeline.record("send capabilities failed", error.to_string()),
2788 }
2789 });
2790 }
2791 for (source, refreshed) in local_video.refresh_send_limits() {
2792 match refreshed {
2793 Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?} after a frame size change")),
2794 Ok(None) => {}
2795 Err(error) => timeline.record("send limits failed", error.to_string()),
2796 }
2797 }
2798 if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)
2799 && let Some(average_ms) = local_video.blur_average_ms()
2800 {
2801 control.send(CallUpdate::BlurTiming(average_ms));
2802 if let Some(model) = local_video.blur_model().filter(|model| Some(*model) != segmentation_model) {
2803 timeline.record("segmentation model", format!("{model}, effects {average_ms:.1} ms per frame"));
2804 segmentation_model = Some(model);
2805 }
2806 }
2807 if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {
2808 control.send(CallUpdate::Sample(StatsSample {
2809 audio_in_packets: snapshot.inbound_packets,
2810 audio_out_packets: snapshot.outbound_packets,
2811 audio_in_level: snapshot.audio_level,
2812 audio_out_level: snapshot.local_level,
2813 video: VideoReport {
2814 frames_received: live.video_counters.received.load(Ordering::Relaxed),
2815 frames_published: live.video_counters.published.load(Ordering::Relaxed),
2816 ..snapshot.video.clone()
2817 },
2818 share_in_packets: snapshot.share_inbound_packets,
2819 share_out_packets: snapshot.share_outbound_packets,
2820 }));
2821 }
2822 if ticks.is_multiple_of(HEALTH_EVERY_TICKS)
2823 && snapshot.selected_pair.is_some()
2824 && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)
2825 {
2826 let quality = quality_tracker.observe(std::time::Instant::now(), &sample);
2827 if local_video.camera_on()
2828 && snapshot.camera_target_bitrate > 0
2829 && bitrate_governor.observe(
2830 std::time::Instant::now(),
2831 snapshot.video.remote_round_trip_ms,
2832 sample.loss_percent,
2833 snapshot.camera_target_bitrate,
2834 )
2835 {
2836 let cap = bitrate_governor.cap_bps();
2837 if let Err(error) = local_video.cap_camera_bitrate(cap) {
2838 timeline.record("bitrate cap failed", error.to_string());
2839 } else {
2840 timeline.record(
2841 "bitrate cap",
2842 match cap {
2843 Some(bps) => format!("{} kbit/s", bps / 1000),
2844 None => "cleared".into(),
2845 },
2846 );
2847 }
2848 }
2849 control.send(CallUpdate::Health(CallHealth {
2850 level: quality.level,
2851 cpu_limited: quality.cpu_limited,
2852 sample,
2853 transport: snapshot.transport.clone(),
2854 path: negotiator.path(),
2855 }));
2856 }
2857 let local_level = if muted && software_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };
2858 control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
2859 if snapshot.selected_pair.is_some() {
2860 report.selected_pair = snapshot.selected_pair.clone();
2861 report.tls_version = snapshot.tls_version.clone();
2862 report.dtls_cipher = snapshot.dtls_cipher.clone();
2863 report.srtp_cipher = snapshot.srtp_cipher.clone();
2864 }
2865 report.inbound_packets = snapshot.inbound_packets;
2866 report.inbound_bytes = snapshot.inbound_bytes;
2867 report.outbound_packets = snapshot.outbound_packets;
2868 report.video = VideoReport {
2869 frames_received: live.video_counters.received.load(Ordering::Relaxed),
2870 frames_published: live.video_counters.published.load(Ordering::Relaxed),
2871 ..snapshot.video.clone()
2872 };
2873 if ticks.is_multiple_of(TICKS_PER_SECOND) {
2874 second += 1;
2875 let (decoded_rms, ratio) = {
2876 let recording = recording.lock().await;
2877 recording.per_second.last().copied().unwrap_or_default()
2878 };
2879 if snapshot.inbound_packets > previous_packets {
2880 report.seconds_with_inbound_audio += 1;
2881 }
2882 previous_packets = snapshot.inbound_packets;
2883 report.seconds.push(AudioSecond {
2884 second,
2885 packets: snapshot.inbound_packets,
2886 bytes: snapshot.inbound_bytes,
2887 audio_level: snapshot.audio_level,
2888 decoded_rms,
2889 tone_ratio: ratio,
2890 });
2891 control.send(CallUpdate::Stats {
2892 inbound_packets: snapshot.inbound_packets,
2893 outbound_packets: snapshot.outbound_packets,
2894 });
2895 timeline.record(
2896 "stats",
2897 format!(
2898 "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={:?}{}{}",
2899 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2900 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2901 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2902 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2903 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default(),
2904 local_video.camera_capture_summary().unwrap_or_default()
2905 ),
2906 );
2907 #[cfg(not(windows))]
2908 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2909 let listed = devices::list_devices(&factory);
2910 let previous_ids: Vec<String> = device_lists
2911 .inputs
2912 .iter()
2913 .chain(device_lists.outputs.iter())
2914 .map(|device| device.key())
2915 .collect();
2916 let current_ids: Vec<String> = listed
2917 .inputs
2918 .iter()
2919 .chain(listed.outputs.iter())
2920 .map(|device| device.key())
2921 .collect();
2922 for id in device_watch::endpoint_delta(&previous_ids, &current_ids) {
2923 device_debounce.signal_device(Instant::now(), Some(id));
2924 }
2925 }
2926 }
2927 }
2928 Some(device_id) = device_changes.recv() => {
2929 device_debounce.signal_device(Instant::now(), device_id);
2930 }
2931 _ = sleep_until(device_debounce.deadline().unwrap_or_else(far_future)), if device_debounce.deadline().is_some() => {
2932 if let Some(touched_ids) = device_debounce.take_due_devices(Instant::now()) {
2933 let previous = std::mem::replace(&mut device_lists, devices::list_devices(&factory));
2934 control.send(CallUpdate::Devices(device_lists.clone()));
2935 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2936 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);
2937 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);
2938 if input_changed || output_changed {
2939 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2940 }
2941 if input_changed && software_audio.is_some() {
2942 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);
2943 }
2944 }
2945 }
2946 }
2947 _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => {
2948 advance(state, CallSignal::ReconnectTimedOut, control);
2949 break;
2950 }
2951 _ = sleep_until(leave_at.unwrap_or_else(far_future)), if leave_at.is_some() => {
2952 advance(state, CallSignal::LocalLeave, control);
2953 break;
2954 }
2955 _ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {
2956 if let Some(pending) = next.as_mut().filter(|pending| pending.connected && pending.offered.is_none()) {
2957 pending.retargeted = true;
2958 timeline.record("escalation", "no retargetCompletion, switching anyway");
2959 } else if let Some(pending) = next.take() {
2960 pending.session.peer.close();
2961 negotiator.escalation_failed();
2962 start_camera_pending = false;
2963 if local_video.camera_previewing() {
2964 local_video.stop_camera();
2965 control.send(CallUpdate::Camera(false));
2966 }
2967 share_pending = None;
2968 portal_pending = None;
2969 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2970 timeline.record("escalation failed", "no answer for the new peer connection in time");
2971 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2972 }
2973 }
2974 _ = sleep_until(glare_at.unwrap_or_else(far_future)), if glare_at.is_some() => {
2975 let resend = glare_resend.take();
2976 if let Some(resend) = resend.as_ref().filter(|_| same_peer.is_some() || next.is_some()) {
2977 timeline.record("glare", "another change took over, ours is dropped");
2978 undo_change(resend.change, &mut local_video, control);
2979 } else if let Some(resend) = resend.as_ref().filter(|resend| layout == Layout::OneToOne && negotiator.path() == MediaPath::Mixer && !matches!(resend.change, Change::Hold(_))) {
2980 if negotiator.begin_conference_upgrade() {
2981 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;
2982 if pending.is_none() {
2983 drop_local_media(&mut local_video, control);
2984 }
2985 next = pending.or(next);
2986 } else {
2987 undo_change(resend.change, &mut local_video, control);
2988 }
2989 } else if let Some(resend) = resend {
2990 let (hold, camera, share) = match resend.change {
2991 Change::Hold(hold) => (hold, !hold && local_video.camera_on(), local_video.sharing()),
2992 _ => (local_hold, local_video.camera_on(), local_video.sharing()),
2993 };
2994 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 {
2995 Ok((browser_offer, signaled, reply_tags)) => {
2996 timeline.record_sdp("local offer", &signaled.sdp);
2997 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2998 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2999 same_peer_grace_until = None;
3000 }
3001 Err(error) => {
3002 timeline.record("offer after glare failed", error.to_string());
3003 undo_change(resend.change, &mut local_video, control);
3004 }
3005 }
3006 }
3007 }
3008 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
3009 same_peer_deadline = None;
3010 if same_peer.is_some() {
3011 same_peer_grace_until = Some(Instant::now() + SAME_PEER_LATE_GRACE);
3012 timeline.record(
3013 "same-peer offer",
3014 "no answer yet, waiting a little longer",
3015 );
3016 }
3017 }
3018 _ = sleep_until(same_peer_grace_until.unwrap_or_else(far_future)), if same_peer_grace_until.is_some() => {
3019 same_peer_grace_until = None;
3020 if let Some(pending) = same_peer.take() {
3021 timeline.record("same-peer offer", "no answer in time");
3022 negotiator.same_peer_offer_failed();
3023 rollback_offer(&current.peer).await;
3024 undo_change(pending.change, &mut local_video, control);
3025 }
3026 }
3027 _ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => {
3028 timeline.record("no answer", "outgoing call timed out");
3029 live.cancel_leave = true;
3030 advance(state, CallSignal::RemoteEnd(EndKind::NoAnswer), control);
3031 break;
3032 }
3033 _ = sleep_until(keep_alive_at.unwrap_or_else(far_future)), if keep_alive_at.is_some() => {
3034 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
3035 let remote = remote.clone();
3036 let links = links.clone();
3037 let call_leg = keep_alive_link.clone();
3038 tokio::spawn(async move {
3039 if let Some(url) = call_leg {
3040 let _ = remote.signaling.keep_call_alive(&url).await;
3041 }
3042 let _ = remote.signaling.keep_conversation_alive(&remote.conversation, &remote.participant, &links).await;
3043 });
3044 }
3045 }
3046 }
3047 if software_audio.is_some() {
3048 timeline.record("software audio", "stopping before tear down");
3049 drop(software_audio);
3050 }
3051 live.callbacks = Some(callbacks);
3052 Ok(())
3053}
3054
3055fn far_future() -> Instant {
3056 Instant::now() + FAR_FUTURE
3057}
3058
3059#[cfg(test)]
3060mod tests {
3061 #[test]
3062 fn gathering_settles_shortly_after_a_udp_relay_or_when_complete() {
3063 assert!(!gathering_settled(false, None));
3064 assert!(!gathering_settled(false, Some(Duration::from_millis(50))));
3065 assert!(gathering_settled(false, Some(RELAY_SETTLE)));
3066 assert!(gathering_settled(true, None));
3067 }
3068
3069 #[tokio::test]
3070 async fn a_hanging_setup_step_ends_on_cancel_or_after_the_step_timeout() {
3071 let (handle, mut control) = crate::control::call_channel();
3072 handle.commands.send(CallCommand::Hangup).unwrap();
3073 let limit = Duration::from_millis(20);
3074 let cancelled = setup_step_within(
3075 &mut control,
3076 limit,
3077 std::future::pending::<std::result::Result<(), Error>>(),
3078 )
3079 .await;
3080 assert!(matches!(cancelled, Err(Error::Cancelled)));
3081 let timed_out = setup_step_within(
3082 &mut control,
3083 limit,
3084 std::future::pending::<std::result::Result<(), Error>>(),
3085 )
3086 .await;
3087 assert!(matches!(timed_out, Err(Error::Signaling(_))));
3088 }
3089
3090 use super::*;
3091
3092 #[test]
3093 fn an_echo_call_waits_for_the_echo_bot_before_it_counts_as_connected() {
3094 let mut gate = CalleeGate::new(CallSpec::Echo.callee_count());
3095 assert!(!gate.media_connected());
3096 assert!(gate.callee_joined());
3097 }
3098
3099 #[test]
3100 fn only_a_conflict_answer_retries_a_recording_stop() {
3101 assert!(recorder_busy(&Error::Signaling(
3102 "recording command answered HTTP 409 no answer".into()
3103 )));
3104 assert!(!recorder_busy(&Error::Signaling(
3105 "recording command answered HTTP 500 no answer".into()
3106 )));
3107 assert!(!recorder_busy(&Error::Cancelled));
3108 }
3109
3110 #[test]
3111 fn escalation_keeps_the_software_track_when_it_runs() {
3112 assert_eq!(*pick_track(Some(&1), &0), 1);
3113 assert_eq!(*pick_track(None, &0), 0);
3114 }
3115
3116 #[test]
3117 fn video_is_possible_once_connected_and_not_waiting_on_a_mixer_escalation() {
3118 assert!(video_possible(true, Layout::OneToOne, MediaPath::Direct));
3119 assert!(video_possible(true, Layout::Conference, MediaPath::Mixer));
3120 assert!(!video_possible(true, Layout::OneToOne, MediaPath::Mixer));
3121 assert!(!video_possible(
3122 false,
3123 Layout::Conference,
3124 MediaPath::Direct
3125 ));
3126 }
3127
3128 #[test]
3129 fn camera_does_not_start_while_a_peer_escalation_is_pending() {
3130 assert!(camera_may_start(true, false, true));
3131 assert!(!camera_may_start(true, true, true));
3132 assert!(!camera_may_start(false, false, true));
3133 assert!(!camera_may_start(true, false, false));
3134 }
3135
3136 #[test]
3137 fn leg_switch_keeps_mixer_control_links_when_renegotiation_omits_them() {
3138 let mut media_links = BTreeMap::from([
3139 (
3140 "updateMediaDescriptions".to_owned(),
3141 "https://m/update".to_owned(),
3142 ),
3143 (
3144 "applyChannelParameters".to_owned(),
3145 "https://m/apply".to_owned(),
3146 ),
3147 ("callLeg".to_owned(), "https://m/leg".to_owned()),
3148 ]);
3149 replace_leg_media_links(
3150 &mut media_links,
3151 &BTreeMap::from([("mediaAnswer".to_owned(), "https://m/answer".to_owned())]),
3152 );
3153 assert_eq!(
3154 media_links
3155 .get("updateMediaDescriptions")
3156 .map(String::as_str),
3157 Some("https://m/update")
3158 );
3159 assert_eq!(
3160 media_links
3161 .get("applyChannelParameters")
3162 .map(String::as_str),
3163 Some("https://m/apply")
3164 );
3165 assert_eq!(
3166 media_links.get("mediaAnswer").map(String::as_str),
3167 Some("https://m/answer")
3168 );
3169 replace_leg_media_links(
3170 &mut media_links,
3171 &BTreeMap::from([(
3172 "updateMediaDescriptions".to_owned(),
3173 "https://m/update-new".to_owned(),
3174 )]),
3175 );
3176 assert_eq!(
3177 media_links
3178 .get("updateMediaDescriptions")
3179 .map(String::as_str),
3180 Some("https://m/update-new")
3181 );
3182 }
3183
3184 #[test]
3185 fn keep_alive_fires_at_ninety_percent_of_the_interval() {
3186 assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430));
3187 assert_eq!(keep_alive_period(None), Duration::from_secs(2430));
3188 assert_eq!(keep_alive_period(Some(10)), Duration::from_secs(54));
3189 }
3190
3191 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";
3192
3193 fn directions(sdp: &str) -> Vec<String> {
3194 crate::sdp::parse(sdp)
3195 .unwrap()
3196 .media
3197 .iter()
3198 .map(|line| line.direction().unwrap_or("none").to_owned())
3199 .collect()
3200 }
3201
3202 async fn local_offer(layout: Layout) -> Result<OfferedMedia> {
3203 use libwebrtc::audio_source::native::NativeAudioSource;
3204 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3205 let factory = devices::shared_factory();
3206 let peer = factory
3207 .create_peer_connection(RtcConfiguration::default())
3208 .unwrap();
3209 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3210 let track = factory.create_audio_track("microphone", source);
3211 let offer = create_offer(&peer, &factory, &track, layout, None).await;
3212 peer.close();
3213 offer
3214 }
3215
3216 #[tokio::test]
3217 async fn libwebrtc_accepts_its_own_offer_after_the_direction_rewrite() {
3218 for layout in [Layout::OneToOne, Layout::Conference] {
3219 if let Err(error) = local_offer(layout).await {
3220 panic!("{layout:?}: {error}");
3221 }
3222 }
3223 }
3224
3225 #[tokio::test]
3226 async fn a_peer_to_peer_offer_from_the_teams_client_gets_an_answer() {
3227 use libwebrtc::audio_source::native::NativeAudioSource;
3228 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
3229 let factory = devices::shared_factory();
3230 let peer = factory
3231 .create_peer_connection(RtcConfiguration::default())
3232 .unwrap();
3233 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3234 let track = factory.create_audio_track("microphone", source);
3235 let offer = include_str!("../../tests/fixtures/teams_p2p_offer.sdp");
3236 let answered = answer_offer(
3237 &peer,
3238 Some(&track),
3239 offer,
3240 AnswerVideo::Receive,
3241 None,
3242 false,
3243 None,
3244 )
3245 .await;
3246 peer.close();
3247 if let Err(error) = answered {
3248 panic!("{error}");
3249 }
3250 }
3251
3252 #[test]
3253 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3254 assert_eq!(
3255 directions(&directions_for(
3256 Layout::OneToOne,
3257 false,
3258 false,
3259 false,
3260 CAMERA_MID,
3261 Some(ONE_TO_ONE_SHARE_MID),
3262 false,
3263 BROWSER_OFFER
3264 )),
3265 vec!["sendrecv", "inactive", "inactive"]
3266 );
3267 assert_eq!(
3268 directions(&directions_for(
3269 Layout::OneToOne,
3270 false,
3271 true,
3272 false,
3273 CAMERA_MID,
3274 Some(ONE_TO_ONE_SHARE_MID),
3275 false,
3276 BROWSER_OFFER
3277 )),
3278 vec!["sendrecv", "sendrecv", "inactive"]
3279 );
3280 assert_eq!(
3281 directions(&directions_for(
3282 Layout::OneToOne,
3283 false,
3284 false,
3285 true,
3286 CAMERA_MID,
3287 Some(ONE_TO_ONE_SHARE_MID),
3288 false,
3289 BROWSER_OFFER
3290 )),
3291 vec!["sendrecv", "inactive", "sendonly"]
3292 );
3293 }
3294
3295 #[test]
3296 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3297 for layout in [Layout::OneToOne, Layout::Conference] {
3298 assert_eq!(
3299 directions(&directions_for(
3300 layout,
3301 true,
3302 true,
3303 false,
3304 CAMERA_MID,
3305 None,
3306 false,
3307 BROWSER_OFFER
3308 )),
3309 vec!["inactive", "inactive", "inactive"]
3310 );
3311 }
3312 assert_eq!(
3313 directions_for(
3314 Layout::Conference,
3315 false,
3316 true,
3317 false,
3318 CAMERA_MID,
3319 None,
3320 false,
3321 BROWSER_OFFER
3322 ),
3323 BROWSER_OFFER
3324 );
3325 }
3326
3327 #[test]
3328 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3329 let held = directions_for(
3330 Layout::Conference,
3331 true,
3332 false,
3333 false,
3334 CAMERA_MID,
3335 None,
3336 false,
3337 BROWSER_OFFER,
3338 );
3339 let mut numbers = || 7;
3340 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers)
3341 .unwrap()
3342 .sdp;
3343 assert_eq!(
3344 directions(&signaled),
3345 vec!["inactive", "inactive", "inactive"]
3346 );
3347 assert_eq!(signaled.matches("a=candidate:").count(), 1);
3348 }
3349
3350 #[test]
3351 fn a_move_into_the_meeting_you_are_already_in_is_ignored() {
3352 let target = |thread: &str| MeetingTarget {
3353 thread_id: thread.into(),
3354 tenant_id: "t".into(),
3355 organizer_id: "o".into(),
3356 meeting_data: None,
3357 };
3358 assert!(is_own_meeting(
3359 Some(&target("19:meeting_a@thread.v2")),
3360 &target("19:meeting_a@thread.v2")
3361 ));
3362 assert!(!is_own_meeting(
3363 Some(&target("19:meeting_a@thread.v2")),
3364 &target("19:meeting_b@thread.v2")
3365 ));
3366 assert!(!is_own_meeting(None, &target("19:meeting_a@thread.v2")));
3367 }
3368
3369 #[test]
3370 fn a_video_call_names_the_video_modality_only_when_the_camera_sends() {
3371 assert_eq!(accepted_modalities(false), vec!["Audio".to_owned()]);
3372 assert_eq!(
3373 accepted_modalities(true),
3374 vec!["Audio".to_owned(), "Video".to_owned()]
3375 );
3376 }
3377
3378 #[test]
3379 fn specs_map_to_invitation_targets() {
3380 assert_eq!(CallSpec::Echo.target(), InviteTarget::Echo);
3381 let people = CallSpec::People {
3382 callees: vec![Callee {
3383 mri: "8:orgid:b".into(),
3384 display_name: "Bea".into(),
3385 }],
3386 thread_id: "19:t@thread.v2".into(),
3387 };
3388 assert!(people.is_people() && !people.is_meeting());
3389 assert!(
3390 matches!(people.target(), InviteTarget::People { thread_id, .. } if thread_id == "19:t@thread.v2")
3391 );
3392 let meeting = CallSpec::Meeting(MeetingTarget {
3393 thread_id: "19:meeting@thread.v2".into(),
3394 tenant_id: "t".into(),
3395 organizer_id: "o".into(),
3396 meeting_data: None,
3397 });
3398 assert!(meeting.is_meeting() && !meeting.is_people());
3399 }
3400}