BlueGit

ict rusty-teams

Merge remote-tracking branch 'origin/main' into feat/voice-quality

metis Daniel Däschle · pushed by metis

Authored 2026-10-16 · 6 weeks ago

Hash
491797f92cf8f752bf217463d70310491991823f
11 files changed +849 −113
crates/calling/src/call.rs +448 −110
@@ -36,20 +36,21 @@ use crate::end::EndKind;
36 36 use crate::engine::{CallEngine, EngineConfig, Inner};
37 37 use crate::error::{Error, Result};
38 38 use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
39 use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, keep_media_running, rewrite_directions, stop_sending_on};
39 use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, offer_modalities, is_hold, keep_media_running, rewrite_directions, stop_sending_on};
40 40 use crate::mic_processing::MicSettings;
41 41 use crate::mute::{MuteCommand, MuteEffect};
42 42 use crate::push::CallNotification;
43 43 use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
44 44 use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
45 use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
45 46 use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
46 47 use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
47 48 use crate::meeting_options::{self, OptionWrite};
48 49 use crate::recording::{Consent, RecordingPlan, RecordingStatus};
49 use crate::roster::Roster;
50 use crate::roster::{Roster, direct_roster};
50 51 use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
51 52 use crate::signaling::{
52 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling,
53 Answer, Attached, Callee, one_to_one_thread, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, NegotiationFailure, Participant, Signaling,
53 54 TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
54 55 };
55 56 use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
@@ -58,7 +59,7 @@ use crate::timeline::{Timeline, TimelineEntry};
58 59 use crate::transfer::{Replacement, TransferEvent, TransferTarget};
59 60 use crate::video_frame::VideoKey;
60 61 use crate::video_layout::{
61 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, offer_plan, one_to_one_plan,
62 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines, offer_plan, one_to_one_plan,
62 63 };
63 64 use crate::send_control::{RequestFilter, parse_request};
64 65 use crate::video_send::{LocalVideo, SendSource, VideoMode};
@@ -74,6 +75,7 @@ const STATS_PERIOD: Duration = Duration::from_millis(200);
74 75 const TICKS_PER_SECOND: u32 = 5;
75 76 const RECONNECT_WINDOW: Duration = Duration::from_secs(30);
76 77 const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90);
78 const DIRECT_OUTGOING_TIMEOUT: Duration = Duration::from_secs(185);
77 79 const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365);
78 80 const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700;
79 81 const MIN_KEEP_ALIVE_SECONDS: u64 = 60;
@@ -88,7 +90,13 @@ const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
88 90 const BOT_PREFIX: &str = "28:";
89 91 const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
90 92 const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
93 const GATHERING_LIMIT: Duration = Duration::from_secs(5);
94 const GATHERING_QUIET: Duration = Duration::from_millis(500);
95 const GATHERING_POLL: Duration = Duration::from_millis(50);
91 96 const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
97 const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
98 const GLARE_CODE: i64 = 491;
99 const RETARGET_WAIT: Duration = Duration::from_secs(20);
92 100 const CAMERA_STREAM: &str = "camera";
93 101 const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
94 102
@@ -269,6 +277,43 @@ struct PeerSession {
269 277 peer: PeerConnection,
270 278 events: mpsc::UnboundedReceiver<PeerEvent>,
271 279 _data_channel: Option<DataChannel>,
280 gathered: Gathered,
281 }
282
283 #[derive(Clone, Default)]
284 struct Gathered {
285 candidates: Arc<std::sync::Mutex<Vec<String>>>,
286 complete: Arc<AtomicBool>,
287 relay_seen: Arc<AtomicBool>,
288 last_candidate: Arc<std::sync::Mutex<Option<Instant>>>,
289 }
290
291 impl Gathered {
292 /// libwebrtc gathers continually here, so "done" is a relay candidate followed by a quiet spell.
293 fn settled(&self) -> bool {
294 let quiet = self
295 .last_candidate
296 .lock()
297 .expect("candidate time lock")
298 .is_some_and(|at| at.elapsed() >= GATHERING_QUIET);
299 self.complete.load(Ordering::SeqCst) || (self.relay_seen.load(Ordering::SeqCst) && quiet)
300 }
301
302 async fn candidates(&self) -> Vec<String> {
303 let waited = Instant::now();
304 while !self.settled() && waited.elapsed() < GATHERING_LIMIT {
305 tokio::time::sleep(GATHERING_POLL).await;
306 }
307 self.complete.store(true, Ordering::SeqCst);
308 self.candidates.lock().expect("candidates lock").clone()
309 }
310 }
311
312 async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
313 match gathered {
314 Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind),
315 None => Ok(teams_sdp.to_owned()),
316 }
272 317 }
273 318
274 319 struct OfferedMedia {
@@ -312,11 +357,19 @@ struct SamePeerOffer {
312 357 reply_tags: Vec<String>,
313 358 }
314 359
360 struct GlareResend {
361 change: Change,
362 reply_tags: Vec<String>,
363 at: Instant,
364 }
365
315 366 struct NextPeer {
316 367 session: PeerSession,
317 368 offered: Option<OfferedMedia>,
318 369 reply_tags: Vec<String>,
319 370 deadline: Option<Instant>,
371 connected: bool,
372 retargeted: bool,
320 373 }
321 374
322 375 fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
@@ -442,6 +495,26 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
442 495 .map_err(|error| Error::Webrtc(error.to_string()))?;
443 496 let (sender, events) = mpsc::unbounded_channel();
444 497 let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;
498 let gathered = Gathered::default();
499 let candidate_sink = gathered.candidates.clone();
500 let relay_seen = gathered.relay_seen.clone();
501 let last_candidate = gathered.last_candidate.clone();
502 peer.on_ice_candidate(Some(Box::new(move |candidate| {
503 if candidate.sdp_mline_index() == 0 {
504 let text = candidate.candidate();
505 if is_udp_relay(&text) {
506 relay_seen.store(true, Ordering::SeqCst);
507 }
508 *last_candidate.lock().expect("candidate time lock") = Some(Instant::now());
509 candidate_sink.lock().expect("candidates lock").push(text);
510 }
511 })));
512 let gathering_done = gathered.complete.clone();
513 peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state {
514 IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst),
515 IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst),
516 IceGatheringState::New => {}
517 })));
445 518 let ice_sender = sender.clone();
446 519 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
447 520 let _ = ice_sender.send(PeerEvent::Ice(state));
@@ -459,7 +532,7 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
459 532 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
460 533 }
461 534 })));
462 Ok(PeerSession { peer, events, _data_channel: data_channel })
535 Ok(PeerSession { peer, events, _data_channel: data_channel, gathered })
463 536 }
464 537
465 538 fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {
@@ -472,23 +545,43 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv
472 545 Ok(channel)
473 546 }
474 547
475 fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
548 fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str, share_mid: Option<&'a str>, remote_shares: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
476 549 move |line| match line.kind {
477 550 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
478 "video" if camera_mid == CAMERA_MID && line.mid == ONE_TO_ONE_SHARE_MID => Some(if share { "sendonly" } else { INACTIVE }),
551 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
552 (true, true) => "sendrecv",
553 (true, false) => "sendonly",
554 (false, true) => "recvonly",
555 (false, false) => INACTIVE,
556 }),
479 557 _ => None,
480 558 }
481 559 }
482 560
483 fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, text: &str) -> String {
561 fn share_mid_in(offer_text: &str) -> Option<String> {
562 let mut mid = None;
563 for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) {
564 if line.starts_with("m=") {
565 mid = None;
566 } else if let Some(value) = line.strip_prefix("a=mid:") {
567 mid = Some(value.to_owned());
568 } else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() {
569 return mid;
570 }
571 }
572 None
573 }
574
575 #[allow(clippy::too_many_arguments)]
576 fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, share_mid: Option<&str>, remote_shares: bool, text: &str) -> String {
484 577 match (hold, layout) {
485 578 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
486 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid)),
579 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares)),
487 580 (false, Layout::Conference) => text.to_owned(),
488 581 }
489 582 }
490 583
491 async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout) -> Result<OfferedMedia> {
584 async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout, gathered: Option<&Gathered>) -> Result<OfferedMedia> {
492 585 let transceiver_init = RtpTransceiverInit {
493 586 direction: RtpTransceiverDirection::SendRecv,
494 587 stream_ids: vec![MIC_STREAM.into()],
@@ -508,13 +601,14 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
508 601 })
509 602 .await
510 603 .map_err(|error| Error::Webrtc(error.to_string()))?;
511 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, &offer.to_string());
604 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, &offer.to_string());
512 605 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
513 606 peer.set_local_description(description)
514 607 .await
515 608 .map_err(|error| Error::Webrtc(error.to_string()))?;
516 609 let mut numbers = random_u32;
517 let signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
610 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
611 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
518 612 Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })
519 613 }
520 614
@@ -522,14 +616,15 @@ struct AnsweredMedia {
522 616 remote: RemoteOffer,
523 617 answer_sdp: String,
524 618 camera_mid: Option<String>,
619 receiving_share_mid: Option<String>,
525 620 }
526 621
527 622 fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
528 623 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
529 624 }
530 625
531 fn share_mid(remote: &RemoteOffer) -> Option<String> {
532 remote.lines.iter().find(|line| line.role == LineRole::ScreenShare).and_then(|line| line.browser_mids.first().cloned())
626 fn share_mids(remote: &RemoteOffer) -> Vec<String> {
627 remote.lines.iter().filter(|line| line.role == LineRole::ScreenShare).filter_map(|line| line.browser_mids.first().cloned()).collect()
533 628 }
534 629
535 630 async fn answer_offer(
@@ -537,8 +632,9 @@ async fn answer_offer(
537 632 track: Option<&RtcAudioTrack>,
538 633 teams_offer: &str,
539 634 video: AnswerVideo<'_>,
540 sharing: bool,
635 sending_share_mid: Option<String>,
541 636 camera_on: bool,
637 gathered: Option<&Gathered>,
542 638 ) -> Result<AnsweredMedia> {
543 639 let remote = from_teams_offer(teams_offer)?;
544 640 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
@@ -546,10 +642,13 @@ async fn answer_offer(
546 642 .await
547 643 .map_err(|error| Error::Webrtc(error.to_string()))?;
548 644 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
549 let kept_share_mid = share_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
645 let kept_share_mids = if matches!(video, AnswerVideo::Reject) { Vec::new() } else { share_mids(&remote) };
550 646 for transceiver in peer.transceivers() {
551 647 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
552 if is_video && transceiver.mid() != camera_mid && transceiver.mid() != kept_share_mid {
648 let unused = transceiver
649 .mid()
650 .is_some_and(|mid| Some(&mid) != camera_mid.as_ref() && !kept_share_mids.contains(&mid) && Some(&mid) != sending_share_mid.as_ref());
651 if is_video && unused {
553 652 let _ = transceiver.stop();
554 653 }
555 654 }
@@ -565,10 +664,10 @@ async fn answer_offer(
565 664 .create_answer(AnswerOptions::default())
566 665 .await
567 666 .map_err(|error| Error::Webrtc(error.to_string()))?;
568 let mut answer_text = match kept_share_mid.as_deref() {
569 Some(mid) if !sharing => rewrite_directions(&answer.to_string(), |line| (line.kind == "video" && line.mid == mid).then_some(INACTIVE)),
570 _ => answer.to_string(),
571 };
667 let mut answer_text = answer.to_string();
668 for mid in kept_share_mids.iter().filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) {
669 answer_text = stop_sending_on(&answer_text, mid);
670 }
572 671 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
573 672 if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
574 673 answer_text = stop_sending_on(&answer_text, mid);
@@ -576,12 +675,17 @@ async fn answer_offer(
576 675 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
577 676 .await
578 677 .map_err(|error| Error::Webrtc(error.to_string()))?;
678 let receiving_share_mid = kept_share_mids
679 .into_iter()
680 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
681 .find(|mid| matches!(direction_of(&answer_text, mid).as_deref(), Some("recvonly" | "sendrecv")));
579 682 let mut numbers = random_u32;
580 683 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
581 684 Ok(AnsweredMedia {
582 685 remote,
583 answer_sdp: signaled.sdp,
686 answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
584 687 camera_mid,
688 receiving_share_mid,
585 689 })
586 690 }
587 691
@@ -692,6 +796,7 @@ async fn drive(
692 796 let mut keep_alive_seconds: Option<u64> = None;
693 797 let mut keep_alive_at: Option<Instant> = None;
694 798 let mut outgoing_deadline: Option<Instant> = None;
799 let mut outgoing_limit = OUTGOING_TIMEOUT;
695 800 let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
696 801 let is_echo = matches!(spec, Some(CallSpec::Echo));
697 802 let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count));
@@ -701,7 +806,16 @@ async fn drive(
701 806 };
702 807 let people_thread = match &spec {
703 808 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),
704 _ => None,
809 _ => incoming_media
810 .as_ref()
811 .filter(|(notification, _)| !notification.is_multi_party)
812 .and_then(|(notification, _)| {
813 notification
814 .thread_id
815 .clone()
816 .filter(|thread| *thread != notification.caller.mri)
817 .or_else(|| one_to_one_thread(&inner.identity.object_id, &notification.caller.mri))
818 }),
705 819 };
706 820 let mut layout = match &spec {
707 821 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne,
@@ -718,7 +832,8 @@ async fn drive(
718 832
719 833 let conversation = match (spec, incoming_media) {
720 834 (Some(spec), None) => {
721 let media = create_offer(&current.peer, &factory, &track, layout).await?;
835 let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
836 let media = create_offer(&current.peer, &factory, &track, layout, direct_invite.then_some(&current.gathered)).await?;
722 837 layout_plan = media.plan.clone();
723 838 if layout == Layout::OneToOne {
724 839 direct_video_mid = Some(CAMERA_MID.to_owned());
@@ -749,7 +864,10 @@ async fn drive(
749 864 };
750 865 if spec.is_people() {
751 866 control.send(CallUpdate::Progress(Progress::Calling));
752 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
867 if threadless {
868 outgoing_limit = DIRECT_OUTGOING_TIMEOUT;
869 }
870 outgoing_deadline = Some(Instant::now() + outgoing_limit);
753 871 }
754 872 if let Err(error) = local_video.set_lines(media.video.clone()) {
755 873 timeline.record("video lines not attached", error.to_string());
@@ -787,7 +905,7 @@ async fn drive(
787 905 _ => AnswerVideo::Receive,
788 906 };
789 907 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
790 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, false, false).await?;
908 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, None, false, one_to_one.then_some(&current.gathered)).await?;
791 909 layout_plan = answered.remote.plan();
792 910 direct_video_mid = answered.camera_mid.clone();
793 911 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
@@ -916,6 +1034,9 @@ async fn drive(
916 1034 }
917 1035 let mut start_camera_pending = options.start_camera;
918 1036 let mut share_pending: Option<ShareSource> = None;
1037 let mut glare_resend: Option<GlareResend> = None;
1038 let mut deferred_changes: Vec<Change> = Vec::new();
1039 let mut remote_direct_share: Option<String> = None;
919 1040 let mut sent_replacement: Option<Replacement> = None;
920 1041 loop {
921 1042 if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
@@ -927,11 +1048,61 @@ async fn drive(
927 1048 {
928 1049 control.defer(CallCommand::StartShare(source));
929 1050 }
1051 if next.as_ref().is_some_and(|pending| pending.connected && (pending.offered.is_some() || pending.retargeted))
1052 && let Some(pending) = next.take()
1053 {
1054 timeline.record("escalation", "new peer connection connected, old one dropped");
1055 deferred_changes.clear();
1056 negotiator.server_escalation_done();
1057 if let Some(mid) = remote_direct_share.take() {
1058 video.router().set(&mid, None);
1059 control.send(CallUpdate::ScreenShare(None));
1060 }
1061 let old = std::mem::replace(&mut current, pending.session);
1062 old.peer.close();
1063 if let Some(audio) = &software_audio
1064 && let Err(error) = swap_audio_track(&current.peer, &audio.track)
1065 {
1066 timeline.record("computer sound not carried over", error.to_string());
1067 }
1068 offered = pending.offered;
1069 if let Some(mid) = direct_video_mid.take() {
1070 video.router().set(&mid, None);
1071 }
1072 if let Some(media) = &offered {
1073 layout = Layout::Conference;
1074 layout_plan = media.plan.clone();
1075 if let Err(error) = local_video.set_lines(media.video.clone()) {
1076 timeline.record("video lines not attached", error.to_string());
1077 }
1078 if local_video.camera_on() {
1079 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1080 }
1081 if local_video.sharing() {
1082 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1083 }
1084 }
1085 remote_set = true;
1086 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1087 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;
1088 if pending.is_none() {
1089 drop_local_media(&mut local_video, control);
1090 }
1091 next = pending.or(next);
1092 }
1093 }
930 1094 let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);
1095 let glare_at = glare_resend.as_ref().map(|resend| resend.at);
931 1096 tokio::select! {
932 1097 Some(callback) = callbacks.recv() => {
933 1098 match handle_callback(&callback, timeline) {
934 1099 Ok(CallEvent::Acceptance(acceptance)) => {
1100 if !acceptance.from_mixer
1101 && let Some(accepted_by) = &acceptance.accepted_by
1102 && roster.apply(&direct_roster(&[(own_mri.as_str(), participant.display_name.as_str()), (accepted_by.mri.as_str(), accepted_by.display_name.as_str())]))
1103 {
1104 control.send(CallUpdate::Roster(roster.entries()));
1105 }
935 1106 if !acceptance.from_mixer && callee_gate.callee_joined() {
936 1107 advance(state, CallSignal::MediaConnected, control);
937 1108 }
@@ -996,6 +1167,26 @@ async fn drive(
996 1167 _ => {}
997 1168 }
998 1169 }
1170 Ok(CallEvent::MediaAnswer(answer)) if !remote_set && !answer.from_mixer && same_peer.is_none() && next.is_none() && outgoing_deadline.is_some() => {
1171 timeline.record("provisional answer", if answer.no_ring_back { "no ringback" } else { "ringing" });
1172 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1173 if !answer.no_ring_back {
1174 control.send(CallUpdate::Progress(Progress::Ringing));
1175 }
1176 }
1177 Ok(CallEvent::MediaAnswer(answer))
1178 if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1179 {
1180 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1181 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1182 }
1183 if answer.from_mixer {
1184 negotiator.note_mixer_path();
1185 }
1186 if let Some(resend) = glare_resend.as_mut() {
1187 resend.at = Instant::now();
1188 }
1189 }
999 1190 Ok(CallEvent::MediaAnswer(answer)) => {
1000 1191 let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1001 1192 || next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags));
@@ -1007,6 +1198,11 @@ async fn drive(
1007 1198 continue;
1008 1199 }
1009 1200 let action = negotiator.on_media_answer();
1201 if action == MediaAction::Ignore
1202 && let Some(url) = answer.links.get("mediaAcknowledgement")
1203 {
1204 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1205 }
1010 1206 if action == MediaAction::ApplyOnSamePeer
1011 1207 && let Some(pending) = same_peer.take()
1012 1208 {
@@ -1027,7 +1223,7 @@ async fn drive(
1027 1223 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1028 1224 }
1029 1225 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1030 Change::Share(true) if !answer.from_mixer && !sends_on(&current.peer, ONE_TO_ONE_SHARE_MID) => {
1226 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1031 1227 local_video.stop_share();
1032 1228 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);
1033 1229 control.send(CallUpdate::LocalShare(None));
@@ -1086,18 +1282,28 @@ async fn drive(
1086 1282 }
1087 1283 }
1088 1284 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
1285 if !renegotiation.escalation
1286 && !renegotiation.new_offer
1287 && let Some(pending) = same_peer.take()
1288 {
1289 same_peer_deadline = None;
1290 negotiator.same_peer_offer_failed();
1291 rollback_offer(&current.peer).await;
1292 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
1293 glare_resend = Some(GlareResend { change: pending.change, reply_tags: pending.reply_tags, at: Instant::now() + GLARE_RESEND_LIMIT });
1294 }
1089 1295 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1296 let rejection_link = renegotiation.links.get("rejection").cloned();
1090 1297 let result = match action {
1091 1298 MediaAction::AnswerOnNewPeer => {
1092 1299 if let Some(pending) = same_peer.take() {
1093 1300 same_peer_deadline = None;
1094 1301 timeline.record("same-peer offer", "superseded by the escalation offer");
1095 1302 rollback_offer(&current.peer).await;
1096 match pending.change {
1097 Change::Camera(true) => control.send(CallUpdate::Camera(true)),
1098 Change::Share(true) => {}
1099 change => undo_change(change, &mut local_video, control),
1100 }
1303 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
1304 }
1305 if let Some(resend) = glare_resend.take() {
1306 defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control);
1101 1307 }
1102 1308 match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1103 1309 Ok((session, answered)) => {
@@ -1107,18 +1313,44 @@ async fn drive(
1107 1313 if let Some(replaced) = next.take() {
1108 1314 replaced.session.peer.close();
1109 1315 }
1110 next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: None });
1316 next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: Some(Instant::now() + NEXT_PEER_LIMIT), connected: false, retargeted: false });
1111 1317 sent
1112 1318 }
1113 Err(error) => Err(error),
1319 Err(error) => {
1320 if next.is_none() {
1321 negotiator.server_escalation_failed();
1322 }
1323 for change in deferred_changes.drain(..) {
1324 undo_change(change, &mut local_video, control);
1325 }
1326 if let Some(url) = &rejection_link {
1327 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1328 }
1329 Err(error)
1330 }
1114 1331 }
1115 1332 }
1116 1333 MediaAction::AnswerOnSamePeer => {
1117 1334 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
1118 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer, local_video.sharing(), local_video.camera_on()).await {
1335 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer, local_video.sharing().then(|| local_video.share_mid()).flatten(), local_video.camera_on(), (layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct).then_some(&current.gathered)).await {
1119 1336 Ok(answered) => {
1120 1337 timeline.record_sdp("local answer", &answered.answer_sdp);
1121 1338 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1339 for mid in answered.remote.plan().screen_share_mids {
1340 if !layout_plan.screen_share_mids.contains(&mid) {
1341 layout_plan.screen_share_mids.push(mid);
1342 }
1343 }
1344 if layout == Layout::OneToOne && answered.receiving_share_mid != remote_direct_share {
1345 if let Some(mid) = &remote_direct_share {
1346 video.router().set(mid, None);
1347 }
1348 if let Some(mid) = &answered.receiving_share_mid {
1349 video.router().set(mid, Some(VideoKey::Screen));
1350 }
1351 remote_direct_share = answered.receiving_share_mid.clone();
1352 control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));
1353 }
1122 1354 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
1123 1355 if held != remote_hold {
1124 1356 remote_hold = held;
@@ -1126,8 +1358,22 @@ async fn drive(
1126 1358 }
1127 1359 sent
1128 1360 }
1129 Err(error) => Err(error),
1361 Err(error) => {
1362 if current.peer.signaling_state() == SignalingState::HaveRemoteOffer {
1363 rollback_remote_offer(&current.peer).await;
1364 }
1365 if let Some(url) = &rejection_link {
1366 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1367 }
1368 Err(error)
1369 }
1370 }
1371 }
1372 MediaAction::RejectGlare => {
1373 if let Some(url) = &rejection_link {
1374 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::InProgress).await;
1130 1375 }
1376 Ok(())
1131 1377 }
1132 1378 _ => Ok(()),
1133 1379 };
@@ -1293,6 +1539,9 @@ async fn drive(
1293 1539 Ok(CallEvent::Progress(status)) => {
1294 1540 if status == ProgressStatus::Ringing {
1295 1541 control.send(CallUpdate::Progress(Progress::Ringing));
1542 if outgoing_deadline.is_some() {
1543 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1544 }
1296 1545 }
1297 1546 }
1298 1547 Ok(CallEvent::ControlVideoStreaming(body)) => {
@@ -1321,18 +1570,30 @@ async fn drive(
1321 1570 advance(state, CallSignal::RemoteEnd(kind), control);
1322 1571 break;
1323 1572 }
1573 Ok(CallEvent::Rejection(_))
1574 if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1575 {
1576 if let Some(resend) = glare_resend.as_mut() {
1577 resend.at = Instant::now();
1578 }
1579 }
1324 1580 Ok(CallEvent::Rejection(_))
1325 1581 if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1326 1582 && !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) =>
1327 1583 {
1328 1584 timeline.record("rejection ignored", "it names an offer that is no longer pending");
1329 1585 }
1330 Ok(CallEvent::Rejection(_)) => match negotiator.on_rejection() {
1586 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1331 1587 RejectedOffer::SamePeer => {
1332 1588 same_peer_deadline = None;
1333 1589 if let Some(pending) = same_peer.take() {
1334 1590 rollback_offer(&current.peer).await;
1335 undo_change(pending.change, &mut local_video, control);
1591 if is_glare_rejection(&body) {
1592 timeline.record("glare", "our offer met theirs, it goes out again");
1593 glare_resend = Some(GlareResend { change: pending.change, reply_tags: Vec::new(), at: Instant::now() + GLARE_RESEND_LIMIT });
1594 } else {
1595 undo_change(pending.change, &mut local_video, control);
1596 }
1336 1597 }
1337 1598 }
1338 1599 RejectedOffer::NewPeer => {
@@ -1346,13 +1607,16 @@ async fn drive(
1346 1607 }
1347 1608 RejectedOffer::None => {}
1348 1609 },
1610 Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => {
1611 if let Some(pending) = next.as_mut() {
1612 pending.retargeted = true;
1613 }
1614 }
1349 1615 Ok(CallEvent::RetargetCompletion(body)) => {
1350 if body["retargetCompleted"]["code"].as_i64().is_some_and(|code| code != 0) && let Some(pending) = next.take() {
1616 if body["retargetCompleted"]["code"].as_i64().is_some() && let Some(pending) = next.take() {
1351 1617 pending.session.peer.close();
1352 1618 negotiator.escalation_failed();
1353 if layout == Layout::OneToOne {
1354 drop_local_media(&mut local_video, control);
1355 }
1619 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
1356 1620 timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");
1357 1621 }
1358 1622 }
@@ -1433,39 +1697,11 @@ async fn drive(
1433 1697 },
1434 1698 Some(event) = next_peer_event(&mut next) => match event {
1435 1699 PeerEvent::Connection(PeerConnectionState::Connected) => {
1436 if let Some(pending) = next.take() {
1437 timeline.record("escalation", "new peer connection connected, old one dropped");
1438 let old = std::mem::replace(&mut current, pending.session);
1439 old.peer.close();
1440 if let Some(audio) = &software_audio
1441 && let Err(error) = swap_audio_track(&current.peer, &audio.track)
1442 {
1443 timeline.record("computer sound not carried over", error.to_string());
1444 }
1445 offered = pending.offered;
1446 if let Some(mid) = direct_video_mid.take() {
1447 video.router().set(&mid, None);
1448 }
1449 if let Some(media) = &offered {
1450 layout = Layout::Conference;
1451 layout_plan = media.plan.clone();
1452 if let Err(error) = local_video.set_lines(media.video.clone()) {
1453 timeline.record("video lines not attached", error.to_string());
1454 }
1455 if local_video.camera_on() {
1456 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1457 }
1458 if local_video.sharing() {
1459 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1460 }
1461 }
1462 remote_set = true;
1463 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1464 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;
1465 if pending.is_none() {
1466 drop_local_media(&mut local_video, control);
1467 }
1468 next = pending.or(next);
1700 if let Some(pending) = next.as_mut() {
1701 pending.connected = true;
1702 if pending.offered.is_none() && !pending.retargeted {
1703 pending.deadline = Some(Instant::now() + RETARGET_WAIT);
1704 timeline.record("escalation", "new peer connection up, waiting for retargetCompletion");
1469 1705 }
1470 1706 }
1471 1707 }
@@ -1477,9 +1713,7 @@ async fn drive(
1477 1713 negotiator.escalation_failed();
1478 1714 if let Some(pending) = next.take() {
1479 1715 pending.session.peer.close();
1480 }
1481 if layout == Layout::OneToOne {
1482 drop_local_media(&mut local_video, control);
1716 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
1483 1717 }
1484 1718 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
1485 1719 }
@@ -1555,11 +1789,13 @@ async fn drive(
1555 1789 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
1556 1790 } else if local_hold {
1557 1791 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1792 } else if on && direct && (same_peer.is_some() || glare_resend.is_some()) {
1793 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1558 1794 } else if on {
1559 1795 let started = start_camera_line(&mut local_video, &current.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
1560 1796 match started {
1561 1797 Ok(()) if direct => {
1562 match offer_same_peer(&current.peer, &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 {
1798 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 {
1563 1799 Ok((browser_offer, signaled, reply_tags)) => {
1564 1800 timeline.record_sdp("local offer", &signaled.sdp);
1565 1801 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
@@ -1577,11 +1813,11 @@ async fn drive(
1577 1813 }
1578 1814 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1579 1815 }
1580 } else if direct && same_peer.is_some() {
1816 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1581 1817 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1582 1818 } else if direct {
1583 1819 local_video.stop_camera();
1584 match offer_same_peer(&current.peer, &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 {
1820 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 {
1585 1821 Ok((browser_offer, signaled, reply_tags)) => {
1586 1822 timeline.record_sdp("local offer", &signaled.sdp);
1587 1823 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
@@ -1617,14 +1853,19 @@ async fn drive(
1617 1853 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
1618 1854 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1619 1855 }
1620 } else if direct && same_peer.is_some() {
1856 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1621 1857 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1858 } else if direct
1859 && !local_video.has_share_line()
1860 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
1861 {
1862 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
1622 1863 } else if direct {
1623 1864 match local_video.start_share(&source) {
1624 1865 Ok(()) => {
1625 1866 control.send(CallUpdate::LocalShare(Some(source.label())));
1626 1867 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);
1627 match offer_same_peer(&current.peer, &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 {
1868 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 {
1628 1869 Ok((browser_offer, signaled, reply_tags)) => {
1629 1870 timeline.record_sdp("local offer", &signaled.sdp);
1630 1871 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
@@ -1663,13 +1904,13 @@ async fn drive(
1663 1904 Some(CallCommand::StopShare) => {
1664 1905 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1665 1906 share_pending = None;
1666 if direct && local_video.sharing() && same_peer.is_some() {
1907 if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
1667 1908 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1668 1909 } else if direct && local_video.sharing() {
1669 1910 local_video.stop_share();
1670 1911 control.send(CallUpdate::LocalShare(None));
1671 1912 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);
1672 match offer_same_peer(&current.peer, &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 {
1913 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 {
1673 1914 Ok((browser_offer, signaled, reply_tags)) => {
1674 1915 timeline.record_sdp("local offer", &signaled.sdp);
1675 1916 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
@@ -1889,7 +2130,7 @@ async fn drive(
1889 2130 }
1890 2131 }
1891 2132 Some(CallCommand::Hold(hold)) => {
1892 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || next.is_some() {
2133 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || glare_resend.is_some() || next.is_some() {
1893 2134 continue;
1894 2135 }
1895 2136 if hold && local_video.camera_on() {
@@ -1897,7 +2138,7 @@ async fn drive(
1897 2138 control.send(CallUpdate::Camera(false));
1898 2139 }
1899 2140 let camera = !hold && local_video.camera_on();
1900 match offer_same_peer(&current.peer, &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 {
2141 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 {
1901 2142 Ok((browser_offer, signaled, reply_tags)) => {
1902 2143 timeline.record_sdp("local offer", &signaled.sdp);
1903 2144 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
@@ -2121,18 +2362,52 @@ async fn drive(
2121 2362 break;
2122 2363 }
2123 2364 _ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {
2124 if let Some(pending) = next.take() {
2365 if let Some(pending) = next.as_mut().filter(|pending| pending.connected && pending.offered.is_none()) {
2366 pending.retargeted = true;
2367 timeline.record("escalation", "no retargetCompletion, switching anyway");
2368 } else if let Some(pending) = next.take() {
2125 2369 pending.session.peer.close();
2126 2370 negotiator.escalation_failed();
2127 2371 start_camera_pending = false;
2128 2372 share_pending = None;
2129 if layout == Layout::OneToOne {
2130 drop_local_media(&mut local_video, control);
2131 }
2373 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2132 2374 timeline.record("escalation failed", "no answer for the new peer connection in time");
2133 2375 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2134 2376 }
2135 2377 }
2378 _ = sleep_until(glare_at.unwrap_or_else(far_future)), if glare_at.is_some() => {
2379 let resend = glare_resend.take();
2380 if let Some(resend) = resend.as_ref().filter(|_| same_peer.is_some() || next.is_some()) {
2381 timeline.record("glare", "another change took over, ours is dropped");
2382 undo_change(resend.change, &mut local_video, control);
2383 } else if let Some(resend) = resend.as_ref().filter(|resend| layout == Layout::OneToOne && negotiator.path() == MediaPath::Mixer && !matches!(resend.change, Change::Hold(_))) {
2384 if negotiator.begin_conference_upgrade() {
2385 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;
2386 if pending.is_none() {
2387 drop_local_media(&mut local_video, control);
2388 }
2389 next = pending.or(next);
2390 } else {
2391 undo_change(resend.change, &mut local_video, control);
2392 }
2393 } else if let Some(resend) = resend {
2394 let (hold, camera, share) = match resend.change {
2395 Change::Hold(hold) => (hold, !hold && local_video.camera_on(), local_video.sharing()),
2396 _ => (local_hold, local_video.camera_on(), local_video.sharing()),
2397 };
2398 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 {
2399 Ok((browser_offer, signaled, reply_tags)) => {
2400 timeline.record_sdp("local offer", &signaled.sdp);
2401 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2402 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2403 }
2404 Err(error) => {
2405 timeline.record("offer after glare failed", error.to_string());
2406 undo_change(resend.change, &mut local_video, control);
2407 }
2408 }
2409 }
2410 }
2136 2411 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2137 2412 same_peer_deadline = None;
2138 2413 if let Some(pending) = same_peer.take() {
@@ -2181,7 +2456,7 @@ async fn start_escalation(
2181 2456 .get("mediaRenegotiation")
2182 2457 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2183 2458 let session = open_peer(factory, grant, &options.relay_host, false)?;
2184 let media = create_offer(&session.peer, factory, track, Layout::Conference).await?;
2459 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
2185 2460 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);
2186 2461 let reply_tags = offer_reply_tags(&body);
2187 2462 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
@@ -2190,6 +2465,8 @@ async fn start_escalation(
2190 2465 offered: Some(media),
2191 2466 reply_tags,
2192 2467 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
2468 connected: false,
2469 retargeted: false,
2193 2470 })
2194 2471 }
2195 2472
@@ -2243,7 +2520,7 @@ async fn answer_on_new_peer(
2243 2520 teams_offer: &str,
2244 2521 ) -> Result<(PeerSession, AnsweredMedia)> {
2245 2522 let session = open_peer(factory, grant, &options.relay_host, false)?;
2246 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, false, false).await?;
2523 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, None, false, None).await?;
2247 2524 Ok((session, answered))
2248 2525 }
2249 2526
@@ -2354,10 +2631,15 @@ fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
2354 2631 own.is_some_and(|own| own.thread_id == target.thread_id)
2355 2632 }
2356 2633
2357 fn sends_on(peer: &PeerConnection, mid: &str) -> bool {
2358 peer_transceiver(peer, mid)
2359 .and_then(|transceiver| transceiver.current_direction())
2360 .is_some_and(|direction| matches!(direction, RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv))
2634 fn attach_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory, local_video: &mut LocalVideo, camera_mid: Option<&str>) -> Result<()> {
2635 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
2636 if !local_video.has_lines() && camera.is_none() {
2637 return Err(Error::Webrtc("no video line negotiated".into()));
2638 }
2639 let share = add_share_line(peer, factory)?;
2640 local_video.add_share_line(share.clone(), camera).inspect_err(|_| {
2641 let _ = share.stop();
2642 })
2361 2643 }
2362 2644
2363 2645 fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
@@ -2380,6 +2662,8 @@ fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct
2380 2662 #[allow(clippy::too_many_arguments)]
2381 2663 async fn offer_same_peer(
2382 2664 peer: &PeerConnection,
2665 gathered: &Gathered,
2666 own_share_mid: Option<String>,
2383 2667 plan: &OfferPlan,
2384 2668 layout: Layout,
2385 2669 camera_mid: &str,
@@ -2400,7 +2684,7 @@ async fn offer_same_peer(
2400 2684 if !negotiator.begin_same_peer_offer() {
2401 2685 return Err(Error::Signaling("another media negotiation is running".into()));
2402 2686 }
2403 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid).await;
2687 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid, own_share_mid, direct.then_some(gathered)).await;
2404 2688 let (text, signaled) = match offered {
2405 2689 Ok(offered) => offered,
2406 2690 Err(error) => {
@@ -2408,7 +2692,7 @@ async fn offer_same_peer(
2408 2692 return Err(error);
2409 2693 }
2410 2694 };
2411 let modalities = accepted_modalities(layout == Layout::OneToOne && camera && !hold);
2695 let modalities = offer_modalities(layout == Layout::OneToOne && camera && !hold, share && !hold);
2412 2696 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
2413 2697 let reply_tags = offer_reply_tags(&body);
2414 2698 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
@@ -2419,18 +2703,39 @@ async fn offer_same_peer(
2419 2703 Ok((text, signaled, reply_tags))
2420 2704 }
2421 2705
2422 async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str) -> Result<(String, SignaledOffer)> {
2706 #[allow(clippy::too_many_arguments)]
2707 async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, own_share_mid: Option<String>, gathered: Option<&Gathered>) -> Result<(String, SignaledOffer)> {
2423 2708 let offer = peer
2424 2709 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
2425 2710 .await
2426 2711 .map_err(|error| Error::Webrtc(error.to_string()))?;
2427 let text = directions_for(layout, false, camera, share, camera_mid, &offer.to_string());
2712 let offer_text = offer.to_string();
2713 let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text));
2714 let remote_shares = share_mid.as_deref().is_some_and(|mid| {
2715 peer.current_remote_description()
2716 .and_then(|remote| direction_of(&remote.to_string(), mid))
2717 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
2718 });
2719 let text = directions_for(layout, false, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &offer_text);
2428 2720 let description = parse_sdp(&text, SdpType::Offer)?;
2429 2721 peer.set_local_description(description)
2430 2722 .await
2431 2723 .map_err(|error| Error::Webrtc(error.to_string()))?;
2432 2724 let mut numbers = random_u32;
2433 let signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, &text), plan, &mut numbers)?;
2725 let mut plan = plan.clone();
2726 if let Some(mid) = share_mid.as_ref().filter(|mid| !plan.screen_share_mids.contains(mid)) {
2727 plan.screen_share_mids.push(mid.clone());
2728 }
2729 let mut signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &text), &plan, &mut numbers)?;
2730 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
2731 if gathered.is_some()
2732 && let Some(role) = negotiated_setup(
2733 peer.current_local_description().map(|local| local.to_string()).as_deref(),
2734 peer.current_remote_description().map(|remote| remote.to_string()).as_deref(),
2735 )
2736 {
2737 signaled.sdp = signaled.sdp.replace("a=setup:actpass", &format!("a=setup:{role}"));
2738 }
2434 2739 Ok((text, signaled))
2435 2740 }
2436 2741
@@ -2449,6 +2754,16 @@ async fn rollback_offer(peer: &PeerConnection) {
2449 2754 }
2450 2755 }
2451 2756
2757 async fn rollback_remote_offer(peer: &PeerConnection) {
2758 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
2759 let _ = peer.set_remote_description(rollback).await;
2760 }
2761 }
2762
2763 fn is_glare_rejection(body: &serde_json::Value) -> bool {
2764 body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE)
2765 }
2766
2452 2767 fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2453 2768 let links = &body["mediaNegotiation"]["links"];
2454 2769 ["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
@@ -2476,6 +2791,29 @@ mod reply_tag_tests {
2476 2791 }
2477 2792 }
2478 2793
2794 fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
2795 match change {
2796 Change::Camera(true) => {
2797 control.send(CallUpdate::Camera(true));
2798 deferred.push(change);
2799 }
2800 Change::Share(true) => deferred.push(change),
2801 change => undo_change(change, local_video, control),
2802 }
2803 }
2804
2805 /// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
2806 fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut MediaNegotiator, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
2807 if server {
2808 negotiator.server_escalation_failed();
2809 for change in deferred.drain(..) {
2810 undo_change(change, local_video, control);
2811 }
2812 } else if layout == Layout::OneToOne {
2813 drop_local_media(local_video, control);
2814 }
2815 }
2816
2479 2817 fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2480 2818 if local_video.sharing() {
2481 2819 local_video.stop_share();
@@ -3235,7 +3573,7 @@ mod tests {
3235 3573 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
3236 3574 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3237 3575 let track = factory.create_audio_track("microphone", source);
3238 let offer = create_offer(&peer, &factory, &track, layout).await;
3576 let offer = create_offer(&peer, &factory, &track, layout, None).await;
3239 3577 peer.close();
3240 3578 offer
3241 3579 }
@@ -3258,7 +3596,7 @@ mod tests {
3258 3596 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3259 3597 let track = factory.create_audio_track("microphone", source);
3260 3598 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3261 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, false, false).await;
3599 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, None, false, None).await;
3262 3600 peer.close();
3263 3601 if let Err(error) = answered {
3264 3602 panic!("{error}");
@@ -3267,22 +3605,22 @@ mod tests {
3267 3605
3268 3606 #[test]
3269 3607 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3270 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3271 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
3272 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);
3608 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3609 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
3610 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);
3273 3611 }
3274 3612
3275 3613 #[test]
3276 3614 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3277 3615 for layout in [Layout::OneToOne, Layout::Conference] {
3278 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3616 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, None, false, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3279 3617 }
3280 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, BROWSER_OFFER), BROWSER_OFFER);
3618 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, None, false, BROWSER_OFFER), BROWSER_OFFER);
3281 3619 }
3282 3620
3283 3621 #[test]
3284 3622 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3285 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, BROWSER_OFFER);
3623 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, None, false, BROWSER_OFFER);
3286 3624 let mut numbers = || 7;
3287 3625 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
3288 3626 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
@@ -36,20 +36,21 @@ use crate::end::EndKind;
36use crate::engine::{CallEngine, EngineConfig, Inner};
36use crate::engine::{CallEngine, EngineConfig, Inner};
37use crate::error::{Error, Result};
37use crate::error::{Error, Result};
38use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
38use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
39use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, keep_media_running, rewrite_directions, stop_sending_on};
39use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, direction_of, offer_modalities, is_hold, keep_media_running, rewrite_directions, stop_sending_on};
40use crate::mic_processing::MicSettings;
40use crate::mic_processing::MicSettings;
41use crate::mute::{MuteCommand, MuteEffect};
41use crate::mute::{MuteCommand, MuteEffect};
42use crate::push::CallNotification;
42use crate::push::CallNotification;
43use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
43use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};
44use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
44use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};
45use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};
45use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
46use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};
46use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
47use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};
47use crate::meeting_options::{self, OptionWrite};
48use crate::meeting_options::{self, OptionWrite};
48use crate::recording::{Consent, RecordingPlan, RecordingStatus};
49use crate::recording::{Consent, RecordingPlan, RecordingStatus};
49use crate::roster::Roster;
50use crate::roster::{Roster, direct_roster};
50use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
51use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};
51use crate::signaling::{
52use crate::signaling::{
52 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, Participant, Signaling,
53 Answer, Attached, Callee, one_to_one_thread, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget, NegotiationFailure, Participant, Signaling,
53 TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
54 TenantRouting, chat_thread_id, find_echo_bot_thread, escalation_answer_body, renegotiation_body,
54};
55};
55use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
56use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};
@@ -58,7 +59,7 @@ use crate::timeline::{Timeline, TimelineEntry};
58use crate::transfer::{Replacement, TransferEvent, TransferTarget};
59use crate::transfer::{Replacement, TransferEvent, TransferTarget};
59use crate::video_frame::VideoKey;
60use crate::video_frame::VideoKey;
60use crate::video_layout::{
61use crate::video_layout::{
61 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_video_lines, offer_plan, one_to_one_plan,
62 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines, offer_plan, one_to_one_plan,
62};
63};
63use crate::send_control::{RequestFilter, parse_request};
64use crate::send_control::{RequestFilter, parse_request};
64use crate::video_send::{LocalVideo, SendSource, VideoMode};
65use crate::video_send::{LocalVideo, SendSource, VideoMode};
@@ -74,6 +75,7 @@ const STATS_PERIOD: Duration = Duration::from_millis(200);
74const TICKS_PER_SECOND: u32 = 5;
75const TICKS_PER_SECOND: u32 = 5;
75const RECONNECT_WINDOW: Duration = Duration::from_secs(30);
76const RECONNECT_WINDOW: Duration = Duration::from_secs(30);
76const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90);
77const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90);
78const DIRECT_OUTGOING_TIMEOUT: Duration = Duration::from_secs(185);
77const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365);
79const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365);
78const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700;
80const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700;
79const MIN_KEEP_ALIVE_SECONDS: u64 = 60;
81const MIN_KEEP_ALIVE_SECONDS: u64 = 60;
@@ -88,7 +90,13 @@ const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
88const BOT_PREFIX: &str = "28:";
90const BOT_PREFIX: &str = "28:";
89const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
91const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
90const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
92const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
93const GATHERING_LIMIT: Duration = Duration::from_secs(5);
94const GATHERING_QUIET: Duration = Duration::from_millis(500);
95const GATHERING_POLL: Duration = Duration::from_millis(50);
91const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
96const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
97const GLARE_RESEND_LIMIT: Duration = Duration::from_secs(3);
98const GLARE_CODE: i64 = 491;
99const RETARGET_WAIT: Duration = Duration::from_secs(20);
92const CAMERA_STREAM: &str = "camera";
100const CAMERA_STREAM: &str = "camera";
93const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
101const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
94
102
@@ -269,6 +277,43 @@ struct PeerSession {
269 peer: PeerConnection,
277 peer: PeerConnection,
270 events: mpsc::UnboundedReceiver<PeerEvent>,
278 events: mpsc::UnboundedReceiver<PeerEvent>,
271 _data_channel: Option<DataChannel>,
279 _data_channel: Option<DataChannel>,
280 gathered: Gathered,
281}
282
283#[derive(Clone, Default)]
284struct Gathered {
285 candidates: Arc<std::sync::Mutex<Vec<String>>>,
286 complete: Arc<AtomicBool>,
287 relay_seen: Arc<AtomicBool>,
288 last_candidate: Arc<std::sync::Mutex<Option<Instant>>>,
289}
290
291impl Gathered {
292 /// libwebrtc gathers continually here, so "done" is a relay candidate followed by a quiet spell.
293 fn settled(&self) -> bool {
294 let quiet = self
295 .last_candidate
296 .lock()
297 .expect("candidate time lock")
298 .is_some_and(|at| at.elapsed() >= GATHERING_QUIET);
299 self.complete.load(Ordering::SeqCst) || (self.relay_seen.load(Ordering::SeqCst) && quiet)
300 }
301
302 async fn candidates(&self) -> Vec<String> {
303 let waited = Instant::now();
304 while !self.settled() && waited.elapsed() < GATHERING_LIMIT {
305 tokio::time::sleep(GATHERING_POLL).await;
306 }
307 self.complete.store(true, Ordering::SeqCst);
308 self.candidates.lock().expect("candidates lock").clone()
309 }
310}
311
312async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
313 match gathered {
314 Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind),
315 None => Ok(teams_sdp.to_owned()),
316 }
272}
317}
273
318
274struct OfferedMedia {
319struct OfferedMedia {
@@ -312,11 +357,19 @@ struct SamePeerOffer {
312 reply_tags: Vec<String>,
357 reply_tags: Vec<String>,
313}
358}
314
359
360struct GlareResend {
361 change: Change,
362 reply_tags: Vec<String>,
363 at: Instant,
364}
365
315struct NextPeer {
366struct NextPeer {
316 session: PeerSession,
367 session: PeerSession,
317 offered: Option<OfferedMedia>,
368 offered: Option<OfferedMedia>,
318 reply_tags: Vec<String>,
369 reply_tags: Vec<String>,
319 deadline: Option<Instant>,
370 deadline: Option<Instant>,
371 connected: bool,
372 retargeted: bool,
320}
373}
321
374
322fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
375fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
@@ -442,6 +495,26 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
442 .map_err(|error| Error::Webrtc(error.to_string()))?;
495 .map_err(|error| Error::Webrtc(error.to_string()))?;
443 let (sender, events) = mpsc::unbounded_channel();
496 let (sender, events) = mpsc::unbounded_channel();
444 let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;
497 let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;
498 let gathered = Gathered::default();
499 let candidate_sink = gathered.candidates.clone();
500 let relay_seen = gathered.relay_seen.clone();
501 let last_candidate = gathered.last_candidate.clone();
502 peer.on_ice_candidate(Some(Box::new(move |candidate| {
503 if candidate.sdp_mline_index() == 0 {
504 let text = candidate.candidate();
505 if is_udp_relay(&text) {
506 relay_seen.store(true, Ordering::SeqCst);
507 }
508 *last_candidate.lock().expect("candidate time lock") = Some(Instant::now());
509 candidate_sink.lock().expect("candidates lock").push(text);
510 }
511 })));
512 let gathering_done = gathered.complete.clone();
513 peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state {
514 IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst),
515 IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst),
516 IceGatheringState::New => {}
517 })));
445 let ice_sender = sender.clone();
518 let ice_sender = sender.clone();
446 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
519 peer.on_ice_connection_state_change(Some(Box::new(move |state| {
447 let _ = ice_sender.send(PeerEvent::Ice(state));
520 let _ = ice_sender.send(PeerEvent::Ice(state));
@@ -459,7 +532,7 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
459 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
532 let _ = sender.send(PeerEvent::VideoTrack { mid, track });
460 }
533 }
461 })));
534 })));
462 Ok(PeerSession { peer, events, _data_channel: data_channel })
535 Ok(PeerSession { peer, events, _data_channel: data_channel, gathered })
463}
536}
464
537
465fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {
538fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {
@@ -472,23 +545,43 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv
472 Ok(channel)
545 Ok(channel)
473}
546}
474
547
475fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
548fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str, share_mid: Option<&'a str>, remote_shares: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
476 move |line| match line.kind {
549 move |line| match line.kind {
477 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
550 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
478 "video" if camera_mid == CAMERA_MID && line.mid == ONE_TO_ONE_SHARE_MID => Some(if share { "sendonly" } else { INACTIVE }),
551 "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
552 (true, true) => "sendrecv",
553 (true, false) => "sendonly",
554 (false, true) => "recvonly",
555 (false, false) => INACTIVE,
556 }),
479 _ => None,
557 _ => None,
480 }
558 }
481}
559}
482
560
483fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, text: &str) -> String {
561fn share_mid_in(offer_text: &str) -> Option<String> {
562 let mut mid = None;
563 for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) {
564 if line.starts_with("m=") {
565 mid = None;
566 } else if let Some(value) = line.strip_prefix("a=mid:") {
567 mid = Some(value.to_owned());
568 } else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() {
569 return mid;
570 }
571 }
572 None
573}
574
575#[allow(clippy::too_many_arguments)]
576fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, share_mid: Option<&str>, remote_shares: bool, text: &str) -> String {
484 match (hold, layout) {
577 match (hold, layout) {
485 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
578 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
486 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid)),
579 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares)),
487 (false, Layout::Conference) => text.to_owned(),
580 (false, Layout::Conference) => text.to_owned(),
488 }
581 }
489}
582}
490
583
491async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout) -> Result<OfferedMedia> {
584async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout, gathered: Option<&Gathered>) -> Result<OfferedMedia> {
492 let transceiver_init = RtpTransceiverInit {
585 let transceiver_init = RtpTransceiverInit {
493 direction: RtpTransceiverDirection::SendRecv,
586 direction: RtpTransceiverDirection::SendRecv,
494 stream_ids: vec![MIC_STREAM.into()],
587 stream_ids: vec![MIC_STREAM.into()],
@@ -508,13 +601,14 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
508 })
601 })
509 .await
602 .await
510 .map_err(|error| Error::Webrtc(error.to_string()))?;
603 .map_err(|error| Error::Webrtc(error.to_string()))?;
511 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, &offer.to_string());
604 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, &offer.to_string());
512 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
605 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
513 peer.set_local_description(description)
606 peer.set_local_description(description)
514 .await
607 .await
515 .map_err(|error| Error::Webrtc(error.to_string()))?;
608 .map_err(|error| Error::Webrtc(error.to_string()))?;
516 let mut numbers = random_u32;
609 let mut numbers = random_u32;
517 let signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
610 let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
611 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
518 Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })
612 Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })
519}
613}
520
614
@@ -522,14 +616,15 @@ struct AnsweredMedia {
522 remote: RemoteOffer,
616 remote: RemoteOffer,
523 answer_sdp: String,
617 answer_sdp: String,
524 camera_mid: Option<String>,
618 camera_mid: Option<String>,
619 receiving_share_mid: Option<String>,
525}
620}
526
621
527fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
622fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
528 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
623 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
529}
624}
530
625
531fn share_mid(remote: &RemoteOffer) -> Option<String> {
626fn share_mids(remote: &RemoteOffer) -> Vec<String> {
532 remote.lines.iter().find(|line| line.role == LineRole::ScreenShare).and_then(|line| line.browser_mids.first().cloned())
627 remote.lines.iter().filter(|line| line.role == LineRole::ScreenShare).filter_map(|line| line.browser_mids.first().cloned()).collect()
533}
628}
534
629
535async fn answer_offer(
630async fn answer_offer(
@@ -537,8 +632,9 @@ async fn answer_offer(
537 track: Option<&RtcAudioTrack>,
632 track: Option<&RtcAudioTrack>,
538 teams_offer: &str,
633 teams_offer: &str,
539 video: AnswerVideo<'_>,
634 video: AnswerVideo<'_>,
540 sharing: bool,
635 sending_share_mid: Option<String>,
541 camera_on: bool,
636 camera_on: bool,
637 gathered: Option<&Gathered>,
542) -> Result<AnsweredMedia> {
638) -> Result<AnsweredMedia> {
543 let remote = from_teams_offer(teams_offer)?;
639 let remote = from_teams_offer(teams_offer)?;
544 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
640 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
@@ -546,10 +642,13 @@ async fn answer_offer(
546 .await
642 .await
547 .map_err(|error| Error::Webrtc(error.to_string()))?;
643 .map_err(|error| Error::Webrtc(error.to_string()))?;
548 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
644 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
549 let kept_share_mid = share_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
645 let kept_share_mids = if matches!(video, AnswerVideo::Reject) { Vec::new() } else { share_mids(&remote) };
550 for transceiver in peer.transceivers() {
646 for transceiver in peer.transceivers() {
551 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
647 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
552 if is_video && transceiver.mid() != camera_mid && transceiver.mid() != kept_share_mid {
648 let unused = transceiver
649 .mid()
650 .is_some_and(|mid| Some(&mid) != camera_mid.as_ref() && !kept_share_mids.contains(&mid) && Some(&mid) != sending_share_mid.as_ref());
651 if is_video && unused {
553 let _ = transceiver.stop();
652 let _ = transceiver.stop();
554 }
653 }
555 }
654 }
@@ -565,10 +664,10 @@ async fn answer_offer(
565 .create_answer(AnswerOptions::default())
664 .create_answer(AnswerOptions::default())
566 .await
665 .await
567 .map_err(|error| Error::Webrtc(error.to_string()))?;
666 .map_err(|error| Error::Webrtc(error.to_string()))?;
568 let mut answer_text = match kept_share_mid.as_deref() {
667 let mut answer_text = answer.to_string();
569 Some(mid) if !sharing => rewrite_directions(&answer.to_string(), |line| (line.kind == "video" && line.mid == mid).then_some(INACTIVE)),
668 for mid in kept_share_mids.iter().filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) {
570 _ => answer.to_string(),
669 answer_text = stop_sending_on(&answer_text, mid);
571 };
670 }
572 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
671 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
573 if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
672 if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
574 answer_text = stop_sending_on(&answer_text, mid);
673 answer_text = stop_sending_on(&answer_text, mid);
@@ -576,12 +675,17 @@ async fn answer_offer(
576 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
675 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
577 .await
676 .await
578 .map_err(|error| Error::Webrtc(error.to_string()))?;
677 .map_err(|error| Error::Webrtc(error.to_string()))?;
678 let receiving_share_mid = kept_share_mids
679 .into_iter()
680 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
681 .find(|mid| matches!(direction_of(&answer_text, mid).as_deref(), Some("recvonly" | "sendrecv")));
579 let mut numbers = random_u32;
682 let mut numbers = random_u32;
580 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
683 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
581 Ok(AnsweredMedia {
684 Ok(AnsweredMedia {
582 remote,
685 remote,
583 answer_sdp: signaled.sdp,
686 answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
584 camera_mid,
687 camera_mid,
688 receiving_share_mid,
585 })
689 })
586}
690}
587
691
@@ -692,6 +796,7 @@ async fn drive(
692 let mut keep_alive_seconds: Option<u64> = None;
796 let mut keep_alive_seconds: Option<u64> = None;
693 let mut keep_alive_at: Option<Instant> = None;
797 let mut keep_alive_at: Option<Instant> = None;
694 let mut outgoing_deadline: Option<Instant> = None;
798 let mut outgoing_deadline: Option<Instant> = None;
799 let mut outgoing_limit = OUTGOING_TIMEOUT;
695 let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
800 let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
696 let is_echo = matches!(spec, Some(CallSpec::Echo));
801 let is_echo = matches!(spec, Some(CallSpec::Echo));
697 let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count));
802 let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count));
@@ -701,7 +806,16 @@ async fn drive(
701 };
806 };
702 let people_thread = match &spec {
807 let people_thread = match &spec {
703 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),
808 Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),
704 _ => None,
809 _ => incoming_media
810 .as_ref()
811 .filter(|(notification, _)| !notification.is_multi_party)
812 .and_then(|(notification, _)| {
813 notification
814 .thread_id
815 .clone()
816 .filter(|thread| *thread != notification.caller.mri)
817 .or_else(|| one_to_one_thread(&inner.identity.object_id, &notification.caller.mri))
818 }),
705 };
819 };
706 let mut layout = match &spec {
820 let mut layout = match &spec {
707 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne,
821 Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne,
@@ -718,7 +832,8 @@ async fn drive(
718
832
719 let conversation = match (spec, incoming_media) {
833 let conversation = match (spec, incoming_media) {
720 (Some(spec), None) => {
834 (Some(spec), None) => {
721 let media = create_offer(&current.peer, &factory, &track, layout).await?;
835 let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
836 let media = create_offer(&current.peer, &factory, &track, layout, direct_invite.then_some(&current.gathered)).await?;
722 layout_plan = media.plan.clone();
837 layout_plan = media.plan.clone();
723 if layout == Layout::OneToOne {
838 if layout == Layout::OneToOne {
724 direct_video_mid = Some(CAMERA_MID.to_owned());
839 direct_video_mid = Some(CAMERA_MID.to_owned());
@@ -749,7 +864,10 @@ async fn drive(
749 };
864 };
750 if spec.is_people() {
865 if spec.is_people() {
751 control.send(CallUpdate::Progress(Progress::Calling));
866 control.send(CallUpdate::Progress(Progress::Calling));
752 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
867 if threadless {
868 outgoing_limit = DIRECT_OUTGOING_TIMEOUT;
869 }
870 outgoing_deadline = Some(Instant::now() + outgoing_limit);
753 }
871 }
754 if let Err(error) = local_video.set_lines(media.video.clone()) {
872 if let Err(error) = local_video.set_lines(media.video.clone()) {
755 timeline.record("video lines not attached", error.to_string());
873 timeline.record("video lines not attached", error.to_string());
@@ -787,7 +905,7 @@ async fn drive(
787 _ => AnswerVideo::Receive,
905 _ => AnswerVideo::Receive,
788 };
906 };
789 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
907 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
790 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, false, false).await?;
908 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, None, false, one_to_one.then_some(&current.gathered)).await?;
791 layout_plan = answered.remote.plan();
909 layout_plan = answered.remote.plan();
792 direct_video_mid = answered.camera_mid.clone();
910 direct_video_mid = answered.camera_mid.clone();
793 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
911 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
@@ -916,6 +1034,9 @@ async fn drive(
916 }
1034 }
917 let mut start_camera_pending = options.start_camera;
1035 let mut start_camera_pending = options.start_camera;
918 let mut share_pending: Option<ShareSource> = None;
1036 let mut share_pending: Option<ShareSource> = None;
1037 let mut glare_resend: Option<GlareResend> = None;
1038 let mut deferred_changes: Vec<Change> = Vec::new();
1039 let mut remote_direct_share: Option<String> = None;
919 let mut sent_replacement: Option<Replacement> = None;
1040 let mut sent_replacement: Option<Replacement> = None;
920 loop {
1041 loop {
921 if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
1042 if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
@@ -927,11 +1048,61 @@ async fn drive(
927 {
1048 {
928 control.defer(CallCommand::StartShare(source));
1049 control.defer(CallCommand::StartShare(source));
929 }
1050 }
1051 if next.as_ref().is_some_and(|pending| pending.connected && (pending.offered.is_some() || pending.retargeted))
1052 && let Some(pending) = next.take()
1053 {
1054 timeline.record("escalation", "new peer connection connected, old one dropped");
1055 deferred_changes.clear();
1056 negotiator.server_escalation_done();
1057 if let Some(mid) = remote_direct_share.take() {
1058 video.router().set(&mid, None);
1059 control.send(CallUpdate::ScreenShare(None));
1060 }
1061 let old = std::mem::replace(&mut current, pending.session);
1062 old.peer.close();
1063 if let Some(audio) = &software_audio
1064 && let Err(error) = swap_audio_track(&current.peer, &audio.track)
1065 {
1066 timeline.record("computer sound not carried over", error.to_string());
1067 }
1068 offered = pending.offered;
1069 if let Some(mid) = direct_video_mid.take() {
1070 video.router().set(&mid, None);
1071 }
1072 if let Some(media) = &offered {
1073 layout = Layout::Conference;
1074 layout_plan = media.plan.clone();
1075 if let Err(error) = local_video.set_lines(media.video.clone()) {
1076 timeline.record("video lines not attached", error.to_string());
1077 }
1078 if local_video.camera_on() {
1079 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1080 }
1081 if local_video.sharing() {
1082 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1083 }
1084 }
1085 remote_set = true;
1086 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1087 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;
1088 if pending.is_none() {
1089 drop_local_media(&mut local_video, control);
1090 }
1091 next = pending.or(next);
1092 }
1093 }
930 let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);
1094 let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);
1095 let glare_at = glare_resend.as_ref().map(|resend| resend.at);
931 tokio::select! {
1096 tokio::select! {
932 Some(callback) = callbacks.recv() => {
1097 Some(callback) = callbacks.recv() => {
933 match handle_callback(&callback, timeline) {
1098 match handle_callback(&callback, timeline) {
934 Ok(CallEvent::Acceptance(acceptance)) => {
1099 Ok(CallEvent::Acceptance(acceptance)) => {
1100 if !acceptance.from_mixer
1101 && let Some(accepted_by) = &acceptance.accepted_by
1102 && roster.apply(&direct_roster(&[(own_mri.as_str(), participant.display_name.as_str()), (accepted_by.mri.as_str(), accepted_by.display_name.as_str())]))
1103 {
1104 control.send(CallUpdate::Roster(roster.entries()));
1105 }
935 if !acceptance.from_mixer && callee_gate.callee_joined() {
1106 if !acceptance.from_mixer && callee_gate.callee_joined() {
936 advance(state, CallSignal::MediaConnected, control);
1107 advance(state, CallSignal::MediaConnected, control);
937 }
1108 }
@@ -996,6 +1167,26 @@ async fn drive(
996 _ => {}
1167 _ => {}
997 }
1168 }
998 }
1169 }
1170 Ok(CallEvent::MediaAnswer(answer)) if !remote_set && !answer.from_mixer && same_peer.is_none() && next.is_none() && outgoing_deadline.is_some() => {
1171 timeline.record("provisional answer", if answer.no_ring_back { "no ringback" } else { "ringing" });
1172 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1173 if !answer.no_ring_back {
1174 control.send(CallUpdate::Progress(Progress::Ringing));
1175 }
1176 }
1177 Ok(CallEvent::MediaAnswer(answer))
1178 if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1179 {
1180 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1181 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1182 }
1183 if answer.from_mixer {
1184 negotiator.note_mixer_path();
1185 }
1186 if let Some(resend) = glare_resend.as_mut() {
1187 resend.at = Instant::now();
1188 }
1189 }
999 Ok(CallEvent::MediaAnswer(answer)) => {
1190 Ok(CallEvent::MediaAnswer(answer)) => {
1000 let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1191 let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1001 || next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags));
1192 || next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags));
@@ -1007,6 +1198,11 @@ async fn drive(
1007 continue;
1198 continue;
1008 }
1199 }
1009 let action = negotiator.on_media_answer();
1200 let action = negotiator.on_media_answer();
1201 if action == MediaAction::Ignore
1202 && let Some(url) = answer.links.get("mediaAcknowledgement")
1203 {
1204 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1205 }
1010 if action == MediaAction::ApplyOnSamePeer
1206 if action == MediaAction::ApplyOnSamePeer
1011 && let Some(pending) = same_peer.take()
1207 && let Some(pending) = same_peer.take()
1012 {
1208 {
@@ -1027,7 +1223,7 @@ async fn drive(
1027 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1223 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1028 }
1224 }
1029 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1225 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1030 Change::Share(true) if !answer.from_mixer && !sends_on(&current.peer, ONE_TO_ONE_SHARE_MID) => {
1226 Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1031 local_video.stop_share();
1227 local_video.stop_share();
1032 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);
1228 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);
1033 control.send(CallUpdate::LocalShare(None));
1229 control.send(CallUpdate::LocalShare(None));
@@ -1086,18 +1282,28 @@ async fn drive(
1086 }
1282 }
1087 }
1283 }
1088 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
1284 Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
1285 if !renegotiation.escalation
1286 && !renegotiation.new_offer
1287 && let Some(pending) = same_peer.take()
1288 {
1289 same_peer_deadline = None;
1290 negotiator.same_peer_offer_failed();
1291 rollback_offer(&current.peer).await;
1292 timeline.record("glare", "the remote offer is answered first, ours goes out again after");
1293 glare_resend = Some(GlareResend { change: pending.change, reply_tags: pending.reply_tags, at: Instant::now() + GLARE_RESEND_LIMIT });
1294 }
1089 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1295 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1296 let rejection_link = renegotiation.links.get("rejection").cloned();
1090 let result = match action {
1297 let result = match action {
1091 MediaAction::AnswerOnNewPeer => {
1298 MediaAction::AnswerOnNewPeer => {
1092 if let Some(pending) = same_peer.take() {
1299 if let Some(pending) = same_peer.take() {
1093 same_peer_deadline = None;
1300 same_peer_deadline = None;
1094 timeline.record("same-peer offer", "superseded by the escalation offer");
1301 timeline.record("same-peer offer", "superseded by the escalation offer");
1095 rollback_offer(&current.peer).await;
1302 rollback_offer(&current.peer).await;
1096 match pending.change {
1303 defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
1097 Change::Camera(true) => control.send(CallUpdate::Camera(true)),
1304 }
1098 Change::Share(true) => {}
1305 if let Some(resend) = glare_resend.take() {
1099 change => undo_change(change, &mut local_video, control),
1306 defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control);
1100 }
1101 }
1307 }
1102 match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1308 match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1103 Ok((session, answered)) => {
1309 Ok((session, answered)) => {
@@ -1107,18 +1313,44 @@ async fn drive(
1107 if let Some(replaced) = next.take() {
1313 if let Some(replaced) = next.take() {
1108 replaced.session.peer.close();
1314 replaced.session.peer.close();
1109 }
1315 }
1110 next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: None });
1316 next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: Some(Instant::now() + NEXT_PEER_LIMIT), connected: false, retargeted: false });
1111 sent
1317 sent
1112 }
1318 }
1113 Err(error) => Err(error),
1319 Err(error) => {
1320 if next.is_none() {
1321 negotiator.server_escalation_failed();
1322 }
1323 for change in deferred_changes.drain(..) {
1324 undo_change(change, &mut local_video, control);
1325 }
1326 if let Some(url) = &rejection_link {
1327 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1328 }
1329 Err(error)
1330 }
1114 }
1331 }
1115 }
1332 }
1116 MediaAction::AnswerOnSamePeer => {
1333 MediaAction::AnswerOnSamePeer => {
1117 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
1334 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
1118 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer, local_video.sharing(), local_video.camera_on()).await {
1335 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer, local_video.sharing().then(|| local_video.share_mid()).flatten(), local_video.camera_on(), (layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct).then_some(&current.gathered)).await {
1119 Ok(answered) => {
1336 Ok(answered) => {
1120 timeline.record_sdp("local answer", &answered.answer_sdp);
1337 timeline.record_sdp("local answer", &answered.answer_sdp);
1121 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1338 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1339 for mid in answered.remote.plan().screen_share_mids {
1340 if !layout_plan.screen_share_mids.contains(&mid) {
1341 layout_plan.screen_share_mids.push(mid);
1342 }
1343 }
1344 if layout == Layout::OneToOne && answered.receiving_share_mid != remote_direct_share {
1345 if let Some(mid) = &remote_direct_share {
1346 video.router().set(mid, None);
1347 }
1348 if let Some(mid) = &answered.receiving_share_mid {
1349 video.router().set(mid, Some(VideoKey::Screen));
1350 }
1351 remote_direct_share = answered.receiving_share_mid.clone();
1352 control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));
1353 }
1122 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
1354 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
1123 if held != remote_hold {
1355 if held != remote_hold {
1124 remote_hold = held;
1356 remote_hold = held;
@@ -1126,8 +1358,22 @@ async fn drive(
1126 }
1358 }
1127 sent
1359 sent
1128 }
1360 }
1129 Err(error) => Err(error),
1361 Err(error) => {
1362 if current.peer.signaling_state() == SignalingState::HaveRemoteOffer {
1363 rollback_remote_offer(&current.peer).await;
1364 }
1365 if let Some(url) = &rejection_link {
1366 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1367 }
1368 Err(error)
1369 }
1370 }
1371 }
1372 MediaAction::RejectGlare => {
1373 if let Some(url) = &rejection_link {
1374 let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::InProgress).await;
1130 }
1375 }
1376 Ok(())
1131 }
1377 }
1132 _ => Ok(()),
1378 _ => Ok(()),
1133 };
1379 };
@@ -1293,6 +1539,9 @@ async fn drive(
1293 Ok(CallEvent::Progress(status)) => {
1539 Ok(CallEvent::Progress(status)) => {
1294 if status == ProgressStatus::Ringing {
1540 if status == ProgressStatus::Ringing {
1295 control.send(CallUpdate::Progress(Progress::Ringing));
1541 control.send(CallUpdate::Progress(Progress::Ringing));
1542 if outgoing_deadline.is_some() {
1543 outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1544 }
1296 }
1545 }
1297 }
1546 }
1298 Ok(CallEvent::ControlVideoStreaming(body)) => {
1547 Ok(CallEvent::ControlVideoStreaming(body)) => {
@@ -1321,18 +1570,30 @@ async fn drive(
1321 advance(state, CallSignal::RemoteEnd(kind), control);
1570 advance(state, CallSignal::RemoteEnd(kind), control);
1322 break;
1571 break;
1323 }
1572 }
1573 Ok(CallEvent::Rejection(_))
1574 if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1575 {
1576 if let Some(resend) = glare_resend.as_mut() {
1577 resend.at = Instant::now();
1578 }
1579 }
1324 Ok(CallEvent::Rejection(_))
1580 Ok(CallEvent::Rejection(_))
1325 if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1581 if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1326 && !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) =>
1582 && !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) =>
1327 {
1583 {
1328 timeline.record("rejection ignored", "it names an offer that is no longer pending");
1584 timeline.record("rejection ignored", "it names an offer that is no longer pending");
1329 }
1585 }
1330 Ok(CallEvent::Rejection(_)) => match negotiator.on_rejection() {
1586 Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1331 RejectedOffer::SamePeer => {
1587 RejectedOffer::SamePeer => {
1332 same_peer_deadline = None;
1588 same_peer_deadline = None;
1333 if let Some(pending) = same_peer.take() {
1589 if let Some(pending) = same_peer.take() {
1334 rollback_offer(&current.peer).await;
1590 rollback_offer(&current.peer).await;
1335 undo_change(pending.change, &mut local_video, control);
1591 if is_glare_rejection(&body) {
1592 timeline.record("glare", "our offer met theirs, it goes out again");
1593 glare_resend = Some(GlareResend { change: pending.change, reply_tags: Vec::new(), at: Instant::now() + GLARE_RESEND_LIMIT });
1594 } else {
1595 undo_change(pending.change, &mut local_video, control);
1596 }
1336 }
1597 }
1337 }
1598 }
1338 RejectedOffer::NewPeer => {
1599 RejectedOffer::NewPeer => {
@@ -1346,13 +1607,16 @@ async fn drive(
1346 }
1607 }
1347 RejectedOffer::None => {}
1608 RejectedOffer::None => {}
1348 },
1609 },
1610 Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => {
1611 if let Some(pending) = next.as_mut() {
1612 pending.retargeted = true;
1613 }
1614 }
1349 Ok(CallEvent::RetargetCompletion(body)) => {
1615 Ok(CallEvent::RetargetCompletion(body)) => {
1350 if body["retargetCompleted"]["code"].as_i64().is_some_and(|code| code != 0) && let Some(pending) = next.take() {
1616 if body["retargetCompleted"]["code"].as_i64().is_some() && let Some(pending) = next.take() {
1351 pending.session.peer.close();
1617 pending.session.peer.close();
1352 negotiator.escalation_failed();
1618 negotiator.escalation_failed();
1353 if layout == Layout::OneToOne {
1619 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
1354 drop_local_media(&mut local_video, control);
1355 }
1356 timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");
1620 timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");
1357 }
1621 }
1358 }
1622 }
@@ -1433,39 +1697,11 @@ async fn drive(
1433 },
1697 },
1434 Some(event) = next_peer_event(&mut next) => match event {
1698 Some(event) = next_peer_event(&mut next) => match event {
1435 PeerEvent::Connection(PeerConnectionState::Connected) => {
1699 PeerEvent::Connection(PeerConnectionState::Connected) => {
1436 if let Some(pending) = next.take() {
1700 if let Some(pending) = next.as_mut() {
1437 timeline.record("escalation", "new peer connection connected, old one dropped");
1701 pending.connected = true;
1438 let old = std::mem::replace(&mut current, pending.session);
1702 if pending.offered.is_none() && !pending.retargeted {
1439 old.peer.close();
1703 pending.deadline = Some(Instant::now() + RETARGET_WAIT);
1440 if let Some(audio) = &software_audio
1704 timeline.record("escalation", "new peer connection up, waiting for retargetCompletion");
1441 && let Err(error) = swap_audio_track(&current.peer, &audio.track)
1442 {
1443 timeline.record("computer sound not carried over", error.to_string());
1444 }
1445 offered = pending.offered;
1446 if let Some(mid) = direct_video_mid.take() {
1447 video.router().set(&mid, None);
1448 }
1449 if let Some(media) = &offered {
1450 layout = Layout::Conference;
1451 layout_plan = media.plan.clone();
1452 if let Err(error) = local_video.set_lines(media.video.clone()) {
1453 timeline.record("video lines not attached", error.to_string());
1454 }
1455 if local_video.camera_on() {
1456 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1457 }
1458 if local_video.sharing() {
1459 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1460 }
1461 }
1462 remote_set = true;
1463 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1464 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;
1465 if pending.is_none() {
1466 drop_local_media(&mut local_video, control);
1467 }
1468 next = pending.or(next);
1469 }
1705 }
1470 }
1706 }
1471 }
1707 }
@@ -1477,9 +1713,7 @@ async fn drive(
1477 negotiator.escalation_failed();
1713 negotiator.escalation_failed();
1478 if let Some(pending) = next.take() {
1714 if let Some(pending) = next.take() {
1479 pending.session.peer.close();
1715 pending.session.peer.close();
1480 }
1716 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
1481 if layout == Layout::OneToOne {
1482 drop_local_media(&mut local_video, control);
1483 }
1717 }
1484 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
1718 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
1485 }
1719 }
@@ -1555,11 +1789,13 @@ async fn drive(
1555 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
1789 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
1556 } else if local_hold {
1790 } else if local_hold {
1557 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1791 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1792 } else if on && direct && (same_peer.is_some() || glare_resend.is_some()) {
1793 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1558 } else if on {
1794 } else if on {
1559 let started = start_camera_line(&mut local_video, &current.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
1795 let started = start_camera_line(&mut local_video, &current.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
1560 match started {
1796 match started {
1561 Ok(()) if direct => {
1797 Ok(()) if direct => {
1562 match offer_same_peer(&current.peer, &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 {
1798 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 {
1563 Ok((browser_offer, signaled, reply_tags)) => {
1799 Ok((browser_offer, signaled, reply_tags)) => {
1564 timeline.record_sdp("local offer", &signaled.sdp);
1800 timeline.record_sdp("local offer", &signaled.sdp);
1565 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
1801 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
@@ -1577,11 +1813,11 @@ async fn drive(
1577 }
1813 }
1578 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1814 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1579 }
1815 }
1580 } else if direct && same_peer.is_some() {
1816 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1581 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1817 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1582 } else if direct {
1818 } else if direct {
1583 local_video.stop_camera();
1819 local_video.stop_camera();
1584 match offer_same_peer(&current.peer, &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 {
1820 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 {
1585 Ok((browser_offer, signaled, reply_tags)) => {
1821 Ok((browser_offer, signaled, reply_tags)) => {
1586 timeline.record_sdp("local offer", &signaled.sdp);
1822 timeline.record_sdp("local offer", &signaled.sdp);
1587 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
1823 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
@@ -1617,14 +1853,19 @@ async fn drive(
1617 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
1853 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
1618 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1854 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1619 }
1855 }
1620 } else if direct && same_peer.is_some() {
1856 } else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1621 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1857 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1858 } else if direct
1859 && !local_video.has_share_line()
1860 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
1861 {
1862 control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
1622 } else if direct {
1863 } else if direct {
1623 match local_video.start_share(&source) {
1864 match local_video.start_share(&source) {
1624 Ok(()) => {
1865 Ok(()) => {
1625 control.send(CallUpdate::LocalShare(Some(source.label())));
1866 control.send(CallUpdate::LocalShare(Some(source.label())));
1626 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);
1867 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);
1627 match offer_same_peer(&current.peer, &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 {
1868 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 {
1628 Ok((browser_offer, signaled, reply_tags)) => {
1869 Ok((browser_offer, signaled, reply_tags)) => {
1629 timeline.record_sdp("local offer", &signaled.sdp);
1870 timeline.record_sdp("local offer", &signaled.sdp);
1630 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
1871 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
@@ -1663,13 +1904,13 @@ async fn drive(
1663 Some(CallCommand::StopShare) => {
1904 Some(CallCommand::StopShare) => {
1664 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1905 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1665 share_pending = None;
1906 share_pending = None;
1666 if direct && local_video.sharing() && same_peer.is_some() {
1907 if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
1667 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1908 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1668 } else if direct && local_video.sharing() {
1909 } else if direct && local_video.sharing() {
1669 local_video.stop_share();
1910 local_video.stop_share();
1670 control.send(CallUpdate::LocalShare(None));
1911 control.send(CallUpdate::LocalShare(None));
1671 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);
1912 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);
1672 match offer_same_peer(&current.peer, &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 {
1913 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 {
1673 Ok((browser_offer, signaled, reply_tags)) => {
1914 Ok((browser_offer, signaled, reply_tags)) => {
1674 timeline.record_sdp("local offer", &signaled.sdp);
1915 timeline.record_sdp("local offer", &signaled.sdp);
1675 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
1916 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
@@ -1889,7 +2130,7 @@ async fn drive(
1889 }
2130 }
1890 }
2131 }
1891 Some(CallCommand::Hold(hold)) => {
2132 Some(CallCommand::Hold(hold)) => {
1892 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || next.is_some() {
2133 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || glare_resend.is_some() || next.is_some() {
1893 continue;
2134 continue;
1894 }
2135 }
1895 if hold && local_video.camera_on() {
2136 if hold && local_video.camera_on() {
@@ -1897,7 +2138,7 @@ async fn drive(
1897 control.send(CallUpdate::Camera(false));
2138 control.send(CallUpdate::Camera(false));
1898 }
2139 }
1899 let camera = !hold && local_video.camera_on();
2140 let camera = !hold && local_video.camera_on();
1900 match offer_same_peer(&current.peer, &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 {
2141 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 {
1901 Ok((browser_offer, signaled, reply_tags)) => {
2142 Ok((browser_offer, signaled, reply_tags)) => {
1902 timeline.record_sdp("local offer", &signaled.sdp);
2143 timeline.record_sdp("local offer", &signaled.sdp);
1903 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
2144 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
@@ -2121,18 +2362,52 @@ async fn drive(
2121 break;
2362 break;
2122 }
2363 }
2123 _ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {
2364 _ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {
2124 if let Some(pending) = next.take() {
2365 if let Some(pending) = next.as_mut().filter(|pending| pending.connected && pending.offered.is_none()) {
2366 pending.retargeted = true;
2367 timeline.record("escalation", "no retargetCompletion, switching anyway");
2368 } else if let Some(pending) = next.take() {
2125 pending.session.peer.close();
2369 pending.session.peer.close();
2126 negotiator.escalation_failed();
2370 negotiator.escalation_failed();
2127 start_camera_pending = false;
2371 start_camera_pending = false;
2128 share_pending = None;
2372 share_pending = None;
2129 if layout == Layout::OneToOne {
2373 settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2130 drop_local_media(&mut local_video, control);
2131 }
2132 timeline.record("escalation failed", "no answer for the new peer connection in time");
2374 timeline.record("escalation failed", "no answer for the new peer connection in time");
2133 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2375 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2134 }
2376 }
2135 }
2377 }
2378 _ = sleep_until(glare_at.unwrap_or_else(far_future)), if glare_at.is_some() => {
2379 let resend = glare_resend.take();
2380 if let Some(resend) = resend.as_ref().filter(|_| same_peer.is_some() || next.is_some()) {
2381 timeline.record("glare", "another change took over, ours is dropped");
2382 undo_change(resend.change, &mut local_video, control);
2383 } else if let Some(resend) = resend.as_ref().filter(|resend| layout == Layout::OneToOne && negotiator.path() == MediaPath::Mixer && !matches!(resend.change, Change::Hold(_))) {
2384 if negotiator.begin_conference_upgrade() {
2385 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;
2386 if pending.is_none() {
2387 drop_local_media(&mut local_video, control);
2388 }
2389 next = pending.or(next);
2390 } else {
2391 undo_change(resend.change, &mut local_video, control);
2392 }
2393 } else if let Some(resend) = resend {
2394 let (hold, camera, share) = match resend.change {
2395 Change::Hold(hold) => (hold, !hold && local_video.camera_on(), local_video.sharing()),
2396 _ => (local_hold, local_video.camera_on(), local_video.sharing()),
2397 };
2398 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 {
2399 Ok((browser_offer, signaled, reply_tags)) => {
2400 timeline.record_sdp("local offer", &signaled.sdp);
2401 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2402 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2403 }
2404 Err(error) => {
2405 timeline.record("offer after glare failed", error.to_string());
2406 undo_change(resend.change, &mut local_video, control);
2407 }
2408 }
2409 }
2410 }
2136 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2411 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2137 same_peer_deadline = None;
2412 same_peer_deadline = None;
2138 if let Some(pending) = same_peer.take() {
2413 if let Some(pending) = same_peer.take() {
@@ -2181,7 +2456,7 @@ async fn start_escalation(
2181 .get("mediaRenegotiation")
2456 .get("mediaRenegotiation")
2182 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2457 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2183 let session = open_peer(factory, grant, &options.relay_host, false)?;
2458 let session = open_peer(factory, grant, &options.relay_host, false)?;
2184 let media = create_offer(&session.peer, factory, track, Layout::Conference).await?;
2459 let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
2185 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);
2460 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);
2186 let reply_tags = offer_reply_tags(&body);
2461 let reply_tags = offer_reply_tags(&body);
2187 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
2462 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
@@ -2190,6 +2465,8 @@ async fn start_escalation(
2190 offered: Some(media),
2465 offered: Some(media),
2191 reply_tags,
2466 reply_tags,
2192 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
2467 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
2468 connected: false,
2469 retargeted: false,
2193 })
2470 })
2194}
2471}
2195
2472
@@ -2243,7 +2520,7 @@ async fn answer_on_new_peer(
2243 teams_offer: &str,
2520 teams_offer: &str,
2244) -> Result<(PeerSession, AnsweredMedia)> {
2521) -> Result<(PeerSession, AnsweredMedia)> {
2245 let session = open_peer(factory, grant, &options.relay_host, false)?;
2522 let session = open_peer(factory, grant, &options.relay_host, false)?;
2246 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, false, false).await?;
2523 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, None, false, None).await?;
2247 Ok((session, answered))
2524 Ok((session, answered))
2248}
2525}
2249
2526
@@ -2354,10 +2631,15 @@ fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
2354 own.is_some_and(|own| own.thread_id == target.thread_id)
2631 own.is_some_and(|own| own.thread_id == target.thread_id)
2355}
2632}
2356
2633
2357fn sends_on(peer: &PeerConnection, mid: &str) -> bool {
2634fn attach_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory, local_video: &mut LocalVideo, camera_mid: Option<&str>) -> Result<()> {
2358 peer_transceiver(peer, mid)
2635 let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
2359 .and_then(|transceiver| transceiver.current_direction())
2636 if !local_video.has_lines() && camera.is_none() {
2360 .is_some_and(|direction| matches!(direction, RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv))
2637 return Err(Error::Webrtc("no video line negotiated".into()));
2638 }
2639 let share = add_share_line(peer, factory)?;
2640 local_video.add_share_line(share.clone(), camera).inspect_err(|_| {
2641 let _ = share.stop();
2642 })
2361}
2643}
2362
2644
2363fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
2645fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
@@ -2380,6 +2662,8 @@ fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct
2380#[allow(clippy::too_many_arguments)]
2662#[allow(clippy::too_many_arguments)]
2381async fn offer_same_peer(
2663async fn offer_same_peer(
2382 peer: &PeerConnection,
2664 peer: &PeerConnection,
2665 gathered: &Gathered,
2666 own_share_mid: Option<String>,
2383 plan: &OfferPlan,
2667 plan: &OfferPlan,
2384 layout: Layout,
2668 layout: Layout,
2385 camera_mid: &str,
2669 camera_mid: &str,
@@ -2400,7 +2684,7 @@ async fn offer_same_peer(
2400 if !negotiator.begin_same_peer_offer() {
2684 if !negotiator.begin_same_peer_offer() {
2401 return Err(Error::Signaling("another media negotiation is running".into()));
2685 return Err(Error::Signaling("another media negotiation is running".into()));
2402 }
2686 }
2403 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid).await;
2687 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid, own_share_mid, direct.then_some(gathered)).await;
2404 let (text, signaled) = match offered {
2688 let (text, signaled) = match offered {
2405 Ok(offered) => offered,
2689 Ok(offered) => offered,
2406 Err(error) => {
2690 Err(error) => {
@@ -2408,7 +2692,7 @@ async fn offer_same_peer(
2408 return Err(error);
2692 return Err(error);
2409 }
2693 }
2410 };
2694 };
2411 let modalities = accepted_modalities(layout == Layout::OneToOne && camera && !hold);
2695 let modalities = offer_modalities(layout == Layout::OneToOne && camera && !hold, share && !hold);
2412 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
2696 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
2413 let reply_tags = offer_reply_tags(&body);
2697 let reply_tags = offer_reply_tags(&body);
2414 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
2698 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
@@ -2419,18 +2703,39 @@ async fn offer_same_peer(
2419 Ok((text, signaled, reply_tags))
2703 Ok((text, signaled, reply_tags))
2420}
2704}
2421
2705
2422async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str) -> Result<(String, SignaledOffer)> {
2706#[allow(clippy::too_many_arguments)]
2707async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, own_share_mid: Option<String>, gathered: Option<&Gathered>) -> Result<(String, SignaledOffer)> {
2423 let offer = peer
2708 let offer = peer
2424 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
2709 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
2425 .await
2710 .await
2426 .map_err(|error| Error::Webrtc(error.to_string()))?;
2711 .map_err(|error| Error::Webrtc(error.to_string()))?;
2427 let text = directions_for(layout, false, camera, share, camera_mid, &offer.to_string());
2712 let offer_text = offer.to_string();
2713 let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text));
2714 let remote_shares = share_mid.as_deref().is_some_and(|mid| {
2715 peer.current_remote_description()
2716 .and_then(|remote| direction_of(&remote.to_string(), mid))
2717 .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
2718 });
2719 let text = directions_for(layout, false, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &offer_text);
2428 let description = parse_sdp(&text, SdpType::Offer)?;
2720 let description = parse_sdp(&text, SdpType::Offer)?;
2429 peer.set_local_description(description)
2721 peer.set_local_description(description)
2430 .await
2722 .await
2431 .map_err(|error| Error::Webrtc(error.to_string()))?;
2723 .map_err(|error| Error::Webrtc(error.to_string()))?;
2432 let mut numbers = random_u32;
2724 let mut numbers = random_u32;
2433 let signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, &text), plan, &mut numbers)?;
2725 let mut plan = plan.clone();
2726 if let Some(mid) = share_mid.as_ref().filter(|mid| !plan.screen_share_mids.contains(mid)) {
2727 plan.screen_share_mids.push(mid.clone());
2728 }
2729 let mut signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &text), &plan, &mut numbers)?;
2730 signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
2731 if gathered.is_some()
2732 && let Some(role) = negotiated_setup(
2733 peer.current_local_description().map(|local| local.to_string()).as_deref(),
2734 peer.current_remote_description().map(|remote| remote.to_string()).as_deref(),
2735 )
2736 {
2737 signaled.sdp = signaled.sdp.replace("a=setup:actpass", &format!("a=setup:{role}"));
2738 }
2434 Ok((text, signaled))
2739 Ok((text, signaled))
2435}
2740}
2436
2741
@@ -2449,6 +2754,16 @@ async fn rollback_offer(peer: &PeerConnection) {
2449 }
2754 }
2450}
2755}
2451
2756
2757async fn rollback_remote_offer(peer: &PeerConnection) {
2758 if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
2759 let _ = peer.set_remote_description(rollback).await;
2760 }
2761}
2762
2763fn is_glare_rejection(body: &serde_json::Value) -> bool {
2764 body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE)
2765}
2766
2452fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2767fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2453 let links = &body["mediaNegotiation"]["links"];
2768 let links = &body["mediaNegotiation"]["links"];
2454 ["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
2769 ["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
@@ -2476,6 +2791,29 @@ mod reply_tag_tests {
2476 }
2791 }
2477}
2792}
2478
2793
2794fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
2795 match change {
2796 Change::Camera(true) => {
2797 control.send(CallUpdate::Camera(true));
2798 deferred.push(change);
2799 }
2800 Change::Share(true) => deferred.push(change),
2801 change => undo_change(change, local_video, control),
2802 }
2803}
2804
2805/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
2806fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut MediaNegotiator, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
2807 if server {
2808 negotiator.server_escalation_failed();
2809 for change in deferred.drain(..) {
2810 undo_change(change, local_video, control);
2811 }
2812 } else if layout == Layout::OneToOne {
2813 drop_local_media(local_video, control);
2814 }
2815}
2816
2479fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2817fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2480 if local_video.sharing() {
2818 if local_video.sharing() {
2481 local_video.stop_share();
2819 local_video.stop_share();
@@ -3235,7 +3573,7 @@ mod tests {
3235 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
3573 let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
3236 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3574 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3237 let track = factory.create_audio_track("microphone", source);
3575 let track = factory.create_audio_track("microphone", source);
3238 let offer = create_offer(&peer, &factory, &track, layout).await;
3576 let offer = create_offer(&peer, &factory, &track, layout, None).await;
3239 peer.close();
3577 peer.close();
3240 offer
3578 offer
3241 }
3579 }
@@ -3258,7 +3596,7 @@ mod tests {
3258 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3596 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3259 let track = factory.create_audio_track("microphone", source);
3597 let track = factory.create_audio_track("microphone", source);
3260 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3598 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3261 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, false, false).await;
3599 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, None, false, None).await;
3262 peer.close();
3600 peer.close();
3263 if let Err(error) = answered {
3601 if let Err(error) = answered {
3264 panic!("{error}");
3602 panic!("{error}");
@@ -3267,22 +3605,22 @@ mod tests {
3267
3605
3268 #[test]
3606 #[test]
3269 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3607 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3270 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3608 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3271 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
3609 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
3272 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);
3610 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);
3273 }
3611 }
3274
3612
3275 #[test]
3613 #[test]
3276 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3614 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3277 for layout in [Layout::OneToOne, Layout::Conference] {
3615 for layout in [Layout::OneToOne, Layout::Conference] {
3278 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3616 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, None, false, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3279 }
3617 }
3280 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, BROWSER_OFFER), BROWSER_OFFER);
3618 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, None, false, BROWSER_OFFER), BROWSER_OFFER);
3281 }
3619 }
3282
3620
3283 #[test]
3621 #[test]
3284 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3622 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3285 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, BROWSER_OFFER);
3623 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, None, false, BROWSER_OFFER);
3286 let mut numbers = || 7;
3624 let mut numbers = || 7;
3287 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
3625 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
3288 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
3626 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
crates/calling/src/candidates.rs added +197 −0
@@ -0,0 +1,197 @@
1 use crate::sdp::{self, Attribute};
2
3 pub fn teams_candidate(browser: &str) -> Option<String> {
4 let line = browser.trim().trim_start_matches("a=").trim_start_matches("candidate:");
5 let tokens: Vec<&str> = line.split_whitespace().collect();
6 let [foundation, component, transport, priority, address, port, "typ", kind, rest @ ..] = tokens.as_slice() else {
7 return None;
8 };
9 if address.ends_with(".local") {
10 return None;
11 }
12 let mut related = Vec::new();
13 let mut tcp_type = None;
14 for pair in rest.chunks(2) {
15 match pair {
16 ["raddr", value] | ["rport", value] => related.push(format!("{} {value}", pair[0])),
17 ["tcptype", value] => tcp_type = Some(*value),
18 _ => {}
19 }
20 }
21 let transport = match (transport.to_ascii_lowercase().as_str(), tcp_type) {
22 ("udp", _) => "UDP",
23 ("tcp", Some("active")) => "TCP-ACT",
24 ("tcp", Some("passive")) => "TCP-PASS",
25 ("tcp", Some("so")) => "TCP-SO",
26 _ => return None,
27 };
28 let mut text = format!("{foundation} {component} {transport} {priority} {address} {port} typ {kind}");
29 for part in related {
30 text.push(' ');
31 text.push_str(&part);
32 }
33 Some(text)
34 }
35
36 fn candidate_ufrag(browser: &str) -> Option<&str> {
37 let tokens: Vec<&str> = browser.split_whitespace().collect();
38 tokens.windows(2).find(|pair| pair[0] == "ufrag").map(|pair| pair[1])
39 }
40
41 pub fn is_udp_relay(browser: &str) -> bool {
42 let lower = browser.to_ascii_lowercase();
43 lower.contains(" udp ") && lower.contains(" typ relay")
44 }
45
46 struct DefaultAddress {
47 address: String,
48 port: String,
49 }
50
51 fn default_address(candidates: &[String]) -> Option<DefaultAddress> {
52 let rank = |kind: &str| match kind {
53 "relay" => 0,
54 "srflx" => 1,
55 _ => 2,
56 };
57 candidates
58 .iter()
59 .filter_map(|candidate| {
60 let tokens: Vec<&str> = candidate.split_whitespace().collect();
61 (tokens.get(1) == Some(&"1")).then_some(())?;
62 let transport_rank = if tokens.get(2) == Some(&"UDP") { 0 } else { 1 };
63 Some(((transport_rank, rank(tokens.get(7)?)), tokens.get(4)?.to_string(), tokens.get(5)?.to_string()))
64 })
65 .min_by_key(|(rank, _, _)| *rank)
66 .map(|(_, address, port)| DefaultAddress { address, port })
67 }
68
69 fn connection_for(address: &str) -> String {
70 if address.contains(':') { format!("IN IP6 {address}") } else { format!("IN IP4 {address}") }
71 }
72
73 /// Replaces the placeholder transport of a signaled SDP with the gathered candidates, for a peer that is not the mixer.
74 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
75 pub enum SdpKind {
76 Offer,
77 Answer,
78 }
79
80 fn settled_role(sdp: &str) -> Option<&str> {
81 sdp.lines()
82 .filter_map(|line| line.trim_end_matches('\r').strip_prefix("a=setup:"))
83 .find(|role| matches!(*role, "active" | "passive"))
84 }
85
86 /// The DTLS role this side took in the last negotiation; Teams keeps it in re-offers instead of `actpass`.
87 pub fn negotiated_setup(local_sdp: Option<&str>, remote_sdp: Option<&str>) -> Option<String> {
88 if let Some(role) = local_sdp.and_then(settled_role) {
89 return Some(role.to_owned());
90 }
91 match remote_sdp.and_then(settled_role)? {
92 "active" => Some("passive".to_owned()),
93 _ => Some("active".to_owned()),
94 }
95 }
96
97 pub fn with_candidates(teams_sdp: &str, browser_candidates: &[String], kind: SdpKind) -> crate::error::Result<String> {
98 let mut description = sdp::parse(teams_sdp)?;
99 let ufrag = description.media.first().and_then(|media| media.value("ice-ufrag")).map(str::to_owned);
100 let candidates: Vec<String> = browser_candidates
101 .iter()
102 .filter(|candidate| ufrag.as_deref().is_none_or(|ufrag| candidate_ufrag(candidate).is_none_or(|own| own == ufrag)))
103 .filter_map(|candidate| teams_candidate(candidate))
104 .collect();
105 let Some(default) = default_address(&candidates) else {
106 return Ok(teams_sdp.to_owned());
107 };
108 let connection = connection_for(&default.address);
109 if description.session.connection.is_some() {
110 description.session.connection = Some(connection.clone());
111 }
112 for media in &mut description.media {
113 if media.port == "0" {
114 continue;
115 }
116 media.port = default.port.clone();
117 media.connection = Some(connection.clone());
118 let carried_candidates = media.attributes.iter().any(|attribute| attribute.name == "candidate");
119 let mut attributes = Vec::with_capacity(media.attributes.len() + candidates.len());
120 for attribute in media.attributes.drain(..) {
121 match attribute.name.as_str() {
122 "candidate" => {}
123 "rtcp" if kind == SdpKind::Offer => attributes.push(Attribute::with_value("rtcp", &default.port)),
124 "rtcp" => {}
125 _ => attributes.push(attribute),
126 }
127 }
128 if carried_candidates {
129 let position = attributes.iter().position(|attribute| attribute.name == "ssrc" || attribute.name == "label").unwrap_or(attributes.len());
130 for (offset, candidate) in candidates.iter().enumerate() {
131 attributes.insert(position + offset, Attribute::with_value("candidate", candidate));
132 }
133 }
134 media.attributes = attributes;
135 }
136 Ok(sdp::write(&description))
137 }
138
139 #[cfg(test)]
140 mod tests {
141 use super::*;
142
143 #[test]
144 fn browser_candidates_take_the_teams_form() {
145 assert_eq!(
146 teams_candidate("candidate:842163049 1 udp 1677729535 203.0.113.7 61001 typ srflx raddr 10.0.0.2 rport 61001 generation 0 ufrag abc network-id 1 network-cost 10").as_deref(),
147 Some("842163049 1 UDP 1677729535 203.0.113.7 61001 typ srflx raddr 10.0.0.2 rport 61001")
148 );
149 assert_eq!(
150 teams_candidate("a=candidate:1 1 tcp 1518280447 10.0.0.2 9 typ host tcptype active generation 0").as_deref(),
151 Some("1 1 TCP-ACT 1518280447 10.0.0.2 9 typ host")
152 );
153 assert_eq!(teams_candidate("candidate:2 1 udp 2122260223 abcd-1234.local 50000 typ host generation 0"), None);
154 }
155
156 #[test]
157 fn the_relay_candidate_becomes_the_default_transport() {
158 let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nc=IN IP4 10.10.10.10\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtcp:1234\r\na=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\r\na=rtpmap:111 opus/48000/2\r\na=label:main-audio\r\na=mid:0\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtcp:1234\r\na=rtpmap:102 H264/90000\r\na=label:main-video\r\na=mid:1\r\nm=video 0 RTP/SAVP 102\r\na=mid:2\r\n";
159 let gathered = vec![
160 "candidate:1 1 udp 2122260223 10.0.0.2 50000 typ host generation 0".to_owned(),
161 "candidate:2 1 udp 1677729535 203.0.113.7 61001 typ srflx raddr 10.0.0.2 rport 50000".to_owned(),
162 "candidate:3 1 udp 41885439 52.114.0.9 3480 typ relay raddr 203.0.113.7 rport 61001".to_owned(),
163 ];
164 let text = with_candidates(teams, &gathered, SdpKind::Offer).unwrap();
165 assert!(text.contains("m=audio 3480 RTP/SAVP 111"));
166 assert!(text.contains("m=video 3480 RTP/SAVP 102"));
167 assert!(text.contains("m=video 0 RTP/SAVP 102"));
168 assert!(text.contains("c=IN IP4 52.114.0.9"));
169 assert!(text.contains("a=rtcp:3480"));
170 assert!(!text.contains("10.10.10.10"));
171 assert_eq!(text.matches("a=candidate:").count(), 3);
172 assert!(text.contains("a=candidate:3 1 UDP 41885439 52.114.0.9 3480 typ relay raddr 203.0.113.7 rport 61001"));
173 }
174
175 #[test]
176 fn old_ice_generations_and_tcp_only_gathering_are_handled() {
177 let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=ice-ufrag:new\r\na=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\r\na=mid:0\r\n";
178 let gathered = vec![
179 "candidate:1 1 udp 2122260223 10.0.0.2 50000 typ host generation 0 ufrag old".to_owned(),
180 "candidate:2 1 tcp 1518280447 10.0.0.2 9 typ host tcptype active generation 0 ufrag new".to_owned(),
181 ];
182 let text = with_candidates(teams, &gathered, SdpKind::Offer).unwrap();
183 assert!(!text.contains("50000"));
184 assert!(text.contains("m=audio 9 RTP/SAVP 111"));
185 assert!(text.contains("a=candidate:2 1 TCP-ACT 1518280447 10.0.0.2 9 typ host"));
186 assert!(is_udp_relay("candidate:3 1 udp 41885439 52.114.0.9 3480 typ relay raddr 1.2.3.4 rport 5"));
187 assert!(!is_udp_relay("candidate:3 1 tcp 41885439 52.114.0.9 443 typ relay tcptype passive"));
188 }
189
190 #[test]
191 fn without_candidates_the_sdp_stays_as_it_is() {
192 assert_eq!(with_candidates("v=0\r\n", &[], SdpKind::Offer).unwrap(), "v=0\r\n");
193 assert_eq!(negotiated_setup(Some("v=0\r\na=setup:actpass\r\na=setup:active\r\n"), None).as_deref(), Some("active"));
194 assert_eq!(negotiated_setup(Some("a=setup:actpass\r\n"), Some("a=setup:active\r\n")).as_deref(), Some("passive"));
195 assert_eq!(negotiated_setup(Some("a=setup:actpass\r\n"), None), None);
196 }
197 }
@@ -0,0 +1,197 @@
1use crate::sdp::{self, Attribute};
2
3pub fn teams_candidate(browser: &str) -> Option<String> {
4 let line = browser.trim().trim_start_matches("a=").trim_start_matches("candidate:");
5 let tokens: Vec<&str> = line.split_whitespace().collect();
6 let [foundation, component, transport, priority, address, port, "typ", kind, rest @ ..] = tokens.as_slice() else {
7 return None;
8 };
9 if address.ends_with(".local") {
10 return None;
11 }
12 let mut related = Vec::new();
13 let mut tcp_type = None;
14 for pair in rest.chunks(2) {
15 match pair {
16 ["raddr", value] | ["rport", value] => related.push(format!("{} {value}", pair[0])),
17 ["tcptype", value] => tcp_type = Some(*value),
18 _ => {}
19 }
20 }
21 let transport = match (transport.to_ascii_lowercase().as_str(), tcp_type) {
22 ("udp", _) => "UDP",
23 ("tcp", Some("active")) => "TCP-ACT",
24 ("tcp", Some("passive")) => "TCP-PASS",
25 ("tcp", Some("so")) => "TCP-SO",
26 _ => return None,
27 };
28 let mut text = format!("{foundation} {component} {transport} {priority} {address} {port} typ {kind}");
29 for part in related {
30 text.push(' ');
31 text.push_str(&part);
32 }
33 Some(text)
34}
35
36fn candidate_ufrag(browser: &str) -> Option<&str> {
37 let tokens: Vec<&str> = browser.split_whitespace().collect();
38 tokens.windows(2).find(|pair| pair[0] == "ufrag").map(|pair| pair[1])
39}
40
41pub fn is_udp_relay(browser: &str) -> bool {
42 let lower = browser.to_ascii_lowercase();
43 lower.contains(" udp ") && lower.contains(" typ relay")
44}
45
46struct DefaultAddress {
47 address: String,
48 port: String,
49}
50
51fn default_address(candidates: &[String]) -> Option<DefaultAddress> {
52 let rank = |kind: &str| match kind {
53 "relay" => 0,
54 "srflx" => 1,
55 _ => 2,
56 };
57 candidates
58 .iter()
59 .filter_map(|candidate| {
60 let tokens: Vec<&str> = candidate.split_whitespace().collect();
61 (tokens.get(1) == Some(&"1")).then_some(())?;
62 let transport_rank = if tokens.get(2) == Some(&"UDP") { 0 } else { 1 };
63 Some(((transport_rank, rank(tokens.get(7)?)), tokens.get(4)?.to_string(), tokens.get(5)?.to_string()))
64 })
65 .min_by_key(|(rank, _, _)| *rank)
66 .map(|(_, address, port)| DefaultAddress { address, port })
67}
68
69fn connection_for(address: &str) -> String {
70 if address.contains(':') { format!("IN IP6 {address}") } else { format!("IN IP4 {address}") }
71}
72
73/// Replaces the placeholder transport of a signaled SDP with the gathered candidates, for a peer that is not the mixer.
74#[derive(Debug, Clone, Copy, PartialEq, Eq)]
75pub enum SdpKind {
76 Offer,
77 Answer,
78}
79
80fn settled_role(sdp: &str) -> Option<&str> {
81 sdp.lines()
82 .filter_map(|line| line.trim_end_matches('\r').strip_prefix("a=setup:"))
83 .find(|role| matches!(*role, "active" | "passive"))
84}
85
86/// The DTLS role this side took in the last negotiation; Teams keeps it in re-offers instead of `actpass`.
87pub fn negotiated_setup(local_sdp: Option<&str>, remote_sdp: Option<&str>) -> Option<String> {
88 if let Some(role) = local_sdp.and_then(settled_role) {
89 return Some(role.to_owned());
90 }
91 match remote_sdp.and_then(settled_role)? {
92 "active" => Some("passive".to_owned()),
93 _ => Some("active".to_owned()),
94 }
95}
96
97pub fn with_candidates(teams_sdp: &str, browser_candidates: &[String], kind: SdpKind) -> crate::error::Result<String> {
98 let mut description = sdp::parse(teams_sdp)?;
99 let ufrag = description.media.first().and_then(|media| media.value("ice-ufrag")).map(str::to_owned);
100 let candidates: Vec<String> = browser_candidates
101 .iter()
102 .filter(|candidate| ufrag.as_deref().is_none_or(|ufrag| candidate_ufrag(candidate).is_none_or(|own| own == ufrag)))
103 .filter_map(|candidate| teams_candidate(candidate))
104 .collect();
105 let Some(default) = default_address(&candidates) else {
106 return Ok(teams_sdp.to_owned());
107 };
108 let connection = connection_for(&default.address);
109 if description.session.connection.is_some() {
110 description.session.connection = Some(connection.clone());
111 }
112 for media in &mut description.media {
113 if media.port == "0" {
114 continue;
115 }
116 media.port = default.port.clone();
117 media.connection = Some(connection.clone());
118 let carried_candidates = media.attributes.iter().any(|attribute| attribute.name == "candidate");
119 let mut attributes = Vec::with_capacity(media.attributes.len() + candidates.len());
120 for attribute in media.attributes.drain(..) {
121 match attribute.name.as_str() {
122 "candidate" => {}
123 "rtcp" if kind == SdpKind::Offer => attributes.push(Attribute::with_value("rtcp", &default.port)),
124 "rtcp" => {}
125 _ => attributes.push(attribute),
126 }
127 }
128 if carried_candidates {
129 let position = attributes.iter().position(|attribute| attribute.name == "ssrc" || attribute.name == "label").unwrap_or(attributes.len());
130 for (offset, candidate) in candidates.iter().enumerate() {
131 attributes.insert(position + offset, Attribute::with_value("candidate", candidate));
132 }
133 }
134 media.attributes = attributes;
135 }
136 Ok(sdp::write(&description))
137}
138
139#[cfg(test)]
140mod tests {
141 use super::*;
142
143 #[test]
144 fn browser_candidates_take_the_teams_form() {
145 assert_eq!(
146 teams_candidate("candidate:842163049 1 udp 1677729535 203.0.113.7 61001 typ srflx raddr 10.0.0.2 rport 61001 generation 0 ufrag abc network-id 1 network-cost 10").as_deref(),
147 Some("842163049 1 UDP 1677729535 203.0.113.7 61001 typ srflx raddr 10.0.0.2 rport 61001")
148 );
149 assert_eq!(
150 teams_candidate("a=candidate:1 1 tcp 1518280447 10.0.0.2 9 typ host tcptype active generation 0").as_deref(),
151 Some("1 1 TCP-ACT 1518280447 10.0.0.2 9 typ host")
152 );
153 assert_eq!(teams_candidate("candidate:2 1 udp 2122260223 abcd-1234.local 50000 typ host generation 0"), None);
154 }
155
156 #[test]
157 fn the_relay_candidate_becomes_the_default_transport() {
158 let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nc=IN IP4 10.10.10.10\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtcp:1234\r\na=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\r\na=rtpmap:111 opus/48000/2\r\na=label:main-audio\r\na=mid:0\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtcp:1234\r\na=rtpmap:102 H264/90000\r\na=label:main-video\r\na=mid:1\r\nm=video 0 RTP/SAVP 102\r\na=mid:2\r\n";
159 let gathered = vec![
160 "candidate:1 1 udp 2122260223 10.0.0.2 50000 typ host generation 0".to_owned(),
161 "candidate:2 1 udp 1677729535 203.0.113.7 61001 typ srflx raddr 10.0.0.2 rport 50000".to_owned(),
162 "candidate:3 1 udp 41885439 52.114.0.9 3480 typ relay raddr 203.0.113.7 rport 61001".to_owned(),
163 ];
164 let text = with_candidates(teams, &gathered, SdpKind::Offer).unwrap();
165 assert!(text.contains("m=audio 3480 RTP/SAVP 111"));
166 assert!(text.contains("m=video 3480 RTP/SAVP 102"));
167 assert!(text.contains("m=video 0 RTP/SAVP 102"));
168 assert!(text.contains("c=IN IP4 52.114.0.9"));
169 assert!(text.contains("a=rtcp:3480"));
170 assert!(!text.contains("10.10.10.10"));
171 assert_eq!(text.matches("a=candidate:").count(), 3);
172 assert!(text.contains("a=candidate:3 1 UDP 41885439 52.114.0.9 3480 typ relay raddr 203.0.113.7 rport 61001"));
173 }
174
175 #[test]
176 fn old_ice_generations_and_tcp_only_gathering_are_handled() {
177 let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=ice-ufrag:new\r\na=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\r\na=mid:0\r\n";
178 let gathered = vec![
179 "candidate:1 1 udp 2122260223 10.0.0.2 50000 typ host generation 0 ufrag old".to_owned(),
180 "candidate:2 1 tcp 1518280447 10.0.0.2 9 typ host tcptype active generation 0 ufrag new".to_owned(),
181 ];
182 let text = with_candidates(teams, &gathered, SdpKind::Offer).unwrap();
183 assert!(!text.contains("50000"));
184 assert!(text.contains("m=audio 9 RTP/SAVP 111"));
185 assert!(text.contains("a=candidate:2 1 TCP-ACT 1518280447 10.0.0.2 9 typ host"));
186 assert!(is_udp_relay("candidate:3 1 udp 41885439 52.114.0.9 3480 typ relay raddr 1.2.3.4 rport 5"));
187 assert!(!is_udp_relay("candidate:3 1 tcp 41885439 52.114.0.9 443 typ relay tcptype passive"));
188 }
189
190 #[test]
191 fn without_candidates_the_sdp_stays_as_it_is() {
192 assert_eq!(with_candidates("v=0\r\n", &[], SdpKind::Offer).unwrap(), "v=0\r\n");
193 assert_eq!(negotiated_setup(Some("v=0\r\na=setup:actpass\r\na=setup:active\r\n"), None).as_deref(), Some("active"));
194 assert_eq!(negotiated_setup(Some("a=setup:actpass\r\n"), Some("a=setup:active\r\n")).as_deref(), Some("passive"));
195 assert_eq!(negotiated_setup(Some("a=setup:actpass\r\n"), None), None);
196 }
197}
crates/calling/src/hold.rs +28 −0
@@ -70,6 +70,15 @@ pub fn rewrite_directions(sdp: &str, pick: impl Fn(MediaLine<'_>) -> Option<&'st
70 70 lines.join(newline)
71 71 }
72 72
73 pub fn direction_of(sdp: &str, mid: &str) -> Option<String> {
74 let lines: Vec<String> = sdp.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();
75 sections(&lines)
76 .into_iter()
77 .find(|section| section.mid == mid)
78 .and_then(|section| section.direction_line)
79 .and_then(|line| lines[line].strip_prefix("a=").map(str::to_owned))
80 }
81
73 82 pub fn stop_sending_on(sdp: &str, mid: &str) -> String {
74 83 let newline = if sdp.contains("\r\n") { "\r\n" } else { "\n" };
75 84 let mut lines: Vec<String> = sdp.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();
@@ -137,6 +146,16 @@ pub fn offer_sends_video(teams_sdp: &str) -> bool {
137 146 })
138 147 }
139 148
149 pub fn offer_modalities(video: bool, sharing: bool) -> Vec<String> {
150 let mut modalities = accepted_modalities(video);
151 if sharing {
152 modalities.push(SCREEN_SHARER.to_owned());
153 }
154 modalities
155 }
156
157 const SCREEN_SHARER: &str = "ScreenSharer";
158
140 159 pub fn accepted_modalities(video: bool) -> Vec<String> {
141 160 let mut modalities = vec!["Audio".to_owned()];
142 161 if video {
@@ -147,6 +166,13 @@ pub fn accepted_modalities(video: bool) -> Vec<String> {
147 166
148 167 #[cfg(test)]
149 168 mod tests {
169 #[test]
170 fn the_direction_of_a_line_is_read_by_mid() {
171 let sdp = "v=0\r\nm=audio 9 RTP 0\r\na=mid:0\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:2\r\na=recvonly\r\n";
172 assert_eq!(super::direction_of(sdp, "2").as_deref(), Some("recvonly"));
173 assert_eq!(super::direction_of(sdp, "7"), None);
174 }
175
150 176 #[test]
151 177 fn a_line_that_stops_sending_keeps_receiving() {
152 178 let sdp = "v=0\r\nm=audio 9 RTP 0\r\na=mid:0\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:1\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:2\r\na=sendonly\r\n";
@@ -242,5 +268,7 @@ mod tests {
242 268 fn accepting_with_video_adds_the_modality() {
243 269 assert_eq!(accepted_modalities(false), vec!["Audio"]);
244 270 assert_eq!(accepted_modalities(true), vec!["Audio", "Video"]);
271 assert_eq!(super::offer_modalities(false, true), vec!["Audio", "ScreenSharer"]);
272 assert_eq!(super::offer_modalities(true, true), vec!["Audio", "Video", "ScreenSharer"]);
245 273 }
246 274 }
@@ -70,6 +70,15 @@ pub fn rewrite_directions(sdp: &str, pick: impl Fn(MediaLine<'_>) -> Option<&'st
70 lines.join(newline)
70 lines.join(newline)
71}
71}
72
72
73pub fn direction_of(sdp: &str, mid: &str) -> Option<String> {
74 let lines: Vec<String> = sdp.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();
75 sections(&lines)
76 .into_iter()
77 .find(|section| section.mid == mid)
78 .and_then(|section| section.direction_line)
79 .and_then(|line| lines[line].strip_prefix("a=").map(str::to_owned))
80}
81
73pub fn stop_sending_on(sdp: &str, mid: &str) -> String {
82pub fn stop_sending_on(sdp: &str, mid: &str) -> String {
74 let newline = if sdp.contains("\r\n") { "\r\n" } else { "\n" };
83 let newline = if sdp.contains("\r\n") { "\r\n" } else { "\n" };
75 let mut lines: Vec<String> = sdp.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();
84 let mut lines: Vec<String> = sdp.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();
@@ -137,6 +146,16 @@ pub fn offer_sends_video(teams_sdp: &str) -> bool {
137 })
146 })
138}
147}
139
148
149pub fn offer_modalities(video: bool, sharing: bool) -> Vec<String> {
150 let mut modalities = accepted_modalities(video);
151 if sharing {
152 modalities.push(SCREEN_SHARER.to_owned());
153 }
154 modalities
155}
156
157const SCREEN_SHARER: &str = "ScreenSharer";
158
140pub fn accepted_modalities(video: bool) -> Vec<String> {
159pub fn accepted_modalities(video: bool) -> Vec<String> {
141 let mut modalities = vec!["Audio".to_owned()];
160 let mut modalities = vec!["Audio".to_owned()];
142 if video {
161 if video {
@@ -147,6 +166,13 @@ pub fn accepted_modalities(video: bool) -> Vec<String> {
147
166
148#[cfg(test)]
167#[cfg(test)]
149mod tests {
168mod tests {
169 #[test]
170 fn the_direction_of_a_line_is_read_by_mid() {
171 let sdp = "v=0\r\nm=audio 9 RTP 0\r\na=mid:0\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:2\r\na=recvonly\r\n";
172 assert_eq!(super::direction_of(sdp, "2").as_deref(), Some("recvonly"));
173 assert_eq!(super::direction_of(sdp, "7"), None);
174 }
175
150 #[test]
176 #[test]
151 fn a_line_that_stops_sending_keeps_receiving() {
177 fn a_line_that_stops_sending_keeps_receiving() {
152 let sdp = "v=0\r\nm=audio 9 RTP 0\r\na=mid:0\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:1\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:2\r\na=sendonly\r\n";
178 let sdp = "v=0\r\nm=audio 9 RTP 0\r\na=mid:0\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:1\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:2\r\na=sendonly\r\n";
@@ -242,5 +268,7 @@ mod tests {
242 fn accepting_with_video_adds_the_modality() {
268 fn accepting_with_video_adds_the_modality() {
243 assert_eq!(accepted_modalities(false), vec!["Audio"]);
269 assert_eq!(accepted_modalities(false), vec!["Audio"]);
244 assert_eq!(accepted_modalities(true), vec!["Audio", "Video"]);
270 assert_eq!(accepted_modalities(true), vec!["Audio", "Video"]);
271 assert_eq!(super::offer_modalities(false, true), vec!["Audio", "ScreenSharer"]);
272 assert_eq!(super::offer_modalities(true, true), vec!["Audio", "Video", "ScreenSharer"]);
245 }
273 }
246}
274}
crates/calling/src/lib.rs +1 −0
@@ -2,6 +2,7 @@ pub mod audio;
2 2 pub mod audio_io;
3 3 pub mod background;
4 4 pub mod call;
5 pub mod candidates;
5 6 pub mod callee_gate;
6 7 pub mod blur;
7 8 pub mod breakout;
@@ -2,6 +2,7 @@ pub mod audio;
2pub mod audio_io;
2pub mod audio_io;
3pub mod background;
3pub mod background;
4pub mod call;
4pub mod call;
5pub mod candidates;
5pub mod callee_gate;
6pub mod callee_gate;
6pub mod blur;
7pub mod blur;
7pub mod breakout;
8pub mod breakout;
crates/calling/src/renegotiation.rs +33 −1
@@ -23,6 +23,7 @@ pub struct MediaNegotiator {
23 23 path: MediaPath,
24 24 own_offer_pending: bool,
25 25 same_peer_offer_pending: bool,
26 path_before_server_escalation: Option<MediaPath>,
26 27 }
27 28
28 29 impl Default for MediaNegotiator {
@@ -31,6 +32,7 @@ impl Default for MediaNegotiator {
31 32 path: MediaPath::Pending,
32 33 own_offer_pending: false,
33 34 same_peer_offer_pending: false,
35 path_before_server_escalation: None,
34 36 }
35 37 }
36 38 }
@@ -88,11 +90,13 @@ impl MediaNegotiator {
88 90 }
89 91
90 92 pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {
91 if self.own_offer_pending || (self.same_peer_offer_pending && !escalation) {
93 let new_peer = new_offer || escalation;
94 if (self.own_offer_pending && new_peer) || (self.same_peer_offer_pending && !escalation) {
92 95 return MediaAction::RejectGlare;
93 96 }
94 97 self.same_peer_offer_pending = false;
95 98 if escalation {
99 self.path_before_server_escalation.get_or_insert(self.path);
96 100 self.path = MediaPath::Mixer;
97 101 }
98 102 if new_offer || escalation {
@@ -102,6 +106,16 @@ impl MediaNegotiator {
102 106 }
103 107 }
104 108
109 pub fn server_escalation_failed(&mut self) {
110 if let Some(path) = self.path_before_server_escalation.take() {
111 self.path = path;
112 }
113 }
114
115 pub fn server_escalation_done(&mut self) {
116 self.path_before_server_escalation = None;
117 }
118
105 119 pub fn escalation_failed(&mut self) {
106 120 self.own_offer_pending = false;
107 121 }
@@ -174,6 +188,24 @@ mod tests {
174 188 assert!(!negotiator.begin_conference_upgrade());
175 189 }
176 190
191 #[test]
192 fn a_failed_server_escalation_goes_back_to_the_direct_path() {
193 let mut negotiator = MediaNegotiator::default();
194 negotiator.on_acceptance(false, true);
195 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::AnswerOnNewPeer);
196 assert_eq!(negotiator.path(), MediaPath::Mixer);
197 negotiator.server_escalation_failed();
198 assert_eq!(negotiator.path(), MediaPath::Direct);
199 }
200
201 #[test]
202 fn a_remote_same_peer_offer_is_answered_while_our_escalation_runs() {
203 let mut negotiator = MediaNegotiator::default();
204 assert_eq!(negotiator.on_acceptance(true, true), MediaAction::ApplyAnswerThenEscalate);
205 assert_eq!(negotiator.on_renegotiation(false, false), MediaAction::AnswerOnSamePeer);
206 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::RejectGlare);
207 }
208
177 209 #[test]
178 210 fn a_rejection_clears_the_pending_offer() {
179 211 let mut negotiator = MediaNegotiator::default();
@@ -23,6 +23,7 @@ pub struct MediaNegotiator {
23 path: MediaPath,
23 path: MediaPath,
24 own_offer_pending: bool,
24 own_offer_pending: bool,
25 same_peer_offer_pending: bool,
25 same_peer_offer_pending: bool,
26 path_before_server_escalation: Option<MediaPath>,
26}
27}
27
28
28impl Default for MediaNegotiator {
29impl Default for MediaNegotiator {
@@ -31,6 +32,7 @@ impl Default for MediaNegotiator {
31 path: MediaPath::Pending,
32 path: MediaPath::Pending,
32 own_offer_pending: false,
33 own_offer_pending: false,
33 same_peer_offer_pending: false,
34 same_peer_offer_pending: false,
35 path_before_server_escalation: None,
34 }
36 }
35 }
37 }
36}
38}
@@ -88,11 +90,13 @@ impl MediaNegotiator {
88 }
90 }
89
91
90 pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {
92 pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {
91 if self.own_offer_pending || (self.same_peer_offer_pending && !escalation) {
93 let new_peer = new_offer || escalation;
94 if (self.own_offer_pending && new_peer) || (self.same_peer_offer_pending && !escalation) {
92 return MediaAction::RejectGlare;
95 return MediaAction::RejectGlare;
93 }
96 }
94 self.same_peer_offer_pending = false;
97 self.same_peer_offer_pending = false;
95 if escalation {
98 if escalation {
99 self.path_before_server_escalation.get_or_insert(self.path);
96 self.path = MediaPath::Mixer;
100 self.path = MediaPath::Mixer;
97 }
101 }
98 if new_offer || escalation {
102 if new_offer || escalation {
@@ -102,6 +106,16 @@ impl MediaNegotiator {
102 }
106 }
103 }
107 }
104
108
109 pub fn server_escalation_failed(&mut self) {
110 if let Some(path) = self.path_before_server_escalation.take() {
111 self.path = path;
112 }
113 }
114
115 pub fn server_escalation_done(&mut self) {
116 self.path_before_server_escalation = None;
117 }
118
105 pub fn escalation_failed(&mut self) {
119 pub fn escalation_failed(&mut self) {
106 self.own_offer_pending = false;
120 self.own_offer_pending = false;
107 }
121 }
@@ -174,6 +188,24 @@ mod tests {
174 assert!(!negotiator.begin_conference_upgrade());
188 assert!(!negotiator.begin_conference_upgrade());
175 }
189 }
176
190
191 #[test]
192 fn a_failed_server_escalation_goes_back_to_the_direct_path() {
193 let mut negotiator = MediaNegotiator::default();
194 negotiator.on_acceptance(false, true);
195 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::AnswerOnNewPeer);
196 assert_eq!(negotiator.path(), MediaPath::Mixer);
197 negotiator.server_escalation_failed();
198 assert_eq!(negotiator.path(), MediaPath::Direct);
199 }
200
201 #[test]
202 fn a_remote_same_peer_offer_is_answered_while_our_escalation_runs() {
203 let mut negotiator = MediaNegotiator::default();
204 assert_eq!(negotiator.on_acceptance(true, true), MediaAction::ApplyAnswerThenEscalate);
205 assert_eq!(negotiator.on_renegotiation(false, false), MediaAction::AnswerOnSamePeer);
206 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::RejectGlare);
207 }
208
177 #[test]
209 #[test]
178 fn a_rejection_clears_the_pending_offer() {
210 fn a_rejection_clears_the_pending_offer() {
179 let mut negotiator = MediaNegotiator::default();
211 let mut negotiator = MediaNegotiator::default();
crates/calling/src/roster.rs +25 −0
@@ -249,6 +249,23 @@ impl Roster {
249 249 }
250 250 }
251 251
252 /// Teams builds the roster of a direct call from `acceptedBy` because no mixer reports one; later mixer updates replace it.
253 pub fn direct_roster(members: &[(&str, &str)]) -> Value {
254 let participants: serde_json::Map<String, Value> = members
255 .iter()
256 .map(|(mri, name)| {
257 let participant = serde_json::json!({
258 "version": 0,
259 "state": ACTIVE,
260 "details": {"id": mri, "displayName": name},
261 "endpoints": {"direct": {"call": {"mediaStreams": []}}},
262 });
263 ((*mri).to_owned(), participant)
264 })
265 .collect();
266 serde_json::json!({"participants": participants})
267 }
268
252 269 fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&Member>) -> Member {
253 270 let display_name = participant["details"]["displayName"]
254 271 .as_str()
@@ -374,6 +391,14 @@ fn source_id(value: &Value) -> Option<u32> {
374 391
375 392 #[cfg(test)]
376 393 mod tests {
394 #[test]
395 fn a_direct_call_lists_both_people_until_the_mixer_reports() {
396 let mut roster = Roster::default();
397 assert!(roster.apply(&direct_roster(&[("8:orgid:me", "Me"), ("8:orgid:bea", "Bea")])));
398 assert_eq!(roster.members().len(), 2);
399 assert!(!roster.apply(&direct_roster(&[("8:orgid:me", "Me"), ("8:orgid:bea", "Bea")])));
400 }
401
377 402 use serde_json::json;
378 403
379 404 use super::*;
@@ -249,6 +249,23 @@ impl Roster {
249 }
249 }
250}
250}
251
251
252/// Teams builds the roster of a direct call from `acceptedBy` because no mixer reports one; later mixer updates replace it.
253pub fn direct_roster(members: &[(&str, &str)]) -> Value {
254 let participants: serde_json::Map<String, Value> = members
255 .iter()
256 .map(|(mri, name)| {
257 let participant = serde_json::json!({
258 "version": 0,
259 "state": ACTIVE,
260 "details": {"id": mri, "displayName": name},
261 "endpoints": {"direct": {"call": {"mediaStreams": []}}},
262 });
263 ((*mri).to_owned(), participant)
264 })
265 .collect();
266 serde_json::json!({"participants": participants})
267}
268
252fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&Member>) -> Member {
269fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&Member>) -> Member {
253 let display_name = participant["details"]["displayName"]
270 let display_name = participant["details"]["displayName"]
254 .as_str()
271 .as_str()
@@ -374,6 +391,14 @@ fn source_id(value: &Value) -> Option<u32> {
374
391
375#[cfg(test)]
392#[cfg(test)]
376mod tests {
393mod tests {
394 #[test]
395 fn a_direct_call_lists_both_people_until_the_mixer_reports() {
396 let mut roster = Roster::default();
397 assert!(roster.apply(&direct_roster(&[("8:orgid:me", "Me"), ("8:orgid:bea", "Bea")])));
398 assert_eq!(roster.members().len(), 2);
399 assert!(!roster.apply(&direct_roster(&[("8:orgid:me", "Me"), ("8:orgid:bea", "Bea")])));
400 }
401
377 use serde_json::json;
402 use serde_json::json;
378
403
379 use super::*;
404 use super::*;
crates/calling/src/sdp.rs +11 −1
@@ -24,6 +24,10 @@ pub struct Attribute {
24 24 }
25 25
26 26 impl Attribute {
27 pub fn with_value(name: &str, value: impl Into<String>) -> Self {
28 Attribute::new(name, value)
29 }
30
27 31 fn new(name: &str, value: impl Into<String>) -> Self {
28 32 Attribute {
29 33 name: name.to_owned(),
@@ -762,7 +766,7 @@ fn browser_rtp_line(
762 766 attributes.push(Attribute::flag(direction));
763 767 }
764 768 if carries_candidates {
765 attributes.extend(teams_line.values("candidate").map(|value| Attribute::new("candidate", browser_candidate(value))));
769 attributes.extend(teams_line.values("candidate").chain(teams_line.values("x-candidate-ipv6")).map(|value| Attribute::new("candidate", browser_candidate(value))));
766 770 }
767 771 let (primary, retransmission) = stream_ssrcs(teams_line, stream_index);
768 772 if let Some(primary) = primary {
@@ -821,6 +825,7 @@ fn browser_candidate(value: &str) -> String {
821 825 let tcp_type = match parts.get(2).map(|transport| transport.to_ascii_lowercase()).as_deref() {
822 826 Some("tcp-pass") => Some("passive"),
823 827 Some("tcp-act") => Some("active"),
828 Some("tcp-so") => Some("so"),
824 829 _ => None,
825 830 };
826 831 if tcp_type.is_some() {
@@ -993,6 +998,11 @@ fn browser_rtp_from_teams(source: &Media, mid: &str, folded: bool, carries_candi
993 998 let value = attribute.value.as_deref().unwrap_or_default();
994 999 match attribute.name.as_str() {
995 1000 name if TEAMS_ONLY_ATTRIBUTES.contains(&name) => {}
1001 "x-candidate-ipv6" => {
1002 if carries_candidate {
1003 attributes.push(Attribute::new("candidate", browser_candidate(value)));
1004 }
1005 }
996 1006 name if name.starts_with("x-") => {}
997 1007 "mid" | "rtcp-mux" => {}
998 1008 name if TRANSPORT_ATTRIBUTES.contains(&name) => {}
@@ -24,6 +24,10 @@ pub struct Attribute {
24}
24}
25
25
26impl Attribute {
26impl Attribute {
27 pub fn with_value(name: &str, value: impl Into<String>) -> Self {
28 Attribute::new(name, value)
29 }
30
27 fn new(name: &str, value: impl Into<String>) -> Self {
31 fn new(name: &str, value: impl Into<String>) -> Self {
28 Attribute {
32 Attribute {
29 name: name.to_owned(),
33 name: name.to_owned(),
@@ -762,7 +766,7 @@ fn browser_rtp_line(
762 attributes.push(Attribute::flag(direction));
766 attributes.push(Attribute::flag(direction));
763 }
767 }
764 if carries_candidates {
768 if carries_candidates {
765 attributes.extend(teams_line.values("candidate").map(|value| Attribute::new("candidate", browser_candidate(value))));
769 attributes.extend(teams_line.values("candidate").chain(teams_line.values("x-candidate-ipv6")).map(|value| Attribute::new("candidate", browser_candidate(value))));
766 }
770 }
767 let (primary, retransmission) = stream_ssrcs(teams_line, stream_index);
771 let (primary, retransmission) = stream_ssrcs(teams_line, stream_index);
768 if let Some(primary) = primary {
772 if let Some(primary) = primary {
@@ -821,6 +825,7 @@ fn browser_candidate(value: &str) -> String {
821 let tcp_type = match parts.get(2).map(|transport| transport.to_ascii_lowercase()).as_deref() {
825 let tcp_type = match parts.get(2).map(|transport| transport.to_ascii_lowercase()).as_deref() {
822 Some("tcp-pass") => Some("passive"),
826 Some("tcp-pass") => Some("passive"),
823 Some("tcp-act") => Some("active"),
827 Some("tcp-act") => Some("active"),
828 Some("tcp-so") => Some("so"),
824 _ => None,
829 _ => None,
825 };
830 };
826 if tcp_type.is_some() {
831 if tcp_type.is_some() {
@@ -993,6 +998,11 @@ fn browser_rtp_from_teams(source: &Media, mid: &str, folded: bool, carries_candi
993 let value = attribute.value.as_deref().unwrap_or_default();
998 let value = attribute.value.as_deref().unwrap_or_default();
994 match attribute.name.as_str() {
999 match attribute.name.as_str() {
995 name if TEAMS_ONLY_ATTRIBUTES.contains(&name) => {}
1000 name if TEAMS_ONLY_ATTRIBUTES.contains(&name) => {}
1001 "x-candidate-ipv6" => {
1002 if carries_candidate {
1003 attributes.push(Attribute::new("candidate", browser_candidate(value)));
1004 }
1005 }
996 name if name.starts_with("x-") => {}
1006 name if name.starts_with("x-") => {}
997 "mid" | "rtcp-mux" => {}
1007 "mid" | "rtcp-mux" => {}
998 name if TRANSPORT_ATTRIBUTES.contains(&name) => {}
1008 name if TRANSPORT_ATTRIBUTES.contains(&name) => {}
crates/calling/src/signaling.rs +51 −0
@@ -603,6 +603,10 @@ impl Signaling {
603 603 .map(|_| ())
604 604 }
605 605
606 pub async fn reject_renegotiation(&self, url: &str, from: &Participant, call_id: &str, failure: NegotiationFailure) -> Result<()> {
607 self.post_json("POST rejection (renegotiation)", url, negotiation_failure_body(from, call_id, failure)).await
608 }
609
606 610 pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> {
607 611 self.post_json("POST callLeg keep-alive", call_leg_url, json!({"callParticipantUpdate": {}}))
608 612 .await
@@ -666,6 +670,13 @@ fn media_controller_links(callbacks: &CallbackLinks) -> Value {
666 670 })
667 671 }
668 672
673 /// The 1:1 chat of two people: both object ids sorted as plain strings.
674 pub fn one_to_one_thread(own_object_id: &str, peer_mri: &str) -> Option<String> {
675 let peer = peer_mri.strip_prefix("8:orgid:")?;
676 let (first, second) = if own_object_id <= peer { (own_object_id, peer) } else { (peer, own_object_id) };
677 Some(format!("19:{first}_{second}{ONE_TO_ONE_THREAD_SUFFIX}"))
678 }
679
669 680 impl InviteTarget {
670 681 pub fn is_one_to_one(&self) -> bool {
671 682 match self {
@@ -844,6 +855,29 @@ pub fn acceptance_body(answer: &Answer<'_>) -> Value {
844 855 })
845 856 }
846 857
858 #[derive(Debug, Clone, Copy, PartialEq, Eq)]
859 pub enum NegotiationFailure {
860 InProgress,
861 AnswerError,
862 }
863
864 impl NegotiationFailure {
865 fn wire(self) -> (u16, u32, &'static str) {
866 match self {
867 NegotiationFailure::InProgress => (491, 3118, "NegotiationIsInProgress"),
868 NegotiationFailure::AnswerError => (488, 3102, "CallEndReasonMediaAnswerError"),
869 }
870 }
871 }
872
873 pub fn negotiation_failure_body(from: &Participant, call_id: &str, failure: NegotiationFailure) -> Value {
874 let (code, sub_code, phrase) = failure.wire();
875 json!({
876 "mediaNegotiationFailure": {"sender": from.wire(), "code": code, "subCode": sub_code, "phrase": phrase},
877 "debugContent": {"callId": call_id, "endpointId": from.endpoint_id},
878 })
879 }
880
847 881 pub fn renegotiation_body(
848 882 from: &Participant,
849 883 callbacks: &CallbackLinks,
@@ -1328,6 +1362,23 @@ mod tests {
1328 1362 assert_eq!(accepted["callKeepAliveInterval"], Value::Null);
1329 1363 }
1330 1364
1365 #[test]
1366 fn the_one_to_one_chat_sorts_both_ids() {
1367 assert_eq!(one_to_one_thread("f74e", "8:orgid:a1b2").as_deref(), Some("19:a1b2_f74e@unq.gbl.spaces"));
1368 assert_eq!(one_to_one_thread("a1b2", "8:orgid:f74e").as_deref(), Some("19:a1b2_f74e@unq.gbl.spaces"));
1369 assert_eq!(one_to_one_thread("a1b2", "28:bot"), None);
1370 }
1371
1372 #[test]
1373 fn a_refused_offer_says_why() {
1374 let body = negotiation_failure_body(&from(), "call-1", NegotiationFailure::InProgress);
1375 assert_eq!(body["mediaNegotiationFailure"]["code"], 491);
1376 assert_eq!(body["mediaNegotiationFailure"]["subCode"], 3118);
1377 assert_eq!(body["mediaNegotiationFailure"]["phrase"], "NegotiationIsInProgress");
1378 assert_eq!(body["debugContent"]["callId"], "call-1");
1379 assert_eq!(negotiation_failure_body(&from(), "c", NegotiationFailure::AnswerError)["mediaNegotiationFailure"]["code"], 488);
1380 }
1381
1331 1382 #[test]
1332 1383 fn renegotiation_messages_name_their_reply_links() {
1333 1384 let from = from();
@@ -603,6 +603,10 @@ impl Signaling {
603 .map(|_| ())
603 .map(|_| ())
604 }
604 }
605
605
606 pub async fn reject_renegotiation(&self, url: &str, from: &Participant, call_id: &str, failure: NegotiationFailure) -> Result<()> {
607 self.post_json("POST rejection (renegotiation)", url, negotiation_failure_body(from, call_id, failure)).await
608 }
609
606 pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> {
610 pub async fn keep_call_alive(&self, call_leg_url: &str) -> Result<()> {
607 self.post_json("POST callLeg keep-alive", call_leg_url, json!({"callParticipantUpdate": {}}))
611 self.post_json("POST callLeg keep-alive", call_leg_url, json!({"callParticipantUpdate": {}}))
608 .await
612 .await
@@ -666,6 +670,13 @@ fn media_controller_links(callbacks: &CallbackLinks) -> Value {
666 })
670 })
667}
671}
668
672
673/// The 1:1 chat of two people: both object ids sorted as plain strings.
674pub fn one_to_one_thread(own_object_id: &str, peer_mri: &str) -> Option<String> {
675 let peer = peer_mri.strip_prefix("8:orgid:")?;
676 let (first, second) = if own_object_id <= peer { (own_object_id, peer) } else { (peer, own_object_id) };
677 Some(format!("19:{first}_{second}{ONE_TO_ONE_THREAD_SUFFIX}"))
678}
679
669impl InviteTarget {
680impl InviteTarget {
670 pub fn is_one_to_one(&self) -> bool {
681 pub fn is_one_to_one(&self) -> bool {
671 match self {
682 match self {
@@ -844,6 +855,29 @@ pub fn acceptance_body(answer: &Answer<'_>) -> Value {
844 })
855 })
845}
856}
846
857
858#[derive(Debug, Clone, Copy, PartialEq, Eq)]
859pub enum NegotiationFailure {
860 InProgress,
861 AnswerError,
862}
863
864impl NegotiationFailure {
865 fn wire(self) -> (u16, u32, &'static str) {
866 match self {
867 NegotiationFailure::InProgress => (491, 3118, "NegotiationIsInProgress"),
868 NegotiationFailure::AnswerError => (488, 3102, "CallEndReasonMediaAnswerError"),
869 }
870 }
871}
872
873pub fn negotiation_failure_body(from: &Participant, call_id: &str, failure: NegotiationFailure) -> Value {
874 let (code, sub_code, phrase) = failure.wire();
875 json!({
876 "mediaNegotiationFailure": {"sender": from.wire(), "code": code, "subCode": sub_code, "phrase": phrase},
877 "debugContent": {"callId": call_id, "endpointId": from.endpoint_id},
878 })
879}
880
847pub fn renegotiation_body(
881pub fn renegotiation_body(
848 from: &Participant,
882 from: &Participant,
849 callbacks: &CallbackLinks,
883 callbacks: &CallbackLinks,
@@ -1328,6 +1362,23 @@ mod tests {
1328 assert_eq!(accepted["callKeepAliveInterval"], Value::Null);
1362 assert_eq!(accepted["callKeepAliveInterval"], Value::Null);
1329 }
1363 }
1330
1364
1365 #[test]
1366 fn the_one_to_one_chat_sorts_both_ids() {
1367 assert_eq!(one_to_one_thread("f74e", "8:orgid:a1b2").as_deref(), Some("19:a1b2_f74e@unq.gbl.spaces"));
1368 assert_eq!(one_to_one_thread("a1b2", "8:orgid:f74e").as_deref(), Some("19:a1b2_f74e@unq.gbl.spaces"));
1369 assert_eq!(one_to_one_thread("a1b2", "28:bot"), None);
1370 }
1371
1372 #[test]
1373 fn a_refused_offer_says_why() {
1374 let body = negotiation_failure_body(&from(), "call-1", NegotiationFailure::InProgress);
1375 assert_eq!(body["mediaNegotiationFailure"]["code"], 491);
1376 assert_eq!(body["mediaNegotiationFailure"]["subCode"], 3118);
1377 assert_eq!(body["mediaNegotiationFailure"]["phrase"], "NegotiationIsInProgress");
1378 assert_eq!(body["debugContent"]["callId"], "call-1");
1379 assert_eq!(negotiation_failure_body(&from(), "c", NegotiationFailure::AnswerError)["mediaNegotiationFailure"]["code"], 488);
1380 }
1381
1331 #[test]
1382 #[test]
1332 fn renegotiation_messages_name_their_reply_links() {
1383 fn renegotiation_messages_name_their_reply_links() {
1333 let from = from();
1384 let from = from();
crates/calling/src/trouter_events.rs +22 −0
@@ -92,6 +92,13 @@ pub struct Acceptance {
92 92 pub links: BTreeMap<String, String>,
93 93 pub controller_name: Option<String>,
94 94 pub keep_alive_seconds: Option<u64>,
95 pub accepted_by: Option<AcceptedBy>,
96 }
97
98 #[derive(Debug, Clone, PartialEq, Eq)]
99 pub struct AcceptedBy {
100 pub mri: String,
101 pub display_name: String,
95 102 }
96 103
97 104 impl Acceptance {
@@ -113,6 +120,7 @@ pub enum ProgressStatus {
113 120 pub struct MediaAnswer {
114 121 pub sdp: String,
115 122 pub from_mixer: bool,
123 pub no_ring_back: bool,
116 124 pub links: BTreeMap<String, String>,
117 125 }
118 126
@@ -264,6 +272,10 @@ fn acceptance(body: &Value) -> Result<Acceptance> {
264 272 links: string_links(&accepted["links"]),
265 273 controller_name: accepted["controllerName"].as_str().map(str::to_owned),
266 274 keep_alive_seconds: accepted["callKeepAliveInterval"].as_u64(),
275 accepted_by: accepted["acceptedBy"]["id"].as_str().map(|mri| AcceptedBy {
276 mri: mri.to_owned(),
277 display_name: accepted["acceptedBy"]["displayName"].as_str().unwrap_or_default().to_owned(),
278 }),
267 279 })
268 280 }
269 281
@@ -284,6 +296,7 @@ fn media_answer(body: &Value) -> Result<MediaAnswer> {
284 296 Ok(MediaAnswer {
285 297 sdp,
286 298 from_mixer: answer["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
299 no_ring_back: answer["noRingBack"].as_bool().unwrap_or(false),
287 300 links: string_links(&answer["links"]),
288 301 })
289 302 }
@@ -565,6 +578,15 @@ mod tests {
565 578 assert_eq!(end.accepted_elsewhere_by.as_deref(), Some("Daniel"));
566 579 }
567 580
581 #[test]
582 fn a_direct_acceptance_names_who_took_the_call() {
583 let body = json!({"callAcceptance": {"acceptedBy": {"id": "8:orgid:bea", "displayName": "Bea", "endpointId": "e"},
584 "mediaContent": {"blob": "v=0\r\n", "fromMixer": false}}});
585 let (_, event) = classify("callAgent/abc/1/call/acceptance/", body).unwrap();
586 let CallEvent::Acceptance(acceptance) = event else { panic!("not acceptance") };
587 assert_eq!(acceptance.accepted_by, Some(AcceptedBy { mri: "8:orgid:bea".into(), display_name: "Bea".into() }));
588 }
589
568 590 #[test]
569 591 fn acceptance_in_the_lobby_is_flagged() {
570 592 let body = json!({"callAcceptance": {"controllerName": "lobby", "callKeepAliveInterval": 2700,
@@ -92,6 +92,13 @@ pub struct Acceptance {
92 pub links: BTreeMap<String, String>,
92 pub links: BTreeMap<String, String>,
93 pub controller_name: Option<String>,
93 pub controller_name: Option<String>,
94 pub keep_alive_seconds: Option<u64>,
94 pub keep_alive_seconds: Option<u64>,
95 pub accepted_by: Option<AcceptedBy>,
96}
97
98#[derive(Debug, Clone, PartialEq, Eq)]
99pub struct AcceptedBy {
100 pub mri: String,
101 pub display_name: String,
95}
102}
96
103
97impl Acceptance {
104impl Acceptance {
@@ -113,6 +120,7 @@ pub enum ProgressStatus {
113pub struct MediaAnswer {
120pub struct MediaAnswer {
114 pub sdp: String,
121 pub sdp: String,
115 pub from_mixer: bool,
122 pub from_mixer: bool,
123 pub no_ring_back: bool,
116 pub links: BTreeMap<String, String>,
124 pub links: BTreeMap<String, String>,
117}
125}
118
126
@@ -264,6 +272,10 @@ fn acceptance(body: &Value) -> Result<Acceptance> {
264 links: string_links(&accepted["links"]),
272 links: string_links(&accepted["links"]),
265 controller_name: accepted["controllerName"].as_str().map(str::to_owned),
273 controller_name: accepted["controllerName"].as_str().map(str::to_owned),
266 keep_alive_seconds: accepted["callKeepAliveInterval"].as_u64(),
274 keep_alive_seconds: accepted["callKeepAliveInterval"].as_u64(),
275 accepted_by: accepted["acceptedBy"]["id"].as_str().map(|mri| AcceptedBy {
276 mri: mri.to_owned(),
277 display_name: accepted["acceptedBy"]["displayName"].as_str().unwrap_or_default().to_owned(),
278 }),
267 })
279 })
268}
280}
269
281
@@ -284,6 +296,7 @@ fn media_answer(body: &Value) -> Result<MediaAnswer> {
284 Ok(MediaAnswer {
296 Ok(MediaAnswer {
285 sdp,
297 sdp,
286 from_mixer: answer["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
298 from_mixer: answer["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
299 no_ring_back: answer["noRingBack"].as_bool().unwrap_or(false),
287 links: string_links(&answer["links"]),
300 links: string_links(&answer["links"]),
288 })
301 })
289}
302}
@@ -565,6 +578,15 @@ mod tests {
565 assert_eq!(end.accepted_elsewhere_by.as_deref(), Some("Daniel"));
578 assert_eq!(end.accepted_elsewhere_by.as_deref(), Some("Daniel"));
566 }
579 }
567
580
581 #[test]
582 fn a_direct_acceptance_names_who_took_the_call() {
583 let body = json!({"callAcceptance": {"acceptedBy": {"id": "8:orgid:bea", "displayName": "Bea", "endpointId": "e"},
584 "mediaContent": {"blob": "v=0\r\n", "fromMixer": false}}});
585 let (_, event) = classify("callAgent/abc/1/call/acceptance/", body).unwrap();
586 let CallEvent::Acceptance(acceptance) = event else { panic!("not acceptance") };
587 assert_eq!(acceptance.accepted_by, Some(AcceptedBy { mri: "8:orgid:bea".into(), display_name: "Bea".into() }));
588 }
589
568 #[test]
590 #[test]
569 fn acceptance_in_the_lobby_is_flagged() {
591 fn acceptance_in_the_lobby_is_flagged() {
570 let body = json!({"callAcceptance": {"controllerName": "lobby", "callKeepAliveInterval": 2700,
592 let body = json!({"callAcceptance": {"controllerName": "lobby", "callKeepAliveInterval": 2700,
crates/calling/src/video_layout.rs +7 −1
@@ -21,7 +21,7 @@ pub const ONE_TO_ONE_SHARE_MID: &str = "2";
21 21 const CAMERA_LINE_LABEL: &str = "main-video";
22 22 const SHARE_LINE_LABEL: &str = "applicationsharing-video";
23 23 const CAMERA_STREAM: &str = "camera";
24 const SCREEN_STREAM: &str = "screen";
24 pub const SCREEN_STREAM: &str = "screen";
25 25 const H264: &str = "video/h264";
26 26 const RTX: &str = "video/rtx";
27 27 const NO_SOURCE: i64 = -1;
@@ -140,6 +140,12 @@ pub fn add_video_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -
140 140 Ok(VideoLines { camera, share: Some(share) })
141 141 }
142 142
143 /// A sharing line added to a running direct call, the way Teams adds it before its share offer.
144 pub fn add_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<RtpTransceiver> {
145 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
146 add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())
147 }
148
143 149 pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
144 150 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
145 151 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), Vec::new())?;
@@ -21,7 +21,7 @@ pub const ONE_TO_ONE_SHARE_MID: &str = "2";
21const CAMERA_LINE_LABEL: &str = "main-video";
21const CAMERA_LINE_LABEL: &str = "main-video";
22const SHARE_LINE_LABEL: &str = "applicationsharing-video";
22const SHARE_LINE_LABEL: &str = "applicationsharing-video";
23const CAMERA_STREAM: &str = "camera";
23const CAMERA_STREAM: &str = "camera";
24const SCREEN_STREAM: &str = "screen";
24pub const SCREEN_STREAM: &str = "screen";
25const H264: &str = "video/h264";
25const H264: &str = "video/h264";
26const RTX: &str = "video/rtx";
26const RTX: &str = "video/rtx";
27const NO_SOURCE: i64 = -1;
27const NO_SOURCE: i64 = -1;
@@ -140,6 +140,12 @@ pub fn add_video_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -
140 Ok(VideoLines { camera, share: Some(share) })
140 Ok(VideoLines { camera, share: Some(share) })
141}
141}
142
142
143/// A sharing line added to a running direct call, the way Teams adds it before its share offer.
144pub fn add_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<RtpTransceiver> {
145 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
146 add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())
147}
148
143pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
149pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
144 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
150 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
145 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), Vec::new())?;
151 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), Vec::new())?;
crates/calling/src/video_send.rs +26 −0
@@ -6,6 +6,7 @@ use libwebrtc::media_stream_track::MediaStreamTrack;
6 6 use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7 7 use libwebrtc::rtp_parameters::DegradationPreference;
8 8 use libwebrtc::rtp_sender::RtpSender;
9 use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection};
9 10 use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
10 11 use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
11 12 use libwebrtc::video_source::VideoResolution;
@@ -289,6 +290,31 @@ impl LocalVideo {
289 290 self.lines.is_some()
290 291 }
291 292
293 pub fn share_mid(&self) -> Option<String> {
294 self.lines.as_ref().and_then(|lines| lines.share.as_ref()).and_then(|share| share.mid())
295 }
296
297 pub fn has_share_line(&self) -> bool {
298 self.lines.as_ref().is_some_and(|lines| lines.share.is_some())
299 }
300
301 pub fn add_share_line(&mut self, share: RtpTransceiver, camera: Option<RtpTransceiver>) -> Result<()> {
302 match (self.lines.as_mut(), camera) {
303 (Some(lines), _) => lines.share = Some(share),
304 (None, Some(camera)) => self.lines = Some(VideoLines { camera, share: Some(share) }),
305 (None, None) => return Err(Error::Webrtc("no video line negotiated".into())),
306 }
307 Ok(())
308 }
309
310 pub fn share_sending(&self) -> bool {
311 self.lines
312 .as_ref()
313 .and_then(|lines| lines.share.as_ref())
314 .and_then(|share| share.current_direction())
315 .is_some_and(|direction| matches!(direction, RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv))
316 }
317
292 318 pub fn is_available(&self) -> bool {
293 319 self.mode != VideoMode::Off
294 320 }
@@ -6,6 +6,7 @@ use libwebrtc::media_stream_track::MediaStreamTrack;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
6use libwebrtc::peer_connection_factory::PeerConnectionFactory;
7use libwebrtc::rtp_parameters::DegradationPreference;
7use libwebrtc::rtp_parameters::DegradationPreference;
8use libwebrtc::rtp_sender::RtpSender;
8use libwebrtc::rtp_sender::RtpSender;
9use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection};
9use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
10use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;
10use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
11use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};
11use libwebrtc::video_source::VideoResolution;
12use libwebrtc::video_source::VideoResolution;
@@ -289,6 +290,31 @@ impl LocalVideo {
289 self.lines.is_some()
290 self.lines.is_some()
290 }
291 }
291
292
293 pub fn share_mid(&self) -> Option<String> {
294 self.lines.as_ref().and_then(|lines| lines.share.as_ref()).and_then(|share| share.mid())
295 }
296
297 pub fn has_share_line(&self) -> bool {
298 self.lines.as_ref().is_some_and(|lines| lines.share.is_some())
299 }
300
301 pub fn add_share_line(&mut self, share: RtpTransceiver, camera: Option<RtpTransceiver>) -> Result<()> {
302 match (self.lines.as_mut(), camera) {
303 (Some(lines), _) => lines.share = Some(share),
304 (None, Some(camera)) => self.lines = Some(VideoLines { camera, share: Some(share) }),
305 (None, None) => return Err(Error::Webrtc("no video line negotiated".into())),
306 }
307 Ok(())
308 }
309
310 pub fn share_sending(&self) -> bool {
311 self.lines
312 .as_ref()
313 .and_then(|lines| lines.share.as_ref())
314 .and_then(|share| share.current_direction())
315 .is_some_and(|direction| matches!(direction, RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv))
316 }
317
292 pub fn is_available(&self) -> bool {
318 pub fn is_available(&self) -> bool {
293 self.mode != VideoMode::Off
319 self.mode != VideoMode::Off
294 }
320 }