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 let mut camera_choice = options.camera.clone();
1033 if options.start_camera {
1034 match local_video.preview_camera(&camera_choice) {
1035 Ok(()) => control.send(CallUpdate::Camera(true)),
1036 Err(error) => timeline.record("camera preview failed", error.to_string()),
1037 }
1038 }
1039 let mut media_description_request = 1u32;
1040 refresh_cameras(control.updates(), options.video, timeline.clone());
1041 control.send(CallUpdate::SharePicker(current_share_picker()));
1042 refresh_share_sources(control.updates(), options.video, false);
1043
1044 let wants_data_channel =
1045 options.data_channel && spec.as_ref().is_some_and(CallSpec::is_meeting);
1046 let mut current = open_peer(&factory, &grant, &options.relay_host, wants_data_channel)?;
1047 live.peers.push(current.peer.clone());
1048
1049 let signaling = Arc::new(inner.signaling(timeline.clone()));
1050 let media_leg_id = new_media_leg_id();
1051 let call_started = Instant::now();
1052 let mut offered: Option<OfferedMedia> = None;
1053 let mut negotiator = MediaNegotiator::default();
1054 let mut remote_set = false;
1055 let mut keep_alive_link: Option<String> = None;
1056 let mut keep_alive_seconds: Option<u64> = None;
1057 let mut keep_alive_at: Option<Instant> = None;
1058 let mut outgoing_deadline: Option<Instant> = None;
1059 let mut outgoing_limit = OUTGOING_TIMEOUT;
1060 let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
1061 let is_echo = matches!(spec, Some(CallSpec::Echo));
1062 let mut echo_watch = EchoWatch::default();
1063 let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count));
1064 let meeting_target = match &spec {
1065 Some(CallSpec::Meeting(target)) => Some(target.clone()),
1066 _ => None,
1067 };
1068 let people_thread = match &spec {
1069 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => {
1070 Some(thread_id.clone())
1071 }
1072 _ => incoming_media
1073 .as_ref()
1074 .filter(|(notification, _)| !notification.is_multi_party)
1075 .and_then(|(notification, _)| {
1076 notification
1077 .thread_id
1078 .clone()
1079 .filter(|thread| *thread != notification.caller.mri)
1080 .or_else(|| {
1081 one_to_one_thread(&inner.identity.object_id, &notification.caller.mri)
1082 })
1083 }),
1084 };
1085 let mut layout = match &spec {
1086 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne,
1087 _ => Layout::Conference,
1088 };
1089 let peer_mri = match &spec {
1090 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => {
1091 Some(callees[0].mri.clone())
1092 }
1093 _ => incoming_media
1094 .as_ref()
1095 .map(|(notification, _)| notification.caller.mri.clone()),
1096 };
1097 let mut layout_plan: OfferPlan;
1098 let mut direct_video_mid: Option<String> = None;
1099 let mut sending_camera = false;
1100 let mut media_links: BTreeMap<String, String> = BTreeMap::new();
1101
1102 let conversation = match (spec, incoming_media) {
1103 (Some(spec), None) => {
1104 let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
1105 let offer_started = Instant::now();
1106 let media = control
1107 .until_hangup(create_offer(
1108 &current.peer,
1109 &factory,
1110 &track,
1111 layout,
1112 direct_invite.then_some(&current.gathered),
1113 ))
1114 .await??;
1115 timeline.record(
1116 "offer created",
1117 format!("{} ms", offer_started.elapsed().as_millis()),
1118 );
1119 layout_plan = media.plan.clone();
1120 if layout == Layout::OneToOne {
1121 direct_video_mid = Some(CAMERA_MID.to_owned());
1122 }
1123 timeline.record(
1124 "setLocalDescription",
1125 format!("{} m-line(s) signaled", media.signaled.lines.len()),
1126 );
1127 timeline.record_sdp("local offer", &media.signaled.sdp);
1128 dump_sdp(options, "1-browser-offer.sdp", &media.browser_offer);
1129 dump_sdp(options, "2-teams-offer.sdp", &media.signaled.sdp);
1130 let target = spec.target();
1131 let invitation = Invitation {
1132 from: &participant,
1133 offer_sdp: &media.signaled.sdp,
1134 media_leg_id: &media_leg_id,
1135 callbacks: &links,
1136 target: &target,
1137 modalities: &media.modalities,
1138 direct: !options.concurrent,
1139 };
1140 let threadless = invitation.is_direct();
1141 let conversation = match &target {
1142 InviteTarget::Meeting(meeting) => {
1143 let subscribed = control
1144 .until_hangup(signaling.subscribe_meeting(&participant, &links, meeting))
1145 .await??;
1146 setup_step(control, signaling.join_meeting(&subscribed, &invitation)).await?
1147 }
1148 _ => setup_step(control, signaling.create_conversation(&invitation)).await?,
1149 };
1150 // People and the Echo test call share outgoing ringback while connecting.
1151 if spec.is_people() || matches!(spec, CallSpec::Echo) {
1152 control.send(CallUpdate::Progress(Progress::Calling));
1153 }
1154 if spec.is_people() {
1155 if threadless {
1156 outgoing_limit = DIRECT_OUTGOING_TIMEOUT;
1157 }
1158 outgoing_deadline = Some(Instant::now() + outgoing_limit);
1159 }
1160 if let Err(error) = local_video.set_lines(media.video.clone()) {
1161 timeline.record("video lines not attached", error.to_string());
1162 }
1163 offered = Some(media);
1164 live.remote = Some(RemoteCall {
1165 signaling: signaling.clone(),
1166 conversation: conversation.clone(),
1167 participant: participant.clone(),
1168 threadless,
1169 });
1170 conversation
1171 }
1172 (None, Some((notification, attached))) => {
1173 let teams_offer = attached
1174 .offer_sdp
1175 .clone()
1176 .ok_or_else(|| Error::Signaling("attach answer without an offer".into()))?;
1177 let conversation = attached
1178 .conversation
1179 .clone()
1180 .ok_or_else(|| Error::Signaling("attach answer without a conversation".into()))?;
1181 live.remote = Some(RemoteCall {
1182 signaling: signaling.clone(),
1183 conversation: conversation.clone(),
1184 participant: participant.clone(),
1185 threadless: notification.thread_id.is_none(),
1186 });
1187 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
1188 layout = if one_to_one {
1189 Layout::OneToOne
1190 } else {
1191 Layout::Conference
1192 };
1193 let camera_track = local_video.camera_track();
1194 let video_answer = match accept_mode {
1195 _ if !one_to_one => AnswerVideo::Reject,
1196 AcceptMode::Video if local_video.is_available() => AnswerVideo::Send(&camera_track),
1197 _ => AnswerVideo::Receive,
1198 };
1199 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
1200 let answered = answer_offer(
1201 &current.peer,
1202 Some(&track),
1203 &teams_offer,
1204 video_answer,
1205 None,
1206 false,
1207 one_to_one.then_some(&current.gathered),
1208 )
1209 .await?;
1210 layout_plan = answered.remote.plan();
1211 direct_video_mid = answered.camera_mid.clone();
1212 timeline.record(
1213 "setRemoteDescription",
1214 format!(
1215 "offer applied, {} signaled line(s)",
1216 answered.remote.lines.len()
1217 ),
1218 );
1219 if one_to_one {
1220 timeline.record("ice gathered", current.gathered.summary());
1221 }
1222 timeline.record_sdp("remote offer", &teams_offer);
1223 timeline.record_sdp("local answer", &answered.answer_sdp);
1224 dump_sdp(options, "4-teams-answer.sdp", &answered.answer_sdp);
1225 let acceptance_url = attached.links.get("acceptance").ok_or_else(|| {
1226 Error::Signaling("attach answer without an acceptance link".into())
1227 })?;
1228 let modalities = accepted_modalities(
1229 matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some(),
1230 );
1231 let acknowledged = signaling
1232 .accept(
1233 acceptance_url,
1234 &Answer {
1235 from: &participant,
1236 answer_sdp: &answered.answer_sdp,
1237 media_leg_id: &media_leg_id,
1238 callbacks: &links,
1239 modalities: &modalities,
1240 },
1241 )
1242 .await?;
1243 negotiator.answered_incoming(attached.from_mixer);
1244 remote_set = true;
1245 media_links.extend(attached.links.clone());
1246 media_links.extend(acknowledged);
1247 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
1248 let camera = peer_transceiver(&current.peer, mid);
1249 match camera.map(|camera| {
1250 local_video.set_lines(VideoLines {
1251 camera,
1252 share: None,
1253 })
1254 }) {
1255 Some(Ok(())) => match local_video.start_camera(&camera_choice) {
1256 Ok(()) => sending_camera = true,
1257 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(
1258 CAMERA_START_NOTICE,
1259 error,
1260 ))),
1261 },
1262 Some(Err(error)) => {
1263 timeline.record("video lines not attached", error.to_string())
1264 }
1265 None => timeline.record(
1266 "video lines not attached",
1267 "no transceiver for the camera line",
1268 ),
1269 }
1270 }
1271 keep_alive_link = media_links.get("callLeg").cloned();
1272 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
1273 conversation
1274 }
1275 _ => {
1276 return Err(Error::Callback(
1277 "call plan without an offer or an invitation".into(),
1278 ));
1279 }
1280 };
1281 let remote = live.remote.clone().expect("remote call set above");
1282 live.broker_running.store(true, Ordering::SeqCst);
1283 live.broker = Some(tokio::spawn(poll_broker(
1284 signaling.clone(),
1285 conversation.clone(),
1286 live.broker_running.clone(),
1287 )));
1288
1289 let initial = MuteEffect::initial(is_meeting);
1290 let mut muted = initial.muted;
1291 live.audio
1292 .as_ref()
1293 .expect("audio set above")
1294 .track
1295 .set_enabled(initial.track_enabled);
1296 if muted {
1297 control.send(CallUpdate::Muted(true));
1298 }
1299 match setup_step(
1300 control,
1301 signaling.update_endpoint_state(&conversation, &participant, initial.endpoint_is_muted),
1302 )
1303 .await
1304 {
1305 Err(Error::Cancelled) => return Err(Error::Cancelled),
1306 Err(error) => timeline.record("updateEndpointState failed", error.to_string()),
1307 Ok(()) => {}
1308 }
1309
1310 let mut stats_tick = interval(STATS_PERIOD);
1311 let mut speaking_sources: Vec<u32> = Vec::new();
1312 let mut speaker_sources_seen = false;
1313 let hard_deadline = options.hard_limit.map(|limit| call_started + limit);
1314 let mut leave_at = hard_deadline;
1315 let mut reconnect_deadline: Option<Instant> = None;
1316 let mut next: Option<NextPeer> = None;
1317 let mut roster = Roster::default();
1318 if let Some(snapshot) = &conversation.roster
1319 && roster.apply_snapshot(snapshot)
1320 {
1321 let entries = roster.entries();
1322 timeline.record(
1323 "roster",
1324 format!(
1325 "{} participant(s) from the conversation answer",
1326 entries.len()
1327 ),
1328 );
1329 control.send(CallUpdate::Roster(entries));
1330 }
1331 let mut lobby = false;
1332 let mut capability = MeetingCapability::default();
1333 let mut previous_packets = 0u64;
1334 let mut ticks = 0u32;
1335 let mut segmentation_model: Option<&'static str> = None;
1336 let mut health_sampler = HealthSampler::default();
1337 let mut quality_tracker = QualityTracker::default();
1338 let mut second = 0u32;
1339 let echo_thread = thread_id;
1340 let mut video = VideoReceive::new(own_mri.clone(), VideoRouter::default());
1341 if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) {
1342 video.router().set(mid, Some(VideoKey::Person(mri.clone())));
1343 }
1344 if sending_camera {
1345 control.send(CallUpdate::Camera(true));
1346 }
1347 let mut software_audio: Option<SoftwareAudio> = None;
1348 let mut share_sound_wanted = false;
1349 let mut mic_settings = MicSettings::default();
1350 crate::noise_stage::apply(mic_settings);
1351 let mut audio_disabled = false;
1352 let mut remote_audio: Option<RtcAudioTrack> = None;
1353 sync_software_audio(
1354 &factory,
1355 options,
1356 &input,
1357 muted,
1358 None,
1359 &current.peer,
1360 &track,
1361 software_wanted(
1362 mic_settings,
1363 share_sound_wanted,
1364 &local_video,
1365 live.audio.as_ref(),
1366 ),
1367 false,
1368 &mut software_audio,
1369 control,
1370 timeline,
1371 );
1372 let mut own_hand: Option<String> = None;
1373 let mut depacketizer = Depacketizer::default();
1374 let mut caption_flow = CaptionFlow::default();
1375 let mut caption_deadline: Option<Instant> = None;
1376 let mut recording_flow = CaptionFlow::default();
1377 let mut recording_deadline: Option<Instant> = None;
1378 let mut recording_plan = RecordingPlan::default();
1379 let mut recording_audio_only = false;
1380 let mut recording_status = RecordingStatus::default();
1381 let mut bot_pending = false;
1382 let mut consent_pending = false;
1383 let mut room_watcher = RoomWatcher::default();
1384 let mut main_meeting_sent = false;
1385 let mut local_hold = false;
1386 let mut remote_hold = false;
1387 let mut same_peer: Option<SamePeerOffer> = None;
1388 let mut send_requests = RequestFilter::default();
1389 let mut send_capabilities = SendCapabilityReporter::default();
1390 let mut same_peer_deadline: Option<Instant> = None;
1391 let mut same_peer_grace_until: Option<Instant> = None;
1392 let mut meeting_chat = conversation.chat_thread.clone();
1393 if let Some(thread) = &meeting_chat {
1394 control.send(CallUpdate::MeetingChat(thread.clone()));
1395 }
1396 if let Some(target) = &meeting_target {
1397 control.send(CallUpdate::MeetingTenant(target.tenant_id.clone()));
1398 }
1399 if meeting_chat.is_none() {
1400 meeting_chat = people_thread;
1401 }
1402 let mut start_camera_pending = options.start_camera;
1403 let mut share_pending: Option<ShareSource> = None;
1404 let mut portal_pending: Option<ShareKind> = None;
1405 let mut glare_resend: Option<GlareResend> = None;
1406 let mut deferred_changes: Vec<Change> = Vec::new();
1407 let mut remote_direct_share: Option<String> = None;
1408 let mut sent_replacement: Option<Replacement> = None;
1409 let (echo_add_tx, mut echo_add_rx) = mpsc::unbounded_channel::<Result<()>>();
1410 let mut echo_add_pending = false;
1411 loop {
1412 if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
1413 start_camera_pending = false;
1414 control.defer(CallCommand::SetCamera(true));
1415 }
1416 if video_possible(remote_set, layout, negotiator.path())
1417 && let Some(source) = share_pending.take()
1418 {
1419 control.defer(CallCommand::StartShare(source));
1420 }
1421 if video_possible(remote_set, layout, negotiator.path())
1422 && let Some(kind) = portal_pending.take()
1423 {
1424 control.defer(CallCommand::StartPortalShare(kind));
1425 }
1426 if next.as_ref().is_some_and(|pending| {
1427 pending.connected && (pending.offered.is_some() || pending.retargeted)
1428 }) && let Some(pending) = next.take()
1429 {
1430 timeline.record(
1431 "escalation",
1432 "new peer connection connected, old one dropped",
1433 );
1434 deferred_changes.clear();
1435 negotiator.server_escalation_done();
1436 if let Some(mid) = remote_direct_share.take() {
1437 video.router().set(&mid, None);
1438 control.send(CallUpdate::ScreenShare(None));
1439 }
1440 let old = std::mem::replace(&mut current, pending.session);
1441 old.peer.close();
1442 if let Some(audio) = &software_audio
1443 && let Err(error) = swap_audio_track(&current.peer, &audio.track)
1444 {
1445 timeline.record("computer sound not carried over", error.to_string());
1446 }
1447 offered = pending.offered;
1448 if let Some(mid) = direct_video_mid.take() {
1449 video.router().set(&mid, None);
1450 }
1451 if let Some(media) = &offered {
1452 layout = Layout::Conference;
1453 layout_plan = media.plan.clone();
1454 if let Err(error) = local_video.set_lines(media.video.clone()) {
1455 timeline.record("video lines not attached", error.to_string());
1456 }
1457 if local_video.camera_on() {
1458 tell_media_descriptions(
1459 &remote,
1460 &media_links,
1461 MediaDescription::camera(true),
1462 &mut media_description_request,
1463 timeline,
1464 );
1465 }
1466 if local_video.sharing() {
1467 tell_media_descriptions(
1468 &remote,
1469 &media_links,
1470 MediaDescription::share(true),
1471 &mut media_description_request,
1472 timeline,
1473 );
1474 }
1475 }
1476 remote_set = true;
1477 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1478 let pending = escalate(
1479 &factory,
1480 &grant,
1481 options,
1482 outgoing_track(software_audio.as_ref(), &track),
1483 &remote,
1484 &links,
1485 &media_leg_id,
1486 &media_links,
1487 &mut negotiator,
1488 live,
1489 timeline,
1490 )
1491 .await;
1492 if pending.is_none() {
1493 drop_local_media(&mut local_video, control);
1494 }
1495 next = pending.or(next);
1496 }
1497 }
1498 let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);
1499 let glare_at = glare_resend.as_ref().map(|resend| resend.at);
1500 tokio::select! {
1501 Some(callback) = callbacks.recv() => {
1502 match handle_callback(&callback, timeline) {
1503 Ok(CallEvent::Acceptance(acceptance)) => {
1504 if !acceptance.from_mixer
1505 && let Some(accepted_by) = &acceptance.accepted_by
1506 && roster.apply(&direct_roster(&[(own_mri.as_str(), participant.display_name.as_str()), (accepted_by.mri.as_str(), accepted_by.display_name.as_str())]))
1507 {
1508 control.send(CallUpdate::Roster(roster.entries()));
1509 }
1510 if !acceptance.from_mixer && callee_gate.callee_joined() {
1511 advance(state, CallSignal::MediaConnected, control);
1512 }
1513 let action = negotiator.on_acceptance(acceptance.from_mixer, layout == Layout::OneToOne);
1514 match action {
1515 MediaAction::ApplyAnswer | MediaAction::ApplyAnswerThenEscalate => {
1516 let Some(media) = offered.as_ref() else { continue };
1517 dump_sdp(options, "3-teams-answer.sdp", &acceptance.sdp);
1518 if let Ok(answer) = to_browser_answer(&acceptance.sdp, &media.signaled, &media.browser_offer) {
1519 dump_sdp(options, "4-browser-answer.sdp", &answer);
1520 }
1521 apply_answer(&current.peer, &acceptance.sdp, &media.signaled, &media.browser_offer)
1522 .await
1523 .inspect_err(|error| timeline.record("answer rejected", error.to_string()))?;
1524 remote_set = true;
1525 media_links.extend(acceptance.links.clone());
1526 if layout == Layout::Conference {
1527 negotiate_video(&mut video, &signaling, control, timeline, &acceptance.sdp, media, acceptance.from_mixer, &media_links, &roster);
1528 }
1529 if let Some(link) = acceptance.links.get("replacement")
1530 && sent_replacement.as_ref().is_none_or(|sent| sent.participant_id.is_none())
1531 {
1532 let replacement = Replacement::of_call(link.clone());
1533 sent_replacement = Some(replacement.clone());
1534 control.send(CallUpdate::ReplacementLink(replacement));
1535 }
1536 if !callee_gate.is_waiting() {
1537 outgoing_deadline = None;
1538 }
1539 let directions: Vec<String> = current
1540 .peer
1541 .transceivers()
1542 .iter()
1543 .map(|transceiver| format!("{:?}", transceiver.current_direction()))
1544 .collect();
1545 timeline.record("setRemoteDescription", format!("answer applied, directions {}", directions.join(",")));
1546 if acceptance.in_lobby() {
1547 lobby = true;
1548 control.send(CallUpdate::Lobby(true));
1549 }
1550 keep_alive_link = acceptance.links.get("callLeg").cloned();
1551 keep_alive_seconds = acceptance.keep_alive_seconds;
1552 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
1553 if action == MediaAction::ApplyAnswerThenEscalate {
1554 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;
1555 next = pending.or(next);
1556 }
1557 let remote = remote.clone();
1558 let links = links.clone();
1559 let thread_id = echo_thread.clone();
1560 let echo_add_tx = echo_add_tx.clone();
1561 if is_echo {
1562 echo_add_pending = true;
1563 }
1564 tokio::spawn(async move {
1565 if is_echo {
1566 let result = remote
1567 .signaling
1568 .add_echo_bot(
1569 &remote.conversation,
1570 &remote.participant,
1571 thread_id.as_deref(),
1572 &links,
1573 )
1574 .await;
1575 let ok = result.is_ok();
1576 let _ = echo_add_tx.send(result);
1577 if !ok {
1578 return;
1579 }
1580 }
1581 let _ = remote
1582 .signaling
1583 .update_endpoint_metadata(
1584 &remote.conversation,
1585 &remote.participant,
1586 )
1587 .await;
1588 });
1589 }
1590 MediaAction::Escalate => {
1591 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;
1592 next = pending.or(next);
1593 }
1594 _ => {}
1595 }
1596 }
1597 Ok(CallEvent::MediaAnswer(answer)) if !remote_set && !answer.from_mixer && same_peer.is_none() && next.is_none() && outgoing_deadline.is_some() => {
1598 timeline.record("provisional answer", if answer.no_ring_back { "no ringback" } else { "ringing" });
1599 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1600 if !answer.no_ring_back {
1601 control.send(CallUpdate::Progress(Progress::Ringing));
1602 }
1603 }
1604 Ok(CallEvent::MediaAnswer(answer))
1605 if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1606 {
1607 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1608 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1609 }
1610 if answer.from_mixer {
1611 negotiator.note_mixer_path();
1612 }
1613 if let Some(resend) = glare_resend.as_mut() {
1614 resend.at = Instant::now();
1615 }
1616 }
1617 Ok(CallEvent::MediaAnswer(answer)) => {
1618 let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1619 || next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags));
1620 if (same_peer.is_some() || next.is_some()) && !belongs {
1621 timeline.record("media answer ignored", "it answers an offer that is no longer pending");
1622 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1623 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1624 }
1625 continue;
1626 }
1627 let action = negotiator.on_media_answer();
1628 if action == MediaAction::Ignore
1629 && let Some(url) = answer.links.get("mediaAcknowledgement")
1630 {
1631 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1632 }
1633 if action == MediaAction::ApplyOnSamePeer
1634 && let Some(pending) = same_peer.take()
1635 {
1636 same_peer_deadline = None;
1637 same_peer_grace_until = None;
1638 let applied = match pending.change {
1639 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1640 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1641 };
1642 match applied {
1643 Ok(()) => {
1644 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1645 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1646 }
1647 match pending.change {
1648 Change::Hold(hold) => {
1649 local_hold = hold;
1650 silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref());
1651 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1652 }
1653 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1654 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1655 local_video.stop_share();
1656 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);
1657 clear_share(control);
1658 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1659 }
1660 Change::Share(_) => {}
1661 }
1662 if answer.from_mixer {
1663 media_links.extend(answer.links.clone());
1664 let wants_video = !local_hold && (local_video.camera_on() || local_video.sharing());
1665 let upgrade = wants_video
1666 && (negotiator.escalate_after_mixer_answer() || (layout == Layout::OneToOne && next.is_none() && negotiator.begin_conference_upgrade()));
1667 if !wants_video {
1668 negotiator.note_mixer_path();
1669 } else if upgrade {
1670 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;
1671 if pending.is_none() {
1672 drop_local_media(&mut local_video, control);
1673 }
1674 next = pending.or(next);
1675 }
1676 }
1677 }
1678 Err(error) => {
1679 timeline.record("same-peer answer rejected", error.to_string());
1680 undo_change(pending.change, &mut local_video, control);
1681 }
1682 }
1683 }
1684 if action == MediaAction::ApplyOnNewPeer {
1685 let applied = match next.as_ref().and_then(|pending| Some((pending, pending.offered.as_ref()?))) {
1686 Some((pending, media)) => apply_answer(&pending.session.peer, &answer.sdp, &media.signaled, &media.browser_offer).await,
1687 None => Err(Error::Webrtc("no pending peer connection for the answer".into())),
1688 };
1689 match applied {
1690 Ok(()) => {
1691 if let Some(media) = next.as_ref().and_then(|pending| pending.offered.as_ref()) {
1692 media_links.extend(answer.links.clone());
1693 negotiate_video(&mut video, &signaling, control, timeline, &answer.sdp, media, true, &media_links, &roster);
1694 }
1695 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1696 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1697 }
1698 }
1699 Err(error) => {
1700 negotiator.escalation_failed();
1701 if let Some(pending) = next.take() {
1702 pending.session.peer.close();
1703 }
1704 if layout == Layout::OneToOne {
1705 drop_local_media(&mut local_video, control);
1706 }
1707 timeline.record("escalation answer rejected", error.to_string());
1708 }
1709 }
1710 }
1711 }
1712 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
1713 if !renegotiation.escalation
1714 && !renegotiation.new_offer
1715 && let Some(pending) = same_peer.take()
1716 {
1717 same_peer_deadline = None;
1718 same_peer_grace_until = None;
1719 negotiator.same_peer_offer_failed();
1720 rollback_offer(&current.peer).await;
1721 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
1722 glare_resend = Some(GlareResend { change: pending.change, reply_tags: pending.reply_tags, at: Instant::now() + GLARE_RESEND_LIMIT });
1723 }
1724 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1725 let rejection_link = renegotiation.links.get("rejection").cloned();
1726 let result = match action {
1727 MediaAction::AnswerOnNewPeer => {
1728 if let Some(pending) = same_peer.take() {
1729 same_peer_deadline = None;
1730 same_peer_grace_until = None;
1731 timeline.record("same-peer offer", "superseded by the escalation offer");
1732 rollback_offer(&current.peer).await;
1733 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
1734 }
1735 if let Some(resend) = glare_resend.take() {
1736 defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control);
1737 }
1738 match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1739 Ok((session, answered)) => {
1740 timeline.record_sdp("local answer", &answered.answer_sdp);
1741 live.peers.push(session.peer.clone());
1742 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1743 if let Some(replaced) = next.take() {
1744 replaced.session.peer.close();
1745 }
1746 next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: Some(Instant::now() + NEXT_PEER_LIMIT), connected: false, retargeted: false });
1747 sent
1748 }
1749 Err(error) => {
1750 if next.is_none() {
1751 negotiator.server_escalation_failed();
1752 }
1753 for change in deferred_changes.drain(..) {
1754 undo_change(change, &mut local_video, control);
1755 }
1756 if let Some(url) = &rejection_link {
1757 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1758 }
1759 Err(error)
1760 }
1761 }
1762 }
1763 MediaAction::AnswerOnSamePeer => {
1764 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
1765 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 {
1766 Ok(answered) => {
1767 timeline.record_sdp("local answer", &answered.answer_sdp);
1768 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1769 for mid in answered.remote.plan().screen_share_mids {
1770 if !layout_plan.screen_share_mids.contains(&mid) {
1771 layout_plan.screen_share_mids.push(mid);
1772 }
1773 }
1774 if layout == Layout::OneToOne && answered.receiving_share_mid != remote_direct_share {
1775 if let Some(mid) = &remote_direct_share {
1776 video.router().set(mid, None);
1777 }
1778 if let Some(mid) = &answered.receiving_share_mid {
1779 video.router().set(mid, Some(VideoKey::Screen));
1780 }
1781 remote_direct_share = answered.receiving_share_mid.clone();
1782 control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));
1783 }
1784 if layout == Layout::OneToOne
1785 && !offer_sends_video(&renegotiation.sdp)
1786 && let Some(key) = main_video_mid(&answered.remote).and_then(|mid| video.router().key_for(&mid))
1787 {
1788 control.video.forget(&key);
1789 control.send(CallUpdate::VideoStopped(key));
1790 }
1791 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
1792 if held != remote_hold {
1793 remote_hold = held;
1794 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1795 }
1796 sent
1797 }
1798 Err(error) => {
1799 if current.peer.signaling_state() == SignalingState::HaveRemoteOffer {
1800 rollback_remote_offer(&current.peer).await;
1801 }
1802 if let Some(url) = &rejection_link {
1803 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1804 }
1805 Err(error)
1806 }
1807 }
1808 }
1809 MediaAction::RejectGlare => {
1810 if let Some(url) = &rejection_link {
1811 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::InProgress).await;
1812 }
1813 Ok(())
1814 }
1815 _ => Ok(()),
1816 };
1817 if let Err(error) = result {
1818 timeline.record("renegotiation failed", error.to_string());
1819 }
1820 }
1821 Ok(CallEvent::RosterUpdate(body)) => {
1822 if roster.apply(&body) {
1823 let entries = roster.entries();
1824 timeline.record("roster", format!("{} participant(s)", entries.len()));
1825 control.send(CallUpdate::Roster(entries));
1826 if is_echo && echo_watch.bot_left(roster.members().iter().map(|member| member.mri.as_str())) {
1827 timeline.record("echo bot left", "test call ends like in Teams");
1828 advance(state, CallSignal::RemoteEnd(EndKind::Normal), control);
1829 break;
1830 }
1831 if callee_gate.is_waiting() && roster_has_callee(roster.members().iter().map(|member| member.mri.as_str()), &own_mri) {
1832 outgoing_deadline = None;
1833 if callee_gate.callee_joined() {
1834 advance(state, CallSignal::MediaConnected, control);
1835 }
1836 }
1837 let own_streams = roster.stream_summaries(&own_mri);
1838 if own_streams != report.own_streams {
1839 timeline.record("own media streams", own_streams.join("; "));
1840 report.own_streams = own_streams;
1841 }
1842 send_receive_change(control, video.reselect(&roster));
1843 if let Some(replacement) = roster.transfer_replacement(&own_mri)
1844 && sent_replacement.as_ref() != Some(&replacement)
1845 {
1846 sent_replacement = Some(replacement.clone());
1847 control.send(CallUpdate::ReplacementLink(replacement));
1848 }
1849 if let Some(in_lobby) = roster.is_in_lobby(&own_mri)
1850 && in_lobby != lobby
1851 {
1852 lobby = in_lobby;
1853 control.send(CallUpdate::Lobby(lobby));
1854 }
1855 if roster.caption_bot().is_some() {
1856 bot_pending = false;
1857 }
1858 let audio_only = roster.caption_bot().is_some_and(|bot| bot.recording && bot.audio_only);
1859 if audio_only != recording_audio_only {
1860 recording_audio_only = audio_only;
1861 control.send(CallUpdate::RecordingAudioOnly(audio_only));
1862 }
1863 if caption_flow.wanted() {
1864 run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), &RecordingPlan::default(), &mut bot_pending, control, timeline).await;
1865 if caption_flow.on() {
1866 caption_deadline = None;
1867 }
1868 }
1869 if recording_flow.wanted() {
1870 run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await;
1871 }
1872 }
1873 }
1874 Ok(CallEvent::AddParticipantFailure(body)) => {
1875 let bot_add = bot_pending;
1876 bot_pending = false;
1877 if !bot_add && callee_gate.callees_failed(failed_participant_count(&body)) {
1878 let end = embedded_end(&body);
1879 let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind);
1880 report.end = end;
1881 advance(state, CallSignal::RemoteEnd(kind), control);
1882 break;
1883 }
1884 if recording_flow.wanted() && roster.caption_bot().is_none() {
1885 timeline.record("recorder bot failed", "addParticipantFailure");
1886 recording_flow.failed();
1887 recording_deadline = None;
1888 control.send(CallUpdate::RecordingPending(false));
1889 control.send(CallUpdate::Notice(RECORDING_JOIN_FAILED_NOTICE.into()));
1890 }
1891 if caption_flow.wanted() && roster.caption_bot().is_none() {
1892 timeline.record("caption bot failed", "addParticipantFailure");
1893 caption_flow.failed();
1894 caption_deadline = None;
1895 control.send(CallUpdate::Captions(CaptionState::Failed(
1896 CAPTIONS_JOIN_FAILED_NOTICE.into(),
1897 )));
1898 }
1899 }
1900 Ok(CallEvent::ConversationUpdate(body)) => {
1901 if let Some(thread) = chat_thread_id(&body)
1902 && meeting_chat.as_ref() != Some(&thread)
1903 {
1904 control.send(CallUpdate::MeetingChat(thread.clone()));
1905 meeting_chat = Some(thread);
1906 }
1907 if capability.apply(&body) {
1908 control.send(CallUpdate::Capability(capability));
1909 }
1910 let change = recording_status.apply(&body);
1911 if let Some(on) = change.recording {
1912 control.send(CallUpdate::Recording(on));
1913 if on {
1914 recording_deadline = None;
1915 control.send(CallUpdate::RecordingPending(false));
1916 }
1917 }
1918 if let Some(on) = change.transcription {
1919 control.send(CallUpdate::Transcribing(on));
1920 if on {
1921 recording_deadline = None;
1922 control.send(CallUpdate::RecordingPending(false));
1923 }
1924 }
1925 if let Some(required) = change.consent_required {
1926 consent_pending = required;
1927 control.send(CallUpdate::ConsentRequired(required));
1928 if required {
1929 withhold_media(&mut muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, &mut local_video, control);
1930 }
1931 }
1932 if !main_meeting_sent
1933 && let Some(main) = breakout::main_meeting_target(&body)
1934 {
1935 main_meeting_sent = true;
1936 control.send(CallUpdate::BreakoutRoom { main });
1937 }
1938 }
1939 Ok(CallEvent::LocalParticipantUpdate(body)) => {
1940 let moved = room_watcher.apply(breakout::room_assignment(&body)).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1941 if let Some(moved) = moved {
1942 timeline.record("breakout", format!("moved to {}", moved.room_name));
1943 control.send(CallUpdate::BreakoutMove(moved));
1944 }
1945 }
1946 Ok(CallEvent::Replacement(body)) => {
1947 let invited = breakout::invite_move(&body).filter(|moved| !is_own_meeting(meeting_target.as_ref(), &moved.target));
1948 if let Some(moved) = invited {
1949 timeline.record("breakout", format!("invited to {}", moved.room_name));
1950 control.send(CallUpdate::BreakoutMove(moved));
1951 }
1952 }
1953 Ok(CallEvent::ContentShareUpdate(body)) => {
1954 if let Some(share) = whiteboard::content_share(&body).filter(|share| share.whiteboard) {
1955 control.send(CallUpdate::Whiteboard(Some(share)));
1956 }
1957 }
1958 Ok(CallEvent::ContentShareEnd(_)) => {
1959 control.send(CallUpdate::Whiteboard(None));
1960 }
1961 Ok(CallEvent::Transfer(event)) => {
1962 match event {
1963 TransferEvent::Accepted => timeline.record("transfer accepted", "by the target"),
1964 completed if completed.succeeded() => {
1965 timeline.record("transfer", "completed");
1966 control.send(CallUpdate::TransferResult { succeeded: true });
1967 control.send(CallUpdate::Notice(CALL_TRANSFERRED_NOTICE.into()));
1968 advance(state, CallSignal::LocalLeave, control);
1969 break;
1970 }
1971 TransferEvent::Completed { code, sub_code } => {
1972 timeline.record("transfer failed", format!("code {code} subCode {sub_code}"));
1973 control.send(CallUpdate::TransferResult { succeeded: false });
1974 control.send(CallUpdate::Notice(TRANSFER_FAILED_NOTICE.into()));
1975 }
1976 }
1977 }
1978 Ok(CallEvent::Reactions(events)) => {
1979 for event in events {
1980 control.send(CallUpdate::Reaction { mri: event.mri, reaction: event.reaction });
1981 }
1982 }
1983 Ok(CallEvent::Progress(status)) => {
1984 if status == ProgressStatus::Ringing {
1985 control.send(CallUpdate::Progress(Progress::Ringing));
1986 if outgoing_deadline.is_some() {
1987 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1988 }
1989 }
1990 }
1991 Ok(CallEvent::ControlVideoStreaming(body)) => {
1992 let Some(request) = parse_request(&body) else { continue };
1993 let Some(limits) = send_requests.admit(&request) else { continue };
1994 let own_screen = roster.screen_source_of(&own_mri).map(i64::from);
1995 let source = if request.source_id.is_some() && request.source_id == own_screen { SendSource::Screen } else { SendSource::Camera };
1996 match local_video.apply_send_limit(source, &limits) {
1997 Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?}")),
1998 Ok(None) => {}
1999 Err(error) => timeline.record("send limits failed", error.to_string()),
2000 }
2001 }
2002 Ok(CallEvent::Speakers(sources)) => {
2003 let speakers = roster.mris_for_sources(&sources);
2004 if video.note_speakers(&speakers) {
2005 send_receive_change(control, video.reselect(&roster));
2006 }
2007 control.send(CallUpdate::Speakers(speakers));
2008 }
2009 Ok(CallEvent::ConversationEnd(body)) if callee_gate.is_waiting() => {
2010 live.skip_leave = true;
2011 let end = embedded_end(&body);
2012 let kind = end.as_ref().map_or(EndKind::Unavailable, setup_end_kind);
2013 report.end = end;
2014 advance(state, CallSignal::RemoteEnd(kind), control);
2015 break;
2016 }
2017 Ok(CallEvent::Rejection(_))
2018 if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
2019 {
2020 if let Some(resend) = glare_resend.as_mut() {
2021 resend.at = Instant::now();
2022 }
2023 }
2024 Ok(CallEvent::Rejection(_))
2025 if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
2026 && !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) =>
2027 {
2028 timeline.record("rejection ignored", "it names an offer that is no longer pending");
2029 }
2030 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
2031 RejectedOffer::SamePeer => {
2032 same_peer_deadline = None;
2033 same_peer_grace_until = None;
2034 if let Some(pending) = same_peer.take() {
2035 rollback_offer(&current.peer).await;
2036 if is_glare_rejection(&body) {
2037 timeline.record("glare", "our offer met theirs, it goes out again");
2038 glare_resend = Some(GlareResend { change: pending.change, reply_tags: Vec::new(), at: Instant::now() + GLARE_RESEND_LIMIT });
2039 } else {
2040 undo_change(pending.change, &mut local_video, control);
2041 }
2042 }
2043 }
2044 RejectedOffer::NewPeer => {
2045 if let Some(pending) = next.take() {
2046 pending.session.peer.close();
2047 }
2048 if layout == Layout::OneToOne {
2049 drop_local_media(&mut local_video, control);
2050 }
2051 timeline.record("escalation failed", "offer rejected, staying on the old peer connection");
2052 }
2053 RejectedOffer::None => {}
2054 },
2055 Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => {
2056 if let Some(pending) = next.as_mut() {
2057 pending.retargeted = true;
2058 }
2059 }
2060 Ok(CallEvent::RetargetCompletion(body)) => {
2061 if body["retargetCompleted"]["code"].as_i64().is_some() && let Some(pending) = next.take() {
2062 pending.session.peer.close();
2063 negotiator.escalation_failed();
2064 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2065 timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");
2066 }
2067 }
2068 Ok(CallEvent::End(end)) => {
2069 let kind = end.kind();
2070 report.end = Some(end);
2071 advance(state, CallSignal::RemoteEnd(kind), control);
2072 break;
2073 }
2074 Ok(_) => {}
2075 Err(error) => {
2076 timeline.record("callback not understood", error.to_string());
2077 }
2078 }
2079 }
2080 Some(result) = echo_add_rx.recv(), if echo_add_pending => {
2081 echo_add_pending = false;
2082 if let Err(error) = result {
2083 timeline.record("echo bot add failed", error.to_string());
2084 control.send(CallUpdate::Notice(ECHO_TEST_FAILED_NOTICE.into()));
2085 live.cancel_leave = true;
2086 advance(state, CallSignal::RemoteEnd(EndKind::Unavailable), control);
2087 break;
2088 }
2089 }
2090 Some(event) = current.events.recv() => match event {
2091 PeerEvent::Ice(ice_state) => {
2092 timeline.record("ICE state", format!("{ice_state:?}"));
2093 if ice_state == IceConnectionState::Connected && report.ice_connected_ms.is_none() {
2094 report.ice_connected_ms = Some(timeline.elapsed_ms());
2095 }
2096 }
2097 PeerEvent::Connection(connection) => {
2098 timeline.record("PeerConnection state", format!("{connection:?}"));
2099 match connection {
2100 PeerConnectionState::Connected => {
2101 reconnect_deadline = None;
2102 if callee_gate.media_connected() {
2103 advance(state, CallSignal::MediaConnected, control);
2104 }
2105 if report.peer_connected_ms.is_none() {
2106 report.peer_connected_ms = Some(timeline.elapsed_ms());
2107 if let Some(hold) = options.hold_after_connected {
2108 let hold_until = Instant::now() + hold;
2109 leave_at = Some(hard_deadline.map_or(hold_until, |deadline| deadline.min(hold_until)));
2110 }
2111 }
2112 }
2113 PeerConnectionState::Disconnected => {
2114 if advance(state, CallSignal::MediaDisconnected, control) {
2115 reconnect_deadline = Some(Instant::now() + options.reconnect_window);
2116 }
2117 }
2118 PeerConnectionState::Failed => {
2119 advance(state, CallSignal::MediaFailed, control);
2120 break;
2121 }
2122 _ => {}
2123 }
2124 }
2125 PeerEvent::Track(remote_track) => {
2126 timeline.record("remote audio track", "receiving");
2127 let had_far_end = remote_audio.replace(remote_track.clone()).is_some();
2128 if !had_far_end && software_audio.is_some() {
2129 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);
2130 }
2131 if options.record_remote {
2132 tokio::spawn(record_track(remote_track, recording.clone(), options.tone_hz));
2133 }
2134 }
2135 PeerEvent::VideoTrack { mid, track } => {
2136 timeline.record("remote video track", format!("mid {mid}"));
2137 live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));
2138 }
2139 PeerEvent::Data(frame) => {
2140 if let Some(message) = depacketizer.push(&frame)
2141 && message.data_id == CAPTIONS_DATA_ID
2142 {
2143 for entry in parse_caption_message(&message.payload) {
2144 if caption_flow.text_arrived() {
2145 caption_deadline = None;
2146 control.send(CallUpdate::Captions(CaptionState::On));
2147 }
2148 control.send(CallUpdate::Caption(named_caption(entry, &roster)));
2149 }
2150 }
2151 }
2152 },
2153 Some(event) = next_peer_event(&mut next) => match event {
2154 PeerEvent::Connection(PeerConnectionState::Connected) => {
2155 if let Some(pending) = next.as_mut() {
2156 pending.connected = true;
2157 if pending.offered.is_none() && !pending.retargeted {
2158 pending.deadline = Some(Instant::now() + RETARGET_WAIT);
2159 timeline.record("escalation", "new peer connection up, waiting for retargetCompletion");
2160 }
2161 }
2162 }
2163 PeerEvent::VideoTrack { mid, track } => {
2164 timeline.record("remote video track", format!("mid {mid} (new peer)"));
2165 live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));
2166 }
2167 PeerEvent::Connection(PeerConnectionState::Failed) => {
2168 negotiator.escalation_failed();
2169 if let Some(pending) = next.take() {
2170 pending.session.peer.close();
2171 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2172 }
2173 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
2174 }
2175 _ => {}
2176 },
2177 command = control.recv() => match command {
2178 Some(CallCommand::Mute(mute)) => {
2179 if consent_pending && !mute.target(muted) {
2180 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
2181 } else {
2182 muted = apply_mute(mute, muted, live.audio.as_ref().expect("audio set above"), software_audio.as_ref(), &remote, control);
2183 silence_for_hold(local_hold, muted, live.audio.as_ref(), software_audio.as_ref());
2184 }
2185 }
2186 Some(CallCommand::DisableAudio) => {
2187 let audio = live.audio.as_ref().expect("audio set above");
2188 muted = apply_mute(MuteCommand::Mute, muted, audio, software_audio.as_ref(), &remote, control);
2189 audio_disabled = true;
2190 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, None, false, &mut software_audio, control, timeline);
2191 if audio.uses_devices() {
2192 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
2193 factory.set_adm_recording_enabled(false);
2194 factory.set_adm_playout_enabled(false);
2195 }
2196 control.send(CallUpdate::ListenOnly(true));
2197 }
2198 Some(CallCommand::SelectInput(choice)) => {
2199 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2200 timeline.record("input device", format!("{choice:?} applied={}", devices::select_input(&factory, &choice)));
2201 applied_input = devices::applied_device(&device_lists.inputs, &choice, devices::system_default_id(Flow::Capture).as_deref());
2202 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2203 }
2204 input = choice;
2205 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
2206 if software_audio.is_some() {
2207 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);
2208 }
2209 }
2210 Some(CallCommand::SetMicSettings(settings)) if !audio_disabled => {
2211 mic_settings = settings;
2212 crate::noise_stage::apply(mic_settings);
2213 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);
2214 }
2215 Some(CallCommand::SetMicSettings(settings)) => {
2216 mic_settings = settings;
2217 crate::noise_stage::apply(mic_settings);
2218 }
2219 Some(CallCommand::SelectOutput(choice)) => {
2220 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2221 timeline.record("output device", format!("{choice:?} applied={}", devices::select_output(&factory, &choice)));
2222 applied_output = devices::applied_device(&device_lists.outputs, &choice, devices::system_default_id(Flow::Render).as_deref());
2223 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2224 }
2225 output = choice;
2226 control.send(CallUpdate::Selected { input: input.clone(), output: output.clone() });
2227 }
2228 Some(CallCommand::RefreshDevices) => {
2229 device_lists = devices::list_devices(&factory);
2230 control.send(CallUpdate::Devices(device_lists.clone()));
2231 }
2232 Some(CallCommand::SetCamera(false)) if local_video.camera_previewing() => {
2233 start_camera_pending = false;
2234 local_video.stop_camera();
2235 control.send(CallUpdate::Camera(false));
2236 }
2237 Some(CallCommand::SetCamera(on)) => {
2238 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
2239 if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) {
2240 if remote_set && next.is_none() && negotiator.begin_conference_upgrade() {
2241 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;
2242 next = pending.or(next);
2243 }
2244 if remote_set && on && next.is_some() {
2245 start_camera_pending = true;
2246 }
2247 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2248 } else if on && consent_pending {
2249 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
2250 } else if local_hold {
2251 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2252 } else if on && direct && (same_peer.is_some() || glare_resend.is_some()) {
2253 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2254 } else if on {
2255 let started = start_camera_line(&mut local_video, &current.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
2256 match started {
2257 Ok(()) if direct => {
2258 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 {
2259 Ok((browser_offer, signaled, reply_tags)) => {
2260 timeline.record_sdp("local offer", &signaled.sdp);
2261 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
2262 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2263 same_peer_grace_until = None;
2264 }
2265 Err(error) => {
2266 timeline.record("camera offer failed", error.to_string());
2267 undo_change(Change::Camera(true), &mut local_video, control);
2268 }
2269 }
2270 }
2271 Ok(()) => {
2272 control.send(CallUpdate::Camera(true));
2273 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
2274 }
2275 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))),
2276 }
2277 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2278 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2279 } else if direct {
2280 local_video.stop_camera();
2281 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 {
2282 Ok((browser_offer, signaled, reply_tags)) => {
2283 timeline.record_sdp("local offer", &signaled.sdp);
2284 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
2285 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2286 same_peer_grace_until = None;
2287 }
2288 Err(error) => {
2289 timeline.record("camera offer failed", error.to_string());
2290 control.send(CallUpdate::Camera(false));
2291 }
2292 }
2293 } else {
2294 local_video.stop_camera();
2295 control.send(CallUpdate::Camera(false));
2296 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(false), &mut media_description_request, timeline);
2297 }
2298 }
2299 Some(CallCommand::SelectCamera(choice)) => {
2300 camera_choice = choice;
2301 if local_video.camera_previewing()
2302 && let Err(error) = local_video.preview_camera(&camera_choice)
2303 {
2304 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2305 } else if local_video.camera_on()
2306 && let Err(error) = local_video.start_camera(&camera_choice)
2307 {
2308 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2309 }
2310 }
2311 Some(CallCommand::SetVideoQuality(quality)) => {
2312 local_video.set_video_quality(quality);
2313 if let Err(error) = local_video.refresh_camera_capture(&camera_choice) {
2314 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_RESTART_NOTICE, error)));
2315 }
2316 if video.set_video_quality(quality) {
2317 send_receive_change(control, video.reselect(&roster));
2318 }
2319 }
2320 Some(CallCommand::StartPortalShare(kind)) => {
2321 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2322 if !remote_set {
2323 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2324 } else if local_hold {
2325 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2326 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2327 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2328 } else if direct
2329 && !local_video.sharing()
2330 && !local_video.has_share_line()
2331 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2332 {
2333 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2334 } else if !local_video.sharing() && !video_possible(remote_set, layout, negotiator.path()) {
2335 if next.is_none() && negotiator.begin_conference_upgrade() {
2336 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;
2337 next = pending.or(next);
2338 }
2339 if next.is_some() {
2340 portal_pending = Some(kind);
2341 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2342 } else {
2343 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2344 }
2345 } else if let Err(error) = local_video.open_portal(kind, control.command_sender()) {
2346 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2347 }
2348 }
2349 Some(CallCommand::FinishPortalShare { source, generation }) => {
2350 if local_video.accept_portal(generation) {
2351 control.defer(CallCommand::StartShare(source));
2352 }
2353 }
2354 Some(CallCommand::AbandonPortalShare) => {
2355 if local_video.portal_is_open() {
2356 local_video.stop_share();
2357 }
2358 }
2359 Some(CallCommand::StartShare(source)) => {
2360 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2361 if !remote_set {
2362 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2363 } else if local_hold {
2364 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2365 } else if direct && local_video.share_sending() {
2366 match local_video.start_share(&source) {
2367 Ok(()) => announce_share(control, &source),
2368 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2369 }
2370 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
2371 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2372 } else if direct
2373 && !local_video.has_share_line()
2374 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2375 {
2376 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2377 } else if direct {
2378 match local_video.start_share(&source) {
2379 Ok(()) => {
2380 announce_share(control, &source);
2381 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);
2382 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 {
2383 Ok((browser_offer, signaled, reply_tags)) => {
2384 timeline.record_sdp("local offer", &signaled.sdp);
2385 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
2386 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2387 same_peer_grace_until = None;
2388 }
2389 Err(error) => {
2390 timeline.record("share offer failed", error.to_string());
2391 undo_change(Change::Share(true), &mut local_video, control);
2392 }
2393 }
2394 }
2395 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2396 }
2397 } else if !video_possible(remote_set, layout, negotiator.path()) {
2398 if next.is_none() && negotiator.begin_conference_upgrade() {
2399 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;
2400 next = pending.or(next);
2401 }
2402 if next.is_some() {
2403 share_pending = Some(source);
2404 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2405 } else {
2406 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2407 }
2408 } else {
2409 match local_video.start_share(&source) {
2410 Ok(()) => {
2411 announce_share(control, &source);
2412 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
2413 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);
2414 }
2415 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2416 }
2417 }
2418 }
2419 Some(CallCommand::StopShare) => {
2420 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2421 share_pending = None;
2422 portal_pending = None;
2423 if local_video.portal_is_open() {
2424 local_video.stop_share();
2425 } else if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2426 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2427 } else if direct && local_video.sharing() {
2428 local_video.stop_share();
2429 clear_share(control);
2430 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);
2431 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 {
2432 Ok((browser_offer, signaled, reply_tags)) => {
2433 timeline.record_sdp("local offer", &signaled.sdp);
2434 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
2435 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2436 same_peer_grace_until = None;
2437 }
2438 Err(error) => timeline.record("share offer failed", error.to_string()),
2439 }
2440 } else if local_video.sharing() {
2441 local_video.stop_share();
2442 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);
2443 clear_share(control);
2444 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2445 }
2446 }
2447 Some(CallCommand::SetShareSound(on)) => {
2448 share_sound_wanted = on;
2449 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);
2450 }
2451 Some(CallCommand::RefreshShareSources) => refresh_share_sources(control.updates(), options.video, true),
2452 Some(CallCommand::SetHand(true)) => match remote.signaling.raise_hand(&remote.conversation, &remote.participant).await {
2453 Ok(receipt) => {
2454 own_hand = receipt.state_id;
2455 control.send(CallUpdate::OwnHand(Some(receipt.rank)));
2456 }
2457 Err(error) => {
2458 timeline.record("raise hand failed", error.to_string());
2459 control.send(CallUpdate::OwnHand(None));
2460 control.send(CallUpdate::Notice(RAISE_HAND_FAILED_NOTICE.into()));
2461 }
2462 },
2463 Some(CallCommand::SetHand(false)) => {
2464 let state_ids: Vec<String> = roster.hand_of(&own_mri).map(|hand| hand.state_id.clone()).or(own_hand.take()).into_iter().collect();
2465 own_hand = None;
2466 control.send(CallUpdate::OwnHand(None));
2467 if !state_ids.is_empty()
2468 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2469 {
2470 timeline.record("lower hand failed", error.to_string());
2471 control.send(CallUpdate::Notice(LOWER_HAND_FAILED_NOTICE.into()));
2472 }
2473 }
2474 Some(CallCommand::LowerHand { mri }) => {
2475 let state_ids: Vec<String> = roster.hand_of(&mri).map(|hand| hand.state_id.clone()).into_iter().collect();
2476 if !state_ids.is_empty()
2477 && let Err(error) = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await
2478 {
2479 timeline.record("lower hand failed", error.to_string());
2480 control.send(CallUpdate::Notice(LOWER_THAT_HAND_FAILED_NOTICE.into()));
2481 }
2482 }
2483 Some(CallCommand::LowerAllHands) => {
2484 if let Err(error) = remote.signaling.lower_all_hands(&remote.conversation, &remote.participant).await {
2485 timeline.record("lower all hands failed", error.to_string());
2486 control.send(CallUpdate::Notice(LOWER_ALL_HANDS_FAILED_NOTICE.into()));
2487 }
2488 }
2489 Some(CallCommand::Admit { mri }) => {
2490 let result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2491 report_organizer_result(result, "admit", ADMIT_FAILED_NOTICE, control, timeline);
2492 }
2493 Some(CallCommand::AdmitAll) => {
2494 let mut result = Ok(202);
2495 for mri in roster.lobby_mris() {
2496 result = remote.signaling.admit(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2497 if result.is_err() {
2498 break;
2499 }
2500 }
2501 report_organizer_result(result, "admit all", ADMIT_ALL_FAILED_NOTICE, control, timeline);
2502 }
2503 Some(CallCommand::Deny { mri }) => {
2504 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2505 report_organizer_result(result, "deny", DENY_FAILED_NOTICE, control, timeline);
2506 }
2507 Some(CallCommand::RemoveParticipant { mri }) => {
2508 let result = remote.signaling.remove_participant(&remote.conversation, &remote.participant, target_of(&roster, &mri), &links).await;
2509 report_organizer_result(result, "remove participant", REMOVE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2510 }
2511 Some(CallCommand::MuteParticipant { mri }) => {
2512 let result = remote.signaling.mute_participant(&remote.conversation, &remote.participant, &mri).await;
2513 report_organizer_result(result, "mute participant", MUTE_PARTICIPANT_FAILED_NOTICE, control, timeline);
2514 }
2515 Some(CallCommand::MuteAll) => {
2516 let others: Vec<String> = roster
2517 .members()
2518 .iter()
2519 .filter(|member| member.mri != own_mri && !member.in_lobby && !member.mri.starts_with(BOT_PREFIX))
2520 .map(|member| member.mri.clone())
2521 .collect();
2522 let result = remote.signaling.mute_everyone(&remote.conversation, &remote.participant, &others).await;
2523 report_organizer_result(result, "mute all", MUTE_ALL_FAILED_NOTICE, control, timeline);
2524 }
2525 Some(CallCommand::SetLock(locked)) => {
2526 let result = remote.signaling.set_lock(&remote.conversation, &remote.participant, locked).await;
2527 if result.is_ok() {
2528 capability.locked = locked;
2529 control.send(CallUpdate::Capability(capability));
2530 }
2531 report_organizer_result(result, "lock meeting", MEETING_LOCK_FAILED_NOTICE, control, timeline);
2532 }
2533 Some(CallCommand::SetRole { mri, role }) => {
2534 let result = remote.signaling.change_role(&remote.conversation, &remote.participant, &mri, role).await;
2535 report_organizer_result(result, "change role", CHANGE_ROLE_FAILED_NOTICE, control, timeline);
2536 }
2537 Some(CallCommand::SetAttendeeModality { mri, modality, allowed }) => {
2538 let limits = roster.entries().into_iter().find(|entry| entry.mri == mri).map(|entry| entry.limits).unwrap_or_default();
2539 let mut result = Ok(200);
2540 for step in modality_steps(modality, allowed, capability, &limits) {
2541 result = match step {
2542 StateStep::Publish(state_type) => remote.signaling.publish_attendee_state(&remote.conversation, &remote.participant, state_type, &mri).await,
2543 StateStep::Remove(state_id) => remote.signaling.lower_hands(&remote.conversation, &remote.participant, &[state_id]).await.map(|()| 200),
2544 };
2545 if result.is_err() {
2546 break;
2547 }
2548 }
2549 let notice = if modality == Modality::Mic {
2550 MIC_SETTING_FAILED_NOTICE
2551 } else {
2552 CAMERA_SETTING_FAILED_NOTICE
2553 };
2554 report_organizer_result(result, "attendee modality", notice, control, timeline);
2555 }
2556 Some(CallCommand::SetAttendeeRestrictions { mic_off, camera_off }) => {
2557 let result = match &meeting_target {
2558 Some(target) => meeting_options::write(&inner.session, target, &OptionWrite::restrictions(mic_off, camera_off)).await.map(|()| 200),
2559 None => Err(Error::Signaling("no meeting coordinates for the options".into())),
2560 };
2561 if result.is_ok() {
2562 capability.attendee_mic_off = mic_off;
2563 capability.attendee_camera_off = camera_off;
2564 control.send(CallUpdate::Capability(capability));
2565 }
2566 report_organizer_result(result, "attendee restrictions", ATTENDEE_SETTINGS_FAILED_NOTICE, control, timeline);
2567 }
2568 Some(CallCommand::Invite { callees, group_thread }) => {
2569 let thread = group_thread.or_else(|| meeting_chat.clone());
2570 let result = remote.signaling.add_participants(&remote.conversation, &remote.participant, &callees, thread.as_deref(), meeting_target.as_ref(), &links).await;
2571 report_organizer_result(result, "invite", INVITE_PERSON_FAILED_NOTICE, control, timeline);
2572 }
2573 Some(CallCommand::LoadMeetingOptions) => {
2574 let update = match &meeting_target {
2575 Some(target) => meeting_options::fetch(&inner.session, target).await.map_err(|error| error.to_string()),
2576 None => Err("This meeting has no options page".to_owned()),
2577 };
2578 control.send(CallUpdate::MeetingOptions(update));
2579 }
2580 Some(CallCommand::SaveMeetingOptions(writes)) => {
2581 let update = match &meeting_target {
2582 Some(target) => save_meeting_options(&inner.session, target, &writes).await,
2583 None => Err("This meeting has no options page".to_owned()),
2584 };
2585 if let Ok(options) = &update {
2586 let (mic_off, camera_off) = options.attendees_off();
2587 capability.attendee_mic_off = mic_off;
2588 capability.attendee_camera_off = camera_off;
2589 control.send(CallUpdate::Capability(capability));
2590 }
2591 control.send(CallUpdate::MeetingOptionsSaved(update));
2592 }
2593 Some(CallCommand::Spotlight { mri }) => {
2594 let result = remote.signaling.spotlight(&remote.conversation, &remote.participant, &mri).await;
2595 report_organizer_result(result, "spotlight", SPOTLIGHT_FAILED_NOTICE, control, timeline);
2596 }
2597 Some(CallCommand::StopSpotlight { mri }) => {
2598 let state_ids: Vec<String> = roster.spotlight_of(&mri).map(|spotlight| spotlight.state_id.clone()).into_iter().collect();
2599 if !state_ids.is_empty() {
2600 let result = remote.signaling.lower_hands(&remote.conversation, &remote.participant, &state_ids).await.map(|()| 200);
2601 report_organizer_result(result, "stop spotlight", STOP_SPOTLIGHT_FAILED_NOTICE, control, timeline);
2602 }
2603 }
2604 Some(CallCommand::SetCaptions(on)) => {
2605 caption_flow.want(on);
2606 if on {
2607 caption_deadline = Some(Instant::now() + CAPTION_START_LIMIT);
2608 control.send(CallUpdate::Captions(CaptionState::Starting));
2609 } else {
2610 caption_deadline = None;
2611 control.send(CallUpdate::Captions(CaptionState::Off));
2612 }
2613 run_bot_steps(BotJob::Captions, &mut caption_flow, &roster, &remote, &links, meeting_chat.as_deref(), &RecordingPlan::default(), &mut bot_pending, control, timeline).await;
2614 if caption_flow.on() {
2615 caption_deadline = None;
2616 }
2617 }
2618 Some(CallCommand::StartRecording { kind, title }) => {
2619 if !is_echo {
2620 recording_plan = RecordingPlan { title, kind, ..RecordingPlan::default() };
2621 recording_flow.want(true);
2622 recording_deadline = Some(Instant::now() + RECORDING_START_LIMIT);
2623 control.send(CallUpdate::RecordingPending(true));
2624 run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await;
2625 }
2626 }
2627 Some(CallCommand::StopRecording { scope }) => {
2628 if !is_echo {
2629 recording_plan.scope = scope;
2630 recording_flow.stop();
2631 recording_deadline = None;
2632 run_bot_steps(BotJob::Recording, &mut recording_flow, &roster, &remote, &links, meeting_chat.as_deref(), &recording_plan, &mut bot_pending, control, timeline).await;
2633 }
2634 }
2635 Some(CallCommand::SetCaptionLanguage(language)) => {
2636 if let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone())
2637 && let Err(error) = remote.signaling.caption_language_command(&url, &remote.participant, &language).await
2638 {
2639 timeline.record("caption language failed", error.to_string());
2640 control.send(CallUpdate::Notice(CAPTION_LANGUAGE_FAILED_NOTICE.into()));
2641 }
2642 }
2643 Some(CallCommand::ConsentToRecording) => {
2644 match remote.signaling.consent_to_recording(&remote.conversation, &remote.participant, Consent::Give).await {
2645 Ok(_) => {
2646 consent_pending = false;
2647 control.send(CallUpdate::ConsentRequired(false));
2648 }
2649 Err(error) => {
2650 timeline.record("recording consent failed", error.to_string());
2651 control.send(CallUpdate::Notice(CONFIRM_RECORDING_FAILED_NOTICE.into()));
2652 }
2653 }
2654 }
2655 Some(CallCommand::Hold(hold)) => {
2656 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || glare_resend.is_some() || next.is_some() {
2657 continue;
2658 }
2659 if hold && local_video.camera_on() {
2660 local_video.stop_camera();
2661 control.send(CallUpdate::Camera(false));
2662 }
2663 let camera = !hold && local_video.camera_on();
2664 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 {
2665 Ok((browser_offer, signaled, reply_tags)) => {
2666 timeline.record_sdp("local offer", &signaled.sdp);
2667 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2668 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2669 same_peer_grace_until = None;
2670 }
2671 Err(error) => {
2672 timeline.record("hold failed", error.to_string());
2673 control.send(CallUpdate::Notice(if hold {
2674 HOLD_FAILED_NOTICE.into()
2675 } else {
2676 RESUME_FAILED_NOTICE.into()
2677 }));
2678 }
2679 }
2680 }
2681 Some(CallCommand::Transfer { target, replaces }) => {
2682 let Some(url) = media_links.get("transfer").cloned() else {
2683 control.send(CallUpdate::TransferResult { succeeded: false });
2684 control.send(CallUpdate::Notice(TRANSFER_NOT_ALLOWED_NOTICE.into()));
2685 continue;
2686 };
2687 let transfer_target = TransferTarget { mri: &target.mri, replaces: replaces.as_ref() };
2688 match remote.signaling.transfer(&url, &remote.participant, transfer_target, &links).await {
2689 Ok(()) => control.send(CallUpdate::Notice(notice_with_detail(
2690 TRANSFERRING_NOTICE,
2691 target.display_name,
2692 ))),
2693 Err(error) => {
2694 timeline.record("transfer failed", error.to_string());
2695 control.send(CallUpdate::TransferResult { succeeded: false });
2696 control.send(CallUpdate::Notice(TRANSFER_CALL_FAILED_NOTICE.into()));
2697 }
2698 }
2699 }
2700 Some(CallCommand::OpenWhiteboard { title }) => {
2701 let Some(target) = meeting_target.clone() else {
2702 control.send(CallUpdate::Notice(WHITEBOARDS_MEETINGS_ONLY_NOTICE.into()));
2703 continue;
2704 };
2705 let session = inner.session.clone();
2706 let updates = control.updates();
2707 tokio::spawn(async move {
2708 let update = match whiteboard::fetch_board(&session, &target, &title).await {
2709 Ok(url) => CallUpdate::WhiteboardUrl(url),
2710 Err(_) => CallUpdate::Notice(WHITEBOARD_OPEN_FAILED_NOTICE.into()),
2711 };
2712 let _ = updates.send(update);
2713 });
2714 }
2715 Some(CallCommand::SetBackground(choice)) => apply_background(choice, &local_video, control, timeline).await,
2716 Some(CallCommand::SetIncomingVideo(enabled)) => {
2717 video.set_incoming_enabled(enabled);
2718 if let (Some(mid), Some(mri)) = (&direct_video_mid, &peer_mri) {
2719 let key = VideoKey::Person(mri.clone());
2720 control.video.forget(&key);
2721 video.router().set(mid, enabled.then_some(key));
2722 }
2723 send_receive_change(control, video.reselect(&roster));
2724 control.send(CallUpdate::IncomingVideo(enabled));
2725 }
2726 Some(CallCommand::SetVideoWants(wants)) => {
2727 if video.set_wants(wants) {
2728 send_receive_change(control, video.reselect(&roster));
2729 }
2730 }
2731 Some(CallCommand::SetShareMotion(on)) => local_video.set_motion(on),
2732 Some(CallCommand::SetShareStandout(on)) => local_video.set_standout(on),
2733 Some(CallCommand::SetCameraEffects(effects)) => local_video.set_effects(effects),
2734 Some(CallCommand::SendReaction(reaction)) => {
2735 if let Err(error) = remote.signaling.send_reaction(&remote.conversation, &remote.participant, reaction).await {
2736 timeline.record("reaction failed", error.to_string());
2737 control.send(CallUpdate::Notice(REACTION_FAILED_NOTICE.into()));
2738 }
2739 }
2740 Some(CallCommand::EndMeeting) => {
2741 if is_meeting {
2742 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
2743 Ok(()) => {
2744 live.skip_leave = true;
2745 report.left_cleanly = true;
2746 }
2747 Err(error) => timeline.record("end meeting failed", error.to_string()),
2748 }
2749 }
2750 advance(state, CallSignal::LocalLeave, control);
2751 break;
2752 }
2753 Some(CallCommand::Hangup) | None => {
2754 advance(state, CallSignal::LocalLeave, control);
2755 break;
2756 }
2757 },
2758 _ = stats_tick.tick(), if remote_set => {
2759 let speaking = active_speakers::speaking_sources(&active_speakers::audio_sources(&current.peer));
2760 if speaking != speaking_sources {
2761 if speaking_sources.is_empty() && !speaker_sources_seen {
2762 speaker_sources_seen = true;
2763 timeline.record("active speakers", format!("{} source(s) from RTP", speaking.len()));
2764 }
2765 speaking_sources = speaking;
2766 let mut speakers = roster.mris_for_sources(&speaking_sources);
2767 if speakers.is_empty() && !speaking_sources.is_empty() && layout == Layout::OneToOne {
2768 speakers = roster.entries().into_iter().map(|entry| entry.mri).filter(|mri| *mri != own_mri).collect();
2769 }
2770 if video.note_speakers(&speakers) {
2771 send_receive_change(control, video.reselect(&roster));
2772 }
2773 control.send(CallUpdate::Speakers(speakers));
2774 }
2775 let snapshot = collect_stats(&current.peer, &layout_plan.screen_share_mids).await;
2776 ticks += 1;
2777 if caption_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
2778 caption_deadline = None;
2779 caption_flow.failed();
2780 timeline.record("captions", "did not start in time");
2781 control.send(CallUpdate::Captions(CaptionState::Failed("Captions did not start".into())));
2782 }
2783 if recording_deadline.is_some_and(|deadline| Instant::now() >= deadline) {
2784 recording_deadline = None;
2785 recording_flow.failed();
2786 timeline.record("recording", "did not start in time");
2787 control.send(CallUpdate::RecordingPending(false));
2788 control.send(CallUpdate::Notice(RECORDING_NOT_STARTED_NOTICE.into()));
2789 }
2790 if layout == Layout::Conference
2791 && let Some(size) = local_video.camera_size()
2792 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2793 && let Some(body) =
2794 send_capabilities.body_for(size, local_video.video_quality())
2795 {
2796 let signaling = signaling.clone();
2797 let timeline = timeline.clone();
2798 tokio::spawn(async move {
2799 match signaling.post_json(SEND_CAPABILITIES_LABEL, &url, body).await {
2800 Ok(()) => timeline.record("send capabilities", format!("{}x{} accepted", size.0, size.1)),
2801 Err(error) => timeline.record("send capabilities failed", error.to_string()),
2802 }
2803 });
2804 }
2805 for (source, refreshed) in local_video.refresh_send_limits() {
2806 match refreshed {
2807 Ok(Some(plans)) => timeline.record("send limits", format!("{source:?} {plans:?} after a frame size change")),
2808 Ok(None) => {}
2809 Err(error) => timeline.record("send limits failed", error.to_string()),
2810 }
2811 }
2812 if ticks.is_multiple_of(BLUR_TIMING_EVERY_TICKS)
2813 && let Some(average_ms) = local_video.blur_average_ms()
2814 {
2815 control.send(CallUpdate::BlurTiming(average_ms));
2816 if let Some(model) = local_video.blur_model().filter(|model| Some(*model) != segmentation_model) {
2817 timeline.record("segmentation model", format!("{model}, effects {average_ms:.1} ms per frame"));
2818 segmentation_model = Some(model);
2819 }
2820 }
2821 if ticks.is_multiple_of(HEALTH_EVERY_TICKS) {
2822 control.send(CallUpdate::Sample(StatsSample {
2823 audio_in_packets: snapshot.inbound_packets,
2824 audio_out_packets: snapshot.outbound_packets,
2825 audio_in_level: snapshot.audio_level,
2826 audio_out_level: snapshot.local_level,
2827 video: VideoReport {
2828 frames_received: live.video_counters.received.load(Ordering::Relaxed),
2829 frames_published: live.video_counters.published.load(Ordering::Relaxed),
2830 ..snapshot.video.clone()
2831 },
2832 share_in_packets: snapshot.share_inbound_packets,
2833 share_out_packets: snapshot.share_outbound_packets,
2834 }));
2835 }
2836 if ticks.is_multiple_of(HEALTH_EVERY_TICKS)
2837 && snapshot.selected_pair.is_some()
2838 && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)
2839 {
2840 let quality = quality_tracker.observe(std::time::Instant::now(), &sample);
2841 control.send(CallUpdate::Health(CallHealth {
2842 level: quality.level,
2843 cpu_limited: quality.cpu_limited,
2844 sample,
2845 transport: snapshot.transport.clone(),
2846 path: negotiator.path(),
2847 }));
2848 }
2849 let local_level = if muted && software_audio.is_none() { 0.0 } else { snapshot.local_level as f32 };
2850 control.send(CallUpdate::Levels { local: local_level, remote: snapshot.audio_level as f32 });
2851 if snapshot.selected_pair.is_some() {
2852 report.selected_pair = snapshot.selected_pair.clone();
2853 report.tls_version = snapshot.tls_version.clone();
2854 report.dtls_cipher = snapshot.dtls_cipher.clone();
2855 report.srtp_cipher = snapshot.srtp_cipher.clone();
2856 }
2857 report.inbound_packets = snapshot.inbound_packets;
2858 report.inbound_bytes = snapshot.inbound_bytes;
2859 report.outbound_packets = snapshot.outbound_packets;
2860 report.video = VideoReport {
2861 frames_received: live.video_counters.received.load(Ordering::Relaxed),
2862 frames_published: live.video_counters.published.load(Ordering::Relaxed),
2863 ..snapshot.video.clone()
2864 };
2865 if ticks.is_multiple_of(TICKS_PER_SECOND) {
2866 second += 1;
2867 let (decoded_rms, ratio) = {
2868 let recording = recording.lock().await;
2869 recording.per_second.last().copied().unwrap_or_default()
2870 };
2871 if snapshot.inbound_packets > previous_packets {
2872 report.seconds_with_inbound_audio += 1;
2873 }
2874 previous_packets = snapshot.inbound_packets;
2875 report.seconds.push(AudioSecond {
2876 second,
2877 packets: snapshot.inbound_packets,
2878 bytes: snapshot.inbound_bytes,
2879 audio_level: snapshot.audio_level,
2880 decoded_rms,
2881 tone_ratio: ratio,
2882 });
2883 control.send(CallUpdate::Stats {
2884 inbound_packets: snapshot.inbound_packets,
2885 outbound_packets: snapshot.outbound_packets,
2886 });
2887 timeline.record(
2888 "stats",
2889 format!(
2890 "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={:?}{}{}",
2891 snapshot.inbound_packets, snapshot.inbound_bytes, snapshot.audio_level, snapshot.outbound_packets, snapshot.local_level, snapshot.echo_return_loss_enhancement, snapshot.dtls_state,
2892 snapshot.video.inbound_packets, snapshot.video.inbound_frames_decoded, snapshot.video.inbound_width, snapshot.video.inbound_height,
2893 snapshot.video.outbound_packets, snapshot.video.outbound_frames_encoded, snapshot.video.outbound_width, snapshot.video.outbound_height,
2894 snapshot.video.remote_reports, snapshot.video.remote_round_trip_ms, snapshot.outbound_bytes, snapshot.source_levels, snapshot.video_senders,
2895 snapshot.share_receive.as_ref().filter(|_| snapshot.share_inbound_packets > 0).map(ShareReceive::summary).unwrap_or_default(),
2896 local_video.camera_capture_summary().unwrap_or_default()
2897 ),
2898 );
2899 }
2900 }
2901 Some(()) = device_changes.recv() => {
2902 device_debounce.signal(Instant::now());
2903 }
2904 _ = sleep_until(device_debounce.deadline().unwrap_or_else(far_future)), if device_debounce.deadline().is_some() => {
2905 if device_debounce.take_due(Instant::now()) {
2906 let previous = std::mem::replace(&mut device_lists, devices::list_devices(&factory));
2907 control.send(CallUpdate::Devices(device_lists.clone()));
2908 if live.audio.as_ref().is_some_and(AudioSetup::uses_devices) {
2909 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);
2910 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);
2911 if input_changed || output_changed {
2912 record_audio_devices(timeline, &device_lists, applied_input.as_ref(), applied_output.as_ref());
2913 }
2914 if input_changed && software_audio.is_some() {
2915 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);
2916 }
2917 }
2918 }
2919 }
2920 _ = sleep_until(reconnect_deadline.unwrap_or_else(far_future)), if reconnect_deadline.is_some() => {
2921 advance(state, CallSignal::ReconnectTimedOut, control);
2922 break;
2923 }
2924 _ = sleep_until(leave_at.unwrap_or_else(far_future)), if leave_at.is_some() => {
2925 advance(state, CallSignal::LocalLeave, control);
2926 break;
2927 }
2928 _ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {
2929 if let Some(pending) = next.as_mut().filter(|pending| pending.connected && pending.offered.is_none()) {
2930 pending.retargeted = true;
2931 timeline.record("escalation", "no retargetCompletion, switching anyway");
2932 } else if let Some(pending) = next.take() {
2933 pending.session.peer.close();
2934 negotiator.escalation_failed();
2935 start_camera_pending = false;
2936 if local_video.camera_previewing() {
2937 local_video.stop_camera();
2938 control.send(CallUpdate::Camera(false));
2939 }
2940 share_pending = None;
2941 portal_pending = None;
2942 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2943 timeline.record("escalation failed", "no answer for the new peer connection in time");
2944 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2945 }
2946 }
2947 _ = sleep_until(glare_at.unwrap_or_else(far_future)), if glare_at.is_some() => {
2948 let resend = glare_resend.take();
2949 if let Some(resend) = resend.as_ref().filter(|_| same_peer.is_some() || next.is_some()) {
2950 timeline.record("glare", "another change took over, ours is dropped");
2951 undo_change(resend.change, &mut local_video, control);
2952 } else if let Some(resend) = resend.as_ref().filter(|resend| layout == Layout::OneToOne && negotiator.path() == MediaPath::Mixer && !matches!(resend.change, Change::Hold(_))) {
2953 if negotiator.begin_conference_upgrade() {
2954 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;
2955 if pending.is_none() {
2956 drop_local_media(&mut local_video, control);
2957 }
2958 next = pending.or(next);
2959 } else {
2960 undo_change(resend.change, &mut local_video, control);
2961 }
2962 } else if let Some(resend) = resend {
2963 let (hold, camera, share) = match resend.change {
2964 Change::Hold(hold) => (hold, !hold && local_video.camera_on(), local_video.sharing()),
2965 _ => (local_hold, local_video.camera_on(), local_video.sharing()),
2966 };
2967 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 {
2968 Ok((browser_offer, signaled, reply_tags)) => {
2969 timeline.record_sdp("local offer", &signaled.sdp);
2970 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2971 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2972 same_peer_grace_until = None;
2973 }
2974 Err(error) => {
2975 timeline.record("offer after glare failed", error.to_string());
2976 undo_change(resend.change, &mut local_video, control);
2977 }
2978 }
2979 }
2980 }
2981 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2982 same_peer_deadline = None;
2983 if same_peer.is_some() {
2984 same_peer_grace_until = Some(Instant::now() + SAME_PEER_LATE_GRACE);
2985 timeline.record(
2986 "same-peer offer",
2987 "no answer yet, waiting a little longer",
2988 );
2989 }
2990 }
2991 _ = sleep_until(same_peer_grace_until.unwrap_or_else(far_future)), if same_peer_grace_until.is_some() => {
2992 same_peer_grace_until = None;
2993 if let Some(pending) = same_peer.take() {
2994 timeline.record("same-peer offer", "no answer in time");
2995 negotiator.same_peer_offer_failed();
2996 rollback_offer(&current.peer).await;
2997 undo_change(pending.change, &mut local_video, control);
2998 }
2999 }
3000 _ = sleep_until(outgoing_deadline.unwrap_or_else(far_future)), if outgoing_deadline.is_some() => {
3001 timeline.record("no answer", "outgoing call timed out");
3002 live.cancel_leave = true;
3003 advance(state, CallSignal::RemoteEnd(EndKind::NoAnswer), control);
3004 break;
3005 }
3006 _ = sleep_until(keep_alive_at.unwrap_or_else(far_future)), if keep_alive_at.is_some() => {
3007 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
3008 let remote = remote.clone();
3009 let links = links.clone();
3010 let call_leg = keep_alive_link.clone();
3011 tokio::spawn(async move {
3012 if let Some(url) = call_leg {
3013 let _ = remote.signaling.keep_call_alive(&url).await;
3014 }
3015 let _ = remote.signaling.keep_conversation_alive(&remote.conversation, &remote.participant, &links).await;
3016 });
3017 }
3018 }
3019 }
3020 if software_audio.is_some() {
3021 timeline.record("software audio", "stopping before tear down");
3022 drop(software_audio);
3023 }
3024 live.callbacks = Some(callbacks);
3025 Ok(())
3026}
3027
3028#[allow(clippy::too_many_arguments)]
3029async fn start_escalation(
3030 factory: &PeerConnectionFactory,
3031 grant: &RelayGrant,
3032 options: &CallOptions,
3033 track: &RtcAudioTrack,
3034 remote: &RemoteCall,
3035 links: &CallbackLinks,
3036 media_leg_id: &str,
3037 acceptance_links: &BTreeMap<String, String>,
3038) -> Result<NextPeer> {
3039 let url = acceptance_links
3040 .get("mediaRenegotiation")
3041 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
3042 let session = open_peer(factory, grant, &options.relay_host, false)?;
3043 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
3044 let body = renegotiation_body(
3045 &remote.participant,
3046 links,
3047 &media.signaled.sdp,
3048 media_leg_id,
3049 &media.modalities,
3050 true,
3051 false,
3052 );
3053 let reply_tags = offer_reply_tags(&body);
3054 remote
3055 .signaling
3056 .post_json("POST mediaRenegotiation", url, body)
3057 .await?;
3058 Ok(NextPeer {
3059 session,
3060 offered: Some(media),
3061 reply_tags,
3062 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
3063 connected: false,
3064 retargeted: false,
3065 })
3066}
3067
3068#[allow(clippy::too_many_arguments)]
3069async fn escalate(
3070 factory: &PeerConnectionFactory,
3071 grant: &RelayGrant,
3072 options: &CallOptions,
3073 track: &RtcAudioTrack,
3074 remote: &RemoteCall,
3075 links: &CallbackLinks,
3076 media_leg_id: &str,
3077 acceptance_links: &BTreeMap<String, String>,
3078 negotiator: &mut MediaNegotiator,
3079 live: &mut Live,
3080 timeline: &Timeline,
3081) -> Option<NextPeer> {
3082 match start_escalation(
3083 factory,
3084 grant,
3085 options,
3086 track,
3087 remote,
3088 links,
3089 media_leg_id,
3090 acceptance_links,
3091 )
3092 .await
3093 {
3094 Ok(pending) => {
3095 timeline.record("escalation", "new peer connection, new offer sent");
3096 if let Some(media) = &pending.offered {
3097 timeline.record_sdp("local offer", &media.signaled.sdp);
3098 }
3099 live.peers.push(pending.session.peer.clone());
3100 Some(pending)
3101 }
3102 Err(error) => {
3103 negotiator.escalation_failed();
3104 timeline.record("escalation failed", error.to_string());
3105 None
3106 }
3107 }
3108}
3109
3110async fn answer_on_new_peer(
3111 factory: &PeerConnectionFactory,
3112 grant: &RelayGrant,
3113 options: &CallOptions,
3114 track: &RtcAudioTrack,
3115 teams_offer: &str,
3116) -> Result<(PeerSession, AnsweredMedia)> {
3117 let session = open_peer(factory, grant, &options.relay_host, false)?;
3118 let answered = answer_offer(
3119 &session.peer,
3120 Some(track),
3121 teams_offer,
3122 AnswerVideo::Reject,
3123 None,
3124 false,
3125 None,
3126 )
3127 .await?;
3128 Ok((session, answered))
3129}
3130
3131async fn send_media_answer(
3132 remote: &RemoteCall,
3133 links: &CallbackLinks,
3134 reply_links: &BTreeMap<String, String>,
3135 answered: &AnsweredMedia,
3136 media_leg_id: &str,
3137) -> Result<()> {
3138 let url = reply_links
3139 .get("mediaAnswer")
3140 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
3141 let body = escalation_answer_body(
3142 &remote.participant,
3143 links,
3144 &answered.answer_sdp,
3145 media_leg_id,
3146 );
3147 remote
3148 .signaling
3149 .post_json("POST mediaAnswer", url, body)
3150 .await
3151}
3152
3153#[allow(clippy::too_many_arguments)]
3154fn negotiate_video(
3155 video: &mut VideoReceive,
3156 signaling: &Arc<Signaling>,
3157 control: &CallControl,
3158 timeline: &Timeline,
3159 answer_sdp: &str,
3160 media: &OfferedMedia,
3161 from_mixer: bool,
3162 links: &BTreeMap<String, String>,
3163 roster: &Roster,
3164) {
3165 let streams = match stream_lines(answer_sdp, &media.signaled.lines) {
3166 Ok(streams) => streams,
3167 Err(error) => {
3168 timeline.record("video slots unknown", error.to_string());
3169 return;
3170 }
3171 };
3172 let table = SlotTable::from_streams(&streams);
3173 let link = links
3174 .get("applyChannelParameters")
3175 .or_else(|| links.get("controlVideoStreaming"));
3176 timeline.record(
3177 "video slots",
3178 format!(
3179 "{} receive slot(s), screen {}, fromMixer={from_mixer}, request link {}",
3180 table.people.len(),
3181 table.screen.is_some(),
3182 link.is_some()
3183 ),
3184 );
3185 let requester = link.filter(|_| from_mixer).map(|url| {
3186 SourceRequester::start(
3187 signaling.clone(),
3188 url.clone(),
3189 video.router().clone(),
3190 control.video.clone(),
3191 timeline.clone(),
3192 )
3193 });
3194 video.negotiated(table, requester);
3195 send_receive_change(control, video.reselect(roster));
3196}
3197
3198async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3199 match mode {
3200 VideoMode::Pattern => vec![CameraDevice {
3201 key: "pattern".into(),
3202 name: "Test pattern".into(),
3203 }],
3204 VideoMode::Off => Vec::new(),
3205 VideoMode::Platform => tokio::task::spawn_blocking(list_cameras)
3206 .await
3207 .unwrap_or_default(),
3208 }
3209}
3210
3211fn refresh_cameras(
3212 updates: mpsc::UnboundedSender<CallUpdate>,
3213 mode: VideoMode,
3214 timeline: Timeline,
3215) {
3216 tokio::spawn(async move {
3217 let started = Instant::now();
3218 let cameras = camera_devices(mode).await;
3219 timeline.record(
3220 "camera list",
3221 format!(
3222 "{} camera(s) in {} ms",
3223 cameras.len(),
3224 started.elapsed().as_millis()
3225 ),
3226 );
3227 let _ = updates.send(CallUpdate::Cameras(cameras));
3228 });
3229}
3230
3231const SHARE_THUMBNAIL_WINDOWS: usize = 12;
3232const SHARE_THUMBNAIL_WIDTH: u32 = 320;
3233const SHARE_THUMBNAIL_HEIGHT: u32 = 180;
3234
3235fn announce_share(control: &CallControl, source: &ShareSource) {
3236 control.send(CallUpdate::ShareKind(Some(source.kind)));
3237 control.send(CallUpdate::LocalShare(Some(source.label())));
3238}
3239
3240fn clear_share(control: &CallControl) {
3241 control.send(CallUpdate::ShareKind(None));
3242 control.send(CallUpdate::LocalShare(None));
3243}
3244
3245fn refresh_share_sources(
3246 updates: mpsc::UnboundedSender<CallUpdate>,
3247 mode: VideoMode,
3248 with_thumbnails: bool,
3249) {
3250 tokio::spawn(async move {
3251 let picker = current_share_picker();
3252 let sources = match mode {
3253 VideoMode::Pattern => vec![
3254 ShareSource {
3255 id: 1,
3256 kind: ShareKind::Screen,
3257 title: "Test screen".into(),
3258 },
3259 ShareSource {
3260 id: 2,
3261 kind: ShareKind::Window,
3262 title: "Test window".into(),
3263 },
3264 ],
3265 VideoMode::Off => Vec::new(),
3266 VideoMode::Platform if picker == SharePicker::Portal => Vec::new(),
3267 VideoMode::Platform => tokio::task::spawn_blocking(list_share_sources)
3268 .await
3269 .unwrap_or_default(),
3270 };
3271 let sources = share_sources_for_menu(picker, sources);
3272 let _ = updates.send(CallUpdate::ShareSources(sources.clone()));
3273 if picker == SharePicker::Portal || !with_thumbnails {
3274 return;
3275 }
3276 let wanted: Vec<ShareSource> = sources
3277 .iter()
3278 .filter(|source| source.kind == ShareKind::Screen)
3279 .chain(
3280 sources
3281 .iter()
3282 .filter(|source| source.kind == ShareKind::Window)
3283 .take(SHARE_THUMBNAIL_WINDOWS),
3284 )
3285 .cloned()
3286 .collect();
3287 for source in wanted {
3288 let picture = match mode {
3289 VideoMode::Platform => {
3290 let wanted = source.clone();
3291 tokio::task::spawn_blocking(move || {
3292 share_thumbnail(&wanted, SHARE_THUMBNAIL_WIDTH, SHARE_THUMBNAIL_HEIGHT)
3293 })
3294 .await
3295 .ok()
3296 .flatten()
3297 }
3298 VideoMode::Pattern => Some(VideoPicture::solid(
3299 SHARE_THUMBNAIL_WIDTH,
3300 SHARE_THUMBNAIL_HEIGHT,
3301 120,
3302 80,
3303 40,
3304 )),
3305 VideoMode::Off => None,
3306 };
3307 if let Some(picture) = picture
3308 && updates
3309 .send(CallUpdate::ShareThumbnail {
3310 source,
3311 picture: Arc::new(picture),
3312 })
3313 .is_err()
3314 {
3315 return;
3316 }
3317 }
3318 });
3319}
3320
3321fn tell_media_descriptions(
3322 remote: &RemoteCall,
3323 links: &BTreeMap<String, String>,
3324 description: MediaDescription,
3325 request_id: &mut u32,
3326 timeline: &Timeline,
3327) {
3328 let Some(url) = links.get("updateMediaDescriptions").cloned() else {
3329 timeline.record("updateMediaDescriptions skipped", "no link from the mixer");
3330 return;
3331 };
3332 *request_id += 1;
3333 let request_id = *request_id;
3334 let signaling = remote.signaling.clone();
3335 let timeline = timeline.clone();
3336 tokio::spawn(async move {
3337 let sent = format!(
3338 "{} {} request {request_id}",
3339 description.mid, description.direction
3340 );
3341 if let Err(error) = signaling
3342 .update_media_descriptions(&url, &[description], request_id)
3343 .await
3344 {
3345 timeline.record("updateMediaDescriptions failed", format!("{sent}: {error}"));
3346 }
3347 });
3348}
3349
3350fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
3351 own.is_some_and(|own| own.thread_id == target.thread_id)
3352}
3353
3354fn attach_share_line(
3355 peer: &PeerConnection,
3356 factory: &PeerConnectionFactory,
3357 local_video: &mut LocalVideo,
3358 camera_mid: Option<&str>,
3359) -> Result<()> {
3360 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
3361 if !local_video.has_lines() && camera.is_none() {
3362 return Err(Error::Webrtc("no video line negotiated".into()));
3363 }
3364 let share = add_share_line(peer, factory)?;
3365 local_video
3366 .add_share_line(share.clone(), camera)
3367 .inspect_err(|_| {
3368 let _ = share.stop();
3369 })
3370}
3371
3372fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
3373 peer.transceivers()
3374 .into_iter()
3375 .find(|transceiver| transceiver.mid().as_deref() == Some(mid))
3376}
3377
3378fn start_camera_line(
3379 local_video: &mut LocalVideo,
3380 peer: &PeerConnection,
3381 direct_mid: Option<&str>,
3382 choice: &DeviceChoice,
3383) -> Result<()> {
3384 if !local_video.has_lines() {
3385 let mid = direct_mid.ok_or_else(|| Error::Webrtc("no video line negotiated".into()))?;
3386 let camera = peer_transceiver(peer, mid)
3387 .ok_or_else(|| Error::Webrtc("no transceiver for the camera line".into()))?;
3388 if !matches!(
3389 camera.direction(),
3390 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly
3391 ) {
3392 peer.add_track(
3393 MediaStreamTrack::Video(local_video.camera_track()),
3394 &[CAMERA_STREAM],
3395 )
3396 .map_err(|error| Error::Webrtc(error.to_string()))?;
3397 }
3398 local_video.set_lines(VideoLines {
3399 camera,
3400 share: None,
3401 })?;
3402 }
3403 local_video.start_camera(choice)
3404}
3405
3406#[allow(clippy::too_many_arguments)]
3407async fn offer_same_peer(
3408 peer: &PeerConnection,
3409 gathered: &Gathered,
3410 own_share_mid: Option<String>,
3411 plan: &OfferPlan,
3412 layout: Layout,
3413 camera_mid: &str,
3414 hold: bool,
3415 camera: bool,
3416 share: bool,
3417 remote: &RemoteCall,
3418 links: &CallbackLinks,
3419 media_leg_id: &str,
3420 media_links: &BTreeMap<String, String>,
3421 negotiator: &mut MediaNegotiator,
3422) -> Result<(String, SignaledOffer, Vec<String>)> {
3423 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
3424 let url = media_links
3425 .get("mediaRenegotiation")
3426 .cloned()
3427 .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?;
3428 if !negotiator.begin_same_peer_offer() {
3429 return Err(Error::Signaling(
3430 "another media negotiation is running".into(),
3431 ));
3432 }
3433 let offered = build_same_peer_offer(
3434 peer,
3435 plan,
3436 layout,
3437 hold,
3438 camera,
3439 share,
3440 camera_mid,
3441 own_share_mid,
3442 direct.then_some(gathered),
3443 )
3444 .await;
3445 let (text, signaled) = match offered {
3446 Ok(offered) => offered,
3447 Err(error) => {
3448 negotiator.same_peer_offer_failed();
3449 return Err(error);
3450 }
3451 };
3452 let modalities = offer_modalities(
3453 layout == Layout::OneToOne && camera && !hold,
3454 share && !hold,
3455 );
3456 let body = renegotiation_body(
3457 &remote.participant,
3458 links,
3459 &signaled.sdp,
3460 media_leg_id,
3461 &modalities,
3462 false,
3463 direct,
3464 );
3465 let reply_tags = offer_reply_tags(&body);
3466 if let Err(error) = remote
3467 .signaling
3468 .post_json("POST mediaRenegotiation (same peer)", &url, body)
3469 .await
3470 {
3471 negotiator.same_peer_offer_failed();
3472 rollback_offer(peer).await;
3473 return Err(error);
3474 }
3475 Ok((text, signaled, reply_tags))
3476}
3477
3478#[allow(clippy::too_many_arguments)]
3479async fn build_same_peer_offer(
3480 peer: &PeerConnection,
3481 plan: &OfferPlan,
3482 layout: Layout,
3483 hold: bool,
3484 camera: bool,
3485 share: bool,
3486 camera_mid: &str,
3487 own_share_mid: Option<String>,
3488 gathered: Option<&Gathered>,
3489) -> Result<(String, SignaledOffer)> {
3490 let offer = peer
3491 .create_offer(OfferOptions {
3492 offer_to_receive_audio: true,
3493 offer_to_receive_video: true,
3494 ..OfferOptions::default()
3495 })
3496 .await
3497 .map_err(|error| Error::Webrtc(error.to_string()))?;
3498 let offer_text = offer.to_string();
3499 let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text));
3500 let remote_shares = share_mid.as_deref().is_some_and(|mid| {
3501 peer.current_remote_description()
3502 .and_then(|remote| direction_of(&remote.to_string(), mid))
3503 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
3504 });
3505 let text = directions_for(
3506 layout,
3507 false,
3508 camera,
3509 share,
3510 camera_mid,
3511 share_mid.as_deref(),
3512 remote_shares,
3513 &offer_text,
3514 );
3515 let description = parse_sdp(&text, SdpType::Offer)?;
3516 peer.set_local_description(description)
3517 .await
3518 .map_err(|error| Error::Webrtc(error.to_string()))?;
3519 let mut numbers = random_u32;
3520 let mut plan = plan.clone();
3521 if let Some(mid) = share_mid
3522 .as_ref()
3523 .filter(|mid| !plan.screen_share_mids.contains(mid))
3524 {
3525 plan.screen_share_mids.push(mid.clone());
3526 }
3527 let mut signaled = to_teams_offer(
3528 &directions_for(
3529 layout,
3530 hold,
3531 camera,
3532 share,
3533 camera_mid,
3534 share_mid.as_deref(),
3535 remote_shares,
3536 &text,
3537 ),
3538 &plan,
3539 &mut numbers,
3540 )?;
3541 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
3542 if gathered.is_some()
3543 && let Some(role) = negotiated_setup(
3544 peer.current_local_description()
3545 .map(|local| local.to_string())
3546 .as_deref(),
3547 peer.current_remote_description()
3548 .map(|remote| remote.to_string())
3549 .as_deref(),
3550 )
3551 {
3552 signaled.sdp = signaled
3553 .sdp
3554 .replace("a=setup:actpass", &format!("a=setup:{role}"));
3555 }
3556 Ok((text, signaled))
3557}
3558
3559/// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging.
3560fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> {
3561 match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) {
3562 Ok(Ok(description)) => Ok(description),
3563 Ok(Err(error)) => Err(Error::Sdp(format!(
3564 "{kind:?} rejected: {}",
3565 error.description
3566 ))),
3567 Err(_) => Err(Error::Sdp(format!(
3568 "{kind:?} rejected, libwebrtc gave no readable reason"
3569 ))),
3570 }
3571}
3572
3573async fn rollback_offer(peer: &PeerConnection) {
3574 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
3575 let _ = peer.set_local_description(rollback).await;
3576 }
3577}
3578
3579async fn rollback_remote_offer(peer: &PeerConnection) {
3580 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
3581 let _ = peer.set_remote_description(rollback).await;
3582 }
3583}
3584
3585fn is_glare_rejection(body: &serde_json::Value) -> bool {
3586 body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE)
3587}
3588
3589fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
3590 let links = &body["mediaNegotiation"]["links"];
3591 ["mediaAnswer", "rejection"]
3592 .iter()
3593 .filter_map(|name| links[*name].as_str().and_then(callback_tag))
3594 .collect()
3595}
3596
3597#[cfg(test)]
3598mod reply_tag_tests {
3599 use super::*;
3600
3601 #[test]
3602 fn answers_and_rejections_match_the_offer_by_tag() {
3603 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
3604 assert!(answers_offer(
3605 "callAgent/c/aaaa1111/call/mediaAnswer/",
3606 &tags
3607 ));
3608 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
3609 assert!(!answers_offer(
3610 "callAgent/c/cccc3333/call/mediaAnswer/",
3611 &tags
3612 ));
3613 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
3614 }
3615
3616 #[test]
3617 fn an_offer_names_both_reply_tags() {
3618 let body = serde_json::json!({"mediaNegotiation": {"links": {
3619 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
3620 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
3621 assert_eq!(
3622 offer_reply_tags(&body),
3623 vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]
3624 );
3625 }
3626}
3627
3628fn defer_to_new_peer(
3629 change: Change,
3630 deferred: &mut Vec<Change>,
3631 local_video: &mut LocalVideo,
3632 control: &CallControl,
3633) {
3634 match change {
3635 Change::Camera(true) => {
3636 control.send(CallUpdate::Camera(true));
3637 deferred.push(change);
3638 }
3639 Change::Share(true) => deferred.push(change),
3640 change => undo_change(change, local_video, control),
3641 }
3642}
3643
3644/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
3645fn settle_failed_escalation(
3646 server: bool,
3647 layout: Layout,
3648 negotiator: &mut MediaNegotiator,
3649 deferred: &mut Vec<Change>,
3650 local_video: &mut LocalVideo,
3651 control: &CallControl,
3652) {
3653 if server {
3654 negotiator.server_escalation_failed();
3655 for change in deferred.drain(..) {
3656 undo_change(change, local_video, control);
3657 }
3658 } else if layout == Layout::OneToOne {
3659 drop_local_media(local_video, control);
3660 }
3661}
3662
3663fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
3664 if local_video.sharing() {
3665 local_video.stop_share();
3666 clear_share(control);
3667 }
3668 if local_video.camera_on() {
3669 local_video.stop_camera();
3670 control.send(CallUpdate::Camera(false));
3671 }
3672}
3673
3674fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {
3675 match change {
3676 Change::Camera(true) => {
3677 local_video.stop_camera();
3678 control.send(CallUpdate::Camera(false));
3679 }
3680 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
3681 Change::Share(true) => {
3682 local_video.stop_share();
3683 clear_share(control);
3684 control.send(CallUpdate::Notice(notice_with_detail(
3685 SHARING_START_NOTICE,
3686 "",
3687 )));
3688 }
3689 Change::Share(false) => {}
3690 Change::Hold(_) => control.send(CallUpdate::Notice(HOLD_CHANGE_FAILED_NOTICE.into())),
3691 }
3692}
3693
3694fn withhold_media(
3695 muted: &mut bool,
3696 audio: &AudioSetup,
3697 software_audio: Option<&SoftwareAudio>,
3698 remote: &RemoteCall,
3699 local_video: &mut LocalVideo,
3700 control: &CallControl,
3701) {
3702 *muted = apply_mute(
3703 MuteCommand::Mute,
3704 *muted,
3705 audio,
3706 software_audio,
3707 remote,
3708 control,
3709 );
3710 if local_video.camera_on() {
3711 local_video.stop_camera();
3712 control.send(CallUpdate::Camera(false));
3713 }
3714}
3715
3716async fn apply_background(
3717 choice: BackgroundChoice,
3718 local_video: &LocalVideo,
3719 control: &CallControl,
3720 timeline: &Timeline,
3721) {
3722 match choice {
3723 BackgroundChoice::None => local_video.set_background(false, None),
3724 BackgroundChoice::Blur => local_video.set_background(true, None),
3725 BackgroundChoice::Image(path) => {
3726 match tokio::task::spawn_blocking(move || BackgroundPicture::load(&path)).await {
3727 Ok(Ok(picture)) => local_video.set_background(true, Some(Arc::new(picture))),
3728 Ok(Err(error)) => {
3729 timeline.record("background image failed", error.to_string());
3730 control.send(CallUpdate::Notice(BACKGROUND_IMAGE_FAILED_NOTICE.into()));
3731 }
3732 Err(_) => {}
3733 }
3734 }
3735 }
3736}
3737
3738async fn save_meeting_options(
3739 session: &session::Session,
3740 target: &MeetingTarget,
3741 writes: &[OptionWrite],
3742) -> std::result::Result<meeting_options::MeetingOptions, String> {
3743 for change in writes {
3744 meeting_options::write(session, target, change)
3745 .await
3746 .map_err(|error| error.to_string())?;
3747 }
3748 meeting_options::fetch(session, target)
3749 .await
3750 .map_err(|error| error.to_string())
3751}
3752
3753fn target_of<'a>(roster: &'a Roster, mri: &'a str) -> Target<'a> {
3754 let display_name = roster
3755 .members()
3756 .iter()
3757 .find(|member| member.mri == mri)
3758 .map_or("", |member| member.display_name.as_str());
3759 Target { mri, display_name }
3760}
3761
3762const RECORDING_STOP_RETRIES: usize = 6;
3763const RECORDING_STOP_RETRY_WAIT: Duration = Duration::from_secs(5);
3764
3765/// The recorder answers 409 to a stop sent while its start is still settling.
3766fn recorder_busy(error: &Error) -> bool {
3767 matches!(error, Error::Signaling(reason) if reason.contains("HTTP 409"))
3768}
3769
3770fn report_organizer_result(
3771 result: Result<u16>,
3772 label: &str,
3773 notice: &'static str,
3774 control: &CallControl,
3775 timeline: &Timeline,
3776) {
3777 if let Err(error) = &result {
3778 timeline.record(format!("{label} failed"), error.to_string());
3779 control.send(CallUpdate::Notice(notice.to_owned()));
3780 }
3781 control.send(CallUpdate::Organizer {
3782 action: label.to_owned(),
3783 outcome: result.map_err(|error| error.to_string()),
3784 });
3785}
3786
3787fn named_caption(mut entry: CaptionEntry, roster: &Roster) -> CaptionEntry {
3788 if entry.display_name.is_empty() {
3789 entry.display_name = roster
3790 .name_of(&entry.user_id)
3791 .unwrap_or_default()
3792 .to_owned();
3793 }
3794 entry
3795}
3796
3797#[derive(Debug, Clone, Copy, PartialEq, Eq)]
3798enum BotJob {
3799 Captions,
3800 Recording,
3801}
3802
3803#[allow(clippy::too_many_arguments)]
3804async fn run_bot_steps(
3805 job: BotJob,
3806 flow: &mut CaptionFlow,
3807 roster: &Roster,
3808 remote: &RemoteCall,
3809 links: &CallbackLinks,
3810 meeting_chat: Option<&str>,
3811 plan: &RecordingPlan,
3812 bot_pending: &mut bool,
3813 control: &CallControl,
3814 timeline: &Timeline,
3815) {
3816 let is_active: fn(&crate::roster::CaptionBot) -> bool = match job {
3817 BotJob::Captions => |bot| bot.active,
3818 BotJob::Recording => |bot| bot.recording,
3819 };
3820 let fail = |flow: &mut CaptionFlow, reason: &str| {
3821 flow.failed();
3822 control.send(match job {
3823 BotJob::Captions => CallUpdate::Captions(CaptionState::Failed(reason.to_owned())),
3824 BotJob::Recording => CallUpdate::Notice(reason.to_owned()),
3825 });
3826 if job == BotJob::Recording {
3827 control.send(CallUpdate::RecordingPending(false));
3828 }
3829 };
3830 let (join_failure, start_failure) = match job {
3831 BotJob::Captions => (CAPTIONS_JOIN_FAILED_NOTICE, CAPTIONS_START_FAILED_NOTICE),
3832 BotJob::Recording => (RECORDING_JOIN_FAILED_NOTICE, RECORDING_START_FAILED_NOTICE),
3833 };
3834 loop {
3835 match flow.next_for(roster.caption_bot(), is_active) {
3836 CaptionStep::Wait => return,
3837 CaptionStep::AddBot => {
3838 if *bot_pending {
3839 continue;
3840 }
3841 let Some(thread) = meeting_chat else {
3842 return fail(
3843 flow,
3844 "This call has no chat for the captions and the recording",
3845 );
3846 };
3847 *bot_pending = true;
3848 let added = remote
3849 .signaling
3850 .add_caption_bot(
3851 &remote.conversation,
3852 &remote.participant,
3853 thread,
3854 links,
3855 remote.threadless,
3856 )
3857 .await;
3858 if job == BotJob::Recording {
3859 report_organizer_result(
3860 added
3861 .as_ref()
3862 .map(|status| *status)
3863 .map_err(|error| Error::Signaling(error.to_string())),
3864 "recording add bot",
3865 join_failure,
3866 control,
3867 timeline,
3868 );
3869 }
3870 if let Err(error) = added {
3871 timeline.record("bot invitation failed", error.to_string());
3872 *bot_pending = false;
3873 return fail(flow, join_failure);
3874 }
3875 }
3876 CaptionStep::Start => {
3877 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
3878 return;
3879 };
3880 match job {
3881 BotJob::Captions => {
3882 if let Err(error) = remote
3883 .signaling
3884 .caption_command(&url, BotAction::Start, &remote.participant)
3885 .await
3886 {
3887 timeline.record("caption start failed", error.to_string());
3888 return fail(flow, start_failure);
3889 }
3890 if let Err(error) = remote
3891 .signaling
3892 .set_caption_preference(&remote.conversation, &remote.participant, true)
3893 .await
3894 {
3895 timeline.record("caption preference failed", error.to_string());
3896 }
3897 }
3898 BotJob::Recording => {
3899 let started = remote
3900 .signaling
3901 .recording_command(&url, plan.start(), &remote.participant, &plan.title)
3902 .await;
3903 let failed = started.is_err();
3904 report_organizer_result(
3905 started,
3906 "recording start",
3907 start_failure,
3908 control,
3909 timeline,
3910 );
3911 if failed {
3912 return fail(flow, start_failure);
3913 }
3914 }
3915 }
3916 }
3917 CaptionStep::Stop => {
3918 let Some(url) = roster.caption_bot().and_then(|bot| bot.command_url.clone()) else {
3919 continue;
3920 };
3921 match job {
3922 BotJob::Captions => {
3923 if let Err(error) = remote
3924 .signaling
3925 .caption_command(&url, BotAction::Stop, &remote.participant)
3926 .await
3927 {
3928 timeline.record("caption stop failed", error.to_string());
3929 }
3930 if let Err(error) = remote
3931 .signaling
3932 .set_caption_preference(
3933 &remote.conversation,
3934 &remote.participant,
3935 false,
3936 )
3937 .await
3938 {
3939 timeline.record("caption preference failed", error.to_string());
3940 }
3941 }
3942 BotJob::Recording => {
3943 let remote = remote.clone();
3944 let updates = control.updates();
3945 let (command, title) = (plan.stop(), plan.title.clone());
3946 tokio::spawn(async move {
3947 let mut stopped = remote
3948 .signaling
3949 .recording_command(&url, command, &remote.participant, &title)
3950 .await;
3951 for _ in 0..RECORDING_STOP_RETRIES {
3952 if !stopped.as_ref().is_err_and(recorder_busy) {
3953 break;
3954 }
3955 tokio::time::sleep(RECORDING_STOP_RETRY_WAIT).await;
3956 stopped = remote
3957 .signaling
3958 .recording_command(&url, command, &remote.participant, &title)
3959 .await;
3960 }
3961 if stopped.is_err() {
3962 let _ = updates
3963 .send(CallUpdate::Notice(RECORDING_STOP_FAILED_NOTICE.into()));
3964 }
3965 let _ = updates.send(CallUpdate::Organizer {
3966 action: "recording stop".into(),
3967 outcome: stopped.map_err(|error| error.to_string()),
3968 });
3969 });
3970 }
3971 }
3972 }
3973 CaptionStep::ReportOn => {
3974 if job == BotJob::Captions {
3975 control.send(CallUpdate::Captions(CaptionState::On));
3976 }
3977 }
3978 }
3979 }
3980}
3981
3982fn send_receive_change(control: &CallControl, change: ReceiveChange) {
3983 if let Some(sharer) = change.screen_sharer {
3984 control.send(CallUpdate::ScreenShare(sharer));
3985 }
3986}
3987
3988fn record_audio_devices(
3989 timeline: &Timeline,
3990 lists: &devices::DeviceLists,
3991 input: Option<&AppliedDevice>,
3992 output: Option<&AppliedDevice>,
3993) {
3994 let name = |devices: &[AudioDevice], applied: Option<&AppliedDevice>| {
3995 applied
3996 .and_then(|applied| devices.iter().find(|device| device.index == applied.index))
3997 .map_or("none", |device| device.name.as_str())
3998 .to_owned()
3999 };
4000 timeline.record(
4001 "audio devices",
4002 format!(
4003 "input={} output={}",
4004 name(&lists.inputs, input),
4005 name(&lists.outputs, output)
4006 ),
4007 );
4008}
4009
4010fn follow_device_change(
4011 flow: Flow,
4012 (previous, current): (&[AudioDevice], &[AudioDevice]),
4013 choice: &DeviceChoice,
4014 applied: &mut Option<AppliedDevice>,
4015 select: impl Fn(u16) -> bool,
4016 timeline: &Timeline,
4017 control: &CallControl,
4018) -> bool {
4019 let system_default = devices::system_default_id(flow);
4020 let (index, fell_back) =
4021 match devices::reselect(applied.as_ref(), current, choice, system_default.as_deref()) {
4022 Reselect::Keep => return false,
4023 Reselect::Select(index) => (index, false),
4024 Reselect::FallBack(index) => (index, true),
4025 };
4026 let selected = select(index);
4027 timeline.record(
4028 "device change",
4029 format!("{flow:?} {choice:?} -> index {index} fallback={fell_back} applied={selected}"),
4030 );
4031 if selected {
4032 *applied = current
4033 .iter()
4034 .find(|device| device.index == index)
4035 .map(|device| AppliedDevice {
4036 index,
4037 key: device.key(),
4038 });
4039 }
4040 if fell_back {
4041 let fallback = current.iter().find(|device| device.index == index);
4042 control.send(CallUpdate::Notice(devices::disconnect_notice(
4043 previous, choice, fallback,
4044 )));
4045 }
4046 selected
4047}
4048
4049fn far_future() -> Instant {
4050 Instant::now() + FAR_FUTURE
4051}
4052
4053fn apply_mute(
4054 command: MuteCommand,
4055 currently_muted: bool,
4056 audio: &AudioSetup,
4057 software_audio: Option<&SoftwareAudio>,
4058 remote: &RemoteCall,
4059 control: &CallControl,
4060) -> bool {
4061 let effect = MuteEffect::for_muted(command.target(currently_muted));
4062 audio.track.set_enabled(effect.track_enabled);
4063 if let Some(software_audio) = software_audio {
4064 software_audio.set_microphone_muted(effect.muted);
4065 }
4066 control.send(CallUpdate::Muted(effect.muted));
4067 let remote = remote.clone();
4068 tokio::spawn(async move {
4069 let _ = remote
4070 .signaling
4071 .update_endpoint_state(
4072 &remote.conversation,
4073 &remote.participant,
4074 effect.endpoint_is_muted,
4075 )
4076 .await;
4077 });
4078 effect.muted
4079}
4080
4081fn silence_for_hold(
4082 on_hold: bool,
4083 muted: bool,
4084 audio: Option<&AudioSetup>,
4085 software_audio: Option<&SoftwareAudio>,
4086) {
4087 let silent = on_hold || muted;
4088 if let Some(audio) = audio {
4089 audio
4090 .track
4091 .set_enabled(MuteEffect::for_muted(silent).track_enabled);
4092 }
4093 if let Some(software_audio) = software_audio {
4094 software_audio.set_microphone_muted(silent);
4095 }
4096}
4097
4098fn swap_audio_track(peer: &PeerConnection, track: &RtcAudioTrack) -> Result<()> {
4099 let sender = peer
4100 .senders()
4101 .into_iter()
4102 .find(|sender| matches!(sender.track(), Some(MediaStreamTrack::Audio(_))))
4103 .ok_or_else(|| Error::Webrtc("no audio sender".into()))?;
4104 sender
4105 .set_track(Some(MediaStreamTrack::Audio(track.clone())))
4106 .map_err(|error| Error::Webrtc(error.to_string()))
4107}
4108
4109fn outgoing_track<'a>(
4110 software_audio: Option<&'a SoftwareAudio>,
4111 device_track: &'a RtcAudioTrack,
4112) -> &'a RtcAudioTrack {
4113 pick_track(software_audio.map(|audio| &audio.track), device_track)
4114}
4115
4116fn pick_track<'a, T>(software: Option<&'a T>, device: &'a T) -> &'a T {
4117 software.unwrap_or(device)
4118}
4119
4120fn software_wanted(
4121 mic_settings: MicSettings,
4122 share_sound_wanted: bool,
4123 local_video: &LocalVideo,
4124 audio: Option<&AudioSetup>,
4125) -> Option<SoftwareAudioPlan> {
4126 let sharing_sound = share_sound_wanted && local_video.sharing();
4127 SoftwareAudioPlan::wanted(
4128 mic_settings,
4129 sharing_sound,
4130 audio.is_some_and(AudioSetup::uses_devices),
4131 )
4132}
4133
4134fn restore_device_track(
4135 factory: &PeerConnectionFactory,
4136 input: &DeviceChoice,
4137 peer: &PeerConnection,
4138 device_track: &RtcAudioTrack,
4139 timeline: &Timeline,
4140) {
4141 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4142 if !factory.adm_recording_enabled() {
4143 factory.set_adm_recording_enabled(true);
4144 devices::select_input(factory, input);
4145 }
4146 if let Err(error) = swap_audio_track(peer, device_track) {
4147 timeline.record("microphone track not restored", error.to_string());
4148 }
4149}
4150
4151#[allow(clippy::too_many_arguments)]
4152fn sync_software_audio(
4153 factory: &PeerConnectionFactory,
4154 options: &CallOptions,
4155 input: &DeviceChoice,
4156 muted: bool,
4157 remote_audio: Option<RtcAudioTrack>,
4158 peer: &PeerConnection,
4159 device_track: &RtcAudioTrack,
4160 wanted: Option<SoftwareAudioPlan>,
4161 restart: bool,
4162 software_audio: &mut Option<SoftwareAudio>,
4163 control: &CallControl,
4164 timeline: &Timeline,
4165) {
4166 let running = software_audio.as_ref().map(|audio| audio.plan);
4167 if running == wanted && !restart {
4168 return;
4169 }
4170 if running.is_some() {
4171 timeline.record("software audio", "stopping");
4172 }
4173 *software_audio = None;
4174 let was_sharing_sound = running.is_some_and(|plan| plan.computer_sound);
4175 let Some(plan) = wanted else {
4176 restore_device_track(factory, input, peer, device_track, timeline);
4177 control.send(CallUpdate::ShareSound(false));
4178 return;
4179 };
4180 let started = SoftwareAudio::start(
4181 factory,
4182 options.audio,
4183 options.tone_hz,
4184 input,
4185 plan,
4186 muted,
4187 remote_audio,
4188 )
4189 .and_then(|audio| swap_audio_track(peer, &audio.track).map(|()| audio));
4190 match started {
4191 Ok(audio) => {
4192 timeline.record(
4193 "software audio",
4194 format!("{:?}, computer sound {:?}", plan.processing, audio.loopback),
4195 );
4196 if let Some(source) = &audio.microphone_source {
4197 timeline.record("mic capture", source.clone());
4198 }
4199 if audio.microphone_source.is_some() {
4200 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
4201 factory.set_adm_recording_enabled(false);
4202 }
4203 if let Some(warning) = &audio.warning {
4204 timeline.record("computer sound warning", warning.clone());
4205 }
4206 control.send(CallUpdate::ShareSound(plan.computer_sound));
4207 *software_audio = Some(audio);
4208 }
4209 Err(error) => {
4210 timeline.record("software audio failed", error.to_string());
4211 restore_device_track(factory, input, peer, device_track, timeline);
4212 if was_sharing_sound || plan.computer_sound {
4213 control.send(CallUpdate::ShareSound(false));
4214 }
4215 let notice = if plan.computer_sound {
4216 "Computer sound could not start, sharing without it"
4217 } else {
4218 "Microphone processing could not start, using the standard microphone"
4219 };
4220 control.send(CallUpdate::Notice(notice.into()));
4221 }
4222 }
4223}
4224
4225async fn tear_down(
4226 mut live: Live,
4227 inner: &Inner,
4228 timeline: &Timeline,
4229 report: &mut CallReport,
4230 cancelled: bool,
4231) {
4232 for peer in &live.peers {
4233 peer.close();
4234 }
4235 if let Some(audio) = live.audio.take() {
4236 audio.stop().await;
4237 }
4238 live.broker_running.store(false, Ordering::SeqCst);
4239 if !live.skip_leave
4240 && let Some(remote) = &live.remote
4241 {
4242 let reason = if cancelled {
4243 LeaveReason::Cancel
4244 } else {
4245 LeaveReason::Hangup
4246 };
4247 match remote
4248 .signaling
4249 .leave(&remote.conversation, &remote.participant, reason)
4250 .await
4251 {
4252 Ok(()) => report.left_cleanly = true,
4253 Err(error) => timeline.record("leave failed", error.to_string()),
4254 }
4255 }
4256 if report.end.is_none()
4257 && let Some(callbacks) = live.callbacks.as_mut()
4258 && live.remote.is_some()
4259 {
4260 let waited = timeout(END_CALLBACK_WAIT, async {
4261 while let Some(callback) = callbacks.recv().await {
4262 let event = handle_callback(&callback, timeline);
4263 if let Ok(CallEvent::End(end)) = event {
4264 return Some(end);
4265 }
4266 }
4267 None
4268 })
4269 .await;
4270 report.end = waited.ok().flatten();
4271 }
4272 if let Some(broker) = live.broker.take() {
4273 broker.abort();
4274 }
4275 for task in live.video_tasks.drain(..) {
4276 task.abort();
4277 }
4278 if let Some(route_id) = &live.route_id {
4279 inner.unregister_route(route_id);
4280 }
4281 timeline.record("closed", "peer closed, call route removed");
4282}
4283
4284fn setup_end_kind(end: &CallEnd) -> EndKind {
4285 match end.kind() {
4286 EndKind::Normal | EndKind::Other => EndKind::Unavailable,
4287 kind => kind,
4288 }
4289}
4290
4291fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<CallEvent> {
4292 let body = decode_body(callback)?;
4293 let (_, event) = classify(&callback.path, body)?;
4294 let detail = match &event {
4295 CallEvent::Acceptance(acceptance) => format!(
4296 "answer sdp {} bytes, fromMixer={}",
4297 acceptance.sdp.len(),
4298 acceptance.from_mixer
4299 ),
4300 CallEvent::End(end) => format!(
4301 "code={} subCode={} phrase={}",
4302 end.code, end.sub_code, end.phrase
4303 ),
4304 CallEvent::Progress(status) => format!("{status:?}"),
4305 CallEvent::ConversationEnd(body)
4306 | CallEvent::Rejection(body)
4307 | CallEvent::AddParticipantFailure(body)
4308 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
4309 CallEvent::ControlVideoStreaming(body) => parse_request(body)
4310 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
4311 _ => String::new(),
4312 };
4313 timeline.record(format!("Trouter {}", event.name()), detail);
4314 match &event {
4315 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
4316 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
4317 CallEvent::MediaRenegotiation(renegotiation) => {
4318 timeline.record_sdp("remote offer", &renegotiation.sdp)
4319 }
4320 _ => {}
4321 }
4322 Ok(event)
4323}
4324
4325async fn apply_answer(
4326 peer: &PeerConnection,
4327 teams_answer: &str,
4328 signaled: &SignaledOffer,
4329 browser_offer: &str,
4330) -> Result<()> {
4331 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
4332 set_browser_answer(peer, &answer).await
4333}
4334
4335/// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes.
4336async fn apply_hold_answer(
4337 peer: &PeerConnection,
4338 teams_answer: &str,
4339 signaled: &SignaledOffer,
4340 browser_offer: &str,
4341) -> Result<()> {
4342 let answer = to_browser_answer(teams_answer, signaled, browser_offer)?;
4343 set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await
4344}
4345
4346async fn set_browser_answer(peer: &PeerConnection, answer: &str) -> Result<()> {
4347 let description = parse_sdp(answer, SdpType::Answer)?;
4348 peer.set
4349… afgekapt