BlueGit

ict rusty-teams

Files

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

call.rs

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