BlueGit

ict rusty-teams

feat(calls): outgoing 1:1 calls go peer-to-peer, the mixer only when needed

- 1:1 invite like Teams web: groupChat null, no mediaDescriptions, requiredFeatures nonByPass. Consult legs stay on the chat thread and the mixer.
- Screen share on a direct call renegotiates the same peer; a mixer answer or a server escalation offer moves the call to a conference peer connection, also when camera or share is turned on later.
- Answers and rejections are matched to their offer by callback tag; superseded offers roll back, own escalations time out after 40 s.
- Incoming accept keeps the acknowledgement links (mediaRenegotiation, callLeg); answers stop advertising camera and share while they are off.
- Bots join threadless calls via addParticipant; rejected m-lines stay out of BUNDLE; retargetCompletion and setup outcomes are logged.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

metis Daniel Däschle · pushed by metis

Authored 2026-10-16 · 6 weeks ago

Hash
7c8173d22006b1eaef9e3831d84c3d20092b4d26
Parent
7550bb8e
9 files changed +536 −92
crates/calling/src/call.rs +312 −48
@@ -36,7 +36,7 @@ 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};
39 use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_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;
@@ -65,7 +65,7 @@ use crate::video_send::{LocalVideo, SendSource, VideoMode};
65 65 use crate::screen::{ShareKind, ShareSource, list_share_sources};
66 66 use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
67 67 use crate::trouter_events::{
68 CallEnd, CallEvent, CallbackLinks, ProgressStatus, classify, decode_body,
68 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
69 69 };
70 70 use crate::whiteboard;
71 71
@@ -87,7 +87,8 @@ const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
87 87 const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
88 88 const BOT_PREFIX: &str = "28:";
89 89 const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
90 const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(15);
90 const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
91 const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
91 92 const CAMERA_STREAM: &str = "camera";
92 93 const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
93 94
@@ -300,17 +301,28 @@ enum AnswerVideo<'a> {
300 301 enum Change {
301 302 Hold(bool),
302 303 Camera(bool),
304 Share(bool),
303 305 }
304 306
305 307 struct SamePeerOffer {
306 308 browser_offer: String,
307 309 signaled: SignaledOffer,
308 310 change: Change,
311 reply_tags: Vec<String>,
309 312 }
310 313
311 314 struct NextPeer {
312 315 session: PeerSession,
313 316 offered: Option<OfferedMedia>,
317 reply_tags: Vec<String>,
318 deadline: Option<Instant>,
319 }
320
321 fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
322 match callback_tag(callback_path) {
323 Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag),
324 _ => true,
325 }
314 326 }
315 327
316 328 #[derive(Clone)]
@@ -318,6 +330,7 @@ struct RemoteCall {
318 330 signaling: Arc<Signaling>,
319 331 conversation: Conversation,
320 332 participant: Participant,
333 threadless: bool,
321 334 }
322 335
323 336 #[derive(Default)]
@@ -458,18 +471,18 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv
458 471 Ok(channel)
459 472 }
460 473
461 fn one_to_one_directions(camera: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> {
462 move |line| match (line.kind, line.mid) {
463 ("video", CAMERA_MID) => Some(if camera { "sendrecv" } else { INACTIVE }),
464 ("video", ONE_TO_ONE_SHARE_MID) => Some(INACTIVE),
474 fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
475 move |line| match line.kind {
476 "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 }),
465 478 _ => None,
466 479 }
467 480 }
468 481
469 fn directions_for(layout: Layout, hold: bool, camera: bool, text: &str) -> String {
482 fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, text: &str) -> String {
470 483 match (hold, layout) {
471 484 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
472 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera)),
485 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid)),
473 486 (false, Layout::Conference) => text.to_owned(),
474 487 }
475 488 }
@@ -494,7 +507,7 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
494 507 })
495 508 .await
496 509 .map_err(|error| Error::Webrtc(error.to_string()))?;
497 let browser_offer = directions_for(layout, false, false, &offer.to_string());
510 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, &offer.to_string());
498 511 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
499 512 peer.set_local_description(description)
500 513 .await
@@ -514,11 +527,17 @@ fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
514 527 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
515 528 }
516 529
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())
532 }
533
517 534 async fn answer_offer(
518 535 peer: &PeerConnection,
519 536 track: Option<&RtcAudioTrack>,
520 537 teams_offer: &str,
521 538 video: AnswerVideo<'_>,
539 sharing: bool,
540 camera_on: bool,
522 541 ) -> Result<AnsweredMedia> {
523 542 let remote = from_teams_offer(teams_offer)?;
524 543 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
@@ -526,9 +545,10 @@ async fn answer_offer(
526 545 .await
527 546 .map_err(|error| Error::Webrtc(error.to_string()))?;
528 547 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));
529 549 for transceiver in peer.transceivers() {
530 550 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
531 if is_video && transceiver.mid() != camera_mid {
551 if is_video && transceiver.mid() != camera_mid && transceiver.mid() != kept_share_mid {
532 552 let _ = transceiver.stop();
533 553 }
534 554 }
@@ -544,11 +564,19 @@ async fn answer_offer(
544 564 .create_answer(AnswerOptions::default())
545 565 .await
546 566 .map_err(|error| Error::Webrtc(error.to_string()))?;
547 peer.set_local_description(answer.clone())
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 };
571 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
572 if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
573 answer_text = stop_sending_on(&answer_text, mid);
574 }
575 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
548 576 .await
549 577 .map_err(|error| Error::Webrtc(error.to_string()))?;
550 578 let mut numbers = random_u32;
551 let signaled = to_teams_answer(&answer.to_string(), &remote, &mut numbers)?;
579 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
552 580 Ok(AnsweredMedia {
553 581 remote,
554 582 answer_sdp: signaled.sdp,
@@ -706,7 +734,9 @@ async fn drive(
706 734 callbacks: &links,
707 735 target: &target,
708 736 modalities: &media.modalities,
737 direct: !options.concurrent,
709 738 };
739 let threadless = invitation.is_direct();
710 740 let conversation = match &target {
711 741 InviteTarget::Meeting(meeting) => {
712 742 let subscribed = control
@@ -728,6 +758,7 @@ async fn drive(
728 758 signaling: signaling.clone(),
729 759 conversation: conversation.clone(),
730 760 participant: participant.clone(),
761 threadless,
731 762 });
732 763 conversation
733 764 }
@@ -744,6 +775,7 @@ async fn drive(
744 775 signaling: signaling.clone(),
745 776 conversation: conversation.clone(),
746 777 participant: participant.clone(),
778 threadless: notification.thread_id.is_none(),
747 779 });
748 780 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
749 781 layout = if one_to_one { Layout::OneToOne } else { Layout::Conference };
@@ -754,7 +786,7 @@ async fn drive(
754 786 _ => AnswerVideo::Receive,
755 787 };
756 788 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
757 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer).await?;
789 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, false, false).await?;
758 790 layout_plan = answered.remote.plan();
759 791 direct_video_mid = answered.camera_mid.clone();
760 792 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
@@ -766,7 +798,7 @@ async fn drive(
766 798 .get("acceptance")
767 799 .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
768 800 let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some());
769 signaling
801 let acknowledged = signaling
770 802 .accept(
771 803 acceptance_url,
772 804 &Answer {
@@ -781,6 +813,7 @@ async fn drive(
781 813 negotiator.answered_incoming(attached.from_mixer);
782 814 remote_set = true;
783 815 media_links.extend(attached.links.clone());
816 media_links.extend(acknowledged);
784 817 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
785 818 let camera = peer_transceiver(&current.peer, mid);
786 819 match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) {
@@ -792,7 +825,7 @@ async fn drive(
792 825 None => timeline.record("video lines not attached", "no transceiver for the camera line"),
793 826 }
794 827 }
795 keep_alive_link = attached.links.get("callLeg").cloned();
828 keep_alive_link = media_links.get("callLeg").cloned();
796 829 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
797 830 conversation
798 831 }
@@ -881,12 +914,19 @@ async fn drive(
881 914 meeting_chat = people_thread;
882 915 }
883 916 let mut start_camera_pending = options.start_camera;
917 let mut share_pending: Option<ShareSource> = None;
884 918 let mut sent_replacement: Option<Replacement> = None;
885 919 loop {
886 920 if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
887 921 start_camera_pending = false;
888 922 control.defer(CallCommand::SetCamera(true));
889 923 }
924 if video_possible(remote_set, layout, negotiator.path())
925 && let Some(source) = share_pending.take()
926 {
927 control.defer(CallCommand::StartShare(source));
928 }
929 let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);
890 930 tokio::select! {
891 931 Some(callback) = callbacks.recv() => {
892 932 match handle_callback(&callback, timeline) {
@@ -956,6 +996,15 @@ async fn drive(
956 996 }
957 997 }
958 998 Ok(CallEvent::MediaAnswer(answer)) => {
999 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));
1001 if (same_peer.is_some() || next.is_some()) && !belongs {
1002 timeline.record("media answer ignored", "it answers an offer that is no longer pending");
1003 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1004 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1005 }
1006 continue;
1007 }
959 1008 let action = negotiator.on_media_answer();
960 1009 if action == MediaAction::ApplyOnSamePeer
961 1010 && let Some(pending) = same_peer.take()
@@ -963,7 +1012,7 @@ async fn drive(
963 1012 same_peer_deadline = None;
964 1013 let applied = match pending.change {
965 1014 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
966 Change::Camera(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1015 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
967 1016 };
968 1017 match applied {
969 1018 Ok(()) => {
@@ -977,6 +1026,28 @@ async fn drive(
977 1026 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
978 1027 }
979 1028 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1029 Change::Share(true) if !answer.from_mixer && !sends_on(&current.peer, ONE_TO_ONE_SHARE_MID) => {
1030 local_video.stop_share();
1031 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1032 control.send(CallUpdate::LocalShare(None));
1033 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1034 }
1035 Change::Share(_) => {}
1036 }
1037 if answer.from_mixer {
1038 media_links.extend(answer.links.clone());
1039 let wants_video = !local_hold && (local_video.camera_on() || local_video.sharing());
1040 let upgrade = wants_video
1041 && (negotiator.escalate_after_mixer_answer() || (layout == Layout::OneToOne && next.is_none() && negotiator.begin_conference_upgrade()));
1042 if !wants_video {
1043 negotiator.note_mixer_path();
1044 } else if upgrade {
1045 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;
1046 if pending.is_none() {
1047 drop_local_media(&mut local_video, control);
1048 }
1049 next = pending.or(next);
1050 }
980 1051 }
981 1052 }
982 1053 Err(error) => {
@@ -1002,7 +1073,12 @@ async fn drive(
1002 1073 }
1003 1074 Err(error) => {
1004 1075 negotiator.escalation_failed();
1005 next = None;
1076 if let Some(pending) = next.take() {
1077 pending.session.peer.close();
1078 }
1079 if layout == Layout::OneToOne {
1080 drop_local_media(&mut local_video, control);
1081 }
1006 1082 timeline.record("escalation answer rejected", error.to_string());
1007 1083 }
1008 1084 }
@@ -1012,12 +1088,25 @@ async fn drive(
1012 1088 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1013 1089 let result = match action {
1014 1090 MediaAction::AnswerOnNewPeer => {
1091 if let Some(pending) = same_peer.take() {
1092 same_peer_deadline = None;
1093 timeline.record("same-peer offer", "superseded by the escalation offer");
1094 rollback_offer(&current.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 }
1100 }
1015 1101 match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1016 1102 Ok((session, answered)) => {
1017 1103 timeline.record_sdp("local answer", &answered.answer_sdp);
1018 1104 live.peers.push(session.peer.clone());
1019 1105 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1020 next = Some(NextPeer { session, offered: None });
1106 if let Some(replaced) = next.take() {
1107 replaced.session.peer.close();
1108 }
1109 next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: None });
1021 1110 sent
1022 1111 }
1023 1112 Err(error) => Err(error),
@@ -1025,7 +1114,7 @@ async fn drive(
1025 1114 }
1026 1115 MediaAction::AnswerOnSamePeer => {
1027 1116 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
1028 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer).await {
1117 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer, local_video.sharing(), local_video.camera_on()).await {
1029 1118 Ok(answered) => {
1030 1119 timeline.record_sdp("local answer", &answered.answer_sdp);
1031 1120 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
@@ -1231,6 +1320,12 @@ async fn drive(
1231 1320 advance(state, CallSignal::RemoteEnd(kind), control);
1232 1321 break;
1233 1322 }
1323 Ok(CallEvent::Rejection(_))
1324 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)) =>
1326 {
1327 timeline.record("rejection ignored", "it names an offer that is no longer pending");
1328 }
1234 1329 Ok(CallEvent::Rejection(_)) => match negotiator.on_rejection() {
1235 1330 RejectedOffer::SamePeer => {
1236 1331 same_peer_deadline = None;
@@ -1243,10 +1338,23 @@ async fn drive(
1243 1338 if let Some(pending) = next.take() {
1244 1339 pending.session.peer.close();
1245 1340 }
1341 if layout == Layout::OneToOne {
1342 drop_local_media(&mut local_video, control);
1343 }
1246 1344 timeline.record("escalation failed", "offer rejected, staying on the old peer connection");
1247 1345 }
1248 1346 RejectedOffer::None => {}
1249 1347 },
1348 Ok(CallEvent::RetargetCompletion(body)) => {
1349 if body["retargetCompleted"]["code"].as_i64().is_some_and(|code| code != 0) && let Some(pending) = next.take() {
1350 pending.session.peer.close();
1351 negotiator.escalation_failed();
1352 if layout == Layout::OneToOne {
1353 drop_local_media(&mut local_video, control);
1354 }
1355 timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");
1356 }
1357 }
1250 1358 Ok(CallEvent::End(end)) => {
1251 1359 let kind = end.kind();
1252 1360 report.end = Some(end);
@@ -1343,8 +1451,21 @@ async fn drive(
1343 1451 if let Err(error) = local_video.set_lines(media.video.clone()) {
1344 1452 timeline.record("video lines not attached", error.to_string());
1345 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 }
1346 1460 }
1347 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 }
1348 1469 }
1349 1470 }
1350 1471 PeerEvent::VideoTrack { mid, track } => {
@@ -1356,6 +1477,9 @@ async fn drive(
1356 1477 if let Some(pending) = next.take() {
1357 1478 pending.session.peer.close();
1358 1479 }
1480 if layout == Layout::OneToOne {
1481 drop_local_media(&mut local_video, control);
1482 }
1359 1483 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
1360 1484 }
1361 1485 _ => {}
@@ -1418,6 +1542,13 @@ async fn drive(
1418 1542 Some(CallCommand::SetCamera(on)) => {
1419 1543 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
1420 1544 if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) {
1545 if remote_set && next.is_none() && negotiator.begin_conference_upgrade() {
1546 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;
1547 next = pending.or(next);
1548 }
1549 if remote_set && on && next.is_some() {
1550 start_camera_pending = true;
1551 }
1421 1552 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1422 1553 } else if on && consent_pending {
1423 1554 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
@@ -1427,10 +1558,10 @@ async fn drive(
1427 1558 let started = start_camera_line(&mut local_video, &current.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
1428 1559 match started {
1429 1560 Ok(()) if direct => {
1430 match offer_same_peer(&current.peer, &layout_plan, layout, false, true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1431 Ok((browser_offer, signaled)) => {
1561 match offer_same_peer(&current.peer, &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, true, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1562 Ok((browser_offer, signaled, reply_tags)) => {
1432 1563 timeline.record_sdp("local offer", &signaled.sdp);
1433 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true) });
1564 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
1434 1565 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1435 1566 }
1436 1567 Err(error) => {
@@ -1445,12 +1576,14 @@ async fn drive(
1445 1576 }
1446 1577 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1447 1578 }
1579 } else if direct && same_peer.is_some() {
1580 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1448 1581 } else if direct {
1449 1582 local_video.stop_camera();
1450 match offer_same_peer(&current.peer, &layout_plan, layout, false, false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1451 Ok((browser_offer, signaled)) => {
1583 match offer_same_peer(&current.peer, &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, false, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1584 Ok((browser_offer, signaled, reply_tags)) => {
1452 1585 timeline.record_sdp("local offer", &signaled.sdp);
1453 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false) });
1586 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
1454 1587 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1455 1588 }
1456 1589 Err(error) => {
@@ -1473,8 +1606,48 @@ async fn drive(
1473 1606 }
1474 1607 }
1475 1608 Some(CallCommand::StartShare(source)) => {
1609 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1476 1610 if !remote_set {
1477 1611 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1612 } else if local_hold {
1613 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1614 } else if direct && local_video.sharing() {
1615 match local_video.start_share(&source) {
1616 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
1617 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1618 }
1619 } else if direct && same_peer.is_some() {
1620 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1621 } else if direct {
1622 match local_video.start_share(&source) {
1623 Ok(()) => {
1624 control.send(CallUpdate::LocalShare(Some(source.label())));
1625 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1626 match offer_same_peer(&current.peer, &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1627 Ok((browser_offer, signaled, reply_tags)) => {
1628 timeline.record_sdp("local offer", &signaled.sdp);
1629 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
1630 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1631 }
1632 Err(error) => {
1633 timeline.record("share offer failed", error.to_string());
1634 undo_change(Change::Share(true), &mut local_video, control);
1635 }
1636 }
1637 }
1638 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1639 }
1640 } else if !video_possible(remote_set, layout, negotiator.path()) {
1641 if next.is_none() && negotiator.begin_conference_upgrade() {
1642 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;
1643 next = pending.or(next);
1644 }
1645 if next.is_some() {
1646 share_pending = Some(source);
1647 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
1648 } else {
1649 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1650 }
1478 1651 } else {
1479 1652 match local_video.start_share(&source) {
1480 1653 Ok(()) => {
@@ -1487,7 +1660,23 @@ async fn drive(
1487 1660 }
1488 1661 }
1489 1662 Some(CallCommand::StopShare) => {
1490 if local_video.sharing() {
1663 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1664 share_pending = None;
1665 if direct && local_video.sharing() && same_peer.is_some() {
1666 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1667 } else if direct && local_video.sharing() {
1668 local_video.stop_share();
1669 control.send(CallUpdate::LocalShare(None));
1670 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1671 match offer_same_peer(&current.peer, &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1672 Ok((browser_offer, signaled, reply_tags)) => {
1673 timeline.record_sdp("local offer", &signaled.sdp);
1674 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
1675 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1676 }
1677 Err(error) => timeline.record("share offer failed", error.to_string()),
1678 }
1679 } else if local_video.sharing() {
1491 1680 local_video.stop_share();
1492 1681 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1493 1682 control.send(CallUpdate::LocalShare(None));
@@ -1699,7 +1888,7 @@ async fn drive(
1699 1888 }
1700 1889 }
1701 1890 Some(CallCommand::Hold(hold)) => {
1702 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() {
1891 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || next.is_some() {
1703 1892 continue;
1704 1893 }
1705 1894 if hold && local_video.camera_on() {
@@ -1707,10 +1896,10 @@ async fn drive(
1707 1896 control.send(CallUpdate::Camera(false));
1708 1897 }
1709 1898 let camera = !hold && local_video.camera_on();
1710 match offer_same_peer(&current.peer, &layout_plan, layout, hold, camera, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1711 Ok((browser_offer, signaled)) => {
1899 match offer_same_peer(&current.peer, &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), hold, camera, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1900 Ok((browser_offer, signaled, reply_tags)) => {
1712 1901 timeline.record_sdp("local offer", &signaled.sdp);
1713 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold) });
1902 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
1714 1903 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1715 1904 }
1716 1905 Err(error) => {
@@ -1930,6 +2119,19 @@ async fn drive(
1930 2119 advance(state, CallSignal::LocalLeave, control);
1931 2120 break;
1932 2121 }
2122 _ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {
2123 if let Some(pending) = next.take() {
2124 pending.session.peer.close();
2125 negotiator.escalation_failed();
2126 start_camera_pending = false;
2127 share_pending = None;
2128 if layout == Layout::OneToOne {
2129 drop_local_media(&mut local_video, control);
2130 }
2131 timeline.record("escalation failed", "no answer for the new peer connection in time");
2132 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2133 }
2134 }
1933 2135 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
1934 2136 same_peer_deadline = None;
1935 2137 if let Some(pending) = same_peer.take() {
@@ -1979,11 +2181,14 @@ async fn start_escalation(
1979 2181 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
1980 2182 let session = open_peer(factory, grant, &options.relay_host, false)?;
1981 2183 let media = create_offer(&session.peer, factory, track, Layout::Conference).await?;
1982 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true);
2184 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);
1983 2186 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
1984 2187 Ok(NextPeer {
1985 2188 session,
1986 2189 offered: Some(media),
2190 reply_tags,
2191 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
1987 2192 })
1988 2193 }
1989 2194
@@ -2037,7 +2242,7 @@ async fn answer_on_new_peer(
2037 2242 teams_offer: &str,
2038 2243 ) -> Result<(PeerSession, AnsweredMedia)> {
2039 2244 let session = open_peer(factory, grant, &options.relay_host, false)?;
2040 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject).await?;
2245 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, false, false).await?;
2041 2246 Ok((session, answered))
2042 2247 }
2043 2248
@@ -2094,6 +2299,10 @@ fn negotiate_video(
2094 2299
2095 2300 const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";
2096 2301 const ON_HOLD_NOTICE: &str = "Resume the call first";
2302 const CHANGE_RUNNING_NOTICE: &str = "Another change is still running, try again in a moment";
2303 const VIDEO_FAILED_NOTICE: &str = "Video could not start, the call stays audio only";
2304 const SHARE_QUEUED_NOTICE: &str = "Sharing starts in a moment";
2305 const SHARE_REFUSED_NOTICE: &str = "The other side did not accept the screen share";
2097 2306
2098 2307 async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
2099 2308 match mode {
@@ -2144,6 +2353,12 @@ fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
2144 2353 own.is_some_and(|own| own.thread_id == target.thread_id)
2145 2354 }
2146 2355
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))
2360 }
2361
2147 2362 fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
2148 2363 peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid))
2149 2364 }
@@ -2166,14 +2381,17 @@ async fn offer_same_peer(
2166 2381 peer: &PeerConnection,
2167 2382 plan: &OfferPlan,
2168 2383 layout: Layout,
2384 camera_mid: &str,
2169 2385 hold: bool,
2170 2386 camera: bool,
2387 share: bool,
2171 2388 remote: &RemoteCall,
2172 2389 links: &CallbackLinks,
2173 2390 media_leg_id: &str,
2174 2391 media_links: &BTreeMap<String, String>,
2175 2392 negotiator: &mut MediaNegotiator,
2176 ) -> Result<(String, SignaledOffer)> {
2393 ) -> Result<(String, SignaledOffer, Vec<String>)> {
2394 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2177 2395 let url = media_links
2178 2396 .get("mediaRenegotiation")
2179 2397 .cloned()
@@ -2181,7 +2399,7 @@ async fn offer_same_peer(
2181 2399 if !negotiator.begin_same_peer_offer() {
2182 2400 return Err(Error::Signaling("another media negotiation is running".into()));
2183 2401 }
2184 let offered = build_same_peer_offer(peer, plan, layout, hold, camera).await;
2402 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid).await;
2185 2403 let (text, signaled) = match offered {
2186 2404 Ok(offered) => offered,
2187 2405 Err(error) => {
@@ -2190,27 +2408,28 @@ async fn offer_same_peer(
2190 2408 }
2191 2409 };
2192 2410 let modalities = accepted_modalities(layout == Layout::OneToOne && camera && !hold);
2193 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false);
2411 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
2412 let reply_tags = offer_reply_tags(&body);
2194 2413 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
2195 2414 negotiator.same_peer_offer_failed();
2196 2415 rollback_offer(peer).await;
2197 2416 return Err(error);
2198 2417 }
2199 Ok((text, signaled))
2418 Ok((text, signaled, reply_tags))
2200 2419 }
2201 2420
2202 async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool) -> Result<(String, SignaledOffer)> {
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)> {
2203 2422 let offer = peer
2204 2423 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
2205 2424 .await
2206 2425 .map_err(|error| Error::Webrtc(error.to_string()))?;
2207 let text = directions_for(layout, false, camera, &offer.to_string());
2426 let text = directions_for(layout, false, camera, share, camera_mid, &offer.to_string());
2208 2427 let description = parse_sdp(&text, SdpType::Offer)?;
2209 2428 peer.set_local_description(description)
2210 2429 .await
2211 2430 .map_err(|error| Error::Webrtc(error.to_string()))?;
2212 2431 let mut numbers = random_u32;
2213 let signaled = to_teams_offer(&directions_for(layout, hold, camera, &text), plan, &mut numbers)?;
2432 let signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, &text), plan, &mut numbers)?;
2214 2433 Ok((text, signaled))
2215 2434 }
2216 2435
@@ -2229,6 +2448,44 @@ async fn rollback_offer(peer: &PeerConnection) {
2229 2448 }
2230 2449 }
2231 2450
2451 fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2452 let links = &body["mediaNegotiation"]["links"];
2453 ["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
2454 }
2455
2456 #[cfg(test)]
2457 mod reply_tag_tests {
2458 use super::*;
2459
2460 #[test]
2461 fn answers_and_rejections_match_the_offer_by_tag() {
2462 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
2463 assert!(answers_offer("callAgent/c/aaaa1111/call/mediaAnswer/", &tags));
2464 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
2465 assert!(!answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &tags));
2466 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
2467 }
2468
2469 #[test]
2470 fn an_offer_names_both_reply_tags() {
2471 let body = serde_json::json!({"mediaNegotiation": {"links": {
2472 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
2473 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
2474 assert_eq!(offer_reply_tags(&body), vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]);
2475 }
2476 }
2477
2478 fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2479 if local_video.sharing() {
2480 local_video.stop_share();
2481 control.send(CallUpdate::LocalShare(None));
2482 }
2483 if local_video.camera_on() {
2484 local_video.stop_camera();
2485 control.send(CallUpdate::Camera(false));
2486 }
2487 }
2488
2232 2489 fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {
2233 2490 match change {
2234 2491 Change::Camera(true) => {
@@ -2236,6 +2493,12 @@ fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallContr
2236 2493 control.send(CallUpdate::Camera(false));
2237 2494 }
2238 2495 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
2496 Change::Share(true) => {
2497 local_video.stop_share();
2498 control.send(CallUpdate::LocalShare(None));
2499 control.send(CallUpdate::Notice("Sharing could not start".into()));
2500 }
2501 Change::Share(false) => {}
2239 2502 Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())),
2240 2503 }
2241 2504 }
@@ -2353,7 +2616,7 @@ async fn run_bot_steps(
2353 2616 return fail(flow, "This call has no chat for the captions and the recording");
2354 2617 };
2355 2618 *bot_pending = true;
2356 let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links).await;
2619 let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links, remote.threadless).await;
2357 2620 if job == BotJob::Recording {
2358 2621 report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline);
2359 2622 }
@@ -2672,7 +2935,7 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
2672 2935 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
2673 2936 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
2674 2937 CallEvent::Progress(status) => format!("{status:?}"),
2675 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) => outcome_summary(body),
2938 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) | CallEvent::RetargetCompletion(body) => outcome_summary(body),
2676 2939 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
2677 2940 _ => String::new(),
2678 2941 };
@@ -2987,7 +3250,7 @@ mod tests {
2987 3250 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
2988 3251 let track = factory.create_audio_track("microphone", source);
2989 3252 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
2990 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive).await;
3253 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, false, false).await;
2991 3254 peer.close();
2992 3255 if let Err(error) = answered {
2993 3256 panic!("{error}");
@@ -2996,21 +3259,22 @@ mod tests {
2996 3259
2997 3260 #[test]
2998 3261 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
2999 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3000 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "inactive"]);
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"]);
3001 3265 }
3002 3266
3003 3267 #[test]
3004 3268 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3005 3269 for layout in [Layout::OneToOne, Layout::Conference] {
3006 assert_eq!(directions(&directions_for(layout, true, true, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3270 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3007 3271 }
3008 assert_eq!(directions_for(Layout::Conference, false, true, BROWSER_OFFER), BROWSER_OFFER);
3272 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, BROWSER_OFFER), BROWSER_OFFER);
3009 3273 }
3010 3274
3011 3275 #[test]
3012 3276 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3013 let held = directions_for(Layout::Conference, true, false, BROWSER_OFFER);
3277 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, BROWSER_OFFER);
3014 3278 let mut numbers = || 7;
3015 3279 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
3016 3280 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
@@ -36,7 +36,7 @@ use crate::end::EndKind;
36use crate::engine::{CallEngine, EngineConfig, Inner};
36use crate::engine::{CallEngine, EngineConfig, Inner};
37use crate::error::{Error, Result};
37use crate::error::{Error, Result};
38use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
38use crate::health::{CallHealth, HealthCounters, HealthSampler, QualityTracker, TransportDetails, health_from_stats};
39use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, keep_media_running, rewrite_directions};
39use crate::hold::{HoldState, INACTIVE, MediaLine, accepted_modalities, is_hold, keep_media_running, rewrite_directions, stop_sending_on};
40use crate::mic_processing::MicSettings;
40use crate::mic_processing::MicSettings;
41use crate::mute::{MuteCommand, MuteEffect};
41use crate::mute::{MuteCommand, MuteEffect};
42use crate::push::CallNotification;
42use crate::push::CallNotification;
@@ -65,7 +65,7 @@ use crate::video_send::{LocalVideo, SendSource, VideoMode};
65use crate::screen::{ShareKind, ShareSource, list_share_sources};
65use crate::screen::{ShareKind, ShareSource, list_share_sources};
66use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
66use crate::video_receive::{ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump};
67use crate::trouter_events::{
67use crate::trouter_events::{
68 CallEnd, CallEvent, CallbackLinks, ProgressStatus, classify, decode_body,
68 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
69};
69};
70use crate::whiteboard;
70use crate::whiteboard;
71
71
@@ -87,7 +87,8 @@ const BLUR_TIMING_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
87const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
87const HEALTH_EVERY_TICKS: u32 = TICKS_PER_SECOND * 2;
88const BOT_PREFIX: &str = "28:";
88const BOT_PREFIX: &str = "28:";
89const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
89const RECORDING_START_LIMIT: Duration = Duration::from_secs(40);
90const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(15);
90const SAME_PEER_ANSWER_LIMIT: Duration = Duration::from_secs(40);
91const NEXT_PEER_LIMIT: Duration = Duration::from_secs(40);
91const CAMERA_STREAM: &str = "camera";
92const CAMERA_STREAM: &str = "camera";
92const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
93const CONSENT_FIRST_NOTICE: &str = "Accept the recording notice first";
93
94
@@ -300,17 +301,28 @@ enum AnswerVideo<'a> {
300enum Change {
301enum Change {
301 Hold(bool),
302 Hold(bool),
302 Camera(bool),
303 Camera(bool),
304 Share(bool),
303}
305}
304
306
305struct SamePeerOffer {
307struct SamePeerOffer {
306 browser_offer: String,
308 browser_offer: String,
307 signaled: SignaledOffer,
309 signaled: SignaledOffer,
308 change: Change,
310 change: Change,
311 reply_tags: Vec<String>,
309}
312}
310
313
311struct NextPeer {
314struct NextPeer {
312 session: PeerSession,
315 session: PeerSession,
313 offered: Option<OfferedMedia>,
316 offered: Option<OfferedMedia>,
317 reply_tags: Vec<String>,
318 deadline: Option<Instant>,
319}
320
321fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
322 match callback_tag(callback_path) {
323 Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag),
324 _ => true,
325 }
314}
326}
315
327
316#[derive(Clone)]
328#[derive(Clone)]
@@ -318,6 +330,7 @@ struct RemoteCall {
318 signaling: Arc<Signaling>,
330 signaling: Arc<Signaling>,
319 conversation: Conversation,
331 conversation: Conversation,
320 participant: Participant,
332 participant: Participant,
333 threadless: bool,
321}
334}
322
335
323#[derive(Default)]
336#[derive(Default)]
@@ -458,18 +471,18 @@ fn open_data_channel(peer: &PeerConnection, sender: mpsc::UnboundedSender<PeerEv
458 Ok(channel)
471 Ok(channel)
459}
472}
460
473
461fn one_to_one_directions(camera: bool) -> impl Fn(MediaLine<'_>) -> Option<&'static str> {
474fn one_to_one_directions<'a>(camera: bool, share: bool, camera_mid: &'a str) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a {
462 move |line| match (line.kind, line.mid) {
475 move |line| match line.kind {
463 ("video", CAMERA_MID) => Some(if camera { "sendrecv" } else { INACTIVE }),
476 "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }),
464 ("video", ONE_TO_ONE_SHARE_MID) => Some(INACTIVE),
477 "video" if camera_mid == CAMERA_MID && line.mid == ONE_TO_ONE_SHARE_MID => Some(if share { "sendonly" } else { INACTIVE }),
465 _ => None,
478 _ => None,
466 }
479 }
467}
480}
468
481
469fn directions_for(layout: Layout, hold: bool, camera: bool, text: &str) -> String {
482fn directions_for(layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str, text: &str) -> String {
470 match (hold, layout) {
483 match (hold, layout) {
471 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
484 (true, _) => rewrite_directions(text, |_| Some(INACTIVE)),
472 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera)),
485 (false, Layout::OneToOne) => rewrite_directions(text, one_to_one_directions(camera, share, camera_mid)),
473 (false, Layout::Conference) => text.to_owned(),
486 (false, Layout::Conference) => text.to_owned(),
474 }
487 }
475}
488}
@@ -494,7 +507,7 @@ async fn create_offer(peer: &PeerConnection, factory: &PeerConnectionFactory, tr
494 })
507 })
495 .await
508 .await
496 .map_err(|error| Error::Webrtc(error.to_string()))?;
509 .map_err(|error| Error::Webrtc(error.to_string()))?;
497 let browser_offer = directions_for(layout, false, false, &offer.to_string());
510 let browser_offer = directions_for(layout, false, false, false, CAMERA_MID, &offer.to_string());
498 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
511 let description = parse_sdp(&browser_offer, SdpType::Offer)?;
499 peer.set_local_description(description)
512 peer.set_local_description(description)
500 .await
513 .await
@@ -514,11 +527,17 @@ fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
514 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
527 remote.lines.iter().find(|line| line.role == LineRole::MainVideo).and_then(|line| line.browser_mids.first().cloned())
515}
528}
516
529
530fn share_mid(remote: &RemoteOffer) -> Option<String> {
531 remote.lines.iter().find(|line| line.role == LineRole::ScreenShare).and_then(|line| line.browser_mids.first().cloned())
532}
533
517async fn answer_offer(
534async fn answer_offer(
518 peer: &PeerConnection,
535 peer: &PeerConnection,
519 track: Option<&RtcAudioTrack>,
536 track: Option<&RtcAudioTrack>,
520 teams_offer: &str,
537 teams_offer: &str,
521 video: AnswerVideo<'_>,
538 video: AnswerVideo<'_>,
539 sharing: bool,
540 camera_on: bool,
522) -> Result<AnsweredMedia> {
541) -> Result<AnsweredMedia> {
523 let remote = from_teams_offer(teams_offer)?;
542 let remote = from_teams_offer(teams_offer)?;
524 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
543 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
@@ -526,9 +545,10 @@ async fn answer_offer(
526 .await
545 .await
527 .map_err(|error| Error::Webrtc(error.to_string()))?;
546 .map_err(|error| Error::Webrtc(error.to_string()))?;
528 let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject));
547 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));
529 for transceiver in peer.transceivers() {
549 for transceiver in peer.transceivers() {
530 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
550 let is_video = matches!(transceiver.receiver().track(), Some(MediaStreamTrack::Video(_)));
531 if is_video && transceiver.mid() != camera_mid {
551 if is_video && transceiver.mid() != camera_mid && transceiver.mid() != kept_share_mid {
532 let _ = transceiver.stop();
552 let _ = transceiver.stop();
533 }
553 }
534 }
554 }
@@ -544,11 +564,19 @@ async fn answer_offer(
544 .create_answer(AnswerOptions::default())
564 .create_answer(AnswerOptions::default())
545 .await
565 .await
546 .map_err(|error| Error::Webrtc(error.to_string()))?;
566 .map_err(|error| Error::Webrtc(error.to_string()))?;
547 peer.set_local_description(answer.clone())
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 };
571 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
572 if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
573 answer_text = stop_sending_on(&answer_text, mid);
574 }
575 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
548 .await
576 .await
549 .map_err(|error| Error::Webrtc(error.to_string()))?;
577 .map_err(|error| Error::Webrtc(error.to_string()))?;
550 let mut numbers = random_u32;
578 let mut numbers = random_u32;
551 let signaled = to_teams_answer(&answer.to_string(), &remote, &mut numbers)?;
579 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
552 Ok(AnsweredMedia {
580 Ok(AnsweredMedia {
553 remote,
581 remote,
554 answer_sdp: signaled.sdp,
582 answer_sdp: signaled.sdp,
@@ -706,7 +734,9 @@ async fn drive(
706 callbacks: &links,
734 callbacks: &links,
707 target: &target,
735 target: &target,
708 modalities: &media.modalities,
736 modalities: &media.modalities,
737 direct: !options.concurrent,
709 };
738 };
739 let threadless = invitation.is_direct();
710 let conversation = match &target {
740 let conversation = match &target {
711 InviteTarget::Meeting(meeting) => {
741 InviteTarget::Meeting(meeting) => {
712 let subscribed = control
742 let subscribed = control
@@ -728,6 +758,7 @@ async fn drive(
728 signaling: signaling.clone(),
758 signaling: signaling.clone(),
729 conversation: conversation.clone(),
759 conversation: conversation.clone(),
730 participant: participant.clone(),
760 participant: participant.clone(),
761 threadless,
731 });
762 });
732 conversation
763 conversation
733 }
764 }
@@ -744,6 +775,7 @@ async fn drive(
744 signaling: signaling.clone(),
775 signaling: signaling.clone(),
745 conversation: conversation.clone(),
776 conversation: conversation.clone(),
746 participant: participant.clone(),
777 participant: participant.clone(),
778 threadless: notification.thread_id.is_none(),
747 });
779 });
748 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
780 let one_to_one = !attached.from_mixer && !notification.is_multi_party;
749 layout = if one_to_one { Layout::OneToOne } else { Layout::Conference };
781 layout = if one_to_one { Layout::OneToOne } else { Layout::Conference };
@@ -754,7 +786,7 @@ async fn drive(
754 _ => AnswerVideo::Receive,
786 _ => AnswerVideo::Receive,
755 };
787 };
756 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
788 dump_sdp(options, "3-teams-offer.sdp", &teams_offer);
757 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer).await?;
789 let answered = answer_offer(&current.peer, Some(&track), &teams_offer, video_answer, false, false).await?;
758 layout_plan = answered.remote.plan();
790 layout_plan = answered.remote.plan();
759 direct_video_mid = answered.camera_mid.clone();
791 direct_video_mid = answered.camera_mid.clone();
760 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
792 timeline.record("setRemoteDescription", format!("offer applied, {} signaled line(s)", answered.remote.lines.len()));
@@ -766,7 +798,7 @@ async fn drive(
766 .get("acceptance")
798 .get("acceptance")
767 .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
799 .ok_or_else(|| Error::Signaling("attach answer without an acceptance link".into()))?;
768 let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some());
800 let modalities = accepted_modalities(matches!(video_answer, AnswerVideo::Send(_)) && answered.camera_mid.is_some());
769 signaling
801 let acknowledged = signaling
770 .accept(
802 .accept(
771 acceptance_url,
803 acceptance_url,
772 &Answer {
804 &Answer {
@@ -781,6 +813,7 @@ async fn drive(
781 negotiator.answered_incoming(attached.from_mixer);
813 negotiator.answered_incoming(attached.from_mixer);
782 remote_set = true;
814 remote_set = true;
783 media_links.extend(attached.links.clone());
815 media_links.extend(attached.links.clone());
816 media_links.extend(acknowledged);
784 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
817 if let (AnswerVideo::Send(_), Some(mid)) = (video_answer, &answered.camera_mid) {
785 let camera = peer_transceiver(&current.peer, mid);
818 let camera = peer_transceiver(&current.peer, mid);
786 match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) {
819 match camera.map(|camera| local_video.set_lines(VideoLines { camera, share: None })) {
@@ -792,7 +825,7 @@ async fn drive(
792 None => timeline.record("video lines not attached", "no transceiver for the camera line"),
825 None => timeline.record("video lines not attached", "no transceiver for the camera line"),
793 }
826 }
794 }
827 }
795 keep_alive_link = attached.links.get("callLeg").cloned();
828 keep_alive_link = media_links.get("callLeg").cloned();
796 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
829 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
797 conversation
830 conversation
798 }
831 }
@@ -881,12 +914,19 @@ async fn drive(
881 meeting_chat = people_thread;
914 meeting_chat = people_thread;
882 }
915 }
883 let mut start_camera_pending = options.start_camera;
916 let mut start_camera_pending = options.start_camera;
917 let mut share_pending: Option<ShareSource> = None;
884 let mut sent_replacement: Option<Replacement> = None;
918 let mut sent_replacement: Option<Replacement> = None;
885 loop {
919 loop {
886 if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
920 if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
887 start_camera_pending = false;
921 start_camera_pending = false;
888 control.defer(CallCommand::SetCamera(true));
922 control.defer(CallCommand::SetCamera(true));
889 }
923 }
924 if video_possible(remote_set, layout, negotiator.path())
925 && let Some(source) = share_pending.take()
926 {
927 control.defer(CallCommand::StartShare(source));
928 }
929 let next_peer_deadline = next.as_ref().and_then(|pending| pending.deadline);
890 tokio::select! {
930 tokio::select! {
891 Some(callback) = callbacks.recv() => {
931 Some(callback) = callbacks.recv() => {
892 match handle_callback(&callback, timeline) {
932 match handle_callback(&callback, timeline) {
@@ -956,6 +996,15 @@ async fn drive(
956 }
996 }
957 }
997 }
958 Ok(CallEvent::MediaAnswer(answer)) => {
998 Ok(CallEvent::MediaAnswer(answer)) => {
999 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));
1001 if (same_peer.is_some() || next.is_some()) && !belongs {
1002 timeline.record("media answer ignored", "it answers an offer that is no longer pending");
1003 if let Some(url) = answer.links.get("mediaAcknowledgement") {
1004 let _ = remote.signaling.post_empty("POST mediaAcknowledgement", url).await;
1005 }
1006 continue;
1007 }
959 let action = negotiator.on_media_answer();
1008 let action = negotiator.on_media_answer();
960 if action == MediaAction::ApplyOnSamePeer
1009 if action == MediaAction::ApplyOnSamePeer
961 && let Some(pending) = same_peer.take()
1010 && let Some(pending) = same_peer.take()
@@ -963,7 +1012,7 @@ async fn drive(
963 same_peer_deadline = None;
1012 same_peer_deadline = None;
964 let applied = match pending.change {
1013 let applied = match pending.change {
965 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1014 Change::Hold(_) => apply_hold_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
966 Change::Camera(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
1015 Change::Camera(_) | Change::Share(_) => apply_answer(&current.peer, &answer.sdp, &pending.signaled, &pending.browser_offer).await,
967 };
1016 };
968 match applied {
1017 match applied {
969 Ok(()) => {
1018 Ok(()) => {
@@ -977,6 +1026,28 @@ async fn drive(
977 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1026 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
978 }
1027 }
979 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1028 Change::Camera(on) => control.send(CallUpdate::Camera(on)),
1029 Change::Share(true) if !answer.from_mixer && !sends_on(&current.peer, ONE_TO_ONE_SHARE_MID) => {
1030 local_video.stop_share();
1031 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1032 control.send(CallUpdate::LocalShare(None));
1033 control.send(CallUpdate::Notice(SHARE_REFUSED_NOTICE.into()));
1034 }
1035 Change::Share(_) => {}
1036 }
1037 if answer.from_mixer {
1038 media_links.extend(answer.links.clone());
1039 let wants_video = !local_hold && (local_video.camera_on() || local_video.sharing());
1040 let upgrade = wants_video
1041 && (negotiator.escalate_after_mixer_answer() || (layout == Layout::OneToOne && next.is_none() && negotiator.begin_conference_upgrade()));
1042 if !wants_video {
1043 negotiator.note_mixer_path();
1044 } else if upgrade {
1045 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;
1046 if pending.is_none() {
1047 drop_local_media(&mut local_video, control);
1048 }
1049 next = pending.or(next);
1050 }
980 }
1051 }
981 }
1052 }
982 Err(error) => {
1053 Err(error) => {
@@ -1002,7 +1073,12 @@ async fn drive(
1002 }
1073 }
1003 Err(error) => {
1074 Err(error) => {
1004 negotiator.escalation_failed();
1075 negotiator.escalation_failed();
1005 next = None;
1076 if let Some(pending) = next.take() {
1077 pending.session.peer.close();
1078 }
1079 if layout == Layout::OneToOne {
1080 drop_local_media(&mut local_video, control);
1081 }
1006 timeline.record("escalation answer rejected", error.to_string());
1082 timeline.record("escalation answer rejected", error.to_string());
1007 }
1083 }
1008 }
1084 }
@@ -1012,12 +1088,25 @@ async fn drive(
1012 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1088 let action = negotiator.on_renegotiation(renegotiation.new_offer, renegotiation.escalation);
1013 let result = match action {
1089 let result = match action {
1014 MediaAction::AnswerOnNewPeer => {
1090 MediaAction::AnswerOnNewPeer => {
1091 if let Some(pending) = same_peer.take() {
1092 same_peer_deadline = None;
1093 timeline.record("same-peer offer", "superseded by the escalation offer");
1094 rollback_offer(&current.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 }
1100 }
1015 match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1101 match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1016 Ok((session, answered)) => {
1102 Ok((session, answered)) => {
1017 timeline.record_sdp("local answer", &answered.answer_sdp);
1103 timeline.record_sdp("local answer", &answered.answer_sdp);
1018 live.peers.push(session.peer.clone());
1104 live.peers.push(session.peer.clone());
1019 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1105 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1020 next = Some(NextPeer { session, offered: None });
1106 if let Some(replaced) = next.take() {
1107 replaced.session.peer.close();
1108 }
1109 next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: None });
1021 sent
1110 sent
1022 }
1111 }
1023 Err(error) => Err(error),
1112 Err(error) => Err(error),
@@ -1025,7 +1114,7 @@ async fn drive(
1025 }
1114 }
1026 MediaAction::AnswerOnSamePeer => {
1115 MediaAction::AnswerOnSamePeer => {
1027 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
1116 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
1028 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer).await {
1117 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer, local_video.sharing(), local_video.camera_on()).await {
1029 Ok(answered) => {
1118 Ok(answered) => {
1030 timeline.record_sdp("local answer", &answered.answer_sdp);
1119 timeline.record_sdp("local answer", &answered.answer_sdp);
1031 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
1120 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
@@ -1231,6 +1320,12 @@ async fn drive(
1231 advance(state, CallSignal::RemoteEnd(kind), control);
1320 advance(state, CallSignal::RemoteEnd(kind), control);
1232 break;
1321 break;
1233 }
1322 }
1323 Ok(CallEvent::Rejection(_))
1324 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)) =>
1326 {
1327 timeline.record("rejection ignored", "it names an offer that is no longer pending");
1328 }
1234 Ok(CallEvent::Rejection(_)) => match negotiator.on_rejection() {
1329 Ok(CallEvent::Rejection(_)) => match negotiator.on_rejection() {
1235 RejectedOffer::SamePeer => {
1330 RejectedOffer::SamePeer => {
1236 same_peer_deadline = None;
1331 same_peer_deadline = None;
@@ -1243,10 +1338,23 @@ async fn drive(
1243 if let Some(pending) = next.take() {
1338 if let Some(pending) = next.take() {
1244 pending.session.peer.close();
1339 pending.session.peer.close();
1245 }
1340 }
1341 if layout == Layout::OneToOne {
1342 drop_local_media(&mut local_video, control);
1343 }
1246 timeline.record("escalation failed", "offer rejected, staying on the old peer connection");
1344 timeline.record("escalation failed", "offer rejected, staying on the old peer connection");
1247 }
1345 }
1248 RejectedOffer::None => {}
1346 RejectedOffer::None => {}
1249 },
1347 },
1348 Ok(CallEvent::RetargetCompletion(body)) => {
1349 if body["retargetCompleted"]["code"].as_i64().is_some_and(|code| code != 0) && let Some(pending) = next.take() {
1350 pending.session.peer.close();
1351 negotiator.escalation_failed();
1352 if layout == Layout::OneToOne {
1353 drop_local_media(&mut local_video, control);
1354 }
1355 timeline.record("escalation failed", "retarget rejected, staying on the old peer connection");
1356 }
1357 }
1250 Ok(CallEvent::End(end)) => {
1358 Ok(CallEvent::End(end)) => {
1251 let kind = end.kind();
1359 let kind = end.kind();
1252 report.end = Some(end);
1360 report.end = Some(end);
@@ -1343,8 +1451,21 @@ async fn drive(
1343 if let Err(error) = local_video.set_lines(media.video.clone()) {
1451 if let Err(error) = local_video.set_lines(media.video.clone()) {
1344 timeline.record("video lines not attached", error.to_string());
1452 timeline.record("video lines not attached", error.to_string());
1345 }
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 }
1346 }
1460 }
1347 remote_set = true;
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 }
1348 }
1469 }
1349 }
1470 }
1350 PeerEvent::VideoTrack { mid, track } => {
1471 PeerEvent::VideoTrack { mid, track } => {
@@ -1356,6 +1477,9 @@ async fn drive(
1356 if let Some(pending) = next.take() {
1477 if let Some(pending) = next.take() {
1357 pending.session.peer.close();
1478 pending.session.peer.close();
1358 }
1479 }
1480 if layout == Layout::OneToOne {
1481 drop_local_media(&mut local_video, control);
1482 }
1359 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
1483 timeline.record("escalation failed", "new peer connection failed, staying on the old one");
1360 }
1484 }
1361 _ => {}
1485 _ => {}
@@ -1418,6 +1542,13 @@ async fn drive(
1418 Some(CallCommand::SetCamera(on)) => {
1542 Some(CallCommand::SetCamera(on)) => {
1419 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
1543 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
1420 if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) {
1544 if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) {
1545 if remote_set && next.is_none() && negotiator.begin_conference_upgrade() {
1546 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;
1547 next = pending.or(next);
1548 }
1549 if remote_set && on && next.is_some() {
1550 start_camera_pending = true;
1551 }
1421 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1552 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1422 } else if on && consent_pending {
1553 } else if on && consent_pending {
1423 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
1554 control.send(CallUpdate::Notice(CONSENT_FIRST_NOTICE.into()));
@@ -1427,10 +1558,10 @@ async fn drive(
1427 let started = start_camera_line(&mut local_video, &current.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
1558 let started = start_camera_line(&mut local_video, &current.peer, direct.then_some(direct_video_mid.as_deref()).flatten(), &camera_choice);
1428 match started {
1559 match started {
1429 Ok(()) if direct => {
1560 Ok(()) if direct => {
1430 match offer_same_peer(&current.peer, &layout_plan, layout, false, true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1561 match offer_same_peer(&current.peer, &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, true, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1431 Ok((browser_offer, signaled)) => {
1562 Ok((browser_offer, signaled, reply_tags)) => {
1432 timeline.record_sdp("local offer", &signaled.sdp);
1563 timeline.record_sdp("local offer", &signaled.sdp);
1433 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true) });
1564 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(true), reply_tags });
1434 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1565 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1435 }
1566 }
1436 Err(error) => {
1567 Err(error) => {
@@ -1445,12 +1576,14 @@ async fn drive(
1445 }
1576 }
1446 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1577 Err(error) => control.send(CallUpdate::Notice(format!("Camera could not start: {error}"))),
1447 }
1578 }
1579 } else if direct && same_peer.is_some() {
1580 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1448 } else if direct {
1581 } else if direct {
1449 local_video.stop_camera();
1582 local_video.stop_camera();
1450 match offer_same_peer(&current.peer, &layout_plan, layout, false, false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1583 match offer_same_peer(&current.peer, &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, false, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1451 Ok((browser_offer, signaled)) => {
1584 Ok((browser_offer, signaled, reply_tags)) => {
1452 timeline.record_sdp("local offer", &signaled.sdp);
1585 timeline.record_sdp("local offer", &signaled.sdp);
1453 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false) });
1586 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Camera(false), reply_tags });
1454 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1587 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1455 }
1588 }
1456 Err(error) => {
1589 Err(error) => {
@@ -1473,8 +1606,48 @@ async fn drive(
1473 }
1606 }
1474 }
1607 }
1475 Some(CallCommand::StartShare(source)) => {
1608 Some(CallCommand::StartShare(source)) => {
1609 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1476 if !remote_set {
1610 if !remote_set {
1477 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1611 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1612 } else if local_hold {
1613 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
1614 } else if direct && local_video.sharing() {
1615 match local_video.start_share(&source) {
1616 Ok(()) => control.send(CallUpdate::LocalShare(Some(source.label()))),
1617 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1618 }
1619 } else if direct && same_peer.is_some() {
1620 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1621 } else if direct {
1622 match local_video.start_share(&source) {
1623 Ok(()) => {
1624 control.send(CallUpdate::LocalShare(Some(source.label())));
1625 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1626 match offer_same_peer(&current.peer, &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), false, local_video.camera_on(), true, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1627 Ok((browser_offer, signaled, reply_tags)) => {
1628 timeline.record_sdp("local offer", &signaled.sdp);
1629 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(true), reply_tags });
1630 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1631 }
1632 Err(error) => {
1633 timeline.record("share offer failed", error.to_string());
1634 undo_change(Change::Share(true), &mut local_video, control);
1635 }
1636 }
1637 }
1638 Err(error) => control.send(CallUpdate::Notice(format!("Sharing could not start: {error}"))),
1639 }
1640 } else if !video_possible(remote_set, layout, negotiator.path()) {
1641 if next.is_none() && negotiator.begin_conference_upgrade() {
1642 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;
1643 next = pending.or(next);
1644 }
1645 if next.is_some() {
1646 share_pending = Some(source);
1647 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
1648 } else {
1649 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
1650 }
1478 } else {
1651 } else {
1479 match local_video.start_share(&source) {
1652 match local_video.start_share(&source) {
1480 Ok(()) => {
1653 Ok(()) => {
@@ -1487,7 +1660,23 @@ async fn drive(
1487 }
1660 }
1488 }
1661 }
1489 Some(CallCommand::StopShare) => {
1662 Some(CallCommand::StopShare) => {
1490 if local_video.sharing() {
1663 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
1664 share_pending = None;
1665 if direct && local_video.sharing() && same_peer.is_some() {
1666 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
1667 } else if direct && local_video.sharing() {
1668 local_video.stop_share();
1669 control.send(CallUpdate::LocalShare(None));
1670 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1671 match offer_same_peer(&current.peer, &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), local_hold, local_video.camera_on(), false, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1672 Ok((browser_offer, signaled, reply_tags)) => {
1673 timeline.record_sdp("local offer", &signaled.sdp);
1674 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Share(false), reply_tags });
1675 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1676 }
1677 Err(error) => timeline.record("share offer failed", error.to_string()),
1678 }
1679 } else if local_video.sharing() {
1491 local_video.stop_share();
1680 local_video.stop_share();
1492 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1681 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, control, timeline);
1493 control.send(CallUpdate::LocalShare(None));
1682 control.send(CallUpdate::LocalShare(None));
@@ -1699,7 +1888,7 @@ async fn drive(
1699 }
1888 }
1700 }
1889 }
1701 Some(CallCommand::Hold(hold)) => {
1890 Some(CallCommand::Hold(hold)) => {
1702 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() {
1891 if is_meeting || !remote_set || local_hold == hold || same_peer.is_some() || next.is_some() {
1703 continue;
1892 continue;
1704 }
1893 }
1705 if hold && local_video.camera_on() {
1894 if hold && local_video.camera_on() {
@@ -1707,10 +1896,10 @@ async fn drive(
1707 control.send(CallUpdate::Camera(false));
1896 control.send(CallUpdate::Camera(false));
1708 }
1897 }
1709 let camera = !hold && local_video.camera_on();
1898 let camera = !hold && local_video.camera_on();
1710 match offer_same_peer(&current.peer, &layout_plan, layout, hold, camera, &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1899 match offer_same_peer(&current.peer, &layout_plan, layout, direct_video_mid.as_deref().unwrap_or(CAMERA_MID), hold, camera, local_video.sharing(), &remote, &links, &media_leg_id, &media_links, &mut negotiator).await {
1711 Ok((browser_offer, signaled)) => {
1900 Ok((browser_offer, signaled, reply_tags)) => {
1712 timeline.record_sdp("local offer", &signaled.sdp);
1901 timeline.record_sdp("local offer", &signaled.sdp);
1713 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold) });
1902 same_peer = Some(SamePeerOffer { browser_offer, signaled, change: Change::Hold(hold), reply_tags });
1714 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1903 same_peer_deadline = Some(Instant::now() + SAME_PEER_ANSWER_LIMIT);
1715 }
1904 }
1716 Err(error) => {
1905 Err(error) => {
@@ -1930,6 +2119,19 @@ async fn drive(
1930 advance(state, CallSignal::LocalLeave, control);
2119 advance(state, CallSignal::LocalLeave, control);
1931 break;
2120 break;
1932 }
2121 }
2122 _ = sleep_until(next_peer_deadline.unwrap_or_else(far_future)), if next_peer_deadline.is_some() => {
2123 if let Some(pending) = next.take() {
2124 pending.session.peer.close();
2125 negotiator.escalation_failed();
2126 start_camera_pending = false;
2127 share_pending = None;
2128 if layout == Layout::OneToOne {
2129 drop_local_media(&mut local_video, control);
2130 }
2131 timeline.record("escalation failed", "no answer for the new peer connection in time");
2132 control.send(CallUpdate::Notice(VIDEO_FAILED_NOTICE.into()));
2133 }
2134 }
1933 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
2135 _ = sleep_until(same_peer_deadline.unwrap_or_else(far_future)), if same_peer_deadline.is_some() => {
1934 same_peer_deadline = None;
2136 same_peer_deadline = None;
1935 if let Some(pending) = same_peer.take() {
2137 if let Some(pending) = same_peer.take() {
@@ -1979,11 +2181,14 @@ async fn start_escalation(
1979 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
2181 .ok_or_else(|| Error::Signaling("acceptance without a mediaRenegotiation link".into()))?;
1980 let session = open_peer(factory, grant, &options.relay_host, false)?;
2182 let session = open_peer(factory, grant, &options.relay_host, false)?;
1981 let media = create_offer(&session.peer, factory, track, Layout::Conference).await?;
2183 let media = create_offer(&session.peer, factory, track, Layout::Conference).await?;
1982 let body = renegotiation_body(&remote.participant, links, &media.signaled.sdp, media_leg_id, &media.modalities, true);
2184 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);
1983 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
2186 remote.signaling.post_json("POST mediaRenegotiation", url, body).await?;
1984 Ok(NextPeer {
2187 Ok(NextPeer {
1985 session,
2188 session,
1986 offered: Some(media),
2189 offered: Some(media),
2190 reply_tags,
2191 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
1987 })
2192 })
1988}
2193}
1989
2194
@@ -2037,7 +2242,7 @@ async fn answer_on_new_peer(
2037 teams_offer: &str,
2242 teams_offer: &str,
2038) -> Result<(PeerSession, AnsweredMedia)> {
2243) -> Result<(PeerSession, AnsweredMedia)> {
2039 let session = open_peer(factory, grant, &options.relay_host, false)?;
2244 let session = open_peer(factory, grant, &options.relay_host, false)?;
2040 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject).await?;
2245 let answered = answer_offer(&session.peer, Some(track), teams_offer, AnswerVideo::Reject, false, false).await?;
2041 Ok((session, answered))
2246 Ok((session, answered))
2042}
2247}
2043
2248
@@ -2094,6 +2299,10 @@ fn negotiate_video(
2094
2299
2095const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";
2300const NOT_CONNECTED_FOR_VIDEO: &str = "Video starts once the call is connected";
2096const ON_HOLD_NOTICE: &str = "Resume the call first";
2301const ON_HOLD_NOTICE: &str = "Resume the call first";
2302const CHANGE_RUNNING_NOTICE: &str = "Another change is still running, try again in a moment";
2303const VIDEO_FAILED_NOTICE: &str = "Video could not start, the call stays audio only";
2304const SHARE_QUEUED_NOTICE: &str = "Sharing starts in a moment";
2305const SHARE_REFUSED_NOTICE: &str = "The other side did not accept the screen share";
2097
2306
2098async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
2307async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
2099 match mode {
2308 match mode {
@@ -2144,6 +2353,12 @@ fn is_own_meeting(own: Option<&MeetingTarget>, target: &MeetingTarget) -> bool {
2144 own.is_some_and(|own| own.thread_id == target.thread_id)
2353 own.is_some_and(|own| own.thread_id == target.thread_id)
2145}
2354}
2146
2355
2356fn 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))
2360}
2361
2147fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
2362fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> {
2148 peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid))
2363 peer.transceivers().into_iter().find(|transceiver| transceiver.mid().as_deref() == Some(mid))
2149}
2364}
@@ -2166,14 +2381,17 @@ async fn offer_same_peer(
2166 peer: &PeerConnection,
2381 peer: &PeerConnection,
2167 plan: &OfferPlan,
2382 plan: &OfferPlan,
2168 layout: Layout,
2383 layout: Layout,
2384 camera_mid: &str,
2169 hold: bool,
2385 hold: bool,
2170 camera: bool,
2386 camera: bool,
2387 share: bool,
2171 remote: &RemoteCall,
2388 remote: &RemoteCall,
2172 links: &CallbackLinks,
2389 links: &CallbackLinks,
2173 media_leg_id: &str,
2390 media_leg_id: &str,
2174 media_links: &BTreeMap<String, String>,
2391 media_links: &BTreeMap<String, String>,
2175 negotiator: &mut MediaNegotiator,
2392 negotiator: &mut MediaNegotiator,
2176) -> Result<(String, SignaledOffer)> {
2393) -> Result<(String, SignaledOffer, Vec<String>)> {
2394 let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct;
2177 let url = media_links
2395 let url = media_links
2178 .get("mediaRenegotiation")
2396 .get("mediaRenegotiation")
2179 .cloned()
2397 .cloned()
@@ -2181,7 +2399,7 @@ async fn offer_same_peer(
2181 if !negotiator.begin_same_peer_offer() {
2399 if !negotiator.begin_same_peer_offer() {
2182 return Err(Error::Signaling("another media negotiation is running".into()));
2400 return Err(Error::Signaling("another media negotiation is running".into()));
2183 }
2401 }
2184 let offered = build_same_peer_offer(peer, plan, layout, hold, camera).await;
2402 let offered = build_same_peer_offer(peer, plan, layout, hold, camera, share, camera_mid).await;
2185 let (text, signaled) = match offered {
2403 let (text, signaled) = match offered {
2186 Ok(offered) => offered,
2404 Ok(offered) => offered,
2187 Err(error) => {
2405 Err(error) => {
@@ -2190,27 +2408,28 @@ async fn offer_same_peer(
2190 }
2408 }
2191 };
2409 };
2192 let modalities = accepted_modalities(layout == Layout::OneToOne && camera && !hold);
2410 let modalities = accepted_modalities(layout == Layout::OneToOne && camera && !hold);
2193 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false);
2411 let body = renegotiation_body(&remote.participant, links, &signaled.sdp, media_leg_id, &modalities, false, direct);
2412 let reply_tags = offer_reply_tags(&body);
2194 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
2413 if let Err(error) = remote.signaling.post_json("POST mediaRenegotiation (same peer)", &url, body).await {
2195 negotiator.same_peer_offer_failed();
2414 negotiator.same_peer_offer_failed();
2196 rollback_offer(peer).await;
2415 rollback_offer(peer).await;
2197 return Err(error);
2416 return Err(error);
2198 }
2417 }
2199 Ok((text, signaled))
2418 Ok((text, signaled, reply_tags))
2200}
2419}
2201
2420
2202async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool) -> Result<(String, SignaledOffer)> {
2421async fn build_same_peer_offer(peer: &PeerConnection, plan: &OfferPlan, layout: Layout, hold: bool, camera: bool, share: bool, camera_mid: &str) -> Result<(String, SignaledOffer)> {
2203 let offer = peer
2422 let offer = peer
2204 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
2423 .create_offer(OfferOptions { offer_to_receive_audio: true, offer_to_receive_video: true, ..OfferOptions::default() })
2205 .await
2424 .await
2206 .map_err(|error| Error::Webrtc(error.to_string()))?;
2425 .map_err(|error| Error::Webrtc(error.to_string()))?;
2207 let text = directions_for(layout, false, camera, &offer.to_string());
2426 let text = directions_for(layout, false, camera, share, camera_mid, &offer.to_string());
2208 let description = parse_sdp(&text, SdpType::Offer)?;
2427 let description = parse_sdp(&text, SdpType::Offer)?;
2209 peer.set_local_description(description)
2428 peer.set_local_description(description)
2210 .await
2429 .await
2211 .map_err(|error| Error::Webrtc(error.to_string()))?;
2430 .map_err(|error| Error::Webrtc(error.to_string()))?;
2212 let mut numbers = random_u32;
2431 let mut numbers = random_u32;
2213 let signaled = to_teams_offer(&directions_for(layout, hold, camera, &text), plan, &mut numbers)?;
2432 let signaled = to_teams_offer(&directions_for(layout, hold, camera, share, camera_mid, &text), plan, &mut numbers)?;
2214 Ok((text, signaled))
2433 Ok((text, signaled))
2215}
2434}
2216
2435
@@ -2229,6 +2448,44 @@ async fn rollback_offer(peer: &PeerConnection) {
2229 }
2448 }
2230}
2449}
2231
2450
2451fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> {
2452 let links = &body["mediaNegotiation"]["links"];
2453 ["mediaAnswer", "rejection"].iter().filter_map(|name| links[*name].as_str().and_then(callback_tag)).collect()
2454}
2455
2456#[cfg(test)]
2457mod reply_tag_tests {
2458 use super::*;
2459
2460 #[test]
2461 fn answers_and_rejections_match_the_offer_by_tag() {
2462 let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()];
2463 assert!(answers_offer("callAgent/c/aaaa1111/call/mediaAnswer/", &tags));
2464 assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags));
2465 assert!(!answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &tags));
2466 assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[]));
2467 }
2468
2469 #[test]
2470 fn an_offer_names_both_reply_tags() {
2471 let body = serde_json::json!({"mediaNegotiation": {"links": {
2472 "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/",
2473 "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}});
2474 assert_eq!(offer_reply_tags(&body), vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]);
2475 }
2476}
2477
2478fn drop_local_media(local_video: &mut LocalVideo, control: &CallControl) {
2479 if local_video.sharing() {
2480 local_video.stop_share();
2481 control.send(CallUpdate::LocalShare(None));
2482 }
2483 if local_video.camera_on() {
2484 local_video.stop_camera();
2485 control.send(CallUpdate::Camera(false));
2486 }
2487}
2488
2232fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {
2489fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallControl) {
2233 match change {
2490 match change {
2234 Change::Camera(true) => {
2491 Change::Camera(true) => {
@@ -2236,6 +2493,12 @@ fn undo_change(change: Change, local_video: &mut LocalVideo, control: &CallContr
2236 control.send(CallUpdate::Camera(false));
2493 control.send(CallUpdate::Camera(false));
2237 }
2494 }
2238 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
2495 Change::Camera(false) => control.send(CallUpdate::Camera(false)),
2496 Change::Share(true) => {
2497 local_video.stop_share();
2498 control.send(CallUpdate::LocalShare(None));
2499 control.send(CallUpdate::Notice("Sharing could not start".into()));
2500 }
2501 Change::Share(false) => {}
2239 Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())),
2502 Change::Hold(_) => control.send(CallUpdate::Notice("The hold did not go through".into())),
2240 }
2503 }
2241}
2504}
@@ -2353,7 +2616,7 @@ async fn run_bot_steps(
2353 return fail(flow, "This call has no chat for the captions and the recording");
2616 return fail(flow, "This call has no chat for the captions and the recording");
2354 };
2617 };
2355 *bot_pending = true;
2618 *bot_pending = true;
2356 let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links).await;
2619 let added = remote.signaling.add_caption_bot(&remote.conversation, &remote.participant, thread, links, remote.threadless).await;
2357 if job == BotJob::Recording {
2620 if job == BotJob::Recording {
2358 report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline);
2621 report_organizer_result(added.as_ref().map(|status| *status).map_err(|error| Error::Signaling(error.to_string())), "recording add bot", join_failure, control, timeline);
2359 }
2622 }
@@ -2672,7 +2935,7 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
2672 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
2935 CallEvent::Acceptance(acceptance) => format!("answer sdp {} bytes, fromMixer={}", acceptance.sdp.len(), acceptance.from_mixer),
2673 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
2936 CallEvent::End(end) => format!("code={} subCode={} phrase={}", end.code, end.sub_code, end.phrase),
2674 CallEvent::Progress(status) => format!("{status:?}"),
2937 CallEvent::Progress(status) => format!("{status:?}"),
2675 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) => outcome_summary(body),
2938 CallEvent::ConversationEnd(body) | CallEvent::Rejection(body) | CallEvent::AddParticipantFailure(body) | CallEvent::RetargetCompletion(body) => outcome_summary(body),
2676 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
2939 CallEvent::ControlVideoStreaming(body) => parse_request(body).map_or_else(|| "body not understood".to_owned(), |request| request.shape),
2677 _ => String::new(),
2940 _ => String::new(),
2678 };
2941 };
@@ -2987,7 +3250,7 @@ mod tests {
2987 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
3250 let source = NativeAudioSource::new(AudioSourceOptions::default(), SAMPLE_RATE, 1, 100);
2988 let track = factory.create_audio_track("microphone", source);
3251 let track = factory.create_audio_track("microphone", source);
2989 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
3252 let offer = include_str!("../tests/fixtures/teams_p2p_offer.sdp");
2990 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive).await;
3253 let answered = answer_offer(&peer, Some(&track), offer, AnswerVideo::Receive, false, false).await;
2991 peer.close();
3254 peer.close();
2992 if let Err(error) = answered {
3255 if let Err(error) = answered {
2993 panic!("{error}");
3256 panic!("{error}");
@@ -2996,21 +3259,22 @@ mod tests {
2996
3259
2997 #[test]
3260 #[test]
2998 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
3261 fn a_one_to_one_offer_has_audio_and_an_inactive_camera_until_the_camera_is_on() {
2999 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3262 assert_eq!(directions(&directions_for(Layout::OneToOne, false, false, false, CAMERA_MID, BROWSER_OFFER)), vec!["sendrecv", "inactive", "inactive"]);
3000 assert_eq!(directions(&directions_for(Layout::OneToOne, false, true, BROWSER_OFFER)), vec!["sendrecv", "sendrecv", "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"]);
3001 }
3265 }
3002
3266
3003 #[test]
3267 #[test]
3004 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3268 fn a_hold_silences_every_line_and_a_conference_offer_is_left_alone() {
3005 for layout in [Layout::OneToOne, Layout::Conference] {
3269 for layout in [Layout::OneToOne, Layout::Conference] {
3006 assert_eq!(directions(&directions_for(layout, true, true, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3270 assert_eq!(directions(&directions_for(layout, true, true, false, CAMERA_MID, BROWSER_OFFER)), vec!["inactive", "inactive", "inactive"]);
3007 }
3271 }
3008 assert_eq!(directions_for(Layout::Conference, false, true, BROWSER_OFFER), BROWSER_OFFER);
3272 assert_eq!(directions_for(Layout::Conference, false, true, false, CAMERA_MID, BROWSER_OFFER), BROWSER_OFFER);
3009 }
3273 }
3010
3274
3011 #[test]
3275 #[test]
3012 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3276 fn a_hold_offer_body_is_inactive_on_every_teams_line_with_one_placeholder_candidate() {
3013 let held = directions_for(Layout::Conference, true, false, BROWSER_OFFER);
3277 let held = directions_for(Layout::Conference, true, false, false, CAMERA_MID, BROWSER_OFFER);
3014 let mut numbers = || 7;
3278 let mut numbers = || 7;
3015 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
3279 let signaled = to_teams_offer(&held, &offer_plan(), &mut numbers).unwrap().sdp;
3016 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
3280 assert_eq!(directions(&signaled), vec!["inactive", "inactive", "inactive"]);
crates/calling/src/captions.rs +7 −3
@@ -72,7 +72,8 @@ pub fn recorder_features() -> Value {
72 72 })
73 73 }
74 74
75 pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks) -> Value {
75 pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks, threadless: bool) -> Value {
76 let group_chat = if threadless { Value::Null } else { json!({"threadId": thread_id, "messageId": null}) };
76 77 json!({
77 78 "disableUnmute": false,
78 79 "participants": {
@@ -95,7 +96,7 @@ pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name:
95 96 }},
96 97 "replacementDetails": null,
97 98 "groupContext": null,
98 "groupChat": {"threadId": thread_id, "messageId": null},
99 "groupChat": group_chat,
99 100 "links": {
100 101 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
101 102 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
@@ -264,7 +265,10 @@ mod tests {
264 265 #[test]
265 266 fn the_bot_invitation_carries_the_meeting_and_a_token_placeholder() {
266 267 let callbacks = CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1");
267 let body = add_bot_body(json!({"id": "8:orgid:me"}), "19:meeting_x@thread.v2", "call-1", "Me", &callbacks);
268 let body = add_bot_body(json!({"id": "8:orgid:me"}), "19:meeting_x@thread.v2", "call-1", "Me", &callbacks, false);
269 let direct = add_bot_body(json!({"id": "8:orgid:me"}), "19:a_b@unq.gbl.spaces", "call-1", "Me", &callbacks, true);
270 assert_eq!(direct["groupChat"], Value::Null);
271 assert_eq!(direct["participantInvitationData"]["botData"]["threadId"], "19:a_b@unq.gbl.spaces");
268 272 let bot_data = &body["participantInvitationData"]["botData"];
269 273 assert_eq!(body["participants"]["to"][0]["id"], RECORDING_BOT_MRI);
270 274 assert_eq!(bot_data["mode"], "RecordingAndTranscription");
@@ -72,7 +72,8 @@ pub fn recorder_features() -> Value {
72 })
72 })
73}
73}
74
74
75pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks) -> Value {
75pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name: &str, callbacks: &CallbackLinks, threadless: bool) -> Value {
76 let group_chat = if threadless { Value::Null } else { json!({"threadId": thread_id, "messageId": null}) };
76 json!({
77 json!({
77 "disableUnmute": false,
78 "disableUnmute": false,
78 "participants": {
79 "participants": {
@@ -95,7 +96,7 @@ pub fn add_bot_body(from: Value, thread_id: &str, call_id: &str, organizer_name:
95 }},
96 }},
96 "replacementDetails": null,
97 "replacementDetails": null,
97 "groupContext": null,
98 "groupContext": null,
98 "groupChat": {"threadId": thread_id, "messageId": null},
99 "groupChat": group_chat,
99 "links": {
100 "links": {
100 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
101 "addParticipantSuccess": callbacks.conversation("addParticipantSuccess"),
101 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
102 "addParticipantFailure": callbacks.conversation("addParticipantFailure"),
@@ -264,7 +265,10 @@ mod tests {
264 #[test]
265 #[test]
265 fn the_bot_invitation_carries_the_meeting_and_a_token_placeholder() {
266 fn the_bot_invitation_carries_the_meeting_and_a_token_placeholder() {
266 let callbacks = CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1");
267 let callbacks = CallbackLinks::new("https://trouter.example/v4/f/x/", "call-1");
267 let body = add_bot_body(json!({"id": "8:orgid:me"}), "19:meeting_x@thread.v2", "call-1", "Me", &callbacks);
268 let body = add_bot_body(json!({"id": "8:orgid:me"}), "19:meeting_x@thread.v2", "call-1", "Me", &callbacks, false);
269 let direct = add_bot_body(json!({"id": "8:orgid:me"}), "19:a_b@unq.gbl.spaces", "call-1", "Me", &callbacks, true);
270 assert_eq!(direct["groupChat"], Value::Null);
271 assert_eq!(direct["participantInvitationData"]["botData"]["threadId"], "19:a_b@unq.gbl.spaces");
268 let bot_data = &body["participantInvitationData"]["botData"];
272 let bot_data = &body["participantInvitationData"]["botData"];
269 assert_eq!(body["participants"]["to"][0]["id"], RECORDING_BOT_MRI);
273 assert_eq!(body["participants"]["to"][0]["id"], RECORDING_BOT_MRI);
270 assert_eq!(bot_data["mode"], "RecordingAndTranscription");
274 assert_eq!(bot_data["mode"], "RecordingAndTranscription");
crates/calling/src/engine.rs +10 −4
@@ -20,7 +20,7 @@ use crate::signaling::{
20 20 AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self,
21 21 };
22 22 use crate::timeline::Timeline;
23 use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, callback_reply_body, classify, decode_body};
23 use crate::trouter_events::{CallEvent, CallbackLinks, acceptance_acknowledgement, callback_call_id, classify, decode_body, is_acceptance_callback};
24 24
25 25 const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
26 26 const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
@@ -115,7 +115,7 @@ enum RingCommand {
115 115
116 116 struct Route {
117 117 sender: mpsc::UnboundedSender<TrouterCallback>,
118 links: CallbackLinks,
118 acceptance_reply: String,
119 119 }
120 120
121 121 pub(crate) struct Inner {
@@ -144,7 +144,10 @@ impl Inner {
144 144
145 145 pub(crate) fn register_route(&self, links: &CallbackLinks) -> mpsc::UnboundedReceiver<TrouterCallback> {
146 146 let (sender, receiver) = mpsc::unbounded_channel();
147 let route = Route { sender, links: links.clone() };
147 let route = Route {
148 sender,
149 acceptance_reply: acceptance_acknowledgement(links).to_string(),
150 };
148 151 self.routes.lock().expect("routes lock").insert(links.call_id().to_owned(), route);
149 152 receiver
150 153 }
@@ -192,7 +195,10 @@ impl Inner {
192 195 .lock()
193 196 .expect("routes lock")
194 197 .get(&call_id)
195 .map(|route| (route.sender.clone(), callback_reply_body(&callback.path, &route.links)));
198 .map(|route| {
199 let reply = if is_acceptance_callback(&callback.path) { route.acceptance_reply.clone() } else { String::new() };
200 (route.sender.clone(), reply)
201 });
196 202 match route {
197 203 Some((sender, reply)) => {
198 204 self.replier.reply(callback.request_id, 200, reply);
@@ -20,7 +20,7 @@ use crate::signaling::{
20 AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self,
20 AttachRequest, LeaveReason, MeetingTarget, Participant, SelfIdentity, Signaling, TenantRouting, fetch_self,
21};
21};
22use crate::timeline::Timeline;
22use crate::timeline::Timeline;
23use crate::trouter_events::{CallEvent, CallbackLinks, callback_call_id, callback_reply_body, classify, decode_body};
23use crate::trouter_events::{CallEvent, CallbackLinks, acceptance_acknowledgement, callback_call_id, classify, decode_body, is_acceptance_callback};
24
24
25const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
25const ENDPOINT_WAIT: Duration = Duration::from_secs(30);
26const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
26const PRESENCE_SUFFIX: &str = "unifiedPresenceService";
@@ -115,7 +115,7 @@ enum RingCommand {
115
115
116struct Route {
116struct Route {
117 sender: mpsc::UnboundedSender<TrouterCallback>,
117 sender: mpsc::UnboundedSender<TrouterCallback>,
118 links: CallbackLinks,
118 acceptance_reply: String,
119}
119}
120
120
121pub(crate) struct Inner {
121pub(crate) struct Inner {
@@ -144,7 +144,10 @@ impl Inner {
144
144
145 pub(crate) fn register_route(&self, links: &CallbackLinks) -> mpsc::UnboundedReceiver<TrouterCallback> {
145 pub(crate) fn register_route(&self, links: &CallbackLinks) -> mpsc::UnboundedReceiver<TrouterCallback> {
146 let (sender, receiver) = mpsc::unbounded_channel();
146 let (sender, receiver) = mpsc::unbounded_channel();
147 let route = Route { sender, links: links.clone() };
147 let route = Route {
148 sender,
149 acceptance_reply: acceptance_acknowledgement(links).to_string(),
150 };
148 self.routes.lock().expect("routes lock").insert(links.call_id().to_owned(), route);
151 self.routes.lock().expect("routes lock").insert(links.call_id().to_owned(), route);
149 receiver
152 receiver
150 }
153 }
@@ -192,7 +195,10 @@ impl Inner {
192 .lock()
195 .lock()
193 .expect("routes lock")
196 .expect("routes lock")
194 .get(&call_id)
197 .get(&call_id)
195 .map(|route| (route.sender.clone(), callback_reply_body(&callback.path, &route.links)));
198 .map(|route| {
199 let reply = if is_acceptance_callback(&callback.path) { route.acceptance_reply.clone() } else { String::new() };
200 (route.sender.clone(), reply)
201 });
196 match route {
202 match route {
197 Some((sender, reply)) => {
203 Some((sender, reply)) => {
198 self.replier.reply(callback.request_id, 200, reply);
204 self.replier.reply(callback.request_id, 200, reply);
crates/calling/src/hold.rs +27 −0
@@ -70,6 +70,24 @@ pub fn rewrite_directions(sdp: &str, pick: impl Fn(MediaLine<'_>) -> Option<&'st
70 70 lines.join(newline)
71 71 }
72 72
73 pub fn stop_sending_on(sdp: &str, mid: &str) -> String {
74 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();
76 for section in sections(&lines) {
77 let Some(direction_line) = section.direction_line else { continue };
78 if section.mid != mid {
79 continue;
80 }
81 let receive_only = match lines[direction_line].as_str() {
82 "a=sendrecv" => "recvonly",
83 "a=sendonly" => INACTIVE,
84 _ => continue,
85 };
86 lines[direction_line] = format!("a={receive_only}");
87 }
88 lines.join(newline)
89 }
90
73 91 fn mirrored(direction: &str) -> &'static str {
74 92 match direction {
75 93 "sendonly" => "recvonly",
@@ -129,6 +147,15 @@ pub fn accepted_modalities(video: bool) -> Vec<String> {
129 147
130 148 #[cfg(test)]
131 149 mod tests {
150 #[test]
151 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";
153 let camera_off = super::stop_sending_on(sdp, "1");
154 assert!(camera_off.contains("a=mid:1\r\na=recvonly"));
155 assert!(camera_off.contains("a=mid:0\r\na=sendrecv"));
156 assert!(super::stop_sending_on(sdp, "2").contains("a=mid:2\r\na=inactive"));
157 }
158
132 159 use super::*;
133 160
134 161 const OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=mid:0\r\na=sendrecv\r\na=rtpmap:111 opus/48000/2\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:1\r\na=sendrecv\r\na=rtpmap:102 H264/90000\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:2\r\na=recvonly\r\na=rtpmap:102 H264/90000\r\n";
@@ -70,6 +70,24 @@ pub fn rewrite_directions(sdp: &str, pick: impl Fn(MediaLine<'_>) -> Option<&'st
70 lines.join(newline)
70 lines.join(newline)
71}
71}
72
72
73pub fn stop_sending_on(sdp: &str, mid: &str) -> String {
74 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();
76 for section in sections(&lines) {
77 let Some(direction_line) = section.direction_line else { continue };
78 if section.mid != mid {
79 continue;
80 }
81 let receive_only = match lines[direction_line].as_str() {
82 "a=sendrecv" => "recvonly",
83 "a=sendonly" => INACTIVE,
84 _ => continue,
85 };
86 lines[direction_line] = format!("a={receive_only}");
87 }
88 lines.join(newline)
89}
90
73fn mirrored(direction: &str) -> &'static str {
91fn mirrored(direction: &str) -> &'static str {
74 match direction {
92 match direction {
75 "sendonly" => "recvonly",
93 "sendonly" => "recvonly",
@@ -129,6 +147,15 @@ pub fn accepted_modalities(video: bool) -> Vec<String> {
129
147
130#[cfg(test)]
148#[cfg(test)]
131mod tests {
149mod tests {
150 #[test]
151 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";
153 let camera_off = super::stop_sending_on(sdp, "1");
154 assert!(camera_off.contains("a=mid:1\r\na=recvonly"));
155 assert!(camera_off.contains("a=mid:0\r\na=sendrecv"));
156 assert!(super::stop_sending_on(sdp, "2").contains("a=mid:2\r\na=inactive"));
157 }
158
132 use super::*;
159 use super::*;
133
160
134 const OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=mid:0\r\na=sendrecv\r\na=rtpmap:111 opus/48000/2\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:1\r\na=sendrecv\r\na=rtpmap:102 H264/90000\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:2\r\na=recvonly\r\na=rtpmap:102 H264/90000\r\n";
161 const OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=mid:0\r\na=sendrecv\r\na=rtpmap:111 opus/48000/2\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:1\r\na=sendrecv\r\na=rtpmap:102 H264/90000\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:2\r\na=recvonly\r\na=rtpmap:102 H264/90000\r\n";
crates/calling/src/renegotiation.rs +48 −1
@@ -88,9 +88,10 @@ impl MediaNegotiator {
88 88 }
89 89
90 90 pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {
91 if self.own_offer_pending || self.same_peer_offer_pending {
91 if self.own_offer_pending || (self.same_peer_offer_pending && !escalation) {
92 92 return MediaAction::RejectGlare;
93 93 }
94 self.same_peer_offer_pending = false;
94 95 if escalation {
95 96 self.path = MediaPath::Mixer;
96 97 }
@@ -105,6 +106,29 @@ impl MediaNegotiator {
105 106 self.own_offer_pending = false;
106 107 }
107 108
109 pub fn escalate_after_mixer_answer(&mut self) -> bool {
110 if self.path != MediaPath::Direct || self.own_offer_pending {
111 return false;
112 }
113 self.path = MediaPath::Mixer;
114 self.own_offer_pending = true;
115 true
116 }
117
118 pub fn note_mixer_path(&mut self) {
119 if self.path == MediaPath::Direct {
120 self.path = MediaPath::Mixer;
121 }
122 }
123
124 pub fn begin_conference_upgrade(&mut self) -> bool {
125 if self.path != MediaPath::Mixer || self.own_offer_pending || self.same_peer_offer_pending {
126 return false;
127 }
128 self.own_offer_pending = true;
129 true
130 }
131
108 132 pub fn on_rejection(&mut self) -> RejectedOffer {
109 133 if std::mem::take(&mut self.same_peer_offer_pending) {
110 134 return RejectedOffer::SamePeer;
@@ -127,6 +151,29 @@ pub enum RejectedOffer {
127 151 mod tests {
128 152 use super::*;
129 153
154 #[test]
155 fn a_mixer_answer_on_a_direct_call_starts_one_escalation() {
156 let mut negotiator = MediaNegotiator::default();
157 negotiator.on_acceptance(false, true);
158 assert_eq!(negotiator.path(), MediaPath::Direct);
159 assert!(negotiator.escalate_after_mixer_answer());
160 assert_eq!(negotiator.path(), MediaPath::Mixer);
161 assert!(!negotiator.escalate_after_mixer_answer());
162 assert_eq!(negotiator.on_media_answer(), MediaAction::ApplyOnNewPeer);
163 }
164
165 #[test]
166 fn a_server_escalation_wins_over_a_pending_same_peer_offer() {
167 let mut negotiator = MediaNegotiator::default();
168 negotiator.on_acceptance(false, true);
169 assert!(negotiator.begin_same_peer_offer());
170 assert_eq!(negotiator.on_renegotiation(false, false), MediaAction::RejectGlare);
171 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::AnswerOnNewPeer);
172 assert_eq!(negotiator.path(), MediaPath::Mixer);
173 assert!(negotiator.begin_conference_upgrade());
174 assert!(!negotiator.begin_conference_upgrade());
175 }
176
130 177 #[test]
131 178 fn a_rejection_clears_the_pending_offer() {
132 179 let mut negotiator = MediaNegotiator::default();
@@ -88,9 +88,10 @@ impl MediaNegotiator {
88 }
88 }
89
89
90 pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {
90 pub fn on_renegotiation(&mut self, new_offer: bool, escalation: bool) -> MediaAction {
91 if self.own_offer_pending || self.same_peer_offer_pending {
91 if self.own_offer_pending || (self.same_peer_offer_pending && !escalation) {
92 return MediaAction::RejectGlare;
92 return MediaAction::RejectGlare;
93 }
93 }
94 self.same_peer_offer_pending = false;
94 if escalation {
95 if escalation {
95 self.path = MediaPath::Mixer;
96 self.path = MediaPath::Mixer;
96 }
97 }
@@ -105,6 +106,29 @@ impl MediaNegotiator {
105 self.own_offer_pending = false;
106 self.own_offer_pending = false;
106 }
107 }
107
108
109 pub fn escalate_after_mixer_answer(&mut self) -> bool {
110 if self.path != MediaPath::Direct || self.own_offer_pending {
111 return false;
112 }
113 self.path = MediaPath::Mixer;
114 self.own_offer_pending = true;
115 true
116 }
117
118 pub fn note_mixer_path(&mut self) {
119 if self.path == MediaPath::Direct {
120 self.path = MediaPath::Mixer;
121 }
122 }
123
124 pub fn begin_conference_upgrade(&mut self) -> bool {
125 if self.path != MediaPath::Mixer || self.own_offer_pending || self.same_peer_offer_pending {
126 return false;
127 }
128 self.own_offer_pending = true;
129 true
130 }
131
108 pub fn on_rejection(&mut self) -> RejectedOffer {
132 pub fn on_rejection(&mut self) -> RejectedOffer {
109 if std::mem::take(&mut self.same_peer_offer_pending) {
133 if std::mem::take(&mut self.same_peer_offer_pending) {
110 return RejectedOffer::SamePeer;
134 return RejectedOffer::SamePeer;
@@ -127,6 +151,29 @@ pub enum RejectedOffer {
127mod tests {
151mod tests {
128 use super::*;
152 use super::*;
129
153
154 #[test]
155 fn a_mixer_answer_on_a_direct_call_starts_one_escalation() {
156 let mut negotiator = MediaNegotiator::default();
157 negotiator.on_acceptance(false, true);
158 assert_eq!(negotiator.path(), MediaPath::Direct);
159 assert!(negotiator.escalate_after_mixer_answer());
160 assert_eq!(negotiator.path(), MediaPath::Mixer);
161 assert!(!negotiator.escalate_after_mixer_answer());
162 assert_eq!(negotiator.on_media_answer(), MediaAction::ApplyOnNewPeer);
163 }
164
165 #[test]
166 fn a_server_escalation_wins_over_a_pending_same_peer_offer() {
167 let mut negotiator = MediaNegotiator::default();
168 negotiator.on_acceptance(false, true);
169 assert!(negotiator.begin_same_peer_offer());
170 assert_eq!(negotiator.on_renegotiation(false, false), MediaAction::RejectGlare);
171 assert_eq!(negotiator.on_renegotiation(true, true), MediaAction::AnswerOnNewPeer);
172 assert_eq!(negotiator.path(), MediaPath::Mixer);
173 assert!(negotiator.begin_conference_upgrade());
174 assert!(!negotiator.begin_conference_upgrade());
175 }
176
130 #[test]
177 #[test]
131 fn a_rejection_clears_the_pending_offer() {
178 fn a_rejection_clears_the_pending_offer() {
132 let mut negotiator = MediaNegotiator::default();
179 let mut negotiator = MediaNegotiator::default();
crates/calling/src/sdp.rs +13 −4
@@ -584,11 +584,15 @@ pub fn to_browser_answer(teams_sdp: &str, offer: &SignaledOffer, browser_offer_s
584 584 session.attributes.retain(|attribute| attribute.name.starts_with("x-"));
585 585 session.attributes.push(Attribute::flag("extmap-allow-mixed"));
586 586 session.attributes.push(Attribute::new("msid-semantic", " WMS *"));
587 let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect();
588 session.attributes.push(Attribute::new("group", format!("BUNDLE {}", mids.join(" "))));
587 session.attributes.push(Attribute::new("group", bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid())))));
589 588 Ok(write(&SessionDescription { session, media }))
590 589 }
591 590
591 fn bundle_group<'a>(lines: impl Iterator<Item = (&'a str, Option<&'a str>)>) -> String {
592 let mids: Vec<&str> = lines.filter(|(port, _)| *port != "0").filter_map(|(_, mid)| mid).collect();
593 format!("BUNDLE {}", mids.join(" "))
594 }
595
592 596 #[derive(Debug, Clone, PartialEq, Eq)]
593 597 pub struct StreamLine {
594 598 pub mid: String,
@@ -943,8 +947,7 @@ pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
943 947 session.bandwidths.clear();
944 948 session.connection = None;
945 949 session.attributes.retain(|attribute| matches!(attribute.name.as_str(), "extmap-allow-mixed" | "msid-semantic"));
946 let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect();
947 session.attributes.push(Attribute::new("group", format!("BUNDLE {}", mids.join(" "))));
950 session.attributes.push(Attribute::new("group", bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid())))));
948 951 Ok(RemoteOffer {
949 952 browser_sdp: write(&SessionDescription { session, media }),
950 953 lines,
@@ -1068,6 +1071,12 @@ mod tests {
1068 1071 }
1069 1072 }
1070 1073
1074 #[test]
1075 fn rejected_lines_stay_out_of_the_bundle() {
1076 let lines = [("9", Some("0")), ("0", Some("1")), ("9", Some("2"))];
1077 assert_eq!(bundle_group(lines.into_iter()), "BUNDLE 0 2");
1078 }
1079
1071 1080 const AUDIO_ONLY_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS stream\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=ice-options:trickle\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=mid:0\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=sendrecv\r\na=msid:stream track\r\na=rtcp-mux\r\na=rtpmap:111 opus/48000/2\r\na=rtcp-fb:111 transport-cc\r\na=fmtp:111 minptime=10;useinbandfec=1\r\na=rtpmap:63 red/48000/2\r\na=fmtp:63 111/111\r\na=rtpmap:9 G722/8000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:110 telephone-event/48000\r\na=rtpmap:126 telephone-event/8000\r\na=ssrc:42 cname:abc\r\na=ssrc:42 msid:stream track\r\n";
1072 1081
1073 1082 #[test]
@@ -584,11 +584,15 @@ pub fn to_browser_answer(teams_sdp: &str, offer: &SignaledOffer, browser_offer_s
584 session.attributes.retain(|attribute| attribute.name.starts_with("x-"));
584 session.attributes.retain(|attribute| attribute.name.starts_with("x-"));
585 session.attributes.push(Attribute::flag("extmap-allow-mixed"));
585 session.attributes.push(Attribute::flag("extmap-allow-mixed"));
586 session.attributes.push(Attribute::new("msid-semantic", " WMS *"));
586 session.attributes.push(Attribute::new("msid-semantic", " WMS *"));
587 let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect();
587 session.attributes.push(Attribute::new("group", bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid())))));
588 session.attributes.push(Attribute::new("group", format!("BUNDLE {}", mids.join(" "))));
589 Ok(write(&SessionDescription { session, media }))
588 Ok(write(&SessionDescription { session, media }))
590}
589}
591
590
591fn bundle_group<'a>(lines: impl Iterator<Item = (&'a str, Option<&'a str>)>) -> String {
592 let mids: Vec<&str> = lines.filter(|(port, _)| *port != "0").filter_map(|(_, mid)| mid).collect();
593 format!("BUNDLE {}", mids.join(" "))
594}
595
592#[derive(Debug, Clone, PartialEq, Eq)]
596#[derive(Debug, Clone, PartialEq, Eq)]
593pub struct StreamLine {
597pub struct StreamLine {
594 pub mid: String,
598 pub mid: String,
@@ -943,8 +947,7 @@ pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
943 session.bandwidths.clear();
947 session.bandwidths.clear();
944 session.connection = None;
948 session.connection = None;
945 session.attributes.retain(|attribute| matches!(attribute.name.as_str(), "extmap-allow-mixed" | "msid-semantic"));
949 session.attributes.retain(|attribute| matches!(attribute.name.as_str(), "extmap-allow-mixed" | "msid-semantic"));
946 let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect();
950 session.attributes.push(Attribute::new("group", bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid())))));
947 session.attributes.push(Attribute::new("group", format!("BUNDLE {}", mids.join(" "))));
948 Ok(RemoteOffer {
951 Ok(RemoteOffer {
949 browser_sdp: write(&SessionDescription { session, media }),
952 browser_sdp: write(&SessionDescription { session, media }),
950 lines,
953 lines,
@@ -1068,6 +1071,12 @@ mod tests {
1068 }
1071 }
1069 }
1072 }
1070
1073
1074 #[test]
1075 fn rejected_lines_stay_out_of_the_bundle() {
1076 let lines = [("9", Some("0")), ("0", Some("1")), ("9", Some("2"))];
1077 assert_eq!(bundle_group(lines.into_iter()), "BUNDLE 0 2");
1078 }
1079
1071 const AUDIO_ONLY_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS stream\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=ice-options:trickle\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=mid:0\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=sendrecv\r\na=msid:stream track\r\na=rtcp-mux\r\na=rtpmap:111 opus/48000/2\r\na=rtcp-fb:111 transport-cc\r\na=fmtp:111 minptime=10;useinbandfec=1\r\na=rtpmap:63 red/48000/2\r\na=fmtp:63 111/111\r\na=rtpmap:9 G722/8000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:110 telephone-event/48000\r\na=rtpmap:126 telephone-event/8000\r\na=ssrc:42 cname:abc\r\na=ssrc:42 msid:stream track\r\n";
1080 const AUDIO_ONLY_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS stream\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=ice-options:trickle\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=mid:0\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=sendrecv\r\na=msid:stream track\r\na=rtcp-mux\r\na=rtpmap:111 opus/48000/2\r\na=rtcp-fb:111 transport-cc\r\na=fmtp:111 minptime=10;useinbandfec=1\r\na=rtpmap:63 red/48000/2\r\na=fmtp:63 111/111\r\na=rtpmap:9 G722/8000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:110 telephone-event/48000\r\na=rtpmap:126 telephone-event/8000\r\na=ssrc:42 cname:abc\r\na=ssrc:42 msid:stream track\r\n";
1072
1081
1073 #[test]
1082 #[test]
crates/calling/src/signaling.rs +75 −17
@@ -12,7 +12,7 @@ use crate::roster::MeetingRole;
12 12 use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
13 13 use crate::relay::ic3_scope;
14 14 use crate::timeline::Timeline;
15 use crate::trouter_events::{CallbackLinks, acceptance_links};
15 use crate::trouter_events::{CallbackLinks, acceptance_links, acknowledgement_links};
16 16 use crate::video_layout::MediaDescription;
17 17
18 18 pub const EPCONV_URL: &str = "https://api-emea.flightproxy.teams.microsoft.com/api/v2/epconv";
@@ -22,6 +22,8 @@ const CLIENT_HEADER: &str = "SkypeSpaces/1415/26091712213/os=windows; osVer=NT 1
22 22 const PLATFORM_NAME: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36";
23 23 const SDP_CONTENT_TYPE: &str = "application/sdp-ngc-1.0";
24 24 const ENDPOINT_CAPABILITIES: u64 = 73463;
25 const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";
26 const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";
25 27 const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
26 28 const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
27 29 const BACKEND_SUFFIX: &str = ".skype.com";
@@ -199,6 +201,13 @@ pub struct Invitation<'a> {
199 201 pub callbacks: &'a CallbackLinks,
200 202 pub target: &'a InviteTarget,
201 203 pub modalities: &'a [String],
204 pub direct: bool,
205 }
206
207 impl Invitation<'_> {
208 pub fn is_direct(&self) -> bool {
209 self.direct && self.target.is_one_to_one()
210 }
202 211 }
203 212
204 213 pub struct Answer<'a> {
@@ -478,9 +487,11 @@ impl Signaling {
478 487 from: &Participant,
479 488 thread_id: &str,
480 489 callbacks: &CallbackLinks,
490 threadless: bool,
481 491 ) -> Result<u16> {
482 let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks);
483 let mut request = self.request(Method::Post, conversation.link("addParticipantAndModality")?, Some(body));
492 let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks, threadless);
493 let link = if threadless { "addParticipant" } else { "addParticipantAndModality" };
494 let mut request = self.request(Method::Post, conversation.link(link)?, Some(body));
484 495 request = request.with_body_token(captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER);
485 496 self.exchange(&self.session, "POST add (caption bot)", request).await.map(|response| response.status)
486 497 }
@@ -581,8 +592,9 @@ impl Signaling {
581 592 self.post_json("POST progress", url, ringing_body(from)).await
582 593 }
583 594
584 pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<()> {
585 self.post_json("POST acceptance", url, acceptance_body(answer)).await
595 pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<BTreeMap<String, String>> {
596 let response = self.send("POST acceptance", Method::Post, url, Some(acceptance_body(answer))).await?;
597 Ok(acknowledgement_links(&response.body))
586 598 }
587 599
588 600 pub async fn decline(&self, call_leg_url: &str) -> Result<()> {
@@ -654,8 +666,29 @@ fn media_controller_links(callbacks: &CallbackLinks) -> Value {
654 666 })
655 667 }
656 668
657 fn group_chat(target: &InviteTarget) -> Value {
658 match target {
669 impl InviteTarget {
670 pub fn is_one_to_one(&self) -> bool {
671 match self {
672 InviteTarget::People { callees, thread_id } => callees.len() == 1 && thread_id.ends_with(ONE_TO_ONE_THREAD_SUFFIX),
673 InviteTarget::Echo | InviteTarget::Meeting(_) => false,
674 }
675 }
676 }
677
678 fn invitation_media(invitation: &Invitation<'_>) -> Value {
679 if !invitation.is_direct() {
680 return media_content(invitation.offer_sdp, invitation.media_leg_id, true);
681 }
682 let mut content = media_content(invitation.offer_sdp, invitation.media_leg_id, false);
683 content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES);
684 content
685 }
686
687 fn group_chat(invitation: &Invitation<'_>) -> Value {
688 if invitation.is_direct() {
689 return Value::Null;
690 }
691 match invitation.target {
659 692 InviteTarget::Echo => Value::Null,
660 693 InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}),
661 694 InviteTarget::Meeting(meeting) => json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}),
@@ -700,7 +733,7 @@ pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
700 733 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
701 734 "endpointMetadata": {"holographicCapabilities": 3},
702 735 "groupContext": null,
703 "groupChat": group_chat(target),
736 "groupChat": group_chat(invitation),
704 737 "meetingInfo": meeting_info,
705 738 "meetingData": meeting_data,
706 739 "endpointState": endpoint_state(),
@@ -714,7 +747,7 @@ pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
714 747 "clientContentForMediaController": media_controller_links(callbacks),
715 748 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
716 749 "emergencyContent": null,
717 "mediaContent": media_content(invitation.offer_sdp, invitation.media_leg_id, true),
750 "mediaContent": invitation_media(invitation),
718 751 },
719 752 })
720 753 }
@@ -818,6 +851,7 @@ pub fn renegotiation_body(
818 851 media_leg_id: &str,
819 852 modalities: &[String],
820 853 new_offer: bool,
854 direct: bool,
821 855 ) -> Value {
822 856 json!({
823 857 "mediaNegotiation": {
@@ -827,13 +861,16 @@ pub fn renegotiation_body(
827 861 "mediaAnswer": callbacks.call("mediaAnswer"),
828 862 "rejection": callbacks.call("rejection"),
829 863 },
830 "mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer),
864 "mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer, direct),
831 865 },
832 866 })
833 867 }
834 868
835 fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool) -> Value {
836 let mut content = media_content(sdp, media_leg_id, true);
869 fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool, direct: bool) -> Value {
870 let mut content = media_content(sdp, media_leg_id, !direct);
871 if direct {
872 content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES);
873 }
837 874 content["newOffer"] = json!(new_offer);
838 875 content
839 876 }
@@ -1059,6 +1096,7 @@ mod tests {
1059 1096 callbacks: &callbacks,
1060 1097 target,
1061 1098 modalities: &["Audio".to_owned()],
1099 direct: true,
1062 1100 })
1063 1101 }
1064 1102
@@ -1109,19 +1147,33 @@ mod tests {
1109 1147 }
1110 1148
1111 1149 #[test]
1112 fn one_to_one_body_names_the_callee_and_the_chat() {
1150 fn one_to_one_body_names_the_callee_without_a_chat_thread() {
1113 1151 let target = InviteTarget::People {
1114 1152 callees: vec![callee("8:orgid:b", "Bea")],
1115 1153 thread_id: "19:a_b@unq.gbl.spaces".into(),
1116 1154 };
1117 1155 let body = body_for(&target);
1118 1156 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:b", "displayName": "Bea"}]));
1119 assert_eq!(body["groupChat"], json!({"threadId": "19:a_b@unq.gbl.spaces", "messageId": null}));
1157 assert_eq!(body["groupChat"], Value::Null);
1158 let media = &body["callInvitation"]["mediaContent"];
1159 assert_eq!(media["requiredFeatures"], "nonByPass");
1160 assert!(media.get("mediaDescriptions").is_none());
1120 1161 assert!(body["conversationRequest"].get("scenario").is_none());
1121 1162 assert_eq!(body["meetingInfo"], Value::Null);
1122 1163 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1123 1164 }
1124 1165
1166 #[test]
1167 fn a_one_to_one_call_that_may_not_go_direct_keeps_the_chat_thread() {
1168 let from = from();
1169 let callbacks = callbacks();
1170 let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1171 let modalities = vec!["Audio".to_owned()];
1172 let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities, direct: false });
1173 assert_eq!(body["groupChat"]["threadId"], "19:a_b@unq.gbl.spaces");
1174 assert!(body["callInvitation"]["mediaContent"]["mediaDescriptions"].is_object());
1175 }
1176
1125 1177 #[test]
1126 1178 fn group_body_invites_every_callee_on_the_group_thread() {
1127 1179 let target = InviteTarget::People {
@@ -1134,6 +1186,9 @@ mod tests {
1134 1186 assert_eq!(to[2]["id"], "8:orgid:d");
1135 1187 assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2");
1136 1188 assert_eq!(body["groupChat"]["messageId"], Value::Null);
1189 let media = &body["callInvitation"]["mediaContent"];
1190 assert!(media.get("requiredFeatures").is_none());
1191 assert!(media["mediaDescriptions"].is_object());
1137 1192 }
1138 1193
1139 1194 #[test]
@@ -1277,12 +1332,15 @@ mod tests {
1277 1332 fn renegotiation_messages_name_their_reply_links() {
1278 1333 let from = from();
1279 1334 let callbacks = callbacks();
1280 let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned()], true);
1335 let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned()], true, false);
1281 1336 let negotiation = &offer["mediaNegotiation"];
1282 1337 assert_eq!(negotiation["mediaContent"]["newOffer"], true);
1283 1338 assert_eq!(negotiation["callModalities"], json!(["Audio"]));
1284 let same_peer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned(), "Video".to_owned()], false);
1339 let same_peer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned(), "Video".to_owned()], false, true);
1285 1340 assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["newOffer"], false);
1341 assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["requiredFeatures"], "nonByPass");
1342 assert!(same_peer["mediaNegotiation"]["mediaContent"].get("mediaDescriptions").is_none());
1343 assert!(negotiation["mediaContent"]["mediaDescriptions"].is_object());
1286 1344 assert_eq!(same_peer["mediaNegotiation"]["callModalities"], json!(["Audio", "Video"]));
1287 1345 assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));
1288 1346 assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));
@@ -1299,7 +1357,7 @@ mod tests {
1299 1357 let callbacks = callbacks();
1300 1358 let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1301 1359 let modalities = vec!["Audio".to_owned(), "Video".to_owned()];
1302 let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities });
1360 let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities, direct: true });
1303 1361 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio", "Video"]));
1304 1362 }
1305 1363
@@ -12,7 +12,7 @@ use crate::roster::MeetingRole;
12use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
12use crate::reaction::{DEFAULT_SKIN_TONE, Reaction, reaction_message};
13use crate::relay::ic3_scope;
13use crate::relay::ic3_scope;
14use crate::timeline::Timeline;
14use crate::timeline::Timeline;
15use crate::trouter_events::{CallbackLinks, acceptance_links};
15use crate::trouter_events::{CallbackLinks, acceptance_links, acknowledgement_links};
16use crate::video_layout::MediaDescription;
16use crate::video_layout::MediaDescription;
17
17
18pub const EPCONV_URL: &str = "https://api-emea.flightproxy.teams.microsoft.com/api/v2/epconv";
18pub const EPCONV_URL: &str = "https://api-emea.flightproxy.teams.microsoft.com/api/v2/epconv";
@@ -22,6 +22,8 @@ const CLIENT_HEADER: &str = "SkypeSpaces/1415/26091712213/os=windows; osVer=NT 1
22const PLATFORM_NAME: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36";
22const PLATFORM_NAME: &str = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/155.0.0.0 Safari/537.36";
23const SDP_CONTENT_TYPE: &str = "application/sdp-ngc-1.0";
23const SDP_CONTENT_TYPE: &str = "application/sdp-ngc-1.0";
24const ENDPOINT_CAPABILITIES: u64 = 73463;
24const ENDPOINT_CAPABILITIES: u64 = 73463;
25const ONE_TO_ONE_THREAD_SUFFIX: &str = "@unq.gbl.spaces";
26const DIRECT_REQUIRED_FEATURES: &str = "nonByPass";
25const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
27const CLIENT_ENDPOINT_CAPABILITIES: u64 = 47150826;
26const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
28const ALLOWED_HOST_SUFFIXES: [&str; 2] = [".flightproxy.teams.microsoft.com", ".teams.microsoft.com"];
27const BACKEND_SUFFIX: &str = ".skype.com";
29const BACKEND_SUFFIX: &str = ".skype.com";
@@ -199,6 +201,13 @@ pub struct Invitation<'a> {
199 pub callbacks: &'a CallbackLinks,
201 pub callbacks: &'a CallbackLinks,
200 pub target: &'a InviteTarget,
202 pub target: &'a InviteTarget,
201 pub modalities: &'a [String],
203 pub modalities: &'a [String],
204 pub direct: bool,
205}
206
207impl Invitation<'_> {
208 pub fn is_direct(&self) -> bool {
209 self.direct && self.target.is_one_to_one()
210 }
202}
211}
203
212
204pub struct Answer<'a> {
213pub struct Answer<'a> {
@@ -478,9 +487,11 @@ impl Signaling {
478 from: &Participant,
487 from: &Participant,
479 thread_id: &str,
488 thread_id: &str,
480 callbacks: &CallbackLinks,
489 callbacks: &CallbackLinks,
490 threadless: bool,
481 ) -> Result<u16> {
491 ) -> Result<u16> {
482 let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks);
492 let body = captions::add_bot_body(from.wire(), thread_id, callbacks.call_id(), &from.display_name, callbacks, threadless);
483 let mut request = self.request(Method::Post, conversation.link("addParticipantAndModality")?, Some(body));
493 let link = if threadless { "addParticipant" } else { "addParticipantAndModality" };
494 let mut request = self.request(Method::Post, conversation.link(link)?, Some(body));
484 request = request.with_body_token(captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER);
495 request = request.with_body_token(captions::RECORDER_RESOURCE, captions::RECORDER_SCOPE, captions::INITIATOR_TOKEN_PLACEHOLDER);
485 self.exchange(&self.session, "POST add (caption bot)", request).await.map(|response| response.status)
496 self.exchange(&self.session, "POST add (caption bot)", request).await.map(|response| response.status)
486 }
497 }
@@ -581,8 +592,9 @@ impl Signaling {
581 self.post_json("POST progress", url, ringing_body(from)).await
592 self.post_json("POST progress", url, ringing_body(from)).await
582 }
593 }
583
594
584 pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<()> {
595 pub async fn accept(&self, url: &str, answer: &Answer<'_>) -> Result<BTreeMap<String, String>> {
585 self.post_json("POST acceptance", url, acceptance_body(answer)).await
596 let response = self.send("POST acceptance", Method::Post, url, Some(acceptance_body(answer))).await?;
597 Ok(acknowledgement_links(&response.body))
586 }
598 }
587
599
588 pub async fn decline(&self, call_leg_url: &str) -> Result<()> {
600 pub async fn decline(&self, call_leg_url: &str) -> Result<()> {
@@ -654,8 +666,29 @@ fn media_controller_links(callbacks: &CallbackLinks) -> Value {
654 })
666 })
655}
667}
656
668
657fn group_chat(target: &InviteTarget) -> Value {
669impl InviteTarget {
658 match target {
670 pub fn is_one_to_one(&self) -> bool {
671 match self {
672 InviteTarget::People { callees, thread_id } => callees.len() == 1 && thread_id.ends_with(ONE_TO_ONE_THREAD_SUFFIX),
673 InviteTarget::Echo | InviteTarget::Meeting(_) => false,
674 }
675 }
676}
677
678fn invitation_media(invitation: &Invitation<'_>) -> Value {
679 if !invitation.is_direct() {
680 return media_content(invitation.offer_sdp, invitation.media_leg_id, true);
681 }
682 let mut content = media_content(invitation.offer_sdp, invitation.media_leg_id, false);
683 content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES);
684 content
685}
686
687fn group_chat(invitation: &Invitation<'_>) -> Value {
688 if invitation.is_direct() {
689 return Value::Null;
690 }
691 match invitation.target {
659 InviteTarget::Echo => Value::Null,
692 InviteTarget::Echo => Value::Null,
660 InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}),
693 InviteTarget::People { thread_id, .. } => json!({"threadId": thread_id, "messageId": null}),
661 InviteTarget::Meeting(meeting) => json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}),
694 InviteTarget::Meeting(meeting) => json!({"threadId": meeting.thread_id, "messageId": MEETING_MESSAGE_ID}),
@@ -700,7 +733,7 @@ pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
700 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
733 "clientEndpointCapabilities": CLIENT_ENDPOINT_CAPABILITIES,
701 "endpointMetadata": {"holographicCapabilities": 3},
734 "endpointMetadata": {"holographicCapabilities": 3},
702 "groupContext": null,
735 "groupContext": null,
703 "groupChat": group_chat(target),
736 "groupChat": group_chat(invitation),
704 "meetingInfo": meeting_info,
737 "meetingInfo": meeting_info,
705 "meetingData": meeting_data,
738 "meetingData": meeting_data,
706 "endpointState": endpoint_state(),
739 "endpointState": endpoint_state(),
@@ -714,7 +747,7 @@ pub fn epconv_body(invitation: &Invitation<'_>) -> Value {
714 "clientContentForMediaController": media_controller_links(callbacks),
747 "clientContentForMediaController": media_controller_links(callbacks),
715 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
748 "pstnContent": {"emergencyCallCountry": "", "platformName": PLATFORM_NAME, "publicApiCall": false},
716 "emergencyContent": null,
749 "emergencyContent": null,
717 "mediaContent": media_content(invitation.offer_sdp, invitation.media_leg_id, true),
750 "mediaContent": invitation_media(invitation),
718 },
751 },
719 })
752 })
720}
753}
@@ -818,6 +851,7 @@ pub fn renegotiation_body(
818 media_leg_id: &str,
851 media_leg_id: &str,
819 modalities: &[String],
852 modalities: &[String],
820 new_offer: bool,
853 new_offer: bool,
854 direct: bool,
821) -> Value {
855) -> Value {
822 json!({
856 json!({
823 "mediaNegotiation": {
857 "mediaNegotiation": {
@@ -827,13 +861,16 @@ pub fn renegotiation_body(
827 "mediaAnswer": callbacks.call("mediaAnswer"),
861 "mediaAnswer": callbacks.call("mediaAnswer"),
828 "rejection": callbacks.call("rejection"),
862 "rejection": callbacks.call("rejection"),
829 },
863 },
830 "mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer),
864 "mediaContent": renegotiation_content(offer_sdp, media_leg_id, new_offer, direct),
831 },
865 },
832 })
866 })
833}
867}
834
868
835fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool) -> Value {
869fn renegotiation_content(sdp: &str, media_leg_id: &str, new_offer: bool, direct: bool) -> Value {
836 let mut content = media_content(sdp, media_leg_id, true);
870 let mut content = media_content(sdp, media_leg_id, !direct);
871 if direct {
872 content["requiredFeatures"] = json!(DIRECT_REQUIRED_FEATURES);
873 }
837 content["newOffer"] = json!(new_offer);
874 content["newOffer"] = json!(new_offer);
838 content
875 content
839}
876}
@@ -1059,6 +1096,7 @@ mod tests {
1059 callbacks: &callbacks,
1096 callbacks: &callbacks,
1060 target,
1097 target,
1061 modalities: &["Audio".to_owned()],
1098 modalities: &["Audio".to_owned()],
1099 direct: true,
1062 })
1100 })
1063 }
1101 }
1064
1102
@@ -1109,19 +1147,33 @@ mod tests {
1109 }
1147 }
1110
1148
1111 #[test]
1149 #[test]
1112 fn one_to_one_body_names_the_callee_and_the_chat() {
1150 fn one_to_one_body_names_the_callee_without_a_chat_thread() {
1113 let target = InviteTarget::People {
1151 let target = InviteTarget::People {
1114 callees: vec![callee("8:orgid:b", "Bea")],
1152 callees: vec![callee("8:orgid:b", "Bea")],
1115 thread_id: "19:a_b@unq.gbl.spaces".into(),
1153 thread_id: "19:a_b@unq.gbl.spaces".into(),
1116 };
1154 };
1117 let body = body_for(&target);
1155 let body = body_for(&target);
1118 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:b", "displayName": "Bea"}]));
1156 assert_eq!(body["participants"]["to"], json!([{"id": "8:orgid:b", "displayName": "Bea"}]));
1119 assert_eq!(body["groupChat"], json!({"threadId": "19:a_b@unq.gbl.spaces", "messageId": null}));
1157 assert_eq!(body["groupChat"], Value::Null);
1158 let media = &body["callInvitation"]["mediaContent"];
1159 assert_eq!(media["requiredFeatures"], "nonByPass");
1160 assert!(media.get("mediaDescriptions").is_none());
1120 assert!(body["conversationRequest"].get("scenario").is_none());
1161 assert!(body["conversationRequest"].get("scenario").is_none());
1121 assert_eq!(body["meetingInfo"], Value::Null);
1162 assert_eq!(body["meetingInfo"], Value::Null);
1122 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1163 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio"]));
1123 }
1164 }
1124
1165
1166 #[test]
1167 fn a_one_to_one_call_that_may_not_go_direct_keeps_the_chat_thread() {
1168 let from = from();
1169 let callbacks = callbacks();
1170 let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1171 let modalities = vec!["Audio".to_owned()];
1172 let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities, direct: false });
1173 assert_eq!(body["groupChat"]["threadId"], "19:a_b@unq.gbl.spaces");
1174 assert!(body["callInvitation"]["mediaContent"]["mediaDescriptions"].is_object());
1175 }
1176
1125 #[test]
1177 #[test]
1126 fn group_body_invites_every_callee_on_the_group_thread() {
1178 fn group_body_invites_every_callee_on_the_group_thread() {
1127 let target = InviteTarget::People {
1179 let target = InviteTarget::People {
@@ -1134,6 +1186,9 @@ mod tests {
1134 assert_eq!(to[2]["id"], "8:orgid:d");
1186 assert_eq!(to[2]["id"], "8:orgid:d");
1135 assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2");
1187 assert_eq!(body["groupChat"]["threadId"], "19:group@thread.v2");
1136 assert_eq!(body["groupChat"]["messageId"], Value::Null);
1188 assert_eq!(body["groupChat"]["messageId"], Value::Null);
1189 let media = &body["callInvitation"]["mediaContent"];
1190 assert!(media.get("requiredFeatures").is_none());
1191 assert!(media["mediaDescriptions"].is_object());
1137 }
1192 }
1138
1193
1139 #[test]
1194 #[test]
@@ -1277,12 +1332,15 @@ mod tests {
1277 fn renegotiation_messages_name_their_reply_links() {
1332 fn renegotiation_messages_name_their_reply_links() {
1278 let from = from();
1333 let from = from();
1279 let callbacks = callbacks();
1334 let callbacks = callbacks();
1280 let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned()], true);
1335 let offer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned()], true, false);
1281 let negotiation = &offer["mediaNegotiation"];
1336 let negotiation = &offer["mediaNegotiation"];
1282 assert_eq!(negotiation["mediaContent"]["newOffer"], true);
1337 assert_eq!(negotiation["mediaContent"]["newOffer"], true);
1283 assert_eq!(negotiation["callModalities"], json!(["Audio"]));
1338 assert_eq!(negotiation["callModalities"], json!(["Audio"]));
1284 let same_peer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned(), "Video".to_owned()], false);
1339 let same_peer = renegotiation_body(&from, &callbacks, "v=0\r\n", "AB", &["Audio".to_owned(), "Video".to_owned()], false, true);
1285 assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["newOffer"], false);
1340 assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["newOffer"], false);
1341 assert_eq!(same_peer["mediaNegotiation"]["mediaContent"]["requiredFeatures"], "nonByPass");
1342 assert!(same_peer["mediaNegotiation"]["mediaContent"].get("mediaDescriptions").is_none());
1343 assert!(negotiation["mediaContent"]["mediaDescriptions"].is_object());
1286 assert_eq!(same_peer["mediaNegotiation"]["callModalities"], json!(["Audio", "Video"]));
1344 assert_eq!(same_peer["mediaNegotiation"]["callModalities"], json!(["Audio", "Video"]));
1287 assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));
1345 assert!(negotiation["links"]["mediaAnswer"].as_str().unwrap().ends_with("/call/mediaAnswer/"));
1288 assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));
1346 assert!(negotiation["links"]["rejection"].as_str().unwrap().ends_with("/call/rejection/"));
@@ -1299,7 +1357,7 @@ mod tests {
1299 let callbacks = callbacks();
1357 let callbacks = callbacks();
1300 let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1358 let target = InviteTarget::People { callees: vec![callee("8:orgid:b", "Bea")], thread_id: "19:a_b@unq.gbl.spaces".into() };
1301 let modalities = vec!["Audio".to_owned(), "Video".to_owned()];
1359 let modalities = vec!["Audio".to_owned(), "Video".to_owned()];
1302 let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities });
1360 let body = epconv_body(&Invitation { from: &from, offer_sdp: "v=0\r\n", media_leg_id: "AB", callbacks: &callbacks, target: &target, modalities: &modalities, direct: true });
1303 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio", "Video"]));
1361 assert_eq!(body["callInvitation"]["callModalities"], json!(["Audio", "Video"]));
1304 }
1362 }
1305
1363
crates/calling/src/trouter_events.rs +41 −11
@@ -112,6 +112,7 @@ pub enum ProgressStatus {
112 112 #[derive(Debug, Clone, PartialEq, Eq)]
113 113 pub struct MediaAnswer {
114 114 pub sdp: String,
115 pub from_mixer: bool,
115 116 pub links: BTreeMap<String, String>,
116 117 }
117 118
@@ -137,6 +138,7 @@ pub enum CallEvent {
137 138 AddParticipantFailure(Value),
138 139 ConversationEnd(Value),
139 140 Rejection(Value),
141 RetargetCompletion(Value),
140 142 Reactions(Vec<ReactionEvent>),
141 143 LocalParticipantUpdate(Value),
142 144 Replacement(Value),
@@ -162,6 +164,7 @@ impl CallEvent {
162 164 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
163 165 CallEvent::ConversationEnd(_) => "conversation/conversationEnd".into(),
164 166 CallEvent::Rejection(_) => "call/rejection".into(),
167 CallEvent::RetargetCompletion(_) => "call/retargetCompletion".into(),
165 168 CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
166 169 CallEvent::LocalParticipantUpdate(_) => "conversation/localParticipantUpdate".into(),
167 170 CallEvent::Replacement(_) => "call/replacement".into(),
@@ -185,6 +188,7 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
185 188 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
186 189 ("conversation", "conversationEnd") => CallEvent::ConversationEnd(body),
187 190 ("call", "rejection") => CallEvent::Rejection(body),
191 ("call", "retargetCompletion") => CallEvent::RetargetCompletion(body),
188 192 ("conversation", "localParticipantUpdate") => CallEvent::LocalParticipantUpdate(body),
189 193 ("conversation", "contentSharingUpdate") => CallEvent::ContentShareUpdate(body),
190 194 ("conversation", "contentSharingEnd") => CallEvent::ContentShareEnd(body),
@@ -210,11 +214,8 @@ pub fn callback_call_id(path: &str) -> Option<String> {
210 214 split_callback_path(path).ok().map(|(call_id, _, _)| call_id)
211 215 }
212 216
213 pub fn callback_reply_body(path: &str, links: &CallbackLinks) -> String {
214 match split_callback_path(path) {
215 Ok((_, scope, event)) if scope == "call" && event == "acceptance" => acceptance_acknowledgement(links).to_string(),
216 _ => String::new(),
217 }
217 pub fn is_acceptance_callback(path: &str) -> bool {
218 matches!(split_callback_path(path), Ok((_, scope, event)) if scope == "call" && event == "acceptance")
218 219 }
219 220
220 221 fn split_callback_path(path: &str) -> Result<(String, String, String)> {
@@ -228,6 +229,16 @@ fn split_callback_path(path: &str) -> Result<(String, String, String)> {
228 229 Ok(((*call_id).to_owned(), (*scope).to_owned(), (*event).to_owned()))
229 230 }
230 231
232 pub fn callback_tag(path_or_url: &str) -> Option<String> {
233 let start = path_or_url.find(CALLBACK_ROOT)?;
234 split_callback_path(&path_or_url[start..]).ok()?;
235 path_or_url[start + CALLBACK_ROOT.len()..].split('/').nth(1).map(str::to_owned)
236 }
237
238 pub fn acknowledgement_links(body: &Value) -> BTreeMap<String, String> {
239 string_links(&body["callAcceptanceAcknowledgement"]["links"])
240 }
241
231 242 fn string_links(value: &Value) -> BTreeMap<String, String> {
232 243 value
233 244 .as_object()
@@ -272,6 +283,7 @@ fn media_answer(body: &Value) -> Result<MediaAnswer> {
272 283 .to_owned();
273 284 Ok(MediaAnswer {
274 285 sdp,
286 from_mixer: answer["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
275 287 links: string_links(&answer["links"]),
276 288 })
277 289 }
@@ -571,12 +583,30 @@ mod tests {
571 583 }
572 584
573 585 #[test]
574 fn only_the_acceptance_reply_carries_the_acknowledgement() {
586 fn the_tag_names_the_offer_an_answer_belongs_to() {
575 587 let links = CallbackLinks::new("https://trouter.example/", "abc");
576 let acceptance = callback_reply_body("callAgent/abc/1/call/acceptance/", &links);
577 let parsed: Value = serde_json::from_str(&acceptance).unwrap();
578 assert!(parsed["callAcceptanceAcknowledgement"]["links"].is_object());
579 assert_eq!(callback_reply_body("callAgent/abc/1/call/mediaAnswer/", &links), "");
580 assert_eq!(callback_reply_body("callAgent/abc/1/conversation/rosterUpdate/", &links), "");
588 let url = links.call("mediaAnswer");
589 let tag = callback_tag(&url).unwrap();
590 assert_eq!(tag.len(), 8);
591 assert_eq!(callback_tag(&format!("callAgent/abc/{tag}/call/mediaAnswer/")), Some(tag));
592 assert_eq!(callback_tag("unifiedPresenceService"), None);
593 }
594
595 #[test]
596 fn a_media_answer_says_whether_the_mixer_sent_it() {
597 let body = json!({"mediaAnswer": {"mediaContent": {"blob": "v=0\r\n", "fromMixer": true}, "links": {}}});
598 let (_, event) = classify("callAgent/abc/1/call/mediaAnswer/", body).unwrap();
599 let CallEvent::MediaAnswer(answer) = event else { panic!("not a media answer") };
600 assert!(answer.from_mixer);
601 let (_, retarget) = classify("callAgent/abc/1/call/retargetCompletion/", json!({"retargetCompleted": {"code": 0}})).unwrap();
602 assert!(matches!(retarget, CallEvent::RetargetCompletion(_)));
603 }
604
605 #[test]
606 fn only_the_acceptance_callback_gets_the_acknowledgement() {
607 assert!(is_acceptance_callback("callAgent/abc/1/call/acceptance/"));
608 assert!(!is_acceptance_callback("callAgent/abc/1/call/mediaAnswer/"));
609 assert!(!is_acceptance_callback("callAgent/abc/1/conversation/rosterUpdate/"));
610 assert!(!is_acceptance_callback("unifiedPresenceService"));
581 611 }
582 612 }
@@ -112,6 +112,7 @@ pub enum ProgressStatus {
112#[derive(Debug, Clone, PartialEq, Eq)]
112#[derive(Debug, Clone, PartialEq, Eq)]
113pub struct MediaAnswer {
113pub struct MediaAnswer {
114 pub sdp: String,
114 pub sdp: String,
115 pub from_mixer: bool,
115 pub links: BTreeMap<String, String>,
116 pub links: BTreeMap<String, String>,
116}
117}
117
118
@@ -137,6 +138,7 @@ pub enum CallEvent {
137 AddParticipantFailure(Value),
138 AddParticipantFailure(Value),
138 ConversationEnd(Value),
139 ConversationEnd(Value),
139 Rejection(Value),
140 Rejection(Value),
141 RetargetCompletion(Value),
140 Reactions(Vec<ReactionEvent>),
142 Reactions(Vec<ReactionEvent>),
141 LocalParticipantUpdate(Value),
143 LocalParticipantUpdate(Value),
142 Replacement(Value),
144 Replacement(Value),
@@ -162,6 +164,7 @@ impl CallEvent {
162 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
164 CallEvent::AddParticipantFailure(_) => "conversation/addParticipantFailure".into(),
163 CallEvent::ConversationEnd(_) => "conversation/conversationEnd".into(),
165 CallEvent::ConversationEnd(_) => "conversation/conversationEnd".into(),
164 CallEvent::Rejection(_) => "call/rejection".into(),
166 CallEvent::Rejection(_) => "call/rejection".into(),
167 CallEvent::RetargetCompletion(_) => "call/retargetCompletion".into(),
165 CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
168 CallEvent::Reactions(_) => "conversation/receiveMessage".into(),
166 CallEvent::LocalParticipantUpdate(_) => "conversation/localParticipantUpdate".into(),
169 CallEvent::LocalParticipantUpdate(_) => "conversation/localParticipantUpdate".into(),
167 CallEvent::Replacement(_) => "call/replacement".into(),
170 CallEvent::Replacement(_) => "call/replacement".into(),
@@ -185,6 +188,7 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
185 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
188 ("conversation", "addParticipantFailure") => CallEvent::AddParticipantFailure(body),
186 ("conversation", "conversationEnd") => CallEvent::ConversationEnd(body),
189 ("conversation", "conversationEnd") => CallEvent::ConversationEnd(body),
187 ("call", "rejection") => CallEvent::Rejection(body),
190 ("call", "rejection") => CallEvent::Rejection(body),
191 ("call", "retargetCompletion") => CallEvent::RetargetCompletion(body),
188 ("conversation", "localParticipantUpdate") => CallEvent::LocalParticipantUpdate(body),
192 ("conversation", "localParticipantUpdate") => CallEvent::LocalParticipantUpdate(body),
189 ("conversation", "contentSharingUpdate") => CallEvent::ContentShareUpdate(body),
193 ("conversation", "contentSharingUpdate") => CallEvent::ContentShareUpdate(body),
190 ("conversation", "contentSharingEnd") => CallEvent::ContentShareEnd(body),
194 ("conversation", "contentSharingEnd") => CallEvent::ContentShareEnd(body),
@@ -210,11 +214,8 @@ pub fn callback_call_id(path: &str) -> Option<String> {
210 split_callback_path(path).ok().map(|(call_id, _, _)| call_id)
214 split_callback_path(path).ok().map(|(call_id, _, _)| call_id)
211}
215}
212
216
213pub fn callback_reply_body(path: &str, links: &CallbackLinks) -> String {
217pub fn is_acceptance_callback(path: &str) -> bool {
214 match split_callback_path(path) {
218 matches!(split_callback_path(path), Ok((_, scope, event)) if scope == "call" && event == "acceptance")
215 Ok((_, scope, event)) if scope == "call" && event == "acceptance" => acceptance_acknowledgement(links).to_string(),
216 _ => String::new(),
217 }
218}
219}
219
220
220fn split_callback_path(path: &str) -> Result<(String, String, String)> {
221fn split_callback_path(path: &str) -> Result<(String, String, String)> {
@@ -228,6 +229,16 @@ fn split_callback_path(path: &str) -> Result<(String, String, String)> {
228 Ok(((*call_id).to_owned(), (*scope).to_owned(), (*event).to_owned()))
229 Ok(((*call_id).to_owned(), (*scope).to_owned(), (*event).to_owned()))
229}
230}
230
231
232pub fn callback_tag(path_or_url: &str) -> Option<String> {
233 let start = path_or_url.find(CALLBACK_ROOT)?;
234 split_callback_path(&path_or_url[start..]).ok()?;
235 path_or_url[start + CALLBACK_ROOT.len()..].split('/').nth(1).map(str::to_owned)
236}
237
238pub fn acknowledgement_links(body: &Value) -> BTreeMap<String, String> {
239 string_links(&body["callAcceptanceAcknowledgement"]["links"])
240}
241
231fn string_links(value: &Value) -> BTreeMap<String, String> {
242fn string_links(value: &Value) -> BTreeMap<String, String> {
232 value
243 value
233 .as_object()
244 .as_object()
@@ -272,6 +283,7 @@ fn media_answer(body: &Value) -> Result<MediaAnswer> {
272 .to_owned();
283 .to_owned();
273 Ok(MediaAnswer {
284 Ok(MediaAnswer {
274 sdp,
285 sdp,
286 from_mixer: answer["mediaContent"]["fromMixer"].as_bool().unwrap_or(false),
275 links: string_links(&answer["links"]),
287 links: string_links(&answer["links"]),
276 })
288 })
277}
289}
@@ -571,12 +583,30 @@ mod tests {
571 }
583 }
572
584
573 #[test]
585 #[test]
574 fn only_the_acceptance_reply_carries_the_acknowledgement() {
586 fn the_tag_names_the_offer_an_answer_belongs_to() {
575 let links = CallbackLinks::new("https://trouter.example/", "abc");
587 let links = CallbackLinks::new("https://trouter.example/", "abc");
576 let acceptance = callback_reply_body("callAgent/abc/1/call/acceptance/", &links);
588 let url = links.call("mediaAnswer");
577 let parsed: Value = serde_json::from_str(&acceptance).unwrap();
589 let tag = callback_tag(&url).unwrap();
578 assert!(parsed["callAcceptanceAcknowledgement"]["links"].is_object());
590 assert_eq!(tag.len(), 8);
579 assert_eq!(callback_reply_body("callAgent/abc/1/call/mediaAnswer/", &links), "");
591 assert_eq!(callback_tag(&format!("callAgent/abc/{tag}/call/mediaAnswer/")), Some(tag));
580 assert_eq!(callback_reply_body("callAgent/abc/1/conversation/rosterUpdate/", &links), "");
592 assert_eq!(callback_tag("unifiedPresenceService"), None);
593 }
594
595 #[test]
596 fn a_media_answer_says_whether_the_mixer_sent_it() {
597 let body = json!({"mediaAnswer": {"mediaContent": {"blob": "v=0\r\n", "fromMixer": true}, "links": {}}});
598 let (_, event) = classify("callAgent/abc/1/call/mediaAnswer/", body).unwrap();
599 let CallEvent::MediaAnswer(answer) = event else { panic!("not a media answer") };
600 assert!(answer.from_mixer);
601 let (_, retarget) = classify("callAgent/abc/1/call/retargetCompletion/", json!({"retargetCompleted": {"code": 0}})).unwrap();
602 assert!(matches!(retarget, CallEvent::RetargetCompletion(_)));
603 }
604
605 #[test]
606 fn only_the_acceptance_callback_gets_the_acknowledgement() {
607 assert!(is_acceptance_callback("callAgent/abc/1/call/acceptance/"));
608 assert!(!is_acceptance_callback("callAgent/abc/1/call/mediaAnswer/"));
609 assert!(!is_acceptance_callback("callAgent/abc/1/conversation/rosterUpdate/"));
610 assert!(!is_acceptance_callback("unifiedPresenceService"));
581 }
611 }
582}
612}
crates/calling/src/video_layout.rs +3 −4
@@ -142,10 +142,9 @@ pub fn add_video_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -
142 142
143 143 pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
144 144 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
145 let receiving = h264_only(factory.get_rtp_receiver_capabilities(MediaType::Video).codecs);
146 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending, Vec::new())?;
147 add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving, Vec::new())?;
148 Ok(VideoLines { camera, share: None })
145 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), Vec::new())?;
146 let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())?;
147 Ok(VideoLines { camera, share: Some(share) })
149 148 }
150 149
151 150 /// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
@@ -142,10 +142,9 @@ pub fn add_video_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -
142
142
143pub fn add_one_to_one_lines(peer: &PeerConnection, factory: &PeerConnectionFactory) -> Result<VideoLines> {
143pub 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);
144 let sending = h264_only(factory.get_rtp_sender_capabilities(MediaType::Video).codecs);
145 let receiving = h264_only(factory.get_rtp_receiver_capabilities(MediaType::Video).codecs);
145 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending.clone(), Vec::new())?;
146 let camera = add_line(peer, RtpTransceiverDirection::SendRecv, Some(CAMERA_STREAM), sending, Vec::new())?;
146 let share = add_line(peer, RtpTransceiverDirection::SendRecv, Some(SCREEN_STREAM), sending, Vec::new())?;
147 add_line(peer, RtpTransceiverDirection::RecvOnly, None, receiving, Vec::new())?;
147 Ok(VideoLines { camera, share: Some(share) })
148 Ok(VideoLines { camera, share: None })
149}
148}
150
149
151/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
150/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.