BlueGit

ict rusty-teams

Files

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

mod.rs

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