BlueGit

ict rusty-teams

Files

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

call.rs

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