BlueGit

ict rusty-teams

Files

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

call.rs

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