BlueGit

ict rusty-teams

Files

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

call.rs

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