BlueGit

ict rusty-teams

Files

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

call.rs

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