feat(calls): 1:1 P2P like Teams web - real ICE candidates, glare, escalation, callee share
- Direct legs signal the gathered ICE candidates in Teams form (relay as default, TCP-ACT/PASS/SO, IPv6), keep the DTLS role in re-offers and read TCP-SO and IPv6 candidates from the peer. - Glare as Teams does it: the remote offer is answered first, ours goes out again after the 491; offers we cannot take get mediaNegotiationFailure 491/3118 or 488/3102. - Server escalations keep the direct peer until retargetCompletion; a failed one returns to the direct path and undoes only what waited for the new peer. - Ringing: 185 s for a direct call, 90 s after progress or a provisional answer; noRingBack honoured; roster from acceptedBy. - Share: ScreenSharer modality, callee share adds its own sharing line, the remote's share on a direct call is shown, answers keep every sharing line. - Captions and recording on incoming 1:1 calls use the 1:1 chat of both people. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
@@ -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
@@ -268,6 +276,43 @@ struct PeerSession {
268
276
peer: PeerConnection,
269
277
events: mpsc::UnboundedReceiver<PeerEvent>,
270
278
_data_channel: Option<DataChannel>,
279
gathered: Gathered,
280
}
281
282
#[derive(Clone, Default)]
283
struct Gathered {
284
candidates: Arc<std::sync::Mutex<Vec<String>>>,
285
complete: Arc<AtomicBool>,
286
relay_seen: Arc<AtomicBool>,
287
last_candidate: Arc<std::sync::Mutex<Option<Instant>>>,
288
}
289
290
impl Gathered {
291
/// libwebrtc gathers continually here, so "done" is a relay candidate followed by a quiet spell.
292
fn settled(&self) -> bool {
293
let quiet = self
294
.last_candidate
295
.lock()
296
.expect("candidate time lock")
297
.is_some_and(|at| at.elapsed() >= GATHERING_QUIET);
298
self.complete.load(Ordering::SeqCst) || (self.relay_seen.load(Ordering::SeqCst) && quiet)
299
}
300
301
async fn candidates(&self) -> Vec<String> {
302
let waited = Instant::now();
303
while !self.settled() && waited.elapsed() < GATHERING_LIMIT {
304
tokio::time::sleep(GATHERING_POLL).await;
305
}
306
self.complete.store(true, Ordering::SeqCst);
307
self.candidates.lock().expect("candidates lock").clone()
308
}
309
}
310
311
async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {
312
match gathered {
313
Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind),
314
None => Ok(teams_sdp.to_owned()),
315
}
271
316
}
272
317
273
318
struct OfferedMedia {
@@ -311,11 +356,19 @@ struct SamePeerOffer {
311
356
reply_tags: Vec<String>,
312
357
}
313
358
359
struct GlareResend {
360
change: Change,
361
reply_tags: Vec<String>,
362
at: Instant,
363
}
364
314
365
struct NextPeer {
315
366
session: PeerSession,
316
367
offered: Option<OfferedMedia>,
317
368
reply_tags: Vec<String>,
318
369
deadline: Option<Instant>,
370
connected: bool,
371
retargeted: bool,
319
372
}
320
373
321
374
fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
@@ -441,6 +494,26 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
441
494
.map_err(|error| Error::Webrtc(error.to_string()))?;
442
495
let (sender, events) = mpsc::unbounded_channel();
443
496
let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;
497
let gathered = Gathered::default();
498
let candidate_sink = gathered.candidates.clone();
499
let relay_seen = gathered.relay_seen.clone();
500
let last_candidate = gathered.last_candidate.clone();
501
peer.on_ice_candidate(Some(Box::new(move |candidate| {
502
if candidate.sdp_mline_index() == 0 {
503
let text = candidate.candidate();
504
if is_udp_relay(&text) {
505
relay_seen.store(true, Ordering::SeqCst);
506
}
507
*last_candidate.lock().expect("candidate time lock") = Some(Instant::now());
508
candidate_sink.lock().expect("candidates lock").push(text);
509
}
510
})));
511
let gathering_done = gathered.complete.clone();
512
peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state {
513
IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst),
514
IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst),
515
IceGatheringState::New => {}
516
})));
444
517
let ice_sender = sender.clone();
445
518
peer.on_ice_connection_state_change(Some(Box::new(move |state| {
446
519
let _ = ice_sender.send(PeerEvent::Ice(state));
@@ -458,7 +531,7 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s
458
531
let _ = sender.send(PeerEvent::VideoTrack { mid, track });
459
532
}
460
533
})));
461
Ok(PeerSession { peer, events, _data_channel: data_channel })
534
Ok(PeerSession { peer, events, _data_channel: data_channel, gathered })
462
535
}
463
536
464
537
fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {
@@ -471,23 +544,43 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv
471
544
Ok(channel)
472
545
}
473
546
474
fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
547
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 {
475
548
move |line| match line.kind {
476
549
"video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
477
"video" if camera_mid == CAMERA_MID && line.mid == ONE_TO_ONE_SHARE_MID => Some(if share { "sendonly" } else { INACTIVE }),
550
"video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {
551
(true, true) => "sendrecv",
552
(true, false) => "sendonly",
553
(false, true) => "recvonly",
554
(false, false) => INACTIVE,
555
}),
478
556
_ => None,
479
557
}
480
558
}
481
559
482
fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, text: &str) -> String {
560
fn share_mid_in(offer_text: &str) -> Option<String> {
561
let mut mid = None;
562
for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) {
563
if line.starts_with("m=") {
564
mid = None;
565
} else if let Some(value) = line.strip_prefix("a=mid:") {
566
mid = Some(value.to_owned());
567
} else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() {
568
return mid;
569
}
570
}
571
None
572
}
573
574
#[allow(clippy::too_many_arguments)]
575
fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, share_mid: Option<&str>, remote_shares: bool, text: &str) -> String {
483
576
match (hold, layout) {
484
577
(true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
485
(false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid)),
578
(false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares)),
486
579
(false, Layout::Conference) => text.to_owned(),
487
580
}
488
581
}
489
582
490
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout) -> Result<OfferedMedia> {
583
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout, gathered: Option<&Gathered>) -> Result<OfferedMedia> {
491
584
let transceiver_init = RtpTransceiverInit {
492
585
direction: RtpTransceiverDirection::SendRecv,
493
586
stream_ids: vec![MIC_STREAM.into()],
@@ -507,13 +600,14 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
507
600
})
508
601
.await
509
602
.map_err(|error| Error::Webrtc(error.to_string()))?;
510
let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, &offer.to_string());
603
let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, &offer.to_string());
511
604
let description = parse_sdp(&browser_offer, SdpType::Offer)?;
512
605
peer.set_local_description(description)
513
606
.await
514
607
.map_err(|error| Error::Webrtc(error.to_string()))?;
515
608
let mut numbers = random_u32;
516
let signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
609
let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;
610
signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
517
611
Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })
518
612
}
519
613
@@ -521,14 +615,15 @@ struct AnsweredMedia {
521
615
remote: RemoteOffer,
522
616
answer_sdp: String,
523
617
camera_mid: Option<String>,
618
receiving_share_mid: Option<String>,
524
619
}
525
620
526
621
fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
527
622
remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
528
623
}
529
624
530
fn share_mid(remote: &RemoteOffer) -> Option<String> {
531
remote.lines.iter().find(|line| line.role == LineRole::ScreenShare).and_then(|line| line.browser_mids.first().cloned())
625
fn share_mids(remote: &RemoteOffer) -> Vec<String> {
626
remote.lines.iter().filter(|line| line.role == LineRole::ScreenShare).filter_map(|line| line.browser_mids.first().cloned()).collect()
532
627
}
533
628
534
629
async fn answer_offer(
@@ -536,8 +631,9 @@ async fn answer_offer(
536
631
track: Option<&RtcAudioTrack>,
537
632
teams_offer: &str,
538
633
video: AnswerVideo<'_>,
539
sharing: bool,
634
sending_share_mid: Option<String>,
540
635
camera_on: bool,
636
gathered: Option<&Gathered>,
541
637
) -> Result<AnsweredMedia> {
542
638
let remote = from_teams_offer(teams_offer)?;
543
639
let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
@@ -545,10 +641,13 @@ async fn answer_offer(
545
641
.await
546
642
.map_err(|error| Error::Webrtc(error.to_string()))?;
547
643
let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
548
let kept_share_mid = share_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
644
let kept_share_mids = if matches!(video, AnswerVideo::Reject) { Vec::new() } else { share_mids(&remote) };
549
645
for transceiver in peer.transceivers() {
550
646
let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
551
if is_video && transceiver.mid() != camera_mid && transceiver.mid() != kept_share_mid {
647
let unused = transceiver
648
.mid()
649
.is_some_and(|mid| Some(&mid) != camera_mid.as_ref() && !kept_share_mids.contains(&mid) && Some(&mid) != sending_share_mid.as_ref());
650
if is_video && unused {
552
651
let _ = transceiver.stop();
553
652
}
554
653
}
@@ -564,10 +663,10 @@ async fn answer_offer(
564
663
.create_answer(AnswerOptions::default())
565
664
.await
566
665
.map_err(|error| Error::Webrtc(error.to_string()))?;
567
let mut answer_text = match kept_share_mid.as_deref() {
568
Some(mid) if !sharing => rewrite_directions(&answer.to_string(), |line| (line.kind == "video" && line.mid == mid).then_some(INACTIVE)),
569
_ => answer.to_string(),
570
};
666
let mut answer_text = answer.to_string();
667
for mid in kept_share_mids.iter().filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) {
668
answer_text = stop_sending_on(&answer_text, mid);
669
}
571
670
let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
572
671
if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
573
672
answer_text = stop_sending_on(&answer_text, mid);
@@ -575,12 +674,17 @@ async fn answer_offer(
575
674
peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
576
675
.await
577
676
.map_err(|error| Error::Webrtc(error.to_string()))?;
677
let receiving_share_mid = kept_share_mids
678
.into_iter()
679
.filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
680
.find(|mid| matches!(direction_of(&answer_text, mid).as_deref(), Some("recvonly" | "sendrecv")));
578
681
let mut numbers = random_u32;
579
682
let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
580
683
Ok(AnsweredMedia {
581
684
remote,
582
answer_sdp: signaled.sdp,
685
answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
583
686
camera_mid,
687
receiving_share_mid,
584
688
})
585
689
}
586
690
@@ -691,6 +795,7 @@ async fn drive(
691
795
let mut keep_alive_seconds: Option<u64> = None;
692
796
let mut keep_alive_at: Option<Instant> = None;
693
797
let mut outgoing_deadline: Option<Instant> = None;
798
let mut outgoing_limit = OUTGOING_TIMEOUT;
694
799
let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);
695
800
let is_echo = matches!(spec, Some(CallSpec::Echo));
696
801
let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count));
@@ -700,7 +805,16 @@ async fn drive(
700
805
};
701
806
let people_thread = match &spec {
702
807
Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),
703
_ => None,
808
_ => incoming_media
809
.as_ref()
810
.filter(|(notification, _)| !notification.is_multi_party)
811
.and_then(|(notification, _)| {
812
notification
813
.thread_id
814
.clone()
815
.filter(|thread| *thread != notification.caller.mri)
816
.or_else(|| one_to_one_thread(&inner.identity.object_id, ¬ification.caller.mri))
817
}),
704
818
};
705
819
let mut layout = match &spec {
706
820
Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne,
@@ -717,7 +831,8 @@ async fn drive(
717
831
718
832
let conversation = match (spec, incoming_media) {
719
833
(Some(spec), None) => {
720
let media = create_offer(¤t.peer, &factory, &track, layout).await?;
834
let direct_invite = spec.target().is_one_to_one() && !options.concurrent;
835
let media = create_offer(¤t.peer, &factory, &track, layout, direct_invite.then_some(¤t.gathered)).await?;
721
836
layout_plan = media.plan.clone();
722
837
if layout == Layout::OneToOne {
723
838
direct_video_mid = Some(CAMERA_MID.to_owned());
@@ -748,7 +863,10 @@ async fn drive(
748
863
};
749
864
if spec.is_people() {
750
865
control.send(CallUpdate::Progress(Progress::Calling));
751
outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
866
if threadless {
867
outgoing_limit = DIRECT_OUTGOING_TIMEOUT;
868
}
869
outgoing_deadline = Some(Instant::now() + outgoing_limit);
752
870
}
753
871
if let Err(error) = local_video.set_lines(media.video.clone()) {
754
872
timeline.record("video lines not attached", error.to_string());
@@ -786,7 +904,7 @@ async fn drive(
786
904
_ => AnswerVideo::Receive,
787
905
};
788
906
dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
789
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer, video_answer, false, false).await?;
907
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer, video_answer, None, false, one_to_one.then_some(¤t.gathered)).await?;
790
908
layout_plan = answered.remote.plan();
791
909
direct_video_mid = answered.camera_mid.clone();
792
910
timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
@@ -915,6 +1033,9 @@ async fn drive(
915
1033
}
916
1034
let mut start_camera_pending = options.start_camera;
917
1035
let mut share_pending: Option<ShareSource> = None;
1036
let mut glare_resend: Option<GlareResend> = None;
1037
let mut deferred_changes: Vec<Change> = Vec::new();
1038
let mut remote_direct_share: Option<String> = None;
918
1039
let mut sent_replacement: Option<Replacement> = None;
919
1040
loop {
920
1041
if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
@@ -926,11 +1047,61 @@ async fn drive(
926
1047
{
927
1048
control.defer(CallCommand::StartShare(source));
928
1049
}
1050
if next.as_ref().is_some_and(|pending| pending.connected && (pending.offered.is_some() || pending.retargeted))
1051
&& let Some(pending) = next.take()
1052
{
1053
timeline.record("escalation", "new peer connection connected, old one dropped");
1054
deferred_changes.clear();
1055
negotiator.server_escalation_done();
1056
if let Some(mid) = remote_direct_share.take() {
1057
video.router().set(&mid, None);
1058
control.send(CallUpdate::ScreenShare(None));
1059
}
1060
let old = std::mem::replace(&mut current, pending.session);
1061
old.peer.close();
1062
if let Some(audio) = &software_audio
1063
&& let Err(error) = swap_audio_track(¤t.peer, &audio.track)
1064
{
1065
timeline.record("computer sound not carried over", error.to_string());
1066
}
1067
offered = pending.offered;
1068
if let Some(mid) = direct_video_mid.take() {
1069
video.router().set(&mid, None);
1070
}
1071
if let Some(media) = &offered {
1072
layout = Layout::Conference;
1073
layout_plan = media.plan.clone();
1074
if let Err(error) = local_video.set_lines(media.video.clone()) {
1075
timeline.record("video lines not attached", error.to_string());
1076
}
1077
if local_video.camera_on() {
1078
tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1079
}
1080
if local_video.sharing() {
1081
tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1082
}
1083
}
1084
remote_set = true;
1085
if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1086
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;
1087
if pending.is_none() {
1088
drop_local_media(&mut local_video, control);
1089
}
1090
next = pending.or(next);
1091
}
1092
}
929
1093
let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);
1094
let glare_at = glare_resend.as_ref().map(|resend| resend.at);
930
1095
tokio::select! {
931
1096
Some(callback) = callbacks.recv() => {
932
1097
match handle_callback(&callback, timeline) {
933
1098
Ok(CallEvent::Acceptance(acceptance)) => {
1099
if !acceptance.from_mixer
1100
&& let Some(accepted_by) = &acceptance.accepted_by
1101
&& roster.apply(&direct_roster(&[(own_mri.as_str(), participant.display_name.as_str()), (accepted_by.mri.as_str(), accepted_by.display_name.as_str())]))
1102
{
1103
control.send(CallUpdate::Roster(roster.entries()));
1104
}
934
1105
if !acceptance.from_mixer && callee_gate.callee_joined() {
935
1106
advance(state, CallSignal::MediaConnected, control);
936
1107
}
@@ -995,6 +1166,26 @@ async fn drive(
995
1166
_ => {}
996
1167
}
997
1168
}
1169
Ok(CallEvent::MediaAnswer(answer)) if !remote_set && !answer.from_mixer && same_peer.is_none() && next.is_none() && outgoing_deadline.is_some() => {
1170
timeline.record("provisional answer", if answer.no_ring_back { "no ringback" } else { "ringing" });
1171
outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1172
if !answer.no_ring_back {
1173
control.send(CallUpdate::Progress(Progress::Ringing));
1174
}
1175
}
1176
Ok(CallEvent::MediaAnswer(answer))
1177
if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1178
{
1179
if let Some(url) = answer.links.get("mediaAcknowledgement") {
1180
let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1181
}
1182
if answer.from_mixer {
1183
negotiator.note_mixer_path();
1184
}
1185
if let Some(resend) = glare_resend.as_mut() {
1186
resend.at = Instant::now();
1187
}
1188
}
998
1189
Ok(CallEvent::MediaAnswer(answer)) => {
999
1190
let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1000
1191
|| next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags));
@@ -1006,6 +1197,11 @@ async fn drive(
1006
1197
continue;
1007
1198
}
1008
1199
let action = negotiator.on_media_answer();
1200
if action == MediaAction::Ignore
1201
&& let Some(url) = answer.links.get("mediaAcknowledgement")
1202
{
1203
let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1204
}
1009
1205
if action == MediaAction::ApplyOnSamePeer
1010
1206
&& let Some(pending) = same_peer.take()
1011
1207
{
@@ -1026,7 +1222,7 @@ async fn drive(
1026
1222
control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1027
1223
}
1028
1224
Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1029
Change::Share(true) if !answer.from_mixer && !sends_on(¤t.peer, ONE_TO_ONE_SHARE_MID) => {
1225
Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {
1030
1226
local_video.stop_share();
1031
1227
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1032
1228
control.send(CallUpdate::LocalShare(None));
@@ -1085,18 +1281,28 @@ async fn drive(
1085
1281
}
1086
1282
}
1087
1283
Ok(CallEvent::MediaRenegotiation(renegotiation)) => {
1284
if !renegotiation.escalation
1285
&& !renegotiation.new_offer
1286
&& let Some(pending) = same_peer.take()
1287
{
1288
same_peer_deadline = None;
1289
negotiator.same_peer_offer_failed();
1290
rollback_offer(¤t.peer).await;
1291
timeline.record("glare", "the remote offer is answered first, ours goes out again after");
1292
glare_resend = Some(GlareResend { change: pending.change, reply_tags: pending.reply_tags, at: Instant::now() + GLARE_RESEND_LIMIT });
1293
}
1088
1294
let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1295
let rejection_link = renegotiation.links.get("rejection").cloned();
1089
1296
let result = match action {
1090
1297
MediaAction::AnswerOnNewPeer => {
1091
1298
if let Some(pending) = same_peer.take() {
1092
1299
same_peer_deadline = None;
1093
1300
timeline.record("same-peer offer", "superseded by the escalation offer");
1094
1301
rollback_offer(¤t.peer).await;
1095
match pending.change {
1096
Change::Camera(true) => control.send(CallUpdate::Camera(true)),
1097
Change::Share(true) => {}
1098
change => undo_change(change, &mut local_video, control),
1099
}
1302
defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);
1303
}
1304
if let Some(resend) = glare_resend.take() {
1305
defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control);
1100
1306
}
1101
1307
match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1102
1308
Ok((session, answered)) => {
@@ -1106,18 +1312,44 @@ async fn drive(
1106
1312
if let Some(replaced) = next.take() {
1107
1313
replaced.session.peer.close();
1108
1314
}
1109
next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: None });
1315
next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: Some(Instant::now() + NEXT_PEER_LIMIT), connected: false, retargeted: false });
1110
1316
sent
1111
1317
}
1112
Err(error) => Err(error),
1318
Err(error) => {
1319
if next.is_none() {
1320
negotiator.server_escalation_failed();
1321
}
1322
for change in deferred_changes.drain(..) {
1323
undo_change(change, &mut local_video, control);
1324
}
1325
if let Some(url) = &rejection_link {
1326
let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1327
}
1328
Err(error)
1329
}
1113
1330
}
1114
1331
}
1115
1332
MediaAction::AnswerOnSamePeer => {
1116
1333
let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
1117
match answer_offer(¤t.peer, None, &renegotiation.sdp, video_answer, local_video.sharing(), local_video.camera_on()).await {
1334
match answer_offer(¤t.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(¤t.gathered)).await {
1118
1335
Ok(answered) => {
1119
1336
timeline.record_sdp("local answer", &answered.answer_sdp);
1120
1337
let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1338
for mid in answered.remote.plan().screen_share_mids {
1339
if !layout_plan.screen_share_mids.contains(&mid) {
1340
layout_plan.screen_share_mids.push(mid);
1341
}
1342
}
1343
if layout == Layout::OneToOne && answered.receiving_share_mid != remote_direct_share {
1344
if let Some(mid) = &remote_direct_share {
1345
video.router().set(mid, None);
1346
}
1347
if let Some(mid) = &answered.receiving_share_mid {
1348
video.router().set(mid, Some(VideoKey::Screen));
1349
}
1350
remote_direct_share = answered.receiving_share_mid.clone();
1351
control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));
1352
}
1121
1353
let held = is_hold(&renegotiation.sdp).unwrap_or(false);
1122
1354
if held != remote_hold {
1123
1355
remote_hold = held;
@@ -1125,8 +1357,22 @@ async fn drive(
1125
1357
}
1126
1358
sent
1127
1359
}
1128
Err(error) => Err(error),
1360
Err(error) => {
1361
if current.peer.signaling_state() == SignalingState::HaveRemoteOffer {
1362
rollback_remote_offer(¤t.peer).await;
1363
}
1364
if let Some(url) = &rejection_link {
1365
let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;
1366
}
1367
Err(error)
1368
}
1369
}
1370
}
1371
MediaAction::RejectGlare => {
1372
if let Some(url) = &rejection_link {
1373
let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::InProgress).await;
1129
1374
}
1375
Ok(())
1130
1376
}
1131
1377
_ => Ok(()),
1132
1378
};
@@ -1292,6 +1538,9 @@ async fn drive(
1292
1538
Ok(CallEvent::Progress(status)) => {
1293
1539
if status == ProgressStatus::Ringing {
1294
1540
control.send(CallUpdate::Progress(Progress::Ringing));
1541
if outgoing_deadline.is_some() {
1542
outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);
1543
}
1295
1544
}
1296
1545
}
1297
1546
Ok(CallEvent::ControlVideoStreaming(body)) => {
@@ -1320,18 +1569,30 @@ async fn drive(
1320
1569
advance(state, CallSignal::RemoteEnd(kind), control);
1321
1570
break;
1322
1571
}
1572
Ok(CallEvent::Rejection(_))
1573
if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>
1574
{
1575
if let Some(resend) = glare_resend.as_mut() {
1576
resend.at = Instant::now();
1577
}
1578
}
1323
1579
Ok(CallEvent::Rejection(_))
1324
1580
if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))
1325
1581
&& !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) =>
1326
1582
{
1327
1583
timeline.record("rejection ignored", "it names an offer that is no longer pending");
1328
1584
}
1329
Ok(CallEvent::Rejection(_)) => match negotiator.on_rejection() {
1585
Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {
1330
1586
RejectedOffer::SamePeer => {
1331
1587
same_peer_deadline = None;
1332
1588
if let Some(pending) = same_peer.take() {
1333
1589
rollback_offer(¤t.peer).await;
1334
undo_change(pending.change, &mut local_video, control);
1590
if is_glare_rejection(&body) {
1591
timeline.record("glare", "our offer met theirs, it goes out again");
1592
glare_resend = Some(GlareResend { change: pending.change, reply_tags: Vec::new(), at: Instant::now() + GLARE_RESEND_LIMIT });
1593
} else {
1594
undo_change(pending.change, &mut local_video, control);
1595
}
1335
1596
}
1336
1597
}
1337
1598
RejectedOffer::NewPeer => {
@@ -1345,13 +1606,16 @@ async fn drive(
1345
1606
}
1346
1607
RejectedOffer::None => {}
1347
1608
},
1609
Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => {
1610
if let Some(pending) = next.as_mut() {
1611
pending.retargeted = true;
1612
}
1613
}
1348
1614
Ok(CallEvent::RetargetCompletion(body)) => {
1349
if body["retargetCompleted"]["code"].as_i64().is_some_and(|code| code != 0) && let Some(pending) = next.take() {
1615
if body["retargetCompleted"]["code"].as_i64().is_some() && let Some(pending) = next.take() {
1350
1616
pending.session.peer.close();
1351
1617
negotiator.escalation_failed();
1352
if layout == Layout::OneToOne {
1353
drop_local_media(&mut local_video, control);
1354
}
1618
settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
1355
1619
timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");
1356
1620
}
1357
1621
}
@@ -1432,39 +1696,11 @@ async fn drive(
1432
1696
},
1433
1697
Some(event) = next_peer_event(&mut next) => match event {
1434
1698
PeerEvent::Connection(PeerConnectionState::Connected) => {
1435
if let Some(pending) = next.take() {
1436
timeline.record("escalation", "new peer connection connected, old one dropped");
1437
let old = std::mem::replace(&mut current, pending.session);
1438
old.peer.close();
1439
if let Some(audio) = &software_audio
1440
&& let Err(error) = swap_audio_track(¤t.peer, &audio.track)
1441
{
1442
timeline.record("computer sound not carried over", error.to_string());
1443
}
1444
offered = pending.offered;
1445
if let Some(mid) = direct_video_mid.take() {
1446
video.router().set(&mid, None);
1447
}
1448
if let Some(media) = &offered {
1449
layout = Layout::Conference;
1450
layout_plan = media.plan.clone();
1451
if let Err(error) = local_video.set_lines(media.video.clone()) {
1452
timeline.record("video lines not attached", error.to_string());
1453
}
1454
if local_video.camera_on() {
1455
tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
1456
}
1457
if local_video.sharing() {
1458
tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
1459
}
1460
}
1461
remote_set = true;
1462
if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1463
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;
1464
if pending.is_none() {
1465
drop_local_media(&mut local_video, control);
1466
}
1467
next = pending.or(next);
1699
if let Some(pending) = next.as_mut() {
1700
pending.connected = true;
1701
if pending.offered.is_none() && !pending.retargeted {
1702
pending.deadline = Some(Instant::now() + RETARGET_WAIT);
1703
timeline.record("escalation", "new peer connection up, waiting for retargetCompletion");
1468
1704
}
1469
1705
}
1470
1706
}
@@ -1476,9 +1712,7 @@ async fn drive(
1476
1712
negotiator.escalation_failed();
1477
1713
if let Some(pending) = next.take() {
1478
1714
pending.session.peer.close();
1479
}
1480
if layout == Layout::OneToOne {
1481
drop_local_media(&mut local_video, control);
1715
settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
1482
1716
}
1483
1717
timeline.record("escalation failed", "new peer connection failed, staying on the old one");
1484
1718
}
@@ -1554,11 +1788,13 @@ async fn drive(
1554
1788
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
1555
1789
} else if local_hold {
1556
1790
control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1791
} else if on && direct && (same_peer.is_some() || glare_resend.is_some()) {
1792
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1557
1793
} else if on {
1558
1794
let started = start_camera_line(&mut local_video, ¤t.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
1559
1795
match started {
1560
1796
Ok(()) if direct => {
1561
match offer_same_peer(¤t.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 {
1797
match offer_same_peer(¤t.peer, ¤t.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 {
1562
1798
Ok((browser_offer, signaled, reply_tags)) => {
1563
1799
timeline.record_sdp("local offer", &signaled.sdp);
1564
1800
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
@@ -1576,11 +1812,11 @@ async fn drive(
1576
1812
}
1577
1813
Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1578
1814
}
1579
} else if direct && same_peer.is_some() {
1815
} else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1580
1816
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1581
1817
} else if direct {
1582
1818
local_video.stop_camera();
1583
match offer_same_peer(¤t.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 {
1819
match offer_same_peer(¤t.peer, ¤t.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 {
1584
1820
Ok((browser_offer, signaled, reply_tags)) => {
1585
1821
timeline.record_sdp("local offer", &signaled.sdp);
1586
1822
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
@@ -1616,14 +1852,19 @@ async fn drive(
1616
1852
Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
1617
1853
Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1618
1854
}
1619
} else if direct && same_peer.is_some() {
1855
} else if direct && (same_peer.is_some() || glare_resend.is_some()) {
1620
1856
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1857
} else if direct
1858
&& !local_video.has_share_line()
1859
&& let Err(error) = attach_share_line(¤t.peer, &factory, &mut local_video, direct_video_mid.as_deref())
1860
{
1861
control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));
1621
1862
} else if direct {
1622
1863
match local_video.start_share(&source) {
1623
1864
Ok(()) => {
1624
1865
control.send(CallUpdate::LocalShare(Some(source.label())));
1625
1866
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1626
match offer_same_peer(¤t.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 {
1867
match offer_same_peer(¤t.peer, ¤t.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 {
1627
1868
Ok((browser_offer, signaled, reply_tags)) => {
1628
1869
timeline.record_sdp("local offer", &signaled.sdp);
1629
1870
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
@@ -1662,13 +1903,13 @@ async fn drive(
1662
1903
Some(CallCommand::StopShare) => {
1663
1904
let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1664
1905
share_pending = None;
1665
if direct && local_video.sharing() && same_peer.is_some() {
1906
if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
1666
1907
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1667
1908
} else if direct && local_video.sharing() {
1668
1909
local_video.stop_share();
1669
1910
control.send(CallUpdate::LocalShare(None));
1670
1911
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1671
match offer_same_peer(¤t.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 {
1912
match offer_same_peer(¤t.peer, ¤t.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 {
1672
1913
Ok((browser_offer, signaled, reply_tags)) => {
1673
1914
timeline.record_sdp("local offer", &signaled.sdp);
1674
1915
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
@@ -1888,7 +2129,7 @@ async fn drive(
1888
2129
}
1889
2130
}
1890
2131
Some(CallCommand::Hold(hold)) => {
1891
if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || next.is_some() {
2132
if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || glare_resend.is_some() || next.is_some() {
1892
2133
continue;
1893
2134
}
1894
2135
if hold && local_video.camera_on() {
@@ -1896,7 +2137,7 @@ async fn drive(
1896
2137
control.send(CallUpdate::Camera(false));
1897
2138
}
1898
2139
let camera = !hold && local_video.camera_on();
1899
match offer_same_peer(¤t.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 {
2140
match offer_same_peer(¤t.peer, ¤t.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 {
1900
2141
Ok((browser_offer, signaled, reply_tags)) => {
1901
2142
timeline.record_sdp("local offer", &signaled.sdp);
1902
2143
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
@@ -2120,18 +2361,52 @@ async fn drive(
2120
2361
break;
2121
2362
}
2122
2363
_ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {
2123
if let Some(pending) = next.take() {
2364
if let Some(pending) = next.as_mut().filter(|pending| pending.connected && pending.offered.is_none()) {
2365
pending.retargeted = true;
2366
timeline.record("escalation", "no retargetCompletion, switching anyway");
2367
} else if let Some(pending) = next.take() {
2124
2368
pending.session.peer.close();
2125
2369
negotiator.escalation_failed();
2126
2370
start_camera_pending = false;
2127
2371
share_pending = None;
2128
if layout == Layout::OneToOne {
2129
drop_local_media(&mut local_video, control);
2130
}
2372
settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);
2131
2373
timeline.record("escalation failed", "no answer for the new peer connection in time");
2132
2374
control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2133
2375
}
2134
2376
}
2377
_ = sleep_until(glare_at.unwrap_or_else(far_future)), if glare_at.is_some() => {
2378
let resend = glare_resend.take();
2379
if let Some(resend) = resend.as_ref().filter(|_| same_peer.is_some() || next.is_some()) {
2380
timeline.record("glare", "another change took over, ours is dropped");
2381
undo_change(resend.change, &mut local_video, control);
2382
} else if let Some(resend) = resend.as_ref().filter(|resend| layout == Layout::OneToOne && negotiator.path() == MediaPath::Mixer && !matches!(resend.change, Change::Hold(_))) {
2383
if negotiator.begin_conference_upgrade() {
2384
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;
2385
if pending.is_none() {
2386
drop_local_media(&mut local_video, control);
2387
}
2388
next = pending.or(next);
2389
} else {
2390
undo_change(resend.change, &mut local_video, control);
2391
}
2392
} else if let Some(resend) = resend {
2393
let (hold, camera, share) = match resend.change {
2394
Change::Hold(hold) => (hold, !hold && local_video.camera_on(), local_video.sharing()),
2395
_ => (local_hold, local_video.camera_on(), local_video.sharing()),
2396
};
2397
match offer_same_peer(¤t.peer, ¤t.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 {
2398
Ok((browser_offer, signaled, reply_tags)) => {
2399
timeline.record_sdp("local offer", &signaled.sdp);
2400
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });
2401
same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
2402
}
2403
Err(error) => {
2404
timeline.record("offer after glare failed", error.to_string());
2405
undo_change(resend.change, &mut local_video, control);
2406
}
2407
}
2408
}
2409
}
2135
2410
_ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2136
2411
same_peer_deadline = None;
2137
2412
if let Some(pending) = same_peer.take() {
@@ -2180,7 +2455,7 @@ async fn start_escalation(
2180
2455
.get("mediaRenegotiation")
2181
2456
.ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2182
2457
let session = open_peer(factory, grant, &options.relay_host, false)?;
2183
let media = create_offer(&session.peer, factory, track, Layout::Conference).await?;
2458
let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;
2184
2459
let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);
2185
2460
let reply_tags = offer_reply_tags(&body);
2186
2461
remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
@@ -2189,6 +2464,8 @@ async fn start_escalation(
2189
2464
offered: Some(media),
2190
2465
reply_tags,
2191
2466
deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
2467
connected: false,
2468
retargeted: false,
2192
2469
})
2193
2470
}
2194
2471
@@ -2242,7 +2519,7 @@ async fn answer_on_new_peer(
2242
2519
teams_offer: &str,
2243
2520
) -> Result<(PeerSession, AnsweredMedia)> {
2244
2521
let session = open_peer(factory, grant, &options.relay_host, false)?;
2245
let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, false, false).await?;
2522
let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, None, false, None).await?;
2246
2523
Ok((session, answered))
2247
2524
}
2248
2525
@@ -2353,10 +2630,15 @@ fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
2353
2630
own.is_some_and(|own| own.thread_id == target.thread_id)
2354
2631
}
2355
2632
2356
fn sends_on(peer: &PeerConnection, mid: &str) -> bool {
2357
peer_transceiver(peer, mid)
2358
.and_then(|transceiver| transceiver.current_direction())
2359
.is_some_and(|direction| matches!(direction, RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv))
2633
fn attach_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory, local_video: &mut LocalVideo, camera_mid: Option<&str>) -> Result<()> {
2634
let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));
2635
if !local_video.has_lines() && camera.is_none() {
2636
return Err(Error::Webrtc("no video line negotiated".into()));
2637
}
2638
let share = add_share_line(peer, factory)?;
2639
local_video.add_share_line(share.clone(), camera).inspect_err(|_| {
2640
let _ = share.stop();
2641
})
2360
2642
}
2361
2643
2362
2644
fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
@@ -2379,6 +2661,8 @@ fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct
2379
2661
#[allow(clippy::too_many_arguments)]
2380
2662
async fn offer_same_peer(
2381
2663
peer: &PeerConnection,
2664
gathered: &Gathered,
2665
own_share_mid: Option<String>,
2382
2666
plan: &OfferPlan,
2383
2667
layout: Layout,
2384
2668
camera_mid: &str,
@@ -2399,7 +2683,7 @@ async fn offer_same_peer(
2399
2683
if !negotiator.begin_same_peer_offer() {
2400
2684
return Err(Error::Signaling("another media negotiation is running".into()));
2401
2685
}
2402
let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid).await;
2686
let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid, own_share_mid, direct.then_some(gathered)).await;
2403
2687
let (text, signaled) = match offered {
2404
2688
Ok(offered) => offered,
2405
2689
Err(error) => {
@@ -2407,7 +2691,7 @@ async fn offer_same_peer(
2407
2691
return Err(error);
2408
2692
}
2409
2693
};
2410
let modalities = accepted_modalities(layout == Layout::OneToOne && camera && !hold);
2694
let modalities = offer_modalities(layout == Layout::OneToOne && camera && !hold, share && !hold);
2411
2695
let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
2412
2696
let reply_tags = offer_reply_tags(&body);
2413
2697
if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
@@ -2418,18 +2702,39 @@ async fn offer_same_peer(
2418
2702
Ok((text, signaled, reply_tags))
2419
2703
}
2420
2704
2421
async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str) -> Result<(String, SignaledOffer)> {
2705
#[allow(clippy::too_many_arguments)]
2706
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)> {
2422
2707
let offer = peer
2423
2708
.create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
2424
2709
.await
2425
2710
.map_err(|error| Error::Webrtc(error.to_string()))?;
2426
let text = directions_for(layout, false, camera, share, camera_mid, &offer.to_string());
2711
let offer_text = offer.to_string();
2712
let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text));
2713
let remote_shares = share_mid.as_deref().is_some_and(|mid| {
2714
peer.current_remote_description()
2715
.and_then(|remote| direction_of(&remote.to_string(), mid))
2716
.is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))
2717
});
2718
let text = directions_for(layout, false, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &offer_text);
2427
2719
let description = parse_sdp(&text, SdpType::Offer)?;
2428
2720
peer.set_local_description(description)
2429
2721
.await
2430
2722
.map_err(|error| Error::Webrtc(error.to_string()))?;
2431
2723
let mut numbers = random_u32;
2432
let signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, &text), plan, &mut numbers)?;
2724
let mut plan = plan.clone();
2725
if let Some(mid) = share_mid.as_ref().filter(|mid| !plan.screen_share_mids.contains(mid)) {
2726
plan.screen_share_mids.push(mid.clone());
2727
}
2728
let mut signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &text), &plan, &mut numbers)?;
2729
signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;
2730
if gathered.is_some()
2731
&& let Some(role) = negotiated_setup(
2732
peer.current_local_description().map(|local| local.to_string()).as_deref(),
2733
peer.current_remote_description().map(|remote| remote.to_string()).as_deref(),
2734
)
2735
{
2736
signaled.sdp = signaled.sdp.replace("a=setup:actpass", &format!("a=setup:{role}"));
2737
}
2433
2738
Ok((text, signaled))
2434
2739
}
2435
2740
@@ -2448,6 +2753,16 @@ async fn rollback_offer(peer: &PeerConnection) {
2448
2753
}
2449
2754
}
2450
2755
2756
async fn rollback_remote_offer(peer: &PeerConnection) {
2757
if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {
2758
let _ = peer.set_remote_description(rollback).await;
2759
}
2760
}
2761
2762
fn is_glare_rejection(body: &serde_json::Value) -> bool {
2763
body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE)
2764
}
2765
2451
2766
fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2452
2767
let links = &body["mediaNegotiation"]["links"];
2453
2768
["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
@@ -2475,6 +2790,29 @@ mod reply_tag_tests {
2475
2790
}
2476
2791
}
2477
2792
2793
fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
2794
match change {
2795
Change::Camera(true) => {
2796
control.send(CallUpdate::Camera(true));
2797
deferred.push(change);
2798
}
2799
Change::Share(true) => deferred.push(change),
2800
change => undo_change(change, local_video, control),
2801
}
2802
}
2803
2804
/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.
2805
fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut MediaNegotiator, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {
2806
if server {
2807
negotiator.server_escalation_failed();
2808
for change in deferred.drain(..) {
2809
undo_change(change, local_video, control);
2810
}
2811
} else if layout == Layout::OneToOne {
2812
drop_local_media(local_video, control);
2813
}
2814
}
2815
2478
2816
fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2479
2817
if local_video.sharing() {
2480
2818
local_video.stop_share();
@@ -3227,7 +3565,7 @@ mod tests {
3227
3565
let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();
3228
3566
let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3229
3567
let track = factory.create_audio_track("microphone", source);
3230
let offer = create_offer(&peer, &factory, &track, layout).await;
3568
let offer = create_offer(&peer, &factory, &track, layout, None).await;
3231
3569
peer.close();
3232
3570
offer
3233
3571
}
@@ -3250,7 +3588,7 @@ mod tests {
3250
3588
let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3251
3589
let track = factory.create_audio_track("microphone", source);
3252
3590
let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3253
let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, false, false).await;
3591
let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, None, false, None).await;
3254
3592
peer.close();
3255
3593
if let Err(error) = answered {
3256
3594
panic!("{error}");
@@ -3259,22 +3597,22 @@ mod tests {
3259
3597
3260
3598
#[test]
3261
3599
fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3262
assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3263
assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
3264
assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);
3600
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"]);
3601
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"]);
3602
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"]);
3265
3603
}
3266
3604
3267
3605
#[test]
3268
3606
fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3269
3607
for layout in [Layout::OneToOne, Layout::Conference] {
3270
assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3608
assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, None, false, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3271
3609
}
3272
assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, BROWSER_OFFER), BROWSER_OFFER);
3610
assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, None, false, BROWSER_OFFER), BROWSER_OFFER);
3273
3611
}
3274
3612
3275
3613
#[test]
3276
3614
fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3277
let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, BROWSER_OFFER);
3615
let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, None, false, BROWSER_OFFER);
3278
3616
let mut numbers = || 7;
3279
3617
let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
3280
3618
assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
@@ -36,20 +36,21 @@ use crate::end::EndKind;36
use crate::engine::{CallEngine, EngineConfig, Inner};36
use crate::engine::{CallEngine, EngineConfig, Inner};37
use crate::error::{Error, Result};37
use crate::error::{Error, Result};38
use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};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
use crate::mic_processing::MicSettings;40
use crate::mic_processing::MicSettings;41
use crate::mute::{MuteCommand, MuteEffect};41
use crate::mute::{MuteCommand, MuteEffect};42
use crate::push::CallNotification;42
use crate::push::CallNotification;43
use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};43
use crate::relay::{DEFAULT_RELAY_HOST, RelayGrant, fetch_relay_grant};44
use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};44
use crate::renegotiation::{MediaAction, MediaNegotiator, MediaPath, RejectedOffer};45
use crate::candidates::{SdpKind, is_udp_relay, negotiated_setup, with_candidates};45
use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};46
use crate::outcome::{embedded_end, failed_participant_count, outcome_summary};46
use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};47
use crate::organizer::{MeetingCapability, Modality, StateStep, Target, modality_steps};47
use crate::meeting_options::{self, OptionWrite};48
use crate::meeting_options::{self, OptionWrite};48
use crate::recording::{Consent, RecordingPlan, RecordingStatus};49
use crate::recording::{Consent, RecordingPlan, RecordingStatus};49
use crate::roster::Roster;50
use crate::roster::{Roster, direct_roster};50
use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};51
use crate::sdp::{LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines, to_browser_answer, to_teams_answer, to_teams_offer};51
use crate::signaling::{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
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
};55
use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};56
use crate::software_audio::{SoftwareAudio, SoftwareAudioPlan};@@ -58,7 +59,7 @@ use crate::timeline::{Timeline, TimelineEntry};58
use crate::transfer::{Replacement, TransferEvent, TransferTarget};59
use crate::transfer::{Replacement, TransferEvent, TransferTarget};59
use crate::video_frame::VideoKey;60
use crate::video_frame::VideoKey;60
use crate::video_layout::{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
use crate::send_control::{RequestFilter, parse_request};64
use crate::send_control::{RequestFilter, parse_request};64
use crate::video_send::{LocalVideo, SendSource, VideoMode};65
use crate::video_send::{LocalVideo, SendSource, VideoMode};@@ -74,6 +75,7 @@ const STATS_PERIOD: Duration = Duration::from_millis(200);74
const TICKS_PER_SECOND: u32 = 5;75
const TICKS_PER_SECOND: u32 = 5;75
const RECONNECT_WINDOW: Duration = Duration::from_secs(30);76
const RECONNECT_WINDOW: Duration = Duration::from_secs(30);76
const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90);77
const OUTGOING_TIMEOUT: Duration = Duration::from_secs(90);78
const DIRECT_OUTGOING_TIMEOUT: Duration = Duration::from_secs(185);77
const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365);79
const FAR_FUTURE: Duration = Duration::from_secs(60 * 60 * 24 * 365);78
const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700;80
const DEFAULT_KEEP_ALIVE_SECONDS: u64 = 2700;79
const MIN_KEEP_ALIVE_SECONDS: u64 = 60;81
const MIN_KEEP_ALIVE_SECONDS: u64 = 60;@@ -88,7 +90,13 @@ const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;88
const BOT_PREFIX: &str = "28:";90
const BOT_PREFIX: &str = "28:";89
const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);91
const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);90
const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);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
const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);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
const CAMERA_STREAM: &str = "camera";100
const CAMERA_STREAM: &str = "camera";93
const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";101
const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";94
102
@@ -268,6 +276,43 @@ struct PeerSession {268
peer: PeerConnection,276
peer: PeerConnection,269
events: mpsc::UnboundedReceiver<PeerEvent>,277
events: mpsc::UnboundedReceiver<PeerEvent>,270
_data_channel: Option<DataChannel>,278
_data_channel: Option<DataChannel>,279
gathered: Gathered,280
}281
282
#[derive(Clone, Default)]283
struct Gathered {284
candidates: Arc<std::sync::Mutex<Vec<String>>>,285
complete: Arc<AtomicBool>,286
relay_seen: Arc<AtomicBool>,287
last_candidate: Arc<std::sync::Mutex<Option<Instant>>>,288
}289
290
impl Gathered {291
/// libwebrtc gathers continually here, so "done" is a relay candidate followed by a quiet spell.292
fn settled(&self) -> bool {293
let quiet = self294
.last_candidate295
.lock()296
.expect("candidate time lock")297
.is_some_and(|at| at.elapsed() >= GATHERING_QUIET);298
self.complete.load(Ordering::SeqCst) || (self.relay_seen.load(Ordering::SeqCst) && quiet)299
}300
301
async fn candidates(&self) -> Vec<String> {302
let waited = Instant::now();303
while !self.settled() && waited.elapsed() < GATHERING_LIMIT {304
tokio::time::sleep(GATHERING_POLL).await;305
}306
self.complete.store(true, Ordering::SeqCst);307
self.candidates.lock().expect("candidates lock").clone()308
}309
}310
311
async fn direct_sdp(teams_sdp: &str, gathered: Option<&Gathered>, kind: SdpKind) -> Result<String> {312
match gathered {313
Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind),314
None => Ok(teams_sdp.to_owned()),315
}271
}316
}272
317
273
struct OfferedMedia {318
struct OfferedMedia {@@ -311,11 +356,19 @@ struct SamePeerOffer {311
reply_tags: Vec<String>,356
reply_tags: Vec<String>,312
}357
}313
358
359
struct GlareResend {360
change: Change,361
reply_tags: Vec<String>,362
at: Instant,363
}364
314
struct NextPeer {365
struct NextPeer {315
session: PeerSession,366
session: PeerSession,316
offered: Option<OfferedMedia>,367
offered: Option<OfferedMedia>,317
reply_tags: Vec<String>,368
reply_tags: Vec<String>,318
deadline: Option<Instant>,369
deadline: Option<Instant>,370
connected: bool,371
retargeted: bool,319
}372
}320
373
321
fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {374
fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {@@ -441,6 +494,26 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s441
.map_err(|error| Error::Webrtc(error.to_string()))?;494
.map_err(|error| Error::Webrtc(error.to_string()))?;442
let (sender, events) = mpsc::unbounded_channel();495
let (sender, events) = mpsc::unbounded_channel();443
let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;496
let data_channel = with_data_channel.then(|| open_data_channel(&peer, sender.clone())).transpose()?;497
let gathered = Gathered::default();498
let candidate_sink = gathered.candidates.clone();499
let relay_seen = gathered.relay_seen.clone();500
let last_candidate = gathered.last_candidate.clone();501
peer.on_ice_candidate(Some(Box::new(move |candidate| {502
if candidate.sdp_mline_index() == 0 {503
let text = candidate.candidate();504
if is_udp_relay(&text) {505
relay_seen.store(true, Ordering::SeqCst);506
}507
*last_candidate.lock().expect("candidate time lock") = Some(Instant::now());508
candidate_sink.lock().expect("candidates lock").push(text);509
}510
})));511
let gathering_done = gathered.complete.clone();512
peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state {513
IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst),514
IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst),515
IceGatheringState::New => {}516
})));444
let ice_sender = sender.clone();517
let ice_sender = sender.clone();445
peer.on_ice_connection_state_change(Some(Box::new(move |state| {518
peer.on_ice_connection_state_change(Some(Box::new(move |state| {446
let _ = ice_sender.send(PeerEvent::Ice(state));519
let _ = ice_sender.send(PeerEvent::Ice(state));@@ -458,7 +531,7 @@ fn open_peer(factory: &PeerConnectionFactory, grant: &RelayGrant, relay_host: &s458
let _ = sender.send(PeerEvent::VideoTrack { mid, track });531
let _ = sender.send(PeerEvent::VideoTrack { mid, track });459
}532
}460
})));533
})));461
Ok(PeerSession { peer, events, _data_channel: data_channel })534
Ok(PeerSession { peer, events, _data_channel: data_channel, gathered })462
}535
}463
536
464
fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {537
fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEvent>) -> Result<DataChannel> {@@ -471,23 +544,43 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv471
Ok(channel)544
Ok(channel)472
}545
}473
546
474
fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {547
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 {475
move |line| match line.kind {548
move |line| match line.kind {476
"video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),549
"video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),477
"video" if camera_mid == CAMERA_MID && line.mid == ONE_TO_ONE_SHARE_MID => Some(if share { "sendonly" } else { INACTIVE }),550
"video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) {551
(true, true) => "sendrecv",552
(true, false) => "sendonly",553
(false, true) => "recvonly",554
(false, false) => INACTIVE,555
}),478
_ => None,556
_ => None,479
}557
}480
}558
}481
559
482
fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, text: &str) -> String {560
fn share_mid_in(offer_text: &str) -> Option<String> {561
let mut mid = None;562
for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) {563
if line.starts_with("m=") {564
mid = None;565
} else if let Some(value) = line.strip_prefix("a=mid:") {566
mid = Some(value.to_owned());567
} else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() {568
return mid;569
}570
}571
None572
}573
574
#[allow(clippy::too_many_arguments)]575
fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, share_mid: Option<&str>, remote_shares: bool, text: &str) -> String {483
match (hold, layout) {576
match (hold, layout) {484
(true, _) => rewrite_directions(text, |_| Some(INACTIVE)),577
(true, _) => rewrite_directions(text, |_| Some(INACTIVE)),485
(false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid)),578
(false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares)),486
(false, Layout::Conference) => text.to_owned(),579
(false, Layout::Conference) => text.to_owned(),487
}580
}488
}581
}489
582
490
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout) -> Result<OfferedMedia> {583
async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, track: &RtcAudioTrack, layout: Layout, gathered: Option<&Gathered>) -> Result<OfferedMedia> {491
let transceiver_init = RtpTransceiverInit {584
let transceiver_init = RtpTransceiverInit {492
direction: RtpTransceiverDirection::SendRecv,585
direction: RtpTransceiverDirection::SendRecv,493
stream_ids: vec![MIC_STREAM.into()],586
stream_ids: vec![MIC_STREAM.into()],@@ -507,13 +600,14 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr507
})600
})508
.await601
.await509
.map_err(|error| Error::Webrtc(error.to_string()))?;602
.map_err(|error| Error::Webrtc(error.to_string()))?;510
let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, &offer.to_string());603
let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, Some(ONE_TO_ONE_SHARE_MID), false, &offer.to_string());511
let description = parse_sdp(&browser_offer, SdpType::Offer)?;604
let description = parse_sdp(&browser_offer, SdpType::Offer)?;512
peer.set_local_description(description)605
peer.set_local_description(description)513
.await606
.await514
.map_err(|error| Error::Webrtc(error.to_string()))?;607
.map_err(|error| Error::Webrtc(error.to_string()))?;515
let mut numbers = random_u32;608
let mut numbers = random_u32;516
let signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;609
let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?;610
signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;517
Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })611
Ok(OfferedMedia { browser_offer, signaled, video, plan, modalities: accepted_modalities(false) })518
}612
}519
613
@@ -521,14 +615,15 @@ struct AnsweredMedia {521
remote: RemoteOffer,615
remote: RemoteOffer,522
answer_sdp: String,616
answer_sdp: String,523
camera_mid: Option<String>,617
camera_mid: Option<String>,618
receiving_share_mid: Option<String>,524
}619
}525
620
526
fn main_video_mid(remote: &RemoteOffer) -> Option<String> {621
fn main_video_mid(remote: &RemoteOffer) -> Option<String> {527
remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())622
remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())528
}623
}529
624
530
fn share_mid(remote: &RemoteOffer) -> Option<String> {625
fn share_mids(remote: &RemoteOffer) -> Vec<String> {531
remote.lines.iter().find(|line| line.role == LineRole::ScreenShare).and_then(|line| line.browser_mids.first().cloned())626
remote.lines.iter().filter(|line| line.role == LineRole::ScreenShare).filter_map(|line| line.browser_mids.first().cloned()).collect()532
}627
}533
628
534
async fn answer_offer(629
async fn answer_offer(@@ -536,8 +631,9 @@ async fn answer_offer(536
track: Option<&RtcAudioTrack>,631
track: Option<&RtcAudioTrack>,537
teams_offer: &str,632
teams_offer: &str,538
video: AnswerVideo<'_>,633
video: AnswerVideo<'_>,539
sharing: bool,634
sending_share_mid: Option<String>,540
camera_on: bool,635
camera_on: bool,636
gathered: Option<&Gathered>,541
) -> Result<AnsweredMedia> {637
) -> Result<AnsweredMedia> {542
let remote = from_teams_offer(teams_offer)?;638
let remote = from_teams_offer(teams_offer)?;543
let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;639
let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;@@ -545,10 +641,13 @@ async fn answer_offer(545
.await641
.await546
.map_err(|error| Error::Webrtc(error.to_string()))?;642
.map_err(|error| Error::Webrtc(error.to_string()))?;547
let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));643
let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));548
let kept_share_mid = share_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));644
let kept_share_mids = if matches!(video, AnswerVideo::Reject) { Vec::new() } else { share_mids(&remote) };549
for transceiver in peer.transceivers() {645
for transceiver in peer.transceivers() {550
let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));646
let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));551
if is_video && transceiver.mid() != camera_mid && transceiver.mid() != kept_share_mid {647
let unused = transceiver648
.mid()649
.is_some_and(|mid| Some(&mid) != camera_mid.as_ref() && !kept_share_mids.contains(&mid) && Some(&mid) != sending_share_mid.as_ref());650
if is_video && unused {552
let _ = transceiver.stop();651
let _ = transceiver.stop();553
}652
}554
}653
}@@ -564,10 +663,10 @@ async fn answer_offer(564
.create_answer(AnswerOptions::default())663
.create_answer(AnswerOptions::default())565
.await664
.await566
.map_err(|error| Error::Webrtc(error.to_string()))?;665
.map_err(|error| Error::Webrtc(error.to_string()))?;567
let mut answer_text = match kept_share_mid.as_deref() {666
let mut answer_text = answer.to_string();568
Some(mid) if !sharing => rewrite_directions(&answer.to_string(), |line| (line.kind == "video" && line.mid == mid).then_some(INACTIVE)),667
for mid in kept_share_mids.iter().filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) {569
_ => answer.to_string(),668
answer_text = stop_sending_on(&answer_text, mid);570
};669
}571
let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));670
let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));572
if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {671
if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {573
answer_text = stop_sending_on(&answer_text, mid);672
answer_text = stop_sending_on(&answer_text, mid);@@ -575,12 +674,17 @@ async fn answer_offer(575
peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)674
peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)576
.await675
.await577
.map_err(|error| Error::Webrtc(error.to_string()))?;676
.map_err(|error| Error::Webrtc(error.to_string()))?;677
let receiving_share_mid = kept_share_mids678
.into_iter()679
.filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))680
.find(|mid| matches!(direction_of(&answer_text, mid).as_deref(), Some("recvonly" | "sendrecv")));578
let mut numbers = random_u32;681
let mut numbers = random_u32;579
let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;682
let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;580
Ok(AnsweredMedia {683
Ok(AnsweredMedia {581
remote,684
remote,582
answer_sdp: signaled.sdp,685
answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,583
camera_mid,686
camera_mid,687
receiving_share_mid,584
})688
})585
}689
}586
690
@@ -691,6 +795,7 @@ async fn drive(691
let mut keep_alive_seconds: Option<u64> = None;795
let mut keep_alive_seconds: Option<u64> = None;692
let mut keep_alive_at: Option<Instant> = None;796
let mut keep_alive_at: Option<Instant> = None;693
let mut outgoing_deadline: Option<Instant> = None;797
let mut outgoing_deadline: Option<Instant> = None;798
let mut outgoing_limit = OUTGOING_TIMEOUT;694
let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);799
let is_meeting = spec.as_ref().is_some_and(CallSpec::is_meeting);695
let is_echo = matches!(spec, Some(CallSpec::Echo));800
let is_echo = matches!(spec, Some(CallSpec::Echo));696
let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count));801
let mut callee_gate = CalleeGate::new(spec.as_ref().map_or(0, CallSpec::callee_count));@@ -700,7 +805,16 @@ async fn drive(700
};805
};701
let people_thread = match &spec {806
let people_thread = match &spec {702
Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),807
Some(CallSpec::People { thread_id, .. }) if !thread_id.is_empty() => Some(thread_id.clone()),703
_ => None,808
_ => incoming_media809
.as_ref()810
.filter(|(notification, _)| !notification.is_multi_party)811
.and_then(|(notification, _)| {812
notification813
.thread_id814
.clone()815
.filter(|thread| *thread != notification.caller.mri)816
.or_else(|| one_to_one_thread(&inner.identity.object_id, ¬ification.caller.mri))817
}),704
};818
};705
let mut layout = match &spec {819
let mut layout = match &spec {706
Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne,820
Some(CallSpec::People { callees, .. }) if callees.len() == 1 => Layout::OneToOne,@@ -717,7 +831,8 @@ async fn drive(717
831
718
let conversation = match (spec, incoming_media) {832
let conversation = match (spec, incoming_media) {719
(Some(spec), None) => {833
(Some(spec), None) => {720
let media = create_offer(¤t.peer, &factory, &track, layout).await?;834
let direct_invite = spec.target().is_one_to_one() && !options.concurrent;835
let media = create_offer(¤t.peer, &factory, &track, layout, direct_invite.then_some(¤t.gathered)).await?;721
layout_plan = media.plan.clone();836
layout_plan = media.plan.clone();722
if layout == Layout::OneToOne {837
if layout == Layout::OneToOne {723
direct_video_mid = Some(CAMERA_MID.to_owned());838
direct_video_mid = Some(CAMERA_MID.to_owned());@@ -748,7 +863,10 @@ async fn drive(748
};863
};749
if spec.is_people() {864
if spec.is_people() {750
control.send(CallUpdate::Progress(Progress::Calling));865
control.send(CallUpdate::Progress(Progress::Calling));751
outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);866
if threadless {867
outgoing_limit = DIRECT_OUTGOING_TIMEOUT;868
}869
outgoing_deadline = Some(Instant::now() + outgoing_limit);752
}870
}753
if let Err(error) = local_video.set_lines(media.video.clone()) {871
if let Err(error) = local_video.set_lines(media.video.clone()) {754
timeline.record("video lines not attached", error.to_string());872
timeline.record("video lines not attached", error.to_string());@@ -786,7 +904,7 @@ async fn drive(786
_ => AnswerVideo::Receive,904
_ => AnswerVideo::Receive,787
};905
};788
dump_sdp(options, "3-teams-offer.sdp", &teams_offer);906
dump_sdp(options, "3-teams-offer.sdp", &teams_offer);789
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer, video_answer, false, false).await?;907
let answered = answer_offer(¤t.peer, Some(&track), &teams_offer, video_answer, None, false, one_to_one.then_some(¤t.gathered)).await?;790
layout_plan = answered.remote.plan();908
layout_plan = answered.remote.plan();791
direct_video_mid = answered.camera_mid.clone();909
direct_video_mid = answered.camera_mid.clone();792
timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));910
timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));@@ -915,6 +1033,9 @@ async fn drive(915
}1033
}916
let mut start_camera_pending = options.start_camera;1034
let mut start_camera_pending = options.start_camera;917
let mut share_pending: Option<ShareSource> = None;1035
let mut share_pending: Option<ShareSource> = None;1036
let mut glare_resend: Option<GlareResend> = None;1037
let mut deferred_changes: Vec<Change> = Vec::new();1038
let mut remote_direct_share: Option<String> = None;918
let mut sent_replacement: Option<Replacement> = None;1039
let mut sent_replacement: Option<Replacement> = None;919
loop {1040
loop {920
if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {1041
if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {@@ -926,11 +1047,61 @@ async fn drive(926
{1047
{927
control.defer(CallCommand::StartShare(source));1048
control.defer(CallCommand::StartShare(source));928
}1049
}1050
if next.as_ref().is_some_and(|pending| pending.connected && (pending.offered.is_some() || pending.retargeted))1051
&& let Some(pending) = next.take()1052
{1053
timeline.record("escalation", "new peer connection connected, old one dropped");1054
deferred_changes.clear();1055
negotiator.server_escalation_done();1056
if let Some(mid) = remote_direct_share.take() {1057
video.router().set(&mid, None);1058
control.send(CallUpdate::ScreenShare(None));1059
}1060
let old = std::mem::replace(&mut current, pending.session);1061
old.peer.close();1062
if let Some(audio) = &software_audio1063
&& let Err(error) = swap_audio_track(¤t.peer, &audio.track)1064
{1065
timeline.record("computer sound not carried over", error.to_string());1066
}1067
offered = pending.offered;1068
if let Some(mid) = direct_video_mid.take() {1069
video.router().set(&mid, None);1070
}1071
if let Some(media) = &offered {1072
layout = Layout::Conference;1073
layout_plan = media.plan.clone();1074
if let Err(error) = local_video.set_lines(media.video.clone()) {1075
timeline.record("video lines not attached", error.to_string());1076
}1077
if local_video.camera_on() {1078
tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);1079
}1080
if local_video.sharing() {1081
tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);1082
}1083
}1084
remote_set = true;1085
if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {1086
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;1087
if pending.is_none() {1088
drop_local_media(&mut local_video, control);1089
}1090
next = pending.or(next);1091
}1092
}929
let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);1093
let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);1094
let glare_at = glare_resend.as_ref().map(|resend| resend.at);930
tokio::select! {1095
tokio::select! {931
Some(callback) = callbacks.recv() => {1096
Some(callback) = callbacks.recv() => {932
match handle_callback(&callback, timeline) {1097
match handle_callback(&callback, timeline) {933
Ok(CallEvent::Acceptance(acceptance)) => {1098
Ok(CallEvent::Acceptance(acceptance)) => {1099
if !acceptance.from_mixer1100
&& let Some(accepted_by) = &acceptance.accepted_by1101
&& roster.apply(&direct_roster(&[(own_mri.as_str(), participant.display_name.as_str()), (accepted_by.mri.as_str(), accepted_by.display_name.as_str())]))1102
{1103
control.send(CallUpdate::Roster(roster.entries()));1104
}934
if !acceptance.from_mixer && callee_gate.callee_joined() {1105
if !acceptance.from_mixer && callee_gate.callee_joined() {935
advance(state, CallSignal::MediaConnected, control);1106
advance(state, CallSignal::MediaConnected, control);936
}1107
}@@ -995,6 +1166,26 @@ async fn drive(995
_ => {}1166
_ => {}996
}1167
}997
}1168
}1169
Ok(CallEvent::MediaAnswer(answer)) if !remote_set && !answer.from_mixer && same_peer.is_none() && next.is_none() && outgoing_deadline.is_some() => {1170
timeline.record("provisional answer", if answer.no_ring_back { "no ringback" } else { "ringing" });1171
outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);1172
if !answer.no_ring_back {1173
control.send(CallUpdate::Progress(Progress::Ringing));1174
}1175
}1176
Ok(CallEvent::MediaAnswer(answer))1177
if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>1178
{1179
if let Some(url) = answer.links.get("mediaAcknowledgement") {1180
let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;1181
}1182
if answer.from_mixer {1183
negotiator.note_mixer_path();1184
}1185
if let Some(resend) = glare_resend.as_mut() {1186
resend.at = Instant::now();1187
}1188
}998
Ok(CallEvent::MediaAnswer(answer)) => {1189
Ok(CallEvent::MediaAnswer(answer)) => {999
let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))1190
let belongs = same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))1000
|| next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags));1191
|| next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags));@@ -1006,6 +1197,11 @@ async fn drive(1006
continue;1197
continue;1007
}1198
}1008
let action = negotiator.on_media_answer();1199
let action = negotiator.on_media_answer();1200
if action == MediaAction::Ignore1201
&& let Some(url) = answer.links.get("mediaAcknowledgement")1202
{1203
let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;1204
}1009
if action == MediaAction::ApplyOnSamePeer1205
if action == MediaAction::ApplyOnSamePeer1010
&& let Some(pending) = same_peer.take()1206
&& let Some(pending) = same_peer.take()1011
{1207
{@@ -1026,7 +1222,7 @@ async fn drive(1026
control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));1222
control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));1027
}1223
}1028
Change::Camera(on) => control.send(CallUpdate::Camera(on)),1224
Change::Camera(on) => control.send(CallUpdate::Camera(on)),1029
Change::Share(true) if !answer.from_mixer && !sends_on(¤t.peer, ONE_TO_ONE_SHARE_MID) => {1225
Change::Share(true) if !answer.from_mixer && !local_video.share_sending() => {1030
local_video.stop_share();1226
local_video.stop_share();1031
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);1227
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);1032
control.send(CallUpdate::LocalShare(None));1228
control.send(CallUpdate::LocalShare(None));@@ -1085,18 +1281,28 @@ async fn drive(1085
}1281
}1086
}1282
}1087
Ok(CallEvent::MediaRenegotiation(renegotiation)) => {1283
Ok(CallEvent::MediaRenegotiation(renegotiation)) => {1284
if !renegotiation.escalation1285
&& !renegotiation.new_offer1286
&& let Some(pending) = same_peer.take()1287
{1288
same_peer_deadline = None;1289
negotiator.same_peer_offer_failed();1290
rollback_offer(¤t.peer).await;1291
timeline.record("glare", "the remote offer is answered first, ours goes out again after");1292
glare_resend = Some(GlareResend { change: pending.change, reply_tags: pending.reply_tags, at: Instant::now() + GLARE_RESEND_LIMIT });1293
}1088
let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);1294
let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);1295
let rejection_link = renegotiation.links.get("rejection").cloned();1089
let result = match action {1296
let result = match action {1090
MediaAction::AnswerOnNewPeer => {1297
MediaAction::AnswerOnNewPeer => {1091
if let Some(pending) = same_peer.take() {1298
if let Some(pending) = same_peer.take() {1092
same_peer_deadline = None;1299
same_peer_deadline = None;1093
timeline.record("same-peer offer", "superseded by the escalation offer");1300
timeline.record("same-peer offer", "superseded by the escalation offer");1094
rollback_offer(¤t.peer).await;1301
rollback_offer(¤t.peer).await;1095
match pending.change {1302
defer_to_new_peer(pending.change, &mut deferred_changes, &mut local_video, control);1096
Change::Camera(true) => control.send(CallUpdate::Camera(true)),1303
}1097
Change::Share(true) => {}1304
if let Some(resend) = glare_resend.take() {1098
change => undo_change(change, &mut local_video, control),1305
defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control);1099
}1100
}1306
}1101
match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {1307
match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {1102
Ok((session, answered)) => {1308
Ok((session, answered)) => {@@ -1106,18 +1312,44 @@ async fn drive(1106
if let Some(replaced) = next.take() {1312
if let Some(replaced) = next.take() {1107
replaced.session.peer.close();1313
replaced.session.peer.close();1108
}1314
}1109
next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: None });1315
next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: Some(Instant::now() + NEXT_PEER_LIMIT), connected: false, retargeted: false });1110
sent1316
sent1111
}1317
}1112
Err(error) => Err(error),1318
Err(error) => {1319
if next.is_none() {1320
negotiator.server_escalation_failed();1321
}1322
for change in deferred_changes.drain(..) {1323
undo_change(change, &mut local_video, control);1324
}1325
if let Some(url) = &rejection_link {1326
let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;1327
}1328
Err(error)1329
}1113
}1330
}1114
}1331
}1115
MediaAction::AnswerOnSamePeer => {1332
MediaAction::AnswerOnSamePeer => {1116
let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };1333
let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };1117
match answer_offer(¤t.peer, None, &renegotiation.sdp, video_answer, local_video.sharing(), local_video.camera_on()).await {1334
match answer_offer(¤t.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(¤t.gathered)).await {1118
Ok(answered) => {1335
Ok(answered) => {1119
timeline.record_sdp("local answer", &answered.answer_sdp);1336
timeline.record_sdp("local answer", &answered.answer_sdp);1120
let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;1337
let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;1338
for mid in answered.remote.plan().screen_share_mids {1339
if !layout_plan.screen_share_mids.contains(&mid) {1340
layout_plan.screen_share_mids.push(mid);1341
}1342
}1343
if layout == Layout::OneToOne && answered.receiving_share_mid != remote_direct_share {1344
if let Some(mid) = &remote_direct_share {1345
video.router().set(mid, None);1346
}1347
if let Some(mid) = &answered.receiving_share_mid {1348
video.router().set(mid, Some(VideoKey::Screen));1349
}1350
remote_direct_share = answered.receiving_share_mid.clone();1351
control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));1352
}1121
let held = is_hold(&renegotiation.sdp).unwrap_or(false);1353
let held = is_hold(&renegotiation.sdp).unwrap_or(false);1122
if held != remote_hold {1354
if held != remote_hold {1123
remote_hold = held;1355
remote_hold = held;@@ -1125,8 +1357,22 @@ async fn drive(1125
}1357
}1126
sent1358
sent1127
}1359
}1128
Err(error) => Err(error),1360
Err(error) => {1361
if current.peer.signaling_state() == SignalingState::HaveRemoteOffer {1362
rollback_remote_offer(¤t.peer).await;1363
}1364
if let Some(url) = &rejection_link {1365
let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::AnswerError).await;1366
}1367
Err(error)1368
}1369
}1370
}1371
MediaAction::RejectGlare => {1372
if let Some(url) = &rejection_link {1373
let _ = remote.signaling.reject_renegotiation(url, &remote.participant, links.call_id(), NegotiationFailure::InProgress).await;1129
}1374
}1375
Ok(())1130
}1376
}1131
_ => Ok(()),1377
_ => Ok(()),1132
};1378
};@@ -1292,6 +1538,9 @@ async fn drive(1292
Ok(CallEvent::Progress(status)) => {1538
Ok(CallEvent::Progress(status)) => {1293
if status == ProgressStatus::Ringing {1539
if status == ProgressStatus::Ringing {1294
control.send(CallUpdate::Progress(Progress::Ringing));1540
control.send(CallUpdate::Progress(Progress::Ringing));1541
if outgoing_deadline.is_some() {1542
outgoing_deadline = Some(Instant::now() + OUTGOING_TIMEOUT);1543
}1295
}1544
}1296
}1545
}1297
Ok(CallEvent::ControlVideoStreaming(body)) => {1546
Ok(CallEvent::ControlVideoStreaming(body)) => {@@ -1320,18 +1569,30 @@ async fn drive(1320
advance(state, CallSignal::RemoteEnd(kind), control);1569
advance(state, CallSignal::RemoteEnd(kind), control);1321
break;1570
break;1322
}1571
}1572
Ok(CallEvent::Rejection(_))1573
if glare_resend.as_ref().is_some_and(|resend| !resend.reply_tags.is_empty() && answers_offer(&callback.path, &resend.reply_tags)) =>1574
{1575
if let Some(resend) = glare_resend.as_mut() {1576
resend.at = Instant::now();1577
}1578
}1323
Ok(CallEvent::Rejection(_))1579
Ok(CallEvent::Rejection(_))1324
if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))1580
if !same_peer.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags))1325
&& !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) =>1581
&& !next.as_ref().is_some_and(|pending| answers_offer(&callback.path, &pending.reply_tags)) =>1326
{1582
{1327
timeline.record("rejection ignored", "it names an offer that is no longer pending");1583
timeline.record("rejection ignored", "it names an offer that is no longer pending");1328
}1584
}1329
Ok(CallEvent::Rejection(_)) => match negotiator.on_rejection() {1585
Ok(CallEvent::Rejection(body)) => match negotiator.on_rejection() {1330
RejectedOffer::SamePeer => {1586
RejectedOffer::SamePeer => {1331
same_peer_deadline = None;1587
same_peer_deadline = None;1332
if let Some(pending) = same_peer.take() {1588
if let Some(pending) = same_peer.take() {1333
rollback_offer(¤t.peer).await;1589
rollback_offer(¤t.peer).await;1334
undo_change(pending.change, &mut local_video, control);1590
if is_glare_rejection(&body) {1591
timeline.record("glare", "our offer met theirs, it goes out again");1592
glare_resend = Some(GlareResend { change: pending.change, reply_tags: Vec::new(), at: Instant::now() + GLARE_RESEND_LIMIT });1593
} else {1594
undo_change(pending.change, &mut local_video, control);1595
}1335
}1596
}1336
}1597
}1337
RejectedOffer::NewPeer => {1598
RejectedOffer::NewPeer => {@@ -1345,13 +1606,16 @@ async fn drive(1345
}1606
}1346
RejectedOffer::None => {}1607
RejectedOffer::None => {}1347
},1608
},1609
Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => {1610
if let Some(pending) = next.as_mut() {1611
pending.retargeted = true;1612
}1613
}1348
Ok(CallEvent::RetargetCompletion(body)) => {1614
Ok(CallEvent::RetargetCompletion(body)) => {1349
if body["retargetCompleted"]["code"].as_i64().is_some_and(|code| code != 0) && let Some(pending) = next.take() {1615
if body["retargetCompleted"]["code"].as_i64().is_some() && let Some(pending) = next.take() {1350
pending.session.peer.close();1616
pending.session.peer.close();1351
negotiator.escalation_failed();1617
negotiator.escalation_failed();1352
if layout == Layout::OneToOne {1618
settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);1353
drop_local_media(&mut local_video, control);1354
}1355
timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");1619
timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");1356
}1620
}1357
}1621
}@@ -1432,39 +1696,11 @@ async fn drive(1432
},1696
},1433
Some(event) = next_peer_event(&mut next) => match event {1697
Some(event) = next_peer_event(&mut next) => match event {1434
PeerEvent::Connection(PeerConnectionState::Connected) => {1698
PeerEvent::Connection(PeerConnectionState::Connected) => {1435
if let Some(pending) = next.take() {1699
if let Some(pending) = next.as_mut() {1436
timeline.record("escalation", "new peer connection connected, old one dropped");1700
pending.connected = true;1437
let old = std::mem::replace(&mut current, pending.session);1701
if pending.offered.is_none() && !pending.retargeted {1438
old.peer.close();1702
pending.deadline = Some(Instant::now() + RETARGET_WAIT);1439
if let Some(audio) = &software_audio1703
timeline.record("escalation", "new peer connection up, waiting for retargetCompletion");1440
&& let Err(error) = swap_audio_track(¤t.peer, &audio.track)1441
{1442
timeline.record("computer sound not carried over", error.to_string());1443
}1444
offered = pending.offered;1445
if let Some(mid) = direct_video_mid.take() {1446
video.router().set(&mid, None);1447
}1448
if let Some(media) = &offered {1449
layout = Layout::Conference;1450
layout_plan = media.plan.clone();1451
if let Err(error) = local_video.set_lines(media.video.clone()) {1452
timeline.record("video lines not attached", error.to_string());1453
}1454
if local_video.camera_on() {1455
tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);1456
}1457
if local_video.sharing() {1458
tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);1459
}1460
}1461
remote_set = true;1462
if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {1463
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;1464
if pending.is_none() {1465
drop_local_media(&mut local_video, control);1466
}1467
next = pending.or(next);1468
}1704
}1469
}1705
}1470
}1706
}@@ -1476,9 +1712,7 @@ async fn drive(1476
negotiator.escalation_failed();1712
negotiator.escalation_failed();1477
if let Some(pending) = next.take() {1713
if let Some(pending) = next.take() {1478
pending.session.peer.close();1714
pending.session.peer.close();1479
}1715
settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);1480
if layout == Layout::OneToOne {1481
drop_local_media(&mut local_video, control);1482
}1716
}1483
timeline.record("escalation failed", "new peer connection failed, staying on the old one");1717
timeline.record("escalation failed", "new peer connection failed, staying on the old one");1484
}1718
}@@ -1554,11 +1788,13 @@ async fn drive(1554
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));1788
control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));1555
} else if local_hold {1789
} else if local_hold {1556
control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));1790
control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));1791
} else if on && direct && (same_peer.is_some() || glare_resend.is_some()) {1792
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));1557
} else if on {1793
} else if on {1558
let started = start_camera_line(&mut local_video, ¤t.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);1794
let started = start_camera_line(&mut local_video, ¤t.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);1559
match started {1795
match started {1560
Ok(()) if direct => {1796
Ok(()) if direct => {1561
match offer_same_peer(¤t.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 {1797
match offer_same_peer(¤t.peer, ¤t.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 {1562
Ok((browser_offer, signaled, reply_tags)) => {1798
Ok((browser_offer, signaled, reply_tags)) => {1563
timeline.record_sdp("local offer", &signaled.sdp);1799
timeline.record_sdp("local offer", &signaled.sdp);1564
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });1800
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });@@ -1576,11 +1812,11 @@ async fn drive(1576
}1812
}1577
Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),1813
Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),1578
}1814
}1579
} else if direct && same_peer.is_some() {1815
} else if direct && (same_peer.is_some() || glare_resend.is_some()) {1580
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));1816
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));1581
} else if direct {1817
} else if direct {1582
local_video.stop_camera();1818
local_video.stop_camera();1583
match offer_same_peer(¤t.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 {1819
match offer_same_peer(¤t.peer, ¤t.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 {1584
Ok((browser_offer, signaled, reply_tags)) => {1820
Ok((browser_offer, signaled, reply_tags)) => {1585
timeline.record_sdp("local offer", &signaled.sdp);1821
timeline.record_sdp("local offer", &signaled.sdp);1586
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });1822
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });@@ -1616,14 +1852,19 @@ async fn drive(1616
Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),1852
Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),1617
Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),1853
Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),1618
}1854
}1619
} else if direct && same_peer.is_some() {1855
} else if direct && (same_peer.is_some() || glare_resend.is_some()) {1620
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));1856
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));1857
} else if direct1858
&& !local_video.has_share_line()1859
&& let Err(error) = attach_share_line(¤t.peer, &factory, &mut local_video, direct_video_mid.as_deref())1860
{1861
control.send(CallUpdate::Notice(format!("Sharing could not start: {error}")));1621
} else if direct {1862
} else if direct {1622
match local_video.start_share(&source) {1863
match local_video.start_share(&source) {1623
Ok(()) => {1864
Ok(()) => {1624
control.send(CallUpdate::LocalShare(Some(source.label())));1865
control.send(CallUpdate::LocalShare(Some(source.label())));1625
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);1866
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);1626
match offer_same_peer(¤t.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 {1867
match offer_same_peer(¤t.peer, ¤t.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 {1627
Ok((browser_offer, signaled, reply_tags)) => {1868
Ok((browser_offer, signaled, reply_tags)) => {1628
timeline.record_sdp("local offer", &signaled.sdp);1869
timeline.record_sdp("local offer", &signaled.sdp);1629
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });1870
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });@@ -1662,13 +1903,13 @@ async fn drive(1662
Some(CallCommand::StopShare) => {1903
Some(CallCommand::StopShare) => {1663
let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;1904
let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;1664
share_pending = None;1905
share_pending = None;1665
if direct && local_video.sharing() && same_peer.is_some() {1906
if direct && local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {1666
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));1907
control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));1667
} else if direct && local_video.sharing() {1908
} else if direct && local_video.sharing() {1668
local_video.stop_share();1909
local_video.stop_share();1669
control.send(CallUpdate::LocalShare(None));1910
control.send(CallUpdate::LocalShare(None));1670
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);1911
sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), ¤t.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);1671
match offer_same_peer(¤t.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 {1912
match offer_same_peer(¤t.peer, ¤t.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 {1672
Ok((browser_offer, signaled, reply_tags)) => {1913
Ok((browser_offer, signaled, reply_tags)) => {1673
timeline.record_sdp("local offer", &signaled.sdp);1914
timeline.record_sdp("local offer", &signaled.sdp);1674
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });1915
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });@@ -1888,7 +2129,7 @@ async fn drive(1888
}2129
}1889
}2130
}1890
Some(CallCommand::Hold(hold)) => {2131
Some(CallCommand::Hold(hold)) => {1891
if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || next.is_some() {2132
if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || glare_resend.is_some() || next.is_some() {1892
continue;2133
continue;1893
}2134
}1894
if hold && local_video.camera_on() {2135
if hold && local_video.camera_on() {@@ -1896,7 +2137,7 @@ async fn drive(1896
control.send(CallUpdate::Camera(false));2137
control.send(CallUpdate::Camera(false));1897
}2138
}1898
let camera = !hold && local_video.camera_on();2139
let camera = !hold && local_video.camera_on();1899
match offer_same_peer(¤t.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 {2140
match offer_same_peer(¤t.peer, ¤t.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 {1900
Ok((browser_offer, signaled, reply_tags)) => {2141
Ok((browser_offer, signaled, reply_tags)) => {1901
timeline.record_sdp("local offer", &signaled.sdp);2142
timeline.record_sdp("local offer", &signaled.sdp);1902
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });2143
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });@@ -2120,18 +2361,52 @@ async fn drive(2120
break;2361
break;2121
}2362
}2122
_ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {2363
_ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {2123
if let Some(pending) = next.take() {2364
if let Some(pending) = next.as_mut().filter(|pending| pending.connected && pending.offered.is_none()) {2365
pending.retargeted = true;2366
timeline.record("escalation", "no retargetCompletion, switching anyway");2367
} else if let Some(pending) = next.take() {2124
pending.session.peer.close();2368
pending.session.peer.close();2125
negotiator.escalation_failed();2369
negotiator.escalation_failed();2126
start_camera_pending = false;2370
start_camera_pending = false;2127
share_pending = None;2371
share_pending = None;2128
if layout == Layout::OneToOne {2372
settle_failed_escalation(pending.offered.is_none(), layout, &mut negotiator, &mut deferred_changes, &mut local_video, control);2129
drop_local_media(&mut local_video, control);2130
}2131
timeline.record("escalation failed", "no answer for the new peer connection in time");2373
timeline.record("escalation failed", "no answer for the new peer connection in time");2132
control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));2374
control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));2133
}2375
}2134
}2376
}2377
_ = sleep_until(glare_at.unwrap_or_else(far_future)), if glare_at.is_some() => {2378
let resend = glare_resend.take();2379
if let Some(resend) = resend.as_ref().filter(|_| same_peer.is_some() || next.is_some()) {2380
timeline.record("glare", "another change took over, ours is dropped");2381
undo_change(resend.change, &mut local_video, control);2382
} else if let Some(resend) = resend.as_ref().filter(|resend| layout == Layout::OneToOne && negotiator.path() == MediaPath::Mixer && !matches!(resend.change, Change::Hold(_))) {2383
if negotiator.begin_conference_upgrade() {2384
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;2385
if pending.is_none() {2386
drop_local_media(&mut local_video, control);2387
}2388
next = pending.or(next);2389
} else {2390
undo_change(resend.change, &mut local_video, control);2391
}2392
} else if let Some(resend) = resend {2393
let (hold, camera, share) = match resend.change {2394
Change::Hold(hold) => (hold, !hold && local_video.camera_on(), local_video.sharing()),2395
_ => (local_hold, local_video.camera_on(), local_video.sharing()),2396
};2397
match offer_same_peer(¤t.peer, ¤t.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 {2398
Ok((browser_offer, signaled, reply_tags)) => {2399
timeline.record_sdp("local offer", &signaled.sdp);2400
same_peer = Some(SamePeerOffer { browser_offer, signaled, change: resend.change, reply_tags });2401
same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);2402
}2403
Err(error) => {2404
timeline.record("offer after glare failed", error.to_string());2405
undo_change(resend.change, &mut local_video, control);2406
}2407
}2408
}2409
}2135
_ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {2410
_ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {2136
same_peer_deadline = None;2411
same_peer_deadline = None;2137
if let Some(pending) = same_peer.take() {2412
if let Some(pending) = same_peer.take() {@@ -2180,7 +2455,7 @@ async fn start_escalation(2180
.get("mediaRenegotiation")2455
.get("mediaRenegotiation")2181
.ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;2456
.ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;2182
let session = open_peer(factory, grant, &options.relay_host, false)?;2457
let session = open_peer(factory, grant, &options.relay_host, false)?;2183
let media = create_offer(&session.peer, factory, track, Layout::Conference).await?;2458
let media = create_offer(&session.peer, factory, track, Layout::Conference, None).await?;2184
let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);2459
let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true, false);2185
let reply_tags = offer_reply_tags(&body);2460
let reply_tags = offer_reply_tags(&body);2186
remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;2461
remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;@@ -2189,6 +2464,8 @@ async fn start_escalation(2189
offered: Some(media),2464
offered: Some(media),2190
reply_tags,2465
reply_tags,2191
deadline: Some(Instant::now() + NEXT_PEER_LIMIT),2466
deadline: Some(Instant::now() + NEXT_PEER_LIMIT),2467
connected: false,2468
retargeted: false,2192
})2469
})2193
}2470
}2194
2471
@@ -2242,7 +2519,7 @@ async fn answer_on_new_peer(2242
teams_offer: &str,2519
teams_offer: &str,2243
) -> Result<(PeerSession, AnsweredMedia)> {2520
) -> Result<(PeerSession, AnsweredMedia)> {2244
let session = open_peer(factory, grant, &options.relay_host, false)?;2521
let session = open_peer(factory, grant, &options.relay_host, false)?;2245
let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, false, false).await?;2522
let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, None, false, None).await?;2246
Ok((session, answered))2523
Ok((session, answered))2247
}2524
}2248
2525
@@ -2353,10 +2630,15 @@ fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {2353
own.is_some_and(|own| own.thread_id == target.thread_id)2630
own.is_some_and(|own| own.thread_id == target.thread_id)2354
}2631
}2355
2632
2356
fn sends_on(peer: &PeerConnection, mid: &str) -> bool {2633
fn attach_share_line(peer: &PeerConnection, factory: &PeerConnectionFactory, local_video: &mut LocalVideo, camera_mid: Option<&str>) -> Result<()> {2357
peer_transceiver(peer, mid)2634
let camera = camera_mid.and_then(|mid| peer_transceiver(peer, mid));2358
.and_then(|transceiver| transceiver.current_direction())2635
if !local_video.has_lines() && camera.is_none() {2359
.is_some_and(|direction| matches!(direction, RtpTransceiverDirection::SendOnly | RtpTransceiverDirection::SendRecv))2636
return Err(Error::Webrtc("no video line negotiated".into()));2637
}2638
let share = add_share_line(peer, factory)?;2639
local_video.add_share_line(share.clone(), camera).inspect_err(|_| {2640
let _ = share.stop();2641
})2360
}2642
}2361
2643
2362
fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {2644
fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {@@ -2379,6 +2661,8 @@ fn start_camera_line(local_video: &mut LocalVideo, peer: &PeerConnection, direct2379
#[allow(clippy::too_many_arguments)]2661
#[allow(clippy::too_many_arguments)]2380
async fn offer_same_peer(2662
async fn offer_same_peer(2381
peer: &PeerConnection,2663
peer: &PeerConnection,2664
gathered: &Gathered,2665
own_share_mid: Option<String>,2382
plan: &OfferPlan,2666
plan: &OfferPlan,2383
layout: Layout,2667
layout: Layout,2384
camera_mid: &str,2668
camera_mid: &str,@@ -2399,7 +2683,7 @@ async fn offer_same_peer(2399
if !negotiator.begin_same_peer_offer() {2683
if !negotiator.begin_same_peer_offer() {2400
return Err(Error::Signaling("another media negotiation is running".into()));2684
return Err(Error::Signaling("another media negotiation is running".into()));2401
}2685
}2402
let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid).await;2686
let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid, own_share_mid, direct.then_some(gathered)).await;2403
let (text, signaled) = match offered {2687
let (text, signaled) = match offered {2404
Ok(offered) => offered,2688
Ok(offered) => offered,2405
Err(error) => {2689
Err(error) => {@@ -2407,7 +2691,7 @@ async fn offer_same_peer(2407
return Err(error);2691
return Err(error);2408
}2692
}2409
};2693
};2410
let modalities = accepted_modalities(layout == Layout::OneToOne && camera && !hold);2694
let modalities = offer_modalities(layout == Layout::OneToOne && camera && !hold, share && !hold);2411
let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);2695
let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);2412
let reply_tags = offer_reply_tags(&body);2696
let reply_tags = offer_reply_tags(&body);2413
if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {2697
if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {@@ -2418,18 +2702,39 @@ async fn offer_same_peer(2418
Ok((text, signaled, reply_tags))2702
Ok((text, signaled, reply_tags))2419
}2703
}2420
2704
2421
async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str) -> Result<(String, SignaledOffer)> {2705
#[allow(clippy::too_many_arguments)]2706
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)> {2422
let offer = peer2707
let offer = peer2423
.create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })2708
.create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })2424
.await2709
.await2425
.map_err(|error| Error::Webrtc(error.to_string()))?;2710
.map_err(|error| Error::Webrtc(error.to_string()))?;2426
let text = directions_for(layout, false, camera, share, camera_mid, &offer.to_string());2711
let offer_text = offer.to_string();2712
let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text));2713
let remote_shares = share_mid.as_deref().is_some_and(|mid| {2714
peer.current_remote_description()2715
.and_then(|remote| direction_of(&remote.to_string(), mid))2716
.is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv"))2717
});2718
let text = directions_for(layout, false, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &offer_text);2427
let description = parse_sdp(&text, SdpType::Offer)?;2719
let description = parse_sdp(&text, SdpType::Offer)?;2428
peer.set_local_description(description)2720
peer.set_local_description(description)2429
.await2721
.await2430
.map_err(|error| Error::Webrtc(error.to_string()))?;2722
.map_err(|error| Error::Webrtc(error.to_string()))?;2431
let mut numbers = random_u32;2723
let mut numbers = random_u32;2432
let signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, &text), plan, &mut numbers)?;2724
let mut plan = plan.clone();2725
if let Some(mid) = share_mid.as_ref().filter(|mid| !plan.screen_share_mids.contains(mid)) {2726
plan.screen_share_mids.push(mid.clone());2727
}2728
let mut signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, share_mid.as_deref(), remote_shares, &text), &plan, &mut numbers)?;2729
signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?;2730
if gathered.is_some()2731
&& let Some(role) = negotiated_setup(2732
peer.current_local_description().map(|local| local.to_string()).as_deref(),2733
peer.current_remote_description().map(|remote| remote.to_string()).as_deref(),2734
)2735
{2736
signaled.sdp = signaled.sdp.replace("a=setup:actpass", &format!("a=setup:{role}"));2737
}2433
Ok((text, signaled))2738
Ok((text, signaled))2434
}2739
}2435
2740
@@ -2448,6 +2753,16 @@ async fn rollback_offer(peer: &PeerConnection) {2448
}2753
}2449
}2754
}2450
2755
2756
async fn rollback_remote_offer(peer: &PeerConnection) {2757
if let Ok(rollback) = parse_sdp("", SdpType::Rollback) {2758
let _ = peer.set_remote_description(rollback).await;2759
}2760
}2761
2762
fn is_glare_rejection(body: &serde_json::Value) -> bool {2763
body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE)2764
}2765
2451
fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {2766
fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {2452
let links = &body["mediaNegotiation"]["links"];2767
let links = &body["mediaNegotiation"]["links"];2453
["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()2768
["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()@@ -2475,6 +2790,29 @@ mod reply_tag_tests {2475
}2790
}2476
}2791
}2477
2792
2793
fn defer_to_new_peer(change: Change, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {2794
match change {2795
Change::Camera(true) => {2796
control.send(CallUpdate::Camera(true));2797
deferred.push(change);2798
}2799
Change::Share(true) => deferred.push(change),2800
change => undo_change(change, local_video, control),2801
}2802
}2803
2804
/// A server escalation that fails leaves the call direct, so only what waited for the new peer is undone.2805
fn settle_failed_escalation(server: bool, layout: Layout, negotiator: &mut MediaNegotiator, deferred: &mut Vec<Change>, local_video: &mut LocalVideo, control: &CallControl) {2806
if server {2807
negotiator.server_escalation_failed();2808
for change in deferred.drain(..) {2809
undo_change(change, local_video, control);2810
}2811
} else if layout == Layout::OneToOne {2812
drop_local_media(local_video, control);2813
}2814
}2815
2478
fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {2816
fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {2479
if local_video.sharing() {2817
if local_video.sharing() {2480
local_video.stop_share();2818
local_video.stop_share();@@ -3227,7 +3565,7 @@ mod tests {3227
let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();3565
let peer = factory.create_peer_connection(RtcConfiguration::default()).unwrap();3228
let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);3566
let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);3229
let track = factory.create_audio_track("microphone", source);3567
let track = factory.create_audio_track("microphone", source);3230
let offer = create_offer(&peer, &factory, &track, layout).await;3568
let offer = create_offer(&peer, &factory, &track, layout, None).await;3231
peer.close();3569
peer.close();3232
offer3570
offer3233
}3571
}@@ -3250,7 +3588,7 @@ mod tests {3250
let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);3588
let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);3251
let track = factory.create_audio_track("microphone", source);3589
let track = factory.create_audio_track("microphone", source);3252
let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");3590
let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");3253
let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, false, false).await;3591
let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, None, false, None).await;3254
peer.close();3592
peer.close();3255
if let Err(error) = answered {3593
if let Err(error) = answered {3256
panic!("{error}");3594
panic!("{error}");@@ -3259,22 +3597,22 @@ mod tests {3259
3597
3260
#[test]3598
#[test]3261
fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {3599
fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {3262
assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);3600
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"]);3263
assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, false, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);3601
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"]);3264
assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, true, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "inactive", "sendonly"]);3602
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"]);3265
}3603
}3266
3604
3267
#[test]3605
#[test]3268
fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {3606
fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {3269
for layout in [Layout::OneToOne, Layout::Conference] {3607
for layout in [Layout::OneToOne, Layout::Conference] {3270
assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);3608
assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, None, false, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);3271
}3609
}3272
assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, BROWSER_OFFER), BROWSER_OFFER);3610
assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, None, false, BROWSER_OFFER), BROWSER_OFFER);3273
}3611
}3274
3612
3275
#[test]3613
#[test]3276
fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {3614
fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {3277
let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, BROWSER_OFFER);3615
let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, None, false, BROWSER_OFFER);3278
let mut numbers = || 7;3616
let mut numbers = || 7;3279
let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;3617
let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;3280
assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);3618
assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);@@ -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 @@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
candidates58
.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_candidates101
.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
}@@ -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<&'st70
lines.join(newline)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
pub fn stop_sending_on(sdp: &str, mid: &str) -> String {82
pub 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
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
modalities155
}156
157
const SCREEN_SHARER: &str = "ScreenSharer";158
140
pub fn accepted_modalities(video: bool) -> Vec<String> {159
pub 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)]149
mod tests {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
#[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
}@@ -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;2
pub mod audio_io;2
pub mod audio_io;3
pub mod background;3
pub mod background;4
pub mod call;4
pub mod call;5
pub mod candidates;5
pub mod callee_gate;6
pub mod callee_gate;6
pub mod blur;7
pub mod blur;7
pub mod breakout;8
pub mod breakout;@@ -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
28
impl Default for MediaNegotiator {29
impl 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();@@ -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.253
pub fn direct_roster(members: &[(&str, &str)]) -> Value {254
let participants: serde_json::Map<String, Value> = members255
.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
fn member_from(mri: &str, participant: &Value, version: u64, previous: Option<&Member>) -> Member {269
fn 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)]376
mod tests {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
use serde_json::json;402
use serde_json::json;378
403
379
use super::*;404
use super::*;@@ -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
26
impl Attribute {26
impl 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_candi993
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) => {}@@ -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)).await608
}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
.await612
.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
impl InviteTarget {680
impl 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)]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
pub fn renegotiation_body(881
pub 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();@@ -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)]99
pub struct AcceptedBy {100
pub mri: String,101
pub display_name: String,95
}102
}96
103
97
impl Acceptance {104
impl Acceptance {@@ -113,6 +120,7 @@ pub enum ProgressStatus {113
pub struct MediaAnswer {120
pub 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,@@ -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";21
const CAMERA_LINE_LABEL: &str = "main-video";21
const CAMERA_LINE_LABEL: &str = "main-video";22
const SHARE_LINE_LABEL: &str = "applicationsharing-video";22
const SHARE_LINE_LABEL: &str = "applicationsharing-video";23
const CAMERA_STREAM: &str = "camera";23
const CAMERA_STREAM: &str = "camera";24
const SCREEN_STREAM: &str = "screen";24
pub const SCREEN_STREAM: &str = "screen";25
const H264: &str = "video/h264";25
const H264: &str = "video/h264";26
const RTX: &str = "video/rtx";26
const RTX: &str = "video/rtx";27
const NO_SOURCE: i64 = -1;27
const 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.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
pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {149
pub 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())?;@@ -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;6
use libwebrtc::peer_connection_factory::PeerConnectionFactory;6
use libwebrtc::peer_connection_factory::PeerConnectionFactory;7
use libwebrtc::rtp_parameters::DegradationPreference;7
use libwebrtc::rtp_parameters::DegradationPreference;8
use libwebrtc::rtp_sender::RtpSender;8
use libwebrtc::rtp_sender::RtpSender;9
use libwebrtc::rtp_transceiver::{RtpTransceiver, RtpTransceiverDirection};9
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;10
use libwebrtc::peer_connection_factory::native::PeerConnectionFactoryExt;10
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};11
use libwebrtc::video_frame::{I420Buffer, VideoBuffer as _, VideoFrame, VideoRotation};11
use libwebrtc::video_source::VideoResolution;12
use 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.lines312
.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::Off319
self.mode != VideoMode::Off294
}320
}