BlueGit

ict rusty-teams

Merge pull request #42: fix(calling): mixer leg-switch media links, share upgrade, and hangup cleanup

- Conflicts with #48 in call.rs resolved (mic_settings argument, noise stage cleared on hangup)
- Stay-awake inhibitor runs `cat` on a stdin pipe instead of PR_SET_PDEATHSIG: ends with the process, no libc, no unsafe
- A new capture thread waits for stopping ones (max 2 s) instead of the drop blocking, so a quick camera off/on does not hit a busy device
- Descriptive comments removed, em dashes replaced

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

metis Daniel Däschle · pushed by metis

Authored 2026-11-16 · 2 weeks ago

Hash
fb9c63565b59e98b85fe6352058bcd07b0d5a8c3
17 files changed +1410 −163
crates/calling/src/awake.rs +3 −3
@@ -57,16 +57,16 @@ impl StayAwake {
57 57
58 58 #[cfg(not(windows))]
59 59 pub fn new() -> Self {
60 // `cat` ends on EOF when this process dies, so a crash cannot leave the inhibitor behind.
60 61 let inhibitor = std::process::Command::new("systemd-inhibit")
61 62 .args([
62 63 "--what=idle:sleep",
63 64 "--who=Rusty Teams",
64 65 &format!("--why={REASON}"),
65 66 "--mode=block",
66 "sleep",
67 "infinity",
67 "cat",
68 68 ])
69 .stdin(std::process::Stdio::null())
69 .stdin(std::process::Stdio::piped())
70 70 .stdout(std::process::Stdio::null())
71 71 .stderr(std::process::Stdio::null())
72 72 .spawn()
@@ -57,16 +57,16 @@ impl StayAwake {
57
57
58 #[cfg(not(windows))]
58 #[cfg(not(windows))]
59 pub fn new() -> Self {
59 pub fn new() -> Self {
60 // `cat` ends on EOF when this process dies, so a crash cannot leave the inhibitor behind.
60 let inhibitor = std::process::Command::new("systemd-inhibit")
61 let inhibitor = std::process::Command::new("systemd-inhibit")
61 .args([
62 .args([
62 "--what=idle:sleep",
63 "--what=idle:sleep",
63 "--who=Rusty Teams",
64 "--who=Rusty Teams",
64 &format!("--why={REASON}"),
65 &format!("--why={REASON}"),
65 "--mode=block",
66 "--mode=block",
66 "sleep",
67 "cat",
67 "infinity",
68 ])
68 ])
69 .stdin(std::process::Stdio::null())
69 .stdin(std::process::Stdio::piped())
70 .stdout(std::process::Stdio::null())
70 .stdout(std::process::Stdio::null())
71 .stderr(std::process::Stdio::null())
71 .stderr(std::process::Stdio::null())
72 .spawn()
72 .spawn()
crates/calling/src/call.rs +844 −93
@@ -80,7 +80,7 @@ use crate::sdp::{
80 80 LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines,
81 81 to_browser_answer, to_teams_answer, to_teams_offer,
82 82 };
83 use crate::send_control::{RequestFilter, parse_request};
83 use crate::send_control::{BitrateGovernor, RequestFilter, parse_request};
84 84 use crate::signaling::{
85 85 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget,
86 86 NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id,
@@ -92,12 +92,13 @@ use crate::timeline::{Timeline, TimelineEntry};
92 92 use crate::transfer::{Replacement, TransferEvent, TransferTarget};
93 93 use crate::trouter_events::{
94 94 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
95 nested_links, object_keys,
95 96 };
96 97 use crate::video_frame::{VideoKey, VideoPicture};
97 98 use crate::video_layout::{
98 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter,
99 SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines,
100 offer_plan, one_to_one_plan,
99 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SHARE_MID,
100 SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines,
101 add_share_line, add_video_lines, offer_plan, one_to_one_plan,
101 102 };
102 103 use crate::video_receive::{
103 104 ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump,
@@ -429,12 +430,23 @@ struct GlareResend {
429 430 struct NextPeer {
430 431 session: PeerSession,
431 432 offered: Option<OfferedMedia>,
433 answered: Option<AnsweredMedia>,
434 leg_links: BTreeMap<String, String>,
435 remote_audio: Option<RtcAudioTrack>,
432 436 reply_tags: Vec<String>,
433 437 deadline: Option<Instant>,
434 438 connected: bool,
435 439 retargeted: bool,
436 440 }
437 441
442 /// Renegotiation usually carries only `mediaAnswer`/`rejection`; keep the other leg links unless replaced.
443 fn replace_leg_media_links(
444 media_links: &mut BTreeMap<String, String>,
445 leg_links: &BTreeMap<String, String>,
446 ) {
447 media_links.extend(leg_links.clone());
448 }
449
438 450 fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
439 451 match callback_tag(callback_path) {
440 452 Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag),
@@ -459,12 +471,22 @@ struct Live {
459 471 broker_running: Arc<AtomicBool>,
460 472 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
461 473 route_id: Option<String>,
474 call_legs: Vec<String>,
462 475 skip_leave: bool,
463 476 cancel_leave: bool,
464 477 video_tasks: Vec<JoinHandle<()>>,
465 478 video_counters: Arc<VideoCounters>,
466 479 }
467 480
481 fn remember_call_leg(live: &mut Live, url: Option<&str>) {
482 let Some(url) = url.filter(|url| !url.is_empty()) else {
483 return;
484 };
485 if !live.call_legs.iter().any(|known| known == url) {
486 live.call_legs.push(url.to_owned());
487 }
488 }
489
468 490 fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool {
469 491 let next = state.next(signal, std::time::Instant::now());
470 492 if next == *state {
@@ -778,17 +800,28 @@ async fn create_offer(
778 800
779 801 struct AnsweredMedia {
780 802 remote: RemoteOffer,
803 offer_sdp: String,
781 804 answer_sdp: String,
782 805 camera_mid: Option<String>,
783 806 receiving_share_mid: Option<String>,
784 807 }
785 808
786 809 fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
787 remote
810 let main: Vec<_> = remote
788 811 .lines
789 812 .iter()
790 .find(|line| line.role == LineRole::MainVideo)
791 .and_then(|line| line.browser_mids.first().cloned())
813 .filter(|line| line.role == LineRole::MainVideo)
814 .filter_map(|line| line.browser_mids.first().cloned())
815 .collect();
816 main.iter()
817 .find(|mid| {
818 matches!(
819 direction_of(&remote.browser_sdp, mid).as_deref(),
820 Some("sendrecv" | "recvonly")
821 )
822 })
823 .cloned()
824 .or_else(|| main.into_iter().next())
792 825 }
793 826
794 827 fn share_mids(remote: &RemoteOffer) -> Vec<String> {
@@ -796,10 +829,18 @@ fn share_mids(remote: &RemoteOffer) -> Vec<String> {
796 829 .lines
797 830 .iter()
798 831 .filter(|line| line.role == LineRole::ScreenShare)
799 .filter_map(|line| line.browser_mids.first().cloned())
832 .flat_map(|line| line.browser_mids.iter().cloned())
800 833 .collect()
801 834 }
802 835
836 fn share_carrier_mid(remote: &RemoteOffer) -> Option<String> {
837 remote
838 .lines
839 .iter()
840 .find(|line| line.role == LineRole::ScreenShare)
841 .and_then(|line| line.browser_mids.last().cloned())
842 }
843
803 844 async fn answer_offer(
804 845 peer: &PeerConnection,
805 846 track: Option<&RtcAudioTrack>,
@@ -808,6 +849,34 @@ async fn answer_offer(
808 849 sending_share_mid: Option<String>,
809 850 camera_on: bool,
810 851 gathered: Option<&Gathered>,
852 ) -> Result<AnsweredMedia> {
853 answer_offer_with(
854 peer,
855 track,
856 teams_offer,
857 video,
858 sending_share_mid,
859 None,
860 camera_on,
861 gathered,
862 false,
863 false,
864 )
865 .await
866 }
867
868 #[allow(clippy::too_many_arguments)]
869 async fn answer_offer_with(
870 peer: &PeerConnection,
871 track: Option<&RtcAudioTrack>,
872 teams_offer: &str,
873 video: AnswerVideo<'_>,
874 sending_share_mid: Option<String>,
875 share_track: Option<&RtcVideoTrack>,
876 camera_on: bool,
877 gathered: Option<&Gathered>,
878 keep_receive_slots: bool,
879 mixer: bool,
811 880 ) -> Result<AnsweredMedia> {
812 881 let remote = from_teams_offer(teams_offer)?;
813 882 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
@@ -827,25 +896,53 @@ async fn answer_offer(
827 896 } else {
828 897 share_mids(&remote)
829 898 };
830 for transceiver in peer.transceivers() {
831 let is_video = matches!(
832 transceiver.receiver().track(),
833 Some(MediaStreamTrack::Video(_))
834 );
835 let unused = transceiver.mid().is_some_and(|mid| {
836 Some(&mid) != camera_mid.as_ref()
837 && !kept_share_mids.contains(&mid)
838 && Some(&mid) != sending_share_mid.as_ref()
839 });
840 if is_video && unused {
841 let _ = transceiver.stop();
899 if !keep_receive_slots {
900 for transceiver in peer.transceivers() {
901 let is_video = matches!(
902 transceiver.receiver().track(),
903 Some(MediaStreamTrack::Video(_))
904 );
905 let unused = transceiver.mid().is_some_and(|mid| {
906 Some(&mid) != camera_mid.as_ref()
907 && !kept_share_mids.contains(&mid)
908 && Some(&mid) != sending_share_mid.as_ref()
909 });
910 if is_video && unused {
911 let _ = transceiver.stop();
912 }
842 913 }
843 914 }
844 915 if let Some(track) = track {
845 916 peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
846 917 .map_err(|error| Error::Webrtc(error.to_string()))?;
847 918 }
848 if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {
919 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
920 if mixer {
921 // Keep camera sendrecv so a later set_track / updateMediaDescriptions
922 // can start sending without renegotiation. Do NOT force folded
923 // x-multi-stream share lines to sendrecv: Teams rejects that answer
924 // with SdpParsingFailure (301000); starting share upgrades the peer.
925 if let Some(mid) = camera_mid.as_deref()
926 && let Some(camera) = peer_transceiver(peer, mid)
927 {
928 let _ = camera.set_direction(RtpTransceiverDirection::SendRecv);
929 if let AnswerVideo::Send(track) = video {
930 let _ = camera
931 .sender()
932 .set_track(Some(MediaStreamTrack::Video(track.clone())));
933 }
934 }
935 if let Some(mid) = sending_share_mid.as_deref()
936 && let Some(share) = peer_transceiver(peer, mid)
937 {
938 let _ = share.set_direction(RtpTransceiverDirection::SendRecv);
939 if let Some(track) = share_track {
940 let _ = share
941 .sender()
942 .set_track(Some(MediaStreamTrack::Video(track.clone())));
943 }
944 }
945 } else if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {
849 946 peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM])
850 947 .map_err(|error| Error::Webrtc(error.to_string()))?;
851 948 }
@@ -860,15 +957,22 @@ async fn answer_offer(
860 957 {
861 958 answer_text = stop_sending_on(&answer_text, mid);
862 959 }
863 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
864 if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
960 if !mixer && let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
865 961 answer_text = stop_sending_on(&answer_text, mid);
866 962 }
867 963 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
868 964 .await
869 965 .map_err(|error| Error::Webrtc(error.to_string()))?;
870 let receiving_share_mid = kept_share_mids
966 if mixer
967 && !sends_camera
968 && let Some(mid) = camera_mid.as_deref()
969 && let Some(camera) = peer_transceiver(peer, mid)
970 {
971 let _ = LocalVideo::set_sender_active(&camera.sender(), false);
972 }
973 let receiving_share_mid = share_carrier_mid(&remote)
871 974 .into_iter()
975 .chain(kept_share_mids)
872 976 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
873 977 .find(|mid| {
874 978 matches!(
@@ -880,6 +984,7 @@ async fn answer_offer(
880 984 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
881 985 Ok(AnsweredMedia {
882 986 remote,
987 offer_sdp: teams_offer.to_owned(),
883 988 answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
884 989 camera_mid,
885 990 receiving_share_mid,
@@ -925,6 +1030,11 @@ fn video_possible(remote_set: bool, layout: Layout, path: MediaPath) -> bool {
925 1030 remote_set && !(layout == Layout::OneToOne && path == MediaPath::Mixer)
926 1031 }
927 1032
1033 /// Re-queuing while `next` is set spins the call task (defer -> pending -> defer...).
1034 fn camera_may_start(pending: bool, next_is_some: bool, possible: bool) -> bool {
1035 pending && !next_is_some && possible
1036 }
1037
928 1038 #[allow(clippy::too_many_arguments)]
929 1039 async fn drive(
930 1040 inner: &Inner,
@@ -1283,6 +1393,7 @@ async fn drive(
1283 1393 }
1284 1394 }
1285 1395 keep_alive_link = media_links.get("callLeg").cloned();
1396 remember_call_leg(live, keep_alive_link.as_deref());
1286 1397 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
1287 1398 conversation
1288 1399 }
@@ -1401,6 +1512,7 @@ async fn drive(
1401 1512 let mut same_peer: Option<SamePeerOffer> = None;
1402 1513 let mut send_requests = RequestFilter::default();
1403 1514 let mut send_capabilities = SendCapabilityReporter::default();
1515 let mut bitrate_governor = BitrateGovernor::default();
1404 1516 let mut same_peer_deadline: Option<Instant> = None;
1405 1517 let mut same_peer_grace_until: Option<Instant> = None;
1406 1518 let mut meeting_chat = conversation.chat_thread.clone();
@@ -1423,16 +1535,17 @@ async fn drive(
1423 1535 let (echo_add_tx, mut echo_add_rx) = mpsc::unbounded_channel::<Result<()>>();
1424 1536 let mut echo_add_pending = false;
1425 1537 loop {
1426 if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
1538 let possible = video_possible(remote_set, layout, negotiator.path());
1539 if camera_may_start(start_camera_pending, next.is_some(), possible) {
1427 1540 start_camera_pending = false;
1428 1541 control.defer(CallCommand::SetCamera(true));
1429 1542 }
1430 if video_possible(remote_set, layout, negotiator.path())
1543 if camera_may_start(share_pending.is_some(), next.is_some(), possible)
1431 1544 && let Some(source) = share_pending.take()
1432 1545 {
1433 1546 control.defer(CallCommand::StartShare(source));
1434 1547 }
1435 if video_possible(remote_set, layout, negotiator.path())
1548 if camera_may_start(portal_pending.is_some(), next.is_some(), possible)
1436 1549 && let Some(kind) = portal_pending.take()
1437 1550 {
1438 1551 control.defer(CallCommand::StartPortalShare(kind));
@@ -1447,10 +1560,43 @@ async fn drive(
1447 1560 );
1448 1561 deferred_changes.clear();
1449 1562 negotiator.server_escalation_done();
1563 // New mixer leg starts sequence numbers from 1 and has not heard our send capabilities yet.
1564 send_requests = RequestFilter::default();
1565 send_capabilities = SendCapabilityReporter::default();
1450 1566 if let Some(mid) = remote_direct_share.take() {
1451 1567 video.router().set(&mid, None);
1452 1568 control.send(CallUpdate::ScreenShare(None));
1453 1569 }
1570 // Detach local senders before closing: otherwise peer.close can hang
1571 // while the camera/share capture threads still feed the old track.
1572 local_video.clear_lines();
1573 replace_leg_media_links(&mut media_links, &pending.leg_links);
1574 let leg_names = pending
1575 .leg_links
1576 .keys()
1577 .cloned()
1578 .collect::<Vec<_>>()
1579 .join(",");
1580 timeline.record(
1581 "leg links",
1582 if leg_names.is_empty() {
1583 "none".to_owned()
1584 } else {
1585 leg_names
1586 },
1587 );
1588 if let Some(url) = media_links.get("callLeg").cloned()
1589 && keep_alive_link.as_deref() != Some(url.as_str())
1590 {
1591 keep_alive_link = Some(url.clone());
1592 remember_call_leg(live, Some(&url));
1593 }
1594 if let Some(track) = pending.remote_audio {
1595 remote_audio = Some(track.clone());
1596 if options.record_remote {
1597 tokio::spawn(record_track(track, recording.clone(), options.tone_hz));
1598 }
1599 }
1454 1600 let old = std::mem::replace(&mut current, pending.session);
1455 1601 old.peer.close();
1456 1602 reconnect_deadline = None;
@@ -1462,7 +1608,30 @@ async fn drive(
1462 1608 {
1463 1609 timeline.record("computer sound not carried over", error.to_string());
1464 1610 }
1611 if remote_audio.is_some() {
1612 sync_software_audio(
1613 &factory,
1614 options,
1615 &input,
1616 muted,
1617 remote_audio.clone(),
1618 &current.peer,
1619 &track,
1620 software_wanted(
1621 mic_settings,
1622 share_sound_wanted,
1623 &local_video,
1624 live.audio.as_ref(),
1625 ),
1626 true,
1627 &mut software_audio,
1628 mic_settings,
1629 control,
1630 timeline,
1631 );
1632 }
1465 1633 offered = pending.offered;
1634 let answered = pending.answered;
1466 1635 if let Some(mid) = direct_video_mid.take() {
1467 1636 video.router().set(&mid, None);
1468 1637 }
@@ -1472,24 +1641,66 @@ async fn drive(
1472 1641 if let Err(error) = local_video.set_lines(media.video.clone()) {
1473 1642 timeline.record("video lines not attached", error.to_string());
1474 1643 }
1475 if local_video.camera_on() {
1476 tell_media_descriptions(
1477 &remote,
1478 &media_links,
1479 MediaDescription::camera(true),
1480 &mut media_description_request,
1481 timeline,
1482 );
1483 }
1484 if local_video.sharing() {
1485 tell_media_descriptions(
1486 &remote,
1487 &media_links,
1488 MediaDescription::share(true),
1489 &mut media_description_request,
1490 timeline,
1491 );
1644 tell_bound_camera(
1645 &remote,
1646 &media_links,
1647 &local_video,
1648 &mut media_description_request,
1649 timeline,
1650 );
1651 tell_bound_share(
1652 &remote,
1653 &media_links,
1654 &local_video,
1655 &mut media_description_request,
1656 timeline,
1657 );
1658 } else if let Some(answered) = answered {
1659 // Server escalation answered on a new peer: drop the old peer's
1660 // senders and bind the camera/share lines that stayed alive there.
1661 layout = Layout::Conference;
1662 layout_plan = answered.remote.plan();
1663 match video_lines_from_answer(&current.peer, &answered) {
1664 Some(lines) => {
1665 if let Err(error) = local_video.set_lines(lines) {
1666 timeline.record("video lines not attached", error.to_string());
1667 }
1668 }
1669 None => {
1670 local_video.clear_lines();
1671 timeline.record(
1672 "video lines not attached",
1673 "no transceiver for the answered camera line",
1674 );
1675 }
1492 1676 }
1677 negotiate_video_lines(
1678 &mut video,
1679 &signaling,
1680 control,
1681 timeline,
1682 &answered.offer_sdp,
1683 &answered.remote.lines,
1684 true,
1685 &media_links,
1686 &roster,
1687 );
1688 tell_bound_camera(
1689 &remote,
1690 &media_links,
1691 &local_video,
1692 &mut media_description_request,
1693 timeline,
1694 );
1695 tell_bound_share(
1696 &remote,
1697 &media_links,
1698 &local_video,
1699 &mut media_description_request,
1700 timeline,
1701 );
1702 } else {
1703 local_video.clear_lines();
1493 1704 }
1494 1705 remote_set = true;
1495 1706 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
@@ -1566,6 +1777,7 @@ async fn drive(
1566 1777 control.send(CallUpdate::Lobby(true));
1567 1778 }
1568 1779 keep_alive_link = acceptance.links.get("callLeg").cloned();
1780 remember_call_leg(live, keep_alive_link.as_deref());
1569 1781 keep_alive_seconds = acceptance.keep_alive_seconds;
1570 1782 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
1571 1783 if action == MediaAction::ApplyAnswerThenEscalate {
@@ -1706,6 +1918,9 @@ async fn drive(
1706 1918 };
1707 1919 match applied {
1708 1920 Ok(()) => {
1921 if let Some(pending) = next.as_mut() {
1922 pending.leg_links.extend(answer.links.clone());
1923 }
1709 1924 if let Some(media) = next.as_ref().and_then(|pending| pending.offered.as_ref()) {
1710 1925 media_links.extend(answer.links.clone());
1711 1926 negotiate_video(&mut video, &signaling, control, timeline, &answer.sdp, media, true, &media_links, &roster);
@@ -1753,7 +1968,20 @@ async fn drive(
1753 1968 if let Some(resend) = glare_resend.take() {
1754 1969 defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control);
1755 1970 }
1756 match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1971 let camera_track = local_video.camera_track();
1972 let share_track = local_video.share_track();
1973 match answer_on_new_peer(
1974 &factory,
1975 &grant,
1976 options,
1977 outgoing_track(software_audio.as_ref(), &track),
1978 &renegotiation.sdp,
1979 local_video.camera_on(),
1980 local_video.camera_on().then_some(&camera_track),
1981 local_video.sharing().then_some(&share_track),
1982 )
1983 .await
1984 {
1757 1985 Ok((session, answered)) => {
1758 1986 timeline.record_sdp("local answer", &answered.answer_sdp);
1759 1987 live.peers.push(session.peer.clone());
@@ -1761,8 +1989,22 @@ async fn drive(
1761 1989 if let Some(replaced) = next.take() {
1762 1990 replaced.session.peer.close();
1763 1991 }
1764 next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: Some(Instant::now() + NEXT_PEER_LIMIT), connected: false, retargeted: false });
1765 sent
1992 let mut leg_links = renegotiation.links.clone();
1993 if let Ok((extra, keys)) = &sent {
1994 absorb_answered_links(&mut leg_links, extra, timeline, keys);
1995 }
1996 next = Some(NextPeer {
1997 session,
1998 offered: None,
1999 answered: Some(answered),
2000 leg_links,
2001 remote_audio: None,
2002 reply_tags: Vec::new(),
2003 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
2004 connected: false,
2005 retargeted: false,
2006 });
2007 sent.map(|_| ())
1766 2008 }
1767 2009 Err(error) => {
1768 2010 if next.is_none() {
@@ -1779,42 +2021,116 @@ async fn drive(
1779 2021 }
1780 2022 }
1781 2023 MediaAction::AnswerOnSamePeer => {
1782 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
1783 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer, local_video.sharing().then(|| local_video.share_mid()).flatten(), local_video.camera_on(), (layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct).then_some(&current.gathered)).await {
2024 // After a server escalation the follow-up offer matches the
2025 // pending peer's m-line order: never answer it on the old peer.
2026 let on_pending = next.as_ref().is_some_and(|pending| pending.answered.is_some());
2027 let peer = if on_pending {
2028 &next.as_ref().unwrap().session.peer
2029 } else {
2030 &current.peer
2031 };
2032 let camera_track = local_video.camera_track();
2033 let share_track = local_video.share_track();
2034 let video_answer = if local_video.camera_on() {
2035 AnswerVideo::Send(&camera_track)
2036 } else {
2037 AnswerVideo::Receive
2038 };
2039 let keep_slots = on_pending || layout == Layout::Conference;
2040 let gathered = (!on_pending
2041 && layout == Layout::OneToOne
2042 && negotiator.path() == MediaPath::Direct)
2043 .then_some(&current.gathered);
2044 match answer_offer_with(
2045 peer,
2046 None,
2047 &renegotiation.sdp,
2048 video_answer,
2049 local_video.sharing().then(|| local_video.share_mid()).flatten(),
2050 local_video.sharing().then_some(&share_track),
2051 local_video.camera_on(),
2052 gathered,
2053 keep_slots,
2054 keep_slots,
2055 )
2056 .await
2057 {
1784 2058 Ok(answered) => {
1785 2059 timeline.record_sdp("local answer", &answered.answer_sdp);
2060 if on_pending {
2061 if let Some(pending) = next.as_mut() {
2062 pending.leg_links.extend(renegotiation.links.clone());
2063 }
2064 } else {
2065 media_links.extend(renegotiation.links.clone());
2066 }
1786 2067 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
2068 if let Ok((extra, keys)) = &sent {
2069 if on_pending {
2070 if let Some(pending) = next.as_mut() {
2071 absorb_answered_links(&mut pending.leg_links, extra, timeline, keys);
2072 }
2073 } else {
2074 absorb_answered_links(&mut media_links, extra, timeline, keys);
2075 }
2076 }
1787 2077 for mid in answered.remote.plan().screen_share_mids {
1788 2078 if !layout_plan.screen_share_mids.contains(&mid) {
1789 2079 layout_plan.screen_share_mids.push(mid);
1790 2080 }
1791 2081 }
1792 if layout == Layout::OneToOne && answered.receiving_share_mid != remote_direct_share {
1793 if let Some(mid) = &remote_direct_share {
1794 video.router().set(mid, None);
2082 if on_pending {
2083 if let Some(pending) = next.as_mut() {
2084 pending.answered = Some(answered);
1795 2085 }
1796 if let Some(mid) = &answered.receiving_share_mid {
1797 video.router().set(mid, Some(VideoKey::Screen));
2086 } else if layout == Layout::Conference {
2087 negotiate_video_lines(
2088 &mut video,
2089 &signaling,
2090 control,
2091 timeline,
2092 &answered.offer_sdp,
2093 &answered.remote.lines,
2094 true,
2095 &media_links,
2096 &roster,
2097 );
2098 } else if layout == Layout::OneToOne {
2099 if answered.receiving_share_mid != remote_direct_share {
2100 if let Some(mid) = &remote_direct_share {
2101 video.router().set(mid, None);
2102 }
2103 if let Some(mid) = &answered.receiving_share_mid {
2104 video.router().set(mid, Some(VideoKey::Screen));
2105 }
2106 remote_direct_share = answered.receiving_share_mid.clone();
2107 control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));
2108 }
2109 if !offer_sends_video(&renegotiation.sdp)
2110 && let Some(key) = main_video_mid(&answered.remote).and_then(|mid| video.router().key_for(&mid))
2111 {
2112 control.video.forget(&key);
2113 control.send(CallUpdate::VideoStopped(key));
1798 2114 }
1799 remote_direct_share = answered.receiving_share_mid.clone();
1800 control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));
1801 }
1802 if layout == Layout::OneToOne
1803 && !offer_sends_video(&renegotiation.sdp)
1804 && let Some(key) = main_video_mid(&answered.remote).and_then(|mid| video.router().key_for(&mid))
1805 {
1806 control.video.forget(&key);
1807 control.send(CallUpdate::VideoStopped(key));
1808 2115 }
1809 2116 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
1810 2117 if held != remote_hold {
1811 2118 remote_hold = held;
1812 2119 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1813 2120 }
1814 sent
2121 sent.map(|_| ())
1815 2122 }
1816 2123 Err(error) => {
1817 if current.peer.signaling_state() == SignalingState::HaveRemoteOffer {
2124 if on_pending {
2125 if let Some(pending) = next.as_ref()
2126 && pending.session.peer.signaling_state()
2127 == SignalingState::HaveRemoteOffer
2128 {
2129 rollback_remote_offer(&pending.session.peer).await;
2130 }
2131 } else if current.peer.signaling_state()
2132 == SignalingState::HaveRemoteOffer
2133 {
1818 2134 rollback_remote_offer(&current.peer).await;
1819 2135 }
1820 2136 if let Some(url) = &rejection_link {
@@ -2070,6 +2386,70 @@ async fn drive(
2070 2386 }
2071 2387 RejectedOffer::None => {}
2072 2388 },
2389 Ok(CallEvent::MediaAcknowledgement(ack)) => {
2390 if let Some(pending) = next.as_mut() {
2391 pending.leg_links.extend(ack.links);
2392 if pending.answered.is_some() {
2393 // Server-initiated mixer leg switch sends mediaAcknowledgement
2394 // instead of retargetCompletion; switch as soon as ICE connects.
2395 pending.retargeted = true;
2396 }
2397 } else if !ack.links.is_empty() {
2398 let old_request = media_links
2399 .get("applyChannelParameters")
2400 .or_else(|| media_links.get("controlVideoStreaming"))
2401 .cloned();
2402 let old_update = media_links.get("updateMediaDescriptions").cloned();
2403 replace_leg_media_links(&mut media_links, &ack.links);
2404 if let Some(url) = media_links.get("callLeg").cloned()
2405 && keep_alive_link.as_deref() != Some(url.as_str())
2406 {
2407 keep_alive_link = Some(url.clone());
2408 remember_call_leg(live, Some(&url));
2409 }
2410 let new_request = media_links
2411 .get("applyChannelParameters")
2412 .or_else(|| media_links.get("controlVideoStreaming"))
2413 .cloned();
2414 if layout == Layout::Conference
2415 && new_request != old_request
2416 && let Some(url) = new_request
2417 {
2418 video.replace_requester(SourceRequester::start(
2419 signaling.clone(),
2420 url,
2421 video.router().clone(),
2422 control.video.clone(),
2423 timeline.clone(),
2424 ));
2425 send_receive_change(control, video.reselect(&roster));
2426 }
2427 if layout == Layout::Conference
2428 && media_links.get("updateMediaDescriptions") != old_update.as_ref()
2429 && local_video.has_lines()
2430 {
2431 send_capabilities = SendCapabilityReporter::default();
2432 if local_video.camera_on() {
2433 tell_bound_camera(
2434 &remote,
2435 &media_links,
2436 &local_video,
2437 &mut media_description_request,
2438 timeline,
2439 );
2440 }
2441 if local_video.sharing() {
2442 tell_bound_share(
2443 &remote,
2444 &media_links,
2445 &local_video,
2446 &mut media_description_request,
2447 timeline,
2448 );
2449 }
2450 }
2451 }
2452 }
2073 2453 Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => {
2074 2454 if let Some(pending) = next.as_mut() {
2075 2455 pending.retargeted = true;
@@ -2128,16 +2508,14 @@ async fn drive(
2128 2508 }
2129 2509 }
2130 2510 }
2511 // Planned mixer escalation: ignore old-peer death while the new peer is pending.
2512 PeerConnectionState::Disconnected | PeerConnectionState::Failed
2513 if next.is_some() => {}
2131 2514 PeerConnectionState::Disconnected => {
2132 2515 if advance(state, CallSignal::MediaDisconnected, control) {
2133 2516 reconnect_deadline = Some(Instant::now() + options.reconnect_window);
2134 2517 }
2135 2518 }
2136 PeerConnectionState::Failed if next.is_some() => {
2137 if advance(state, CallSignal::MediaDisconnected, control) {
2138 reconnect_deadline = Some(Instant::now() + options.reconnect_window);
2139 }
2140 }
2141 2519 PeerConnectionState::Failed => {
2142 2520 advance(state, CallSignal::MediaFailed, control);
2143 2521 break;
@@ -2187,6 +2565,12 @@ async fn drive(
2187 2565 timeline.record("remote video track", format!("mid {mid} (new peer)"));
2188 2566 live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));
2189 2567 }
2568 PeerEvent::Track(remote_track) => {
2569 timeline.record("remote audio track", "receiving (new peer)");
2570 if let Some(pending) = next.as_mut() {
2571 pending.remote_audio = Some(remote_track);
2572 }
2573 }
2190 2574 PeerEvent::Connection(PeerConnectionState::Failed) => {
2191 2575 negotiator.escalation_failed();
2192 2576 if let Some(pending) = next.take() {
@@ -2258,7 +2642,20 @@ async fn drive(
2258 2642 }
2259 2643 Some(CallCommand::SetCamera(on)) => {
2260 2644 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
2261 if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) {
2645 if on && next.is_some() {
2646 let first = !start_camera_pending;
2647 start_camera_pending = true;
2648 if local_video.is_available()
2649 && !local_video.camera_on()
2650 && !local_video.camera_previewing()
2651 && let Err(error) = local_video.preview_camera(&camera_choice)
2652 {
2653 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2654 }
2655 if first {
2656 control.send(CallUpdate::Camera(true));
2657 }
2658 } else if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) {
2262 2659 if remote_set && next.is_none() && negotiator.begin_conference_upgrade() {
2263 2660 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2264 2661 next = pending.or(next);
@@ -2292,7 +2689,16 @@ async fn drive(
2292 2689 }
2293 2690 Ok(()) => {
2294 2691 control.send(CallUpdate::Camera(true));
2295 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
2692 tell_media_descriptions(
2693 &remote,
2694 &media_links,
2695 MediaDescription::camera_line(
2696 local_video.camera_mid().unwrap_or_else(|| CAMERA_MID.to_owned()),
2697 true,
2698 ),
2699 &mut media_description_request,
2700 timeline,
2701 );
2296 2702 }
2297 2703 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))),
2298 2704 }
@@ -2315,7 +2721,16 @@ async fn drive(
2315 2721 } else {
2316 2722 local_video.stop_camera();
2317 2723 control.send(CallUpdate::Camera(false));
2318 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(false), &mut media_description_request, timeline);
2724 tell_media_descriptions(
2725 &remote,
2726 &media_links,
2727 MediaDescription::camera_line(
2728 local_video.camera_mid().unwrap_or_else(|| CAMERA_MID.to_owned()),
2729 false,
2730 ),
2731 &mut media_description_request,
2732 timeline,
2733 );
2319 2734 }
2320 2735 }
2321 2736 Some(CallCommand::SelectCamera(choice)) => {
@@ -2345,6 +2760,9 @@ async fn drive(
2345 2760 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2346 2761 } else if local_hold {
2347 2762 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2763 } else if !local_video.sharing() && next.is_some() {
2764 portal_pending = Some(kind);
2765 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2348 2766 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2349 2767 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2350 2768 } else if direct
@@ -2353,7 +2771,10 @@ async fn drive(
2353 2771 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2354 2772 {
2355 2773 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2356 } else if !local_video.sharing() && !video_possible(remote_set, layout, negotiator.path()) {
2774 } else if !local_video.sharing()
2775 && (!video_possible(remote_set, layout, negotiator.path())
2776 || !local_video.share_sending())
2777 {
2357 2778 if next.is_none() && negotiator.begin_conference_upgrade() {
2358 2779 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2359 2780 next = pending.or(next);
@@ -2384,6 +2805,9 @@ async fn drive(
2384 2805 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2385 2806 } else if local_hold {
2386 2807 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2808 } else if next.is_some() {
2809 share_pending = Some(source);
2810 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2387 2811 } else if direct && local_video.share_sending() {
2388 2812 match local_video.start_share(&source) {
2389 2813 Ok(()) => announce_share(control, &source),
@@ -2416,7 +2840,9 @@ async fn drive(
2416 2840 }
2417 2841 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2418 2842 }
2419 } else if !video_possible(remote_set, layout, negotiator.path()) {
2843 } else if !video_possible(remote_set, layout, negotiator.path())
2844 || !local_video.share_sending()
2845 {
2420 2846 if next.is_none() && negotiator.begin_conference_upgrade() {
2421 2847 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2422 2848 next = pending.or(next);
@@ -2431,7 +2857,16 @@ async fn drive(
2431 2857 match local_video.start_share(&source) {
2432 2858 Ok(()) => {
2433 2859 announce_share(control, &source);
2434 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
2860 tell_media_descriptions(
2861 &remote,
2862 &media_links,
2863 MediaDescription::share_line(
2864 local_video.share_mid().unwrap_or_else(|| SHARE_MID.to_owned()),
2865 true,
2866 ),
2867 &mut media_description_request,
2868 timeline,
2869 );
2435 2870 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2436 2871 }
2437 2872 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
@@ -2463,7 +2898,16 @@ async fn drive(
2463 2898 local_video.stop_share();
2464 2899 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2465 2900 clear_share(control);
2466 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2901 tell_media_descriptions(
2902 &remote,
2903 &media_links,
2904 MediaDescription::share_line(
2905 local_video.share_mid().unwrap_or_else(|| SHARE_MID.to_owned()),
2906 false,
2907 ),
2908 &mut media_description_request,
2909 timeline,
2910 );
2467 2911 }
2468 2912 }
2469 2913 Some(CallCommand::SetShareSound(on)) => {
@@ -2760,6 +3204,15 @@ async fn drive(
2760 3204 }
2761 3205 }
2762 3206 Some(CallCommand::EndMeeting) => {
3207 stop_local_publish(
3208 &mut local_video,
3209 &remote,
3210 &media_links,
3211 &mut media_description_request,
3212 control,
3213 timeline,
3214 )
3215 .await;
2763 3216 if is_meeting {
2764 3217 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
2765 3218 Ok(()) => {
@@ -2773,6 +3226,16 @@ async fn drive(
2773 3226 break;
2774 3227 }
2775 3228 Some(CallCommand::Hangup) | None => {
3229 // Stop publishing before leave so remotes do not keep a frozen camera tile.
3230 stop_local_publish(
3231 &mut local_video,
3232 &remote,
3233 &media_links,
3234 &mut media_description_request,
3235 control,
3236 timeline,
3237 )
3238 .await;
2776 3239 advance(state, CallSignal::LocalLeave, control);
2777 3240 break;
2778 3241 }
@@ -2816,8 +3279,14 @@ async fn drive(
2816 3279 if layout == Layout::Conference
2817 3280 && let Some(size) = local_video.camera_size()
2818 3281 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2819 && let Some(body) =
2820 send_capabilities.body_for(size, local_video.video_quality())
3282 && let Some(body) = send_capabilities.body_for_mid(
3283 local_video
3284 .camera_mid()
3285 .as_deref()
3286 .unwrap_or(CAMERA_MID),
3287 size,
3288 local_video.video_quality(),
3289 )
2821 3290 {
2822 3291 let signaling = signaling.clone();
2823 3292 let timeline = timeline.clone();
@@ -2864,6 +3333,28 @@ async fn drive(
2864 3333 && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)
2865 3334 {
2866 3335 let quality = quality_tracker.observe(std::time::Instant::now(), &sample);
3336 if local_video.camera_on()
3337 && snapshot.camera_target_bitrate > 0
3338 && bitrate_governor.observe(
3339 std::time::Instant::now(),
3340 snapshot.video.remote_round_trip_ms,
3341 sample.loss_percent,
3342 snapshot.camera_target_bitrate,
3343 )
3344 {
3345 let cap = bitrate_governor.cap_bps();
3346 if let Err(error) = local_video.cap_camera_bitrate(cap) {
3347 timeline.record("bitrate cap failed", error.to_string());
3348 } else {
3349 timeline.record(
3350 "bitrate cap",
3351 match cap {
3352 Some(bps) => format!("{} kbit/s", bps / 1000),
3353 None => "cleared".into(),
3354 },
3355 );
3356 }
3357 }
2867 3358 control.send(CallUpdate::Health(CallHealth {
2868 3359 level: quality.level,
2869 3360 cpu_limited: quality.cpu_limited,
@@ -3084,6 +3575,9 @@ async fn start_escalation(
3084 3575 Ok(NextPeer {
3085 3576 session,
3086 3577 offered: Some(media),
3578 answered: None,
3579 leg_links: acceptance_links.clone(),
3580 remote_audio: None,
3087 3581 reply_tags,
3088 3582 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
3089 3583 connected: false,
@@ -3133,34 +3627,56 @@ async fn escalate(
3133 3627 }
3134 3628 }
3135 3629
3630 #[allow(clippy::too_many_arguments)]
3136 3631 async fn answer_on_new_peer(
3137 3632 factory: &PeerConnectionFactory,
3138 3633 grant: &RelayGrant,
3139 3634 options: &CallOptions,
3140 3635 track: &RtcAudioTrack,
3141 3636 teams_offer: &str,
3637 camera_on: bool,
3638 camera: Option<&RtcVideoTrack>,
3639 share: Option<&RtcVideoTrack>,
3142 3640 ) -> Result<(PeerSession, AnsweredMedia)> {
3143 3641 let session = open_peer(factory, grant, &options.relay_host, false)?;
3144 let answered = answer_offer(
3642 // Keep every video mid from the mixer offer (camera, gallery, share).
3643 // Reject would stop them and leave set_track InvalidState after the new
3644 // peer replaces the old one. When the camera is already on, answer sendrecv
3645 // so the remote keeps receiving across the escalation.
3646 let video = match (camera_on, camera) {
3647 (true, Some(camera)) => AnswerVideo::Send(camera),
3648 _ => AnswerVideo::Receive,
3649 };
3650 let answered = answer_offer_with(
3145 3651 &session.peer,
3146 3652 Some(track),
3147 3653 teams_offer,
3148 AnswerVideo::Reject,
3654 video,
3149 3655 None,
3150 false,
3656 share,
3657 camera_on,
3151 3658 None,
3659 true,
3660 true,
3152 3661 )
3153 3662 .await?;
3154 3663 Ok((session, answered))
3155 3664 }
3156 3665
3666 fn video_lines_from_answer(peer: &PeerConnection, answered: &AnsweredMedia) -> Option<VideoLines> {
3667 let camera_mid = answered.camera_mid.as_deref()?;
3668 let camera = peer_transceiver(peer, camera_mid)?;
3669 let share = share_carrier_mid(&answered.remote).and_then(|mid| peer_transceiver(peer, &mid));
3670 Some(VideoLines { camera, share })
3671 }
3672
3157 3673 async fn send_media_answer(
3158 3674 remote: &RemoteCall,
3159 3675 links: &CallbackLinks,
3160 3676 reply_links: &BTreeMap<String, String>,
3161 3677 answered: &AnsweredMedia,
3162 3678 media_leg_id: &str,
3163 ) -> Result<()> {
3679 ) -> Result<(BTreeMap<String, String>, String)> {
3164 3680 let url = reply_links
3165 3681 .get("mediaAnswer")
3166 3682 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
@@ -3170,10 +3686,31 @@ async fn send_media_answer(
3170 3686 &answered.answer_sdp,
3171 3687 media_leg_id,
3172 3688 );
3173 remote
3689 let response = remote
3174 3690 .signaling
3175 .post_json("POST mediaAnswer", url, body)
3176 .await
3691 .post_json_body("POST mediaAnswer", url, body)
3692 .await?;
3693 Ok((nested_links(&response), object_keys(&response)))
3694 }
3695
3696 fn absorb_answered_links(
3697 into: &mut BTreeMap<String, String>,
3698 extra: &BTreeMap<String, String>,
3699 timeline: &Timeline,
3700 response_keys: &str,
3701 ) {
3702 if extra.is_empty() {
3703 if !response_keys.is_empty() {
3704 timeline.record(
3705 "media answer links",
3706 format!("none, body keys {response_keys}"),
3707 );
3708 }
3709 return;
3710 }
3711 let names = extra.keys().cloned().collect::<Vec<_>>().join(",");
3712 timeline.record("media answer links", names);
3713 into.extend(extra.clone());
3177 3714 }
3178 3715
3179 3716 #[allow(clippy::too_many_arguments)]
@@ -3188,7 +3725,32 @@ fn negotiate_video(
3188 3725 links: &BTreeMap<String, String>,
3189 3726 roster: &Roster,
3190 3727 ) {
3191 let streams = match stream_lines(answer_sdp, &media.signaled.lines) {
3728 negotiate_video_lines(
3729 video,
3730 signaling,
3731 control,
3732 timeline,
3733 answer_sdp,
3734 &media.signaled.lines,
3735 from_mixer,
3736 links,
3737 roster,
3738 );
3739 }
3740
3741 #[allow(clippy::too_many_arguments)]
3742 fn negotiate_video_lines(
3743 video: &mut VideoReceive,
3744 signaling: &Arc<Signaling>,
3745 control: &CallControl,
3746 timeline: &Timeline,
3747 teams_sdp: &str,
3748 lines: &[crate::sdp::SignaledLine],
3749 from_mixer: bool,
3750 links: &BTreeMap<String, String>,
3751 roster: &Roster,
3752 ) {
3753 let streams = match stream_lines(teams_sdp, lines) {
3192 3754 Ok(streams) => streams,
3193 3755 Err(error) => {
3194 3756 timeline.record("video slots unknown", error.to_string());
@@ -3221,6 +3783,47 @@ fn negotiate_video(
3221 3783 send_receive_change(control, video.reselect(roster));
3222 3784 }
3223 3785
3786 fn tell_bound_camera(
3787 remote: &RemoteCall,
3788 links: &BTreeMap<String, String>,
3789 local_video: &LocalVideo,
3790 request_id: &mut u32,
3791 timeline: &Timeline,
3792 ) {
3793 let mid = local_video
3794 .camera_mid()
3795 .unwrap_or_else(|| CAMERA_MID.to_owned());
3796 tell_media_descriptions(
3797 remote,
3798 links,
3799 MediaDescription::camera_line(mid, local_video.camera_on()),
3800 request_id,
3801 timeline,
3802 );
3803 }
3804
3805 fn tell_bound_share(
3806 remote: &RemoteCall,
3807 links: &BTreeMap<String, String>,
3808 local_video: &LocalVideo,
3809 request_id: &mut u32,
3810 timeline: &Timeline,
3811 ) {
3812 if !local_video.sharing() {
3813 return;
3814 }
3815 let mid = local_video
3816 .share_mid()
3817 .unwrap_or_else(|| SHARE_MID.to_owned());
3818 tell_media_descriptions(
3819 remote,
3820 links,
3821 MediaDescription::share_line(mid, true),
3822 request_id,
3823 timeline,
3824 );
3825 }
3826
3224 3827 async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3225 3828 match mode {
3226 3829 VideoMode::Pattern => vec![CameraDevice {
@@ -4255,6 +4858,64 @@ fn sync_software_audio(
4255 4858 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4256 4859 }
4257 4860
4861 async fn stop_local_publish(
4862 local_video: &mut LocalVideo,
4863 remote: &RemoteCall,
4864 media_links: &BTreeMap<String, String>,
4865 request_id: &mut u32,
4866 control: &CallControl,
4867 timeline: &Timeline,
4868 ) {
4869 let camera_mid = local_video.camera_mid();
4870 let share_mid = local_video.share_mid();
4871 let was_sharing = local_video.sharing();
4872 let was_camera = local_video.camera_on() || local_video.camera_previewing();
4873 if was_sharing {
4874 local_video.stop_share();
4875 clear_share(control);
4876 }
4877 if was_camera {
4878 local_video.stop_camera();
4879 control.send(CallUpdate::Camera(false));
4880 }
4881 local_video.clear_lines();
4882 let Some(url) = media_links.get("updateMediaDescriptions").cloned() else {
4883 return;
4884 };
4885 let mut descriptions = Vec::new();
4886 if was_camera {
4887 descriptions.push(MediaDescription::camera_line(
4888 camera_mid.unwrap_or_else(|| CAMERA_MID.to_owned()),
4889 false,
4890 ));
4891 }
4892 if was_sharing {
4893 descriptions.push(MediaDescription::share_line(
4894 share_mid.unwrap_or_else(|| SHARE_MID.to_owned()),
4895 false,
4896 ));
4897 }
4898 if descriptions.is_empty() {
4899 return;
4900 }
4901 *request_id += 1;
4902 let id = *request_id;
4903 match remote
4904 .signaling
4905 .update_media_descriptions(&url, &descriptions, id)
4906 .await
4907 {
4908 Ok(()) => timeline.record(
4909 "updateMediaDescriptions",
4910 format!("publish off before leave, request {id}"),
4911 ),
4912 Err(error) => timeline.record(
4913 "updateMediaDescriptions failed",
4914 format!("publish off before leave: {error}"),
4915 ),
4916 }
4917 }
4918
4258 4919 async fn tear_down(
4259 4920 mut live: Live,
4260 4921 inner: &Inner,
@@ -4266,13 +4927,15 @@ async fn tear_down(
4266 4927 timeline.record("noise suppression", "DeepFilterNet too slow, WebRTC only");
4267 4928 }
4268 4929 crate::noise_stage::clear();
4269 for peer in &live.peers {
4270 peer.close();
4930 // Stop keep-alive / broker first so Teams does not see us as still present.
4931 live.broker_running.store(false, Ordering::SeqCst);
4932 if let Some(broker) = live.broker.take() {
4933 broker.abort();
4271 4934 }
4272 4935 if let Some(audio) = live.audio.take() {
4273 4936 audio.stop().await;
4274 4937 }
4275 live.broker_running.store(false, Ordering::SeqCst);
4938 // Leave and drop call legs while peers are still open, then close media.
4276 4939 if !live.skip_leave
4277 4940 && let Some(remote) = &live.remote
4278 4941 {
@@ -4289,6 +4952,11 @@ async fn tear_down(
4289 4952 Ok(()) => report.left_cleanly = true,
4290 4953 Err(error) => timeline.record("leave failed", error.to_string()),
4291 4954 }
4955 for call_leg in &live.call_legs {
4956 if let Err(error) = remote.signaling.end_call_leg(call_leg).await {
4957 timeline.record("callLeg end failed", error.to_string());
4958 }
4959 }
4292 4960 }
4293 4961 if report.end.is_none()
4294 4962 && let Some(callbacks) = live.callbacks.as_mut()
@@ -4306,8 +4974,8 @@ async fn tear_down(
4306 4974 .await;
4307 4975 report.end = waited.ok().flatten();
4308 4976 }
4309 if let Some(broker) = live.broker.take() {
4310 broker.abort();
4977 for peer in &live.peers {
4978 peer.close();
4311 4979 }
4312 4980 for task in live.video_tasks.drain(..) {
4313 4981 task.abort();
@@ -4345,6 +5013,14 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
4345 5013 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
4346 5014 CallEvent::ControlVideoStreaming(body) => parse_request(body)
4347 5015 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
5016 CallEvent::MediaAcknowledgement(ack) => {
5017 let names = ack.links.keys().cloned().collect::<Vec<_>>().join(",");
5018 if names.is_empty() {
5019 format!("links=none keys={}", ack.keys)
5020 } else {
5021 format!("links={names}")
5022 }
5023 }
4348 5024 _ => String::new(),
4349 5025 };
4350 5026 timeline.record(format!("Trouter {}", event.name()), detail);
@@ -4352,7 +5028,21 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
4352 5028 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
4353 5029 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
4354 5030 CallEvent::MediaRenegotiation(renegotiation) => {
4355 timeline.record_sdp("remote offer", &renegotiation.sdp)
5031 timeline.record_sdp("remote offer", &renegotiation.sdp);
5032 let names = renegotiation
5033 .links
5034 .keys()
5035 .cloned()
5036 .collect::<Vec<_>>()
5037 .join(",");
5038 timeline.record(
5039 "renegotiation links",
5040 if names.is_empty() {
5041 "none".to_owned()
5042 } else {
5043 names
5044 },
5045 );
4356 5046 }
4357 5047 _ => {}
4358 5048 }
@@ -4490,6 +5180,7 @@ struct StatsSnapshot {
4490 5180 local_level: f64,
4491 5181 echo_return_loss_enhancement: f64,
4492 5182 video: VideoReport,
5183 camera_target_bitrate: u64,
4493 5184 share_inbound_packets: u64,
4494 5185 share_outbound_packets: u64,
4495 5186 share_receive: Option<ShareReceive>,
@@ -4604,6 +5295,10 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
4604 5295 snapshot.video.outbound_packets += outbound.sent.packets_sent;
4605 5296 if share_mids.contains(&outbound.outbound.mid) {
4606 5297 snapshot.share_outbound_packets += outbound.sent.packets_sent;
5298 } else if outbound.outbound.active {
5299 snapshot.camera_target_bitrate = snapshot
5300 .camera_target_bitrate
5301 .max(outbound.outbound.target_bitrate as u64);
4607 5302 }
4608 5303 snapshot.video.outbound_frames_encoded +=
4609 5304 u64::from(outbound.outbound.frames_encoded);
@@ -4750,6 +5445,62 @@ mod tests {
4750 5445 ));
4751 5446 }
4752 5447
5448 #[test]
5449 fn camera_does_not_start_while_a_peer_escalation_is_pending() {
5450 assert!(camera_may_start(true, false, true));
5451 assert!(!camera_may_start(true, true, true));
5452 assert!(!camera_may_start(false, false, true));
5453 assert!(!camera_may_start(true, false, false));
5454 }
5455
5456 #[test]
5457 fn leg_switch_keeps_mixer_control_links_when_renegotiation_omits_them() {
5458 let mut media_links = BTreeMap::from([
5459 (
5460 "updateMediaDescriptions".to_owned(),
5461 "https://m/update".to_owned(),
5462 ),
5463 (
5464 "applyChannelParameters".to_owned(),
5465 "https://m/apply".to_owned(),
5466 ),
5467 ("callLeg".to_owned(), "https://m/leg".to_owned()),
5468 ]);
5469 replace_leg_media_links(
5470 &mut media_links,
5471 &BTreeMap::from([("mediaAnswer".to_owned(), "https://m/answer".to_owned())]),
5472 );
5473 assert_eq!(
5474 media_links
5475 .get("updateMediaDescriptions")
5476 .map(String::as_str),
5477 Some("https://m/update")
5478 );
5479 assert_eq!(
5480 media_links
5481 .get("applyChannelParameters")
5482 .map(String::as_str),
5483 Some("https://m/apply")
5484 );
5485 assert_eq!(
5486 media_links.get("mediaAnswer").map(String::as_str),
5487 Some("https://m/answer")
5488 );
5489 replace_leg_media_links(
5490 &mut media_links,
5491 &BTreeMap::from([(
5492 "updateMediaDescriptions".to_owned(),
5493 "https://m/update-new".to_owned(),
5494 )]),
5495 );
5496 assert_eq!(
5497 media_links
5498 .get("updateMediaDescriptions")
5499 .map(String::as_str),
5500 Some("https://m/update-new")
5501 );
5502 }
5503
4753 5504 #[test]
4754 5505 fn keep_alive_fires_at_ninety_percent_of_the_interval() {
4755 5506 assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430));
@@ -80,7 +80,7 @@ use crate::sdp::{
80 LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines,
80 LineRole, OfferPlan, RemoteOffer, SignaledOffer, from_teams_offer, stream_lines,
81 to_browser_answer, to_teams_answer, to_teams_offer,
81 to_browser_answer, to_teams_answer, to_teams_offer,
82};
82};
83use crate::send_control::{RequestFilter, parse_request};
83use crate::send_control::{BitrateGovernor, RequestFilter, parse_request};
84use crate::signaling::{
84use crate::signaling::{
85 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget,
85 Answer, Attached, Callee, Conversation, Invitation, InviteTarget, LeaveReason, MeetingTarget,
86 NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id,
86 NegotiationFailure, Participant, Signaling, TenantRouting, chat_thread_id,
@@ -92,12 +92,13 @@ use crate::timeline::{Timeline, TimelineEntry};
92use crate::transfer::{Replacement, TransferEvent, TransferTarget};
92use crate::transfer::{Replacement, TransferEvent, TransferTarget};
93use crate::trouter_events::{
93use crate::trouter_events::{
94 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
94 CallEnd, CallEvent, CallbackLinks, ProgressStatus, callback_tag, classify, decode_body,
95 nested_links, object_keys,
95};
96};
96use crate::video_frame::{VideoKey, VideoPicture};
97use crate::video_frame::{VideoKey, VideoPicture};
97use crate::video_layout::{
98use crate::video_layout::{
98 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SendCapabilityReporter,
99 CAMERA_MID, MediaDescription, ONE_TO_ONE_SHARE_MID, SCREEN_STREAM, SHARE_MID,
99 SlotTable, VideoLines, VideoRouter, add_one_to_one_lines, add_share_line, add_video_lines,
100 SendCapabilityReporter, SlotTable, VideoLines, VideoRouter, add_one_to_one_lines,
100 offer_plan, one_to_one_plan,
101 add_share_line, add_video_lines, offer_plan, one_to_one_plan,
101};
102};
102use crate::video_receive::{
103use crate::video_receive::{
103 ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump,
104 ReceiveChange, SourceRequester, VideoCounters, VideoReceive, spawn_video_pump,
@@ -429,12 +430,23 @@ struct GlareResend {
429struct NextPeer {
430struct NextPeer {
430 session: PeerSession,
431 session: PeerSession,
431 offered: Option<OfferedMedia>,
432 offered: Option<OfferedMedia>,
433 answered: Option<AnsweredMedia>,
434 leg_links: BTreeMap<String, String>,
435 remote_audio: Option<RtcAudioTrack>,
432 reply_tags: Vec<String>,
436 reply_tags: Vec<String>,
433 deadline: Option<Instant>,
437 deadline: Option<Instant>,
434 connected: bool,
438 connected: bool,
435 retargeted: bool,
439 retargeted: bool,
436}
440}
437
441
442/// Renegotiation usually carries only `mediaAnswer`/`rejection`; keep the other leg links unless replaced.
443fn replace_leg_media_links(
444 media_links: &mut BTreeMap<String, String>,
445 leg_links: &BTreeMap<String, String>,
446) {
447 media_links.extend(leg_links.clone());
448}
449
438fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
450fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool {
439 match callback_tag(callback_path) {
451 match callback_tag(callback_path) {
440 Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag),
452 Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag),
@@ -459,12 +471,22 @@ struct Live {
459 broker_running: Arc<AtomicBool>,
471 broker_running: Arc<AtomicBool>,
460 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
472 callbacks: Option<mpsc::UnboundedReceiver<TrouterCallback>>,
461 route_id: Option<String>,
473 route_id: Option<String>,
474 call_legs: Vec<String>,
462 skip_leave: bool,
475 skip_leave: bool,
463 cancel_leave: bool,
476 cancel_leave: bool,
464 video_tasks: Vec<JoinHandle<()>>,
477 video_tasks: Vec<JoinHandle<()>>,
465 video_counters: Arc<VideoCounters>,
478 video_counters: Arc<VideoCounters>,
466}
479}
467
480
481fn remember_call_leg(live: &mut Live, url: Option<&str>) {
482 let Some(url) = url.filter(|url| !url.is_empty()) else {
483 return;
484 };
485 if !live.call_legs.iter().any(|known| known == url) {
486 live.call_legs.push(url.to_owned());
487 }
488}
489
468fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool {
490fn advance(state: &mut CallState, signal: CallSignal, control: &CallControl) -> bool {
469 let next = state.next(signal, std::time::Instant::now());
491 let next = state.next(signal, std::time::Instant::now());
470 if next == *state {
492 if next == *state {
@@ -778,17 +800,28 @@ async fn create_offer(
778
800
779struct AnsweredMedia {
801struct AnsweredMedia {
780 remote: RemoteOffer,
802 remote: RemoteOffer,
803 offer_sdp: String,
781 answer_sdp: String,
804 answer_sdp: String,
782 camera_mid: Option<String>,
805 camera_mid: Option<String>,
783 receiving_share_mid: Option<String>,
806 receiving_share_mid: Option<String>,
784}
807}
785
808
786fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
809fn main_video_mid(remote: &RemoteOffer) -> Option<String> {
787 remote
810 let main: Vec<_> = remote
788 .lines
811 .lines
789 .iter()
812 .iter()
790 .find(|line| line.role == LineRole::MainVideo)
813 .filter(|line| line.role == LineRole::MainVideo)
791 .and_then(|line| line.browser_mids.first().cloned())
814 .filter_map(|line| line.browser_mids.first().cloned())
815 .collect();
816 main.iter()
817 .find(|mid| {
818 matches!(
819 direction_of(&remote.browser_sdp, mid).as_deref(),
820 Some("sendrecv" | "recvonly")
821 )
822 })
823 .cloned()
824 .or_else(|| main.into_iter().next())
792}
825}
793
826
794fn share_mids(remote: &RemoteOffer) -> Vec<String> {
827fn share_mids(remote: &RemoteOffer) -> Vec<String> {
@@ -796,10 +829,18 @@ fn share_mids(remote: &RemoteOffer) -> Vec<String> {
796 .lines
829 .lines
797 .iter()
830 .iter()
798 .filter(|line| line.role == LineRole::ScreenShare)
831 .filter(|line| line.role == LineRole::ScreenShare)
799 .filter_map(|line| line.browser_mids.first().cloned())
832 .flat_map(|line| line.browser_mids.iter().cloned())
800 .collect()
833 .collect()
801}
834}
802
835
836fn share_carrier_mid(remote: &RemoteOffer) -> Option<String> {
837 remote
838 .lines
839 .iter()
840 .find(|line| line.role == LineRole::ScreenShare)
841 .and_then(|line| line.browser_mids.last().cloned())
842}
843
803async fn answer_offer(
844async fn answer_offer(
804 peer: &PeerConnection,
845 peer: &PeerConnection,
805 track: Option<&RtcAudioTrack>,
846 track: Option<&RtcAudioTrack>,
@@ -808,6 +849,34 @@ async fn answer_offer(
808 sending_share_mid: Option<String>,
849 sending_share_mid: Option<String>,
809 camera_on: bool,
850 camera_on: bool,
810 gathered: Option<&Gathered>,
851 gathered: Option<&Gathered>,
852) -> Result<AnsweredMedia> {
853 answer_offer_with(
854 peer,
855 track,
856 teams_offer,
857 video,
858 sending_share_mid,
859 None,
860 camera_on,
861 gathered,
862 false,
863 false,
864 )
865 .await
866}
867
868#[allow(clippy::too_many_arguments)]
869async fn answer_offer_with(
870 peer: &PeerConnection,
871 track: Option<&RtcAudioTrack>,
872 teams_offer: &str,
873 video: AnswerVideo<'_>,
874 sending_share_mid: Option<String>,
875 share_track: Option<&RtcVideoTrack>,
876 camera_on: bool,
877 gathered: Option<&Gathered>,
878 keep_receive_slots: bool,
879 mixer: bool,
811) -> Result<AnsweredMedia> {
880) -> Result<AnsweredMedia> {
812 let remote = from_teams_offer(teams_offer)?;
881 let remote = from_teams_offer(teams_offer)?;
813 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
882 let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?;
@@ -827,25 +896,53 @@ async fn answer_offer(
827 } else {
896 } else {
828 share_mids(&remote)
897 share_mids(&remote)
829 };
898 };
830 for transceiver in peer.transceivers() {
899 if !keep_receive_slots {
831 let is_video = matches!(
900 for transceiver in peer.transceivers() {
832 transceiver.receiver().track(),
901 let is_video = matches!(
833 Some(MediaStreamTrack::Video(_))
902 transceiver.receiver().track(),
834 );
903 Some(MediaStreamTrack::Video(_))
835 let unused = transceiver.mid().is_some_and(|mid| {
904 );
836 Some(&mid) != camera_mid.as_ref()
905 let unused = transceiver.mid().is_some_and(|mid| {
837 && !kept_share_mids.contains(&mid)
906 Some(&mid) != camera_mid.as_ref()
838 && Some(&mid) != sending_share_mid.as_ref()
907 && !kept_share_mids.contains(&mid)
839 });
908 && Some(&mid) != sending_share_mid.as_ref()
840 if is_video && unused {
909 });
841 let _ = transceiver.stop();
910 if is_video && unused {
911 let _ = transceiver.stop();
912 }
842 }
913 }
843 }
914 }
844 if let Some(track) = track {
915 if let Some(track) = track {
845 peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
916 peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM])
846 .map_err(|error| Error::Webrtc(error.to_string()))?;
917 .map_err(|error| Error::Webrtc(error.to_string()))?;
847 }
918 }
848 if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {
919 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
920 if mixer {
921 // Keep camera sendrecv so a later set_track / updateMediaDescriptions
922 // can start sending without renegotiation. Do NOT force folded
923 // x-multi-stream share lines to sendrecv: Teams rejects that answer
924 // with SdpParsingFailure (301000); starting share upgrades the peer.
925 if let Some(mid) = camera_mid.as_deref()
926 && let Some(camera) = peer_transceiver(peer, mid)
927 {
928 let _ = camera.set_direction(RtpTransceiverDirection::SendRecv);
929 if let AnswerVideo::Send(track) = video {
930 let _ = camera
931 .sender()
932 .set_track(Some(MediaStreamTrack::Video(track.clone())));
933 }
934 }
935 if let Some(mid) = sending_share_mid.as_deref()
936 && let Some(share) = peer_transceiver(peer, mid)
937 {
938 let _ = share.set_direction(RtpTransceiverDirection::SendRecv);
939 if let Some(track) = share_track {
940 let _ = share
941 .sender()
942 .set_track(Some(MediaStreamTrack::Video(track.clone())));
943 }
944 }
945 } else if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) {
849 peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM])
946 peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM])
850 .map_err(|error| Error::Webrtc(error.to_string()))?;
947 .map_err(|error| Error::Webrtc(error.to_string()))?;
851 }
948 }
@@ -860,15 +957,22 @@ async fn answer_offer(
860 {
957 {
861 answer_text = stop_sending_on(&answer_text, mid);
958 answer_text = stop_sending_on(&answer_text, mid);
862 }
959 }
863 let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_));
960 if !mixer && let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
864 if let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) {
865 answer_text = stop_sending_on(&answer_text, mid);
961 answer_text = stop_sending_on(&answer_text, mid);
866 }
962 }
867 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
963 peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?)
868 .await
964 .await
869 .map_err(|error| Error::Webrtc(error.to_string()))?;
965 .map_err(|error| Error::Webrtc(error.to_string()))?;
870 let receiving_share_mid = kept_share_mids
966 if mixer
967 && !sends_camera
968 && let Some(mid) = camera_mid.as_deref()
969 && let Some(camera) = peer_transceiver(peer, mid)
970 {
971 let _ = LocalVideo::set_sender_active(&camera.sender(), false);
972 }
973 let receiving_share_mid = share_carrier_mid(&remote)
871 .into_iter()
974 .into_iter()
975 .chain(kept_share_mids)
872 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
976 .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str()))
873 .find(|mid| {
977 .find(|mid| {
874 matches!(
978 matches!(
@@ -880,6 +984,7 @@ async fn answer_offer(
880 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
984 let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?;
881 Ok(AnsweredMedia {
985 Ok(AnsweredMedia {
882 remote,
986 remote,
987 offer_sdp: teams_offer.to_owned(),
883 answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
988 answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?,
884 camera_mid,
989 camera_mid,
885 receiving_share_mid,
990 receiving_share_mid,
@@ -925,6 +1030,11 @@ fn video_possible(remote_set: bool, layout: Layout, path: MediaPath) -> bool {
925 remote_set && !(layout == Layout::OneToOne && path == MediaPath::Mixer)
1030 remote_set && !(layout == Layout::OneToOne && path == MediaPath::Mixer)
926}
1031}
927
1032
1033/// Re-queuing while `next` is set spins the call task (defer -> pending -> defer...).
1034fn camera_may_start(pending: bool, next_is_some: bool, possible: bool) -> bool {
1035 pending && !next_is_some && possible
1036}
1037
928#[allow(clippy::too_many_arguments)]
1038#[allow(clippy::too_many_arguments)]
929async fn drive(
1039async fn drive(
930 inner: &Inner,
1040 inner: &Inner,
@@ -1283,6 +1393,7 @@ async fn drive(
1283 }
1393 }
1284 }
1394 }
1285 keep_alive_link = media_links.get("callLeg").cloned();
1395 keep_alive_link = media_links.get("callLeg").cloned();
1396 remember_call_leg(live, keep_alive_link.as_deref());
1286 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
1397 keep_alive_at = Some(Instant::now() + keep_alive_period(None));
1287 conversation
1398 conversation
1288 }
1399 }
@@ -1401,6 +1512,7 @@ async fn drive(
1401 let mut same_peer: Option<SamePeerOffer> = None;
1512 let mut same_peer: Option<SamePeerOffer> = None;
1402 let mut send_requests = RequestFilter::default();
1513 let mut send_requests = RequestFilter::default();
1403 let mut send_capabilities = SendCapabilityReporter::default();
1514 let mut send_capabilities = SendCapabilityReporter::default();
1515 let mut bitrate_governor = BitrateGovernor::default();
1404 let mut same_peer_deadline: Option<Instant> = None;
1516 let mut same_peer_deadline: Option<Instant> = None;
1405 let mut same_peer_grace_until: Option<Instant> = None;
1517 let mut same_peer_grace_until: Option<Instant> = None;
1406 let mut meeting_chat = conversation.chat_thread.clone();
1518 let mut meeting_chat = conversation.chat_thread.clone();
@@ -1423,16 +1535,17 @@ async fn drive(
1423 let (echo_add_tx, mut echo_add_rx) = mpsc::unbounded_channel::<Result<()>>();
1535 let (echo_add_tx, mut echo_add_rx) = mpsc::unbounded_channel::<Result<()>>();
1424 let mut echo_add_pending = false;
1536 let mut echo_add_pending = false;
1425 loop {
1537 loop {
1426 if start_camera_pending && video_possible(remote_set, layout, negotiator.path()) {
1538 let possible = video_possible(remote_set, layout, negotiator.path());
1539 if camera_may_start(start_camera_pending, next.is_some(), possible) {
1427 start_camera_pending = false;
1540 start_camera_pending = false;
1428 control.defer(CallCommand::SetCamera(true));
1541 control.defer(CallCommand::SetCamera(true));
1429 }
1542 }
1430 if video_possible(remote_set, layout, negotiator.path())
1543 if camera_may_start(share_pending.is_some(), next.is_some(), possible)
1431 && let Some(source) = share_pending.take()
1544 && let Some(source) = share_pending.take()
1432 {
1545 {
1433 control.defer(CallCommand::StartShare(source));
1546 control.defer(CallCommand::StartShare(source));
1434 }
1547 }
1435 if video_possible(remote_set, layout, negotiator.path())
1548 if camera_may_start(portal_pending.is_some(), next.is_some(), possible)
1436 && let Some(kind) = portal_pending.take()
1549 && let Some(kind) = portal_pending.take()
1437 {
1550 {
1438 control.defer(CallCommand::StartPortalShare(kind));
1551 control.defer(CallCommand::StartPortalShare(kind));
@@ -1447,10 +1560,43 @@ async fn drive(
1447 );
1560 );
1448 deferred_changes.clear();
1561 deferred_changes.clear();
1449 negotiator.server_escalation_done();
1562 negotiator.server_escalation_done();
1563 // New mixer leg starts sequence numbers from 1 and has not heard our send capabilities yet.
1564 send_requests = RequestFilter::default();
1565 send_capabilities = SendCapabilityReporter::default();
1450 if let Some(mid) = remote_direct_share.take() {
1566 if let Some(mid) = remote_direct_share.take() {
1451 video.router().set(&mid, None);
1567 video.router().set(&mid, None);
1452 control.send(CallUpdate::ScreenShare(None));
1568 control.send(CallUpdate::ScreenShare(None));
1453 }
1569 }
1570 // Detach local senders before closing: otherwise peer.close can hang
1571 // while the camera/share capture threads still feed the old track.
1572 local_video.clear_lines();
1573 replace_leg_media_links(&mut media_links, &pending.leg_links);
1574 let leg_names = pending
1575 .leg_links
1576 .keys()
1577 .cloned()
1578 .collect::<Vec<_>>()
1579 .join(",");
1580 timeline.record(
1581 "leg links",
1582 if leg_names.is_empty() {
1583 "none".to_owned()
1584 } else {
1585 leg_names
1586 },
1587 );
1588 if let Some(url) = media_links.get("callLeg").cloned()
1589 && keep_alive_link.as_deref() != Some(url.as_str())
1590 {
1591 keep_alive_link = Some(url.clone());
1592 remember_call_leg(live, Some(&url));
1593 }
1594 if let Some(track) = pending.remote_audio {
1595 remote_audio = Some(track.clone());
1596 if options.record_remote {
1597 tokio::spawn(record_track(track, recording.clone(), options.tone_hz));
1598 }
1599 }
1454 let old = std::mem::replace(&mut current, pending.session);
1600 let old = std::mem::replace(&mut current, pending.session);
1455 old.peer.close();
1601 old.peer.close();
1456 reconnect_deadline = None;
1602 reconnect_deadline = None;
@@ -1462,7 +1608,30 @@ async fn drive(
1462 {
1608 {
1463 timeline.record("computer sound not carried over", error.to_string());
1609 timeline.record("computer sound not carried over", error.to_string());
1464 }
1610 }
1611 if remote_audio.is_some() {
1612 sync_software_audio(
1613 &factory,
1614 options,
1615 &input,
1616 muted,
1617 remote_audio.clone(),
1618 &current.peer,
1619 &track,
1620 software_wanted(
1621 mic_settings,
1622 share_sound_wanted,
1623 &local_video,
1624 live.audio.as_ref(),
1625 ),
1626 true,
1627 &mut software_audio,
1628 mic_settings,
1629 control,
1630 timeline,
1631 );
1632 }
1465 offered = pending.offered;
1633 offered = pending.offered;
1634 let answered = pending.answered;
1466 if let Some(mid) = direct_video_mid.take() {
1635 if let Some(mid) = direct_video_mid.take() {
1467 video.router().set(&mid, None);
1636 video.router().set(&mid, None);
1468 }
1637 }
@@ -1472,24 +1641,66 @@ async fn drive(
1472 if let Err(error) = local_video.set_lines(media.video.clone()) {
1641 if let Err(error) = local_video.set_lines(media.video.clone()) {
1473 timeline.record("video lines not attached", error.to_string());
1642 timeline.record("video lines not attached", error.to_string());
1474 }
1643 }
1475 if local_video.camera_on() {
1644 tell_bound_camera(
1476 tell_media_descriptions(
1645 &remote,
1477 &remote,
1646 &media_links,
1478 &media_links,
1647 &local_video,
1479 MediaDescription::camera(true),
1648 &mut media_description_request,
1480 &mut media_description_request,
1649 timeline,
1481 timeline,
1650 );
1482 );
1651 tell_bound_share(
1483 }
1652 &remote,
1484 if local_video.sharing() {
1653 &media_links,
1485 tell_media_descriptions(
1654 &local_video,
1486 &remote,
1655 &mut media_description_request,
1487 &media_links,
1656 timeline,
1488 MediaDescription::share(true),
1657 );
1489 &mut media_description_request,
1658 } else if let Some(answered) = answered {
1490 timeline,
1659 // Server escalation answered on a new peer: drop the old peer's
1491 );
1660 // senders and bind the camera/share lines that stayed alive there.
1661 layout = Layout::Conference;
1662 layout_plan = answered.remote.plan();
1663 match video_lines_from_answer(&current.peer, &answered) {
1664 Some(lines) => {
1665 if let Err(error) = local_video.set_lines(lines) {
1666 timeline.record("video lines not attached", error.to_string());
1667 }
1668 }
1669 None => {
1670 local_video.clear_lines();
1671 timeline.record(
1672 "video lines not attached",
1673 "no transceiver for the answered camera line",
1674 );
1675 }
1492 }
1676 }
1677 negotiate_video_lines(
1678 &mut video,
1679 &signaling,
1680 control,
1681 timeline,
1682 &answered.offer_sdp,
1683 &answered.remote.lines,
1684 true,
1685 &media_links,
1686 &roster,
1687 );
1688 tell_bound_camera(
1689 &remote,
1690 &media_links,
1691 &local_video,
1692 &mut media_description_request,
1693 timeline,
1694 );
1695 tell_bound_share(
1696 &remote,
1697 &media_links,
1698 &local_video,
1699 &mut media_description_request,
1700 timeline,
1701 );
1702 } else {
1703 local_video.clear_lines();
1493 }
1704 }
1494 remote_set = true;
1705 remote_set = true;
1495 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
1706 if layout == Layout::OneToOne && negotiator.begin_conference_upgrade() {
@@ -1566,6 +1777,7 @@ async fn drive(
1566 control.send(CallUpdate::Lobby(true));
1777 control.send(CallUpdate::Lobby(true));
1567 }
1778 }
1568 keep_alive_link = acceptance.links.get("callLeg").cloned();
1779 keep_alive_link = acceptance.links.get("callLeg").cloned();
1780 remember_call_leg(live, keep_alive_link.as_deref());
1569 keep_alive_seconds = acceptance.keep_alive_seconds;
1781 keep_alive_seconds = acceptance.keep_alive_seconds;
1570 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
1782 keep_alive_at = Some(Instant::now() + keep_alive_period(keep_alive_seconds));
1571 if action == MediaAction::ApplyAnswerThenEscalate {
1783 if action == MediaAction::ApplyAnswerThenEscalate {
@@ -1706,6 +1918,9 @@ async fn drive(
1706 };
1918 };
1707 match applied {
1919 match applied {
1708 Ok(()) => {
1920 Ok(()) => {
1921 if let Some(pending) = next.as_mut() {
1922 pending.leg_links.extend(answer.links.clone());
1923 }
1709 if let Some(media) = next.as_ref().and_then(|pending| pending.offered.as_ref()) {
1924 if let Some(media) = next.as_ref().and_then(|pending| pending.offered.as_ref()) {
1710 media_links.extend(answer.links.clone());
1925 media_links.extend(answer.links.clone());
1711 negotiate_video(&mut video, &signaling, control, timeline, &answer.sdp, media, true, &media_links, &roster);
1926 negotiate_video(&mut video, &signaling, control, timeline, &answer.sdp, media, true, &media_links, &roster);
@@ -1753,7 +1968,20 @@ async fn drive(
1753 if let Some(resend) = glare_resend.take() {
1968 if let Some(resend) = glare_resend.take() {
1754 defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control);
1969 defer_to_new_peer(resend.change, &mut deferred_changes, &mut local_video, control);
1755 }
1970 }
1756 match answer_on_new_peer(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &renegotiation.sdp).await {
1971 let camera_track = local_video.camera_track();
1972 let share_track = local_video.share_track();
1973 match answer_on_new_peer(
1974 &factory,
1975 &grant,
1976 options,
1977 outgoing_track(software_audio.as_ref(), &track),
1978 &renegotiation.sdp,
1979 local_video.camera_on(),
1980 local_video.camera_on().then_some(&camera_track),
1981 local_video.sharing().then_some(&share_track),
1982 )
1983 .await
1984 {
1757 Ok((session, answered)) => {
1985 Ok((session, answered)) => {
1758 timeline.record_sdp("local answer", &answered.answer_sdp);
1986 timeline.record_sdp("local answer", &answered.answer_sdp);
1759 live.peers.push(session.peer.clone());
1987 live.peers.push(session.peer.clone());
@@ -1761,8 +1989,22 @@ async fn drive(
1761 if let Some(replaced) = next.take() {
1989 if let Some(replaced) = next.take() {
1762 replaced.session.peer.close();
1990 replaced.session.peer.close();
1763 }
1991 }
1764 next = Some(NextPeer { session, offered: None, reply_tags: Vec::new(), deadline: Some(Instant::now() + NEXT_PEER_LIMIT), connected: false, retargeted: false });
1992 let mut leg_links = renegotiation.links.clone();
1765 sent
1993 if let Ok((extra, keys)) = &sent {
1994 absorb_answered_links(&mut leg_links, extra, timeline, keys);
1995 }
1996 next = Some(NextPeer {
1997 session,
1998 offered: None,
1999 answered: Some(answered),
2000 leg_links,
2001 remote_audio: None,
2002 reply_tags: Vec::new(),
2003 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
2004 connected: false,
2005 retargeted: false,
2006 });
2007 sent.map(|_| ())
1766 }
2008 }
1767 Err(error) => {
2009 Err(error) => {
1768 if next.is_none() {
2010 if next.is_none() {
@@ -1779,42 +2021,116 @@ async fn drive(
1779 }
2021 }
1780 }
2022 }
1781 MediaAction::AnswerOnSamePeer => {
2023 MediaAction::AnswerOnSamePeer => {
1782 let video_answer = if layout == Layout::OneToOne { AnswerVideo::Receive } else { AnswerVideo::Reject };
2024 // After a server escalation the follow-up offer matches the
1783 match answer_offer(&current.peer, None, &renegotiation.sdp, video_answer, local_video.sharing().then(|| local_video.share_mid()).flatten(), local_video.camera_on(), (layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct).then_some(&current.gathered)).await {
2025 // pending peer's m-line order: never answer it on the old peer.
2026 let on_pending = next.as_ref().is_some_and(|pending| pending.answered.is_some());
2027 let peer = if on_pending {
2028 &next.as_ref().unwrap().session.peer
2029 } else {
2030 &current.peer
2031 };
2032 let camera_track = local_video.camera_track();
2033 let share_track = local_video.share_track();
2034 let video_answer = if local_video.camera_on() {
2035 AnswerVideo::Send(&camera_track)
2036 } else {
2037 AnswerVideo::Receive
2038 };
2039 let keep_slots = on_pending || layout == Layout::Conference;
2040 let gathered = (!on_pending
2041 && layout == Layout::OneToOne
2042 && negotiator.path() == MediaPath::Direct)
2043 .then_some(&current.gathered);
2044 match answer_offer_with(
2045 peer,
2046 None,
2047 &renegotiation.sdp,
2048 video_answer,
2049 local_video.sharing().then(|| local_video.share_mid()).flatten(),
2050 local_video.sharing().then_some(&share_track),
2051 local_video.camera_on(),
2052 gathered,
2053 keep_slots,
2054 keep_slots,
2055 )
2056 .await
2057 {
1784 Ok(answered) => {
2058 Ok(answered) => {
1785 timeline.record_sdp("local answer", &answered.answer_sdp);
2059 timeline.record_sdp("local answer", &answered.answer_sdp);
2060 if on_pending {
2061 if let Some(pending) = next.as_mut() {
2062 pending.leg_links.extend(renegotiation.links.clone());
2063 }
2064 } else {
2065 media_links.extend(renegotiation.links.clone());
2066 }
1786 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
2067 let sent = send_media_answer(&remote, &links, &renegotiation.links, &answered, &media_leg_id).await;
2068 if let Ok((extra, keys)) = &sent {
2069 if on_pending {
2070 if let Some(pending) = next.as_mut() {
2071 absorb_answered_links(&mut pending.leg_links, extra, timeline, keys);
2072 }
2073 } else {
2074 absorb_answered_links(&mut media_links, extra, timeline, keys);
2075 }
2076 }
1787 for mid in answered.remote.plan().screen_share_mids {
2077 for mid in answered.remote.plan().screen_share_mids {
1788 if !layout_plan.screen_share_mids.contains(&mid) {
2078 if !layout_plan.screen_share_mids.contains(&mid) {
1789 layout_plan.screen_share_mids.push(mid);
2079 layout_plan.screen_share_mids.push(mid);
1790 }
2080 }
1791 }
2081 }
1792 if layout == Layout::OneToOne && answered.receiving_share_mid != remote_direct_share {
2082 if on_pending {
1793 if let Some(mid) = &remote_direct_share {
2083 if let Some(pending) = next.as_mut() {
1794 video.router().set(mid, None);
2084 pending.answered = Some(answered);
1795 }
2085 }
1796 if let Some(mid) = &answered.receiving_share_mid {
2086 } else if layout == Layout::Conference {
1797 video.router().set(mid, Some(VideoKey::Screen));
2087 negotiate_video_lines(
2088 &mut video,
2089 &signaling,
2090 control,
2091 timeline,
2092 &answered.offer_sdp,
2093 &answered.remote.lines,
2094 true,
2095 &media_links,
2096 &roster,
2097 );
2098 } else if layout == Layout::OneToOne {
2099 if answered.receiving_share_mid != remote_direct_share {
2100 if let Some(mid) = &remote_direct_share {
2101 video.router().set(mid, None);
2102 }
2103 if let Some(mid) = &answered.receiving_share_mid {
2104 video.router().set(mid, Some(VideoKey::Screen));
2105 }
2106 remote_direct_share = answered.receiving_share_mid.clone();
2107 control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));
2108 }
2109 if !offer_sends_video(&renegotiation.sdp)
2110 && let Some(key) = main_video_mid(&answered.remote).and_then(|mid| video.router().key_for(&mid))
2111 {
2112 control.video.forget(&key);
2113 control.send(CallUpdate::VideoStopped(key));
1798 }
2114 }
1799 remote_direct_share = answered.receiving_share_mid.clone();
1800 control.send(CallUpdate::ScreenShare(remote_direct_share.as_ref().and(peer_mri.clone())));
1801 }
1802 if layout == Layout::OneToOne
1803 && !offer_sends_video(&renegotiation.sdp)
1804 && let Some(key) = main_video_mid(&answered.remote).and_then(|mid| video.router().key_for(&mid))
1805 {
1806 control.video.forget(&key);
1807 control.send(CallUpdate::VideoStopped(key));
1808 }
2115 }
1809 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
2116 let held = is_hold(&renegotiation.sdp).unwrap_or(false);
1810 if held != remote_hold {
2117 if held != remote_hold {
1811 remote_hold = held;
2118 remote_hold = held;
1812 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
2119 control.send(CallUpdate::Hold(HoldState::from_flags(local_hold, remote_hold)));
1813 }
2120 }
1814 sent
2121 sent.map(|_| ())
1815 }
2122 }
1816 Err(error) => {
2123 Err(error) => {
1817 if current.peer.signaling_state() == SignalingState::HaveRemoteOffer {
2124 if on_pending {
2125 if let Some(pending) = next.as_ref()
2126 && pending.session.peer.signaling_state()
2127 == SignalingState::HaveRemoteOffer
2128 {
2129 rollback_remote_offer(&pending.session.peer).await;
2130 }
2131 } else if current.peer.signaling_state()
2132 == SignalingState::HaveRemoteOffer
2133 {
1818 rollback_remote_offer(&current.peer).await;
2134 rollback_remote_offer(&current.peer).await;
1819 }
2135 }
1820 if let Some(url) = &rejection_link {
2136 if let Some(url) = &rejection_link {
@@ -2070,6 +2386,70 @@ async fn drive(
2070 }
2386 }
2071 RejectedOffer::None => {}
2387 RejectedOffer::None => {}
2072 },
2388 },
2389 Ok(CallEvent::MediaAcknowledgement(ack)) => {
2390 if let Some(pending) = next.as_mut() {
2391 pending.leg_links.extend(ack.links);
2392 if pending.answered.is_some() {
2393 // Server-initiated mixer leg switch sends mediaAcknowledgement
2394 // instead of retargetCompletion; switch as soon as ICE connects.
2395 pending.retargeted = true;
2396 }
2397 } else if !ack.links.is_empty() {
2398 let old_request = media_links
2399 .get("applyChannelParameters")
2400 .or_else(|| media_links.get("controlVideoStreaming"))
2401 .cloned();
2402 let old_update = media_links.get("updateMediaDescriptions").cloned();
2403 replace_leg_media_links(&mut media_links, &ack.links);
2404 if let Some(url) = media_links.get("callLeg").cloned()
2405 && keep_alive_link.as_deref() != Some(url.as_str())
2406 {
2407 keep_alive_link = Some(url.clone());
2408 remember_call_leg(live, Some(&url));
2409 }
2410 let new_request = media_links
2411 .get("applyChannelParameters")
2412 .or_else(|| media_links.get("controlVideoStreaming"))
2413 .cloned();
2414 if layout == Layout::Conference
2415 && new_request != old_request
2416 && let Some(url) = new_request
2417 {
2418 video.replace_requester(SourceRequester::start(
2419 signaling.clone(),
2420 url,
2421 video.router().clone(),
2422 control.video.clone(),
2423 timeline.clone(),
2424 ));
2425 send_receive_change(control, video.reselect(&roster));
2426 }
2427 if layout == Layout::Conference
2428 && media_links.get("updateMediaDescriptions") != old_update.as_ref()
2429 && local_video.has_lines()
2430 {
2431 send_capabilities = SendCapabilityReporter::default();
2432 if local_video.camera_on() {
2433 tell_bound_camera(
2434 &remote,
2435 &media_links,
2436 &local_video,
2437 &mut media_description_request,
2438 timeline,
2439 );
2440 }
2441 if local_video.sharing() {
2442 tell_bound_share(
2443 &remote,
2444 &media_links,
2445 &local_video,
2446 &mut media_description_request,
2447 timeline,
2448 );
2449 }
2450 }
2451 }
2452 }
2073 Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => {
2453 Ok(CallEvent::RetargetCompletion(body)) if body["retargetCompleted"]["code"].as_i64() == Some(0) => {
2074 if let Some(pending) = next.as_mut() {
2454 if let Some(pending) = next.as_mut() {
2075 pending.retargeted = true;
2455 pending.retargeted = true;
@@ -2128,16 +2508,14 @@ async fn drive(
2128 }
2508 }
2129 }
2509 }
2130 }
2510 }
2511 // Planned mixer escalation: ignore old-peer death while the new peer is pending.
2512 PeerConnectionState::Disconnected | PeerConnectionState::Failed
2513 if next.is_some() => {}
2131 PeerConnectionState::Disconnected => {
2514 PeerConnectionState::Disconnected => {
2132 if advance(state, CallSignal::MediaDisconnected, control) {
2515 if advance(state, CallSignal::MediaDisconnected, control) {
2133 reconnect_deadline = Some(Instant::now() + options.reconnect_window);
2516 reconnect_deadline = Some(Instant::now() + options.reconnect_window);
2134 }
2517 }
2135 }
2518 }
2136 PeerConnectionState::Failed if next.is_some() => {
2137 if advance(state, CallSignal::MediaDisconnected, control) {
2138 reconnect_deadline = Some(Instant::now() + options.reconnect_window);
2139 }
2140 }
2141 PeerConnectionState::Failed => {
2519 PeerConnectionState::Failed => {
2142 advance(state, CallSignal::MediaFailed, control);
2520 advance(state, CallSignal::MediaFailed, control);
2143 break;
2521 break;
@@ -2187,6 +2565,12 @@ async fn drive(
2187 timeline.record("remote video track", format!("mid {mid} (new peer)"));
2565 timeline.record("remote video track", format!("mid {mid} (new peer)"));
2188 live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));
2566 live.video_tasks.push(spawn_video_pump(track, mid, video.router().clone(), control.video.clone(), live.video_counters.clone()));
2189 }
2567 }
2568 PeerEvent::Track(remote_track) => {
2569 timeline.record("remote audio track", "receiving (new peer)");
2570 if let Some(pending) = next.as_mut() {
2571 pending.remote_audio = Some(remote_track);
2572 }
2573 }
2190 PeerEvent::Connection(PeerConnectionState::Failed) => {
2574 PeerEvent::Connection(PeerConnectionState::Failed) => {
2191 negotiator.escalation_failed();
2575 negotiator.escalation_failed();
2192 if let Some(pending) = next.take() {
2576 if let Some(pending) = next.take() {
@@ -2258,7 +2642,20 @@ async fn drive(
2258 }
2642 }
2259 Some(CallCommand::SetCamera(on)) => {
2643 Some(CallCommand::SetCamera(on)) => {
2260 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
2644 let direct = layout == Layout::OneToOne && negotiator.path() != MediaPath::Mixer;
2261 if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) {
2645 if on && next.is_some() {
2646 let first = !start_camera_pending;
2647 start_camera_pending = true;
2648 if local_video.is_available()
2649 && !local_video.camera_on()
2650 && !local_video.camera_previewing()
2651 && let Err(error) = local_video.preview_camera(&camera_choice)
2652 {
2653 control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error)));
2654 }
2655 if first {
2656 control.send(CallUpdate::Camera(true));
2657 }
2658 } else if !remote_set || (on && !video_possible(remote_set, layout, negotiator.path())) {
2262 if remote_set && next.is_none() && negotiator.begin_conference_upgrade() {
2659 if remote_set && next.is_none() && negotiator.begin_conference_upgrade() {
2263 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;
2660 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2264 next = pending.or(next);
2661 next = pending.or(next);
@@ -2292,7 +2689,16 @@ async fn drive(
2292 }
2689 }
2293 Ok(()) => {
2690 Ok(()) => {
2294 control.send(CallUpdate::Camera(true));
2691 control.send(CallUpdate::Camera(true));
2295 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(true), &mut media_description_request, timeline);
2692 tell_media_descriptions(
2693 &remote,
2694 &media_links,
2695 MediaDescription::camera_line(
2696 local_video.camera_mid().unwrap_or_else(|| CAMERA_MID.to_owned()),
2697 true,
2698 ),
2699 &mut media_description_request,
2700 timeline,
2701 );
2296 }
2702 }
2297 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))),
2703 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(CAMERA_START_NOTICE, error))),
2298 }
2704 }
@@ -2315,7 +2721,16 @@ async fn drive(
2315 } else {
2721 } else {
2316 local_video.stop_camera();
2722 local_video.stop_camera();
2317 control.send(CallUpdate::Camera(false));
2723 control.send(CallUpdate::Camera(false));
2318 tell_media_descriptions(&remote, &media_links, MediaDescription::camera(false), &mut media_description_request, timeline);
2724 tell_media_descriptions(
2725 &remote,
2726 &media_links,
2727 MediaDescription::camera_line(
2728 local_video.camera_mid().unwrap_or_else(|| CAMERA_MID.to_owned()),
2729 false,
2730 ),
2731 &mut media_description_request,
2732 timeline,
2733 );
2319 }
2734 }
2320 }
2735 }
2321 Some(CallCommand::SelectCamera(choice)) => {
2736 Some(CallCommand::SelectCamera(choice)) => {
@@ -2345,6 +2760,9 @@ async fn drive(
2345 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2760 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2346 } else if local_hold {
2761 } else if local_hold {
2347 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2762 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2763 } else if !local_video.sharing() && next.is_some() {
2764 portal_pending = Some(kind);
2765 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2348 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2766 } else if direct && !local_video.sharing() && (same_peer.is_some() || glare_resend.is_some()) {
2349 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2767 control.send(CallUpdate::Notice(CHANGE_RUNNING_NOTICE.into()));
2350 } else if direct
2768 } else if direct
@@ -2353,7 +2771,10 @@ async fn drive(
2353 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2771 && let Err(error) = attach_share_line(&current.peer, &factory, &mut local_video, direct_video_mid.as_deref())
2354 {
2772 {
2355 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2773 control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error)));
2356 } else if !local_video.sharing() && !video_possible(remote_set, layout, negotiator.path()) {
2774 } else if !local_video.sharing()
2775 && (!video_possible(remote_set, layout, negotiator.path())
2776 || !local_video.share_sending())
2777 {
2357 if next.is_none() && negotiator.begin_conference_upgrade() {
2778 if next.is_none() && negotiator.begin_conference_upgrade() {
2358 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;
2779 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2359 next = pending.or(next);
2780 next = pending.or(next);
@@ -2384,6 +2805,9 @@ async fn drive(
2384 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2805 control.send(CallUpdate::Notice(NOT_CONNECTED_FOR_VIDEO.into()));
2385 } else if local_hold {
2806 } else if local_hold {
2386 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2807 control.send(CallUpdate::Notice(ON_HOLD_NOTICE.into()));
2808 } else if next.is_some() {
2809 share_pending = Some(source);
2810 control.send(CallUpdate::Notice(SHARE_QUEUED_NOTICE.into()));
2387 } else if direct && local_video.share_sending() {
2811 } else if direct && local_video.share_sending() {
2388 match local_video.start_share(&source) {
2812 match local_video.start_share(&source) {
2389 Ok(()) => announce_share(control, &source),
2813 Ok(()) => announce_share(control, &source),
@@ -2416,7 +2840,9 @@ async fn drive(
2416 }
2840 }
2417 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2841 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2418 }
2842 }
2419 } else if !video_possible(remote_set, layout, negotiator.path()) {
2843 } else if !video_possible(remote_set, layout, negotiator.path())
2844 || !local_video.share_sending()
2845 {
2420 if next.is_none() && negotiator.begin_conference_upgrade() {
2846 if next.is_none() && negotiator.begin_conference_upgrade() {
2421 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;
2847 let pending = escalate(&factory, &grant, options, outgoing_track(software_audio.as_ref(), &track), &remote, &links, &media_leg_id, &media_links, &mut negotiator, live, timeline).await;
2422 next = pending.or(next);
2848 next = pending.or(next);
@@ -2431,7 +2857,16 @@ async fn drive(
2431 match local_video.start_share(&source) {
2857 match local_video.start_share(&source) {
2432 Ok(()) => {
2858 Ok(()) => {
2433 announce_share(control, &source);
2859 announce_share(control, &source);
2434 tell_media_descriptions(&remote, &media_links, MediaDescription::share(true), &mut media_description_request, timeline);
2860 tell_media_descriptions(
2861 &remote,
2862 &media_links,
2863 MediaDescription::share_line(
2864 local_video.share_mid().unwrap_or_else(|| SHARE_MID.to_owned()),
2865 true,
2866 ),
2867 &mut media_description_request,
2868 timeline,
2869 );
2435 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2870 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2436 }
2871 }
2437 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
2872 Err(error) => control.send(CallUpdate::Notice(notice_with_detail(SHARING_START_NOTICE, error))),
@@ -2463,7 +2898,16 @@ async fn drive(
2463 local_video.stop_share();
2898 local_video.stop_share();
2464 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2899 sync_software_audio(&factory, options, &input, muted, remote_audio.clone(), &current.peer, &track, software_wanted(mic_settings, share_sound_wanted, &local_video, live.audio.as_ref()), false, &mut software_audio, mic_settings, control, timeline);
2465 clear_share(control);
2900 clear_share(control);
2466 tell_media_descriptions(&remote, &media_links, MediaDescription::share(false), &mut media_description_request, timeline);
2901 tell_media_descriptions(
2902 &remote,
2903 &media_links,
2904 MediaDescription::share_line(
2905 local_video.share_mid().unwrap_or_else(|| SHARE_MID.to_owned()),
2906 false,
2907 ),
2908 &mut media_description_request,
2909 timeline,
2910 );
2467 }
2911 }
2468 }
2912 }
2469 Some(CallCommand::SetShareSound(on)) => {
2913 Some(CallCommand::SetShareSound(on)) => {
@@ -2760,6 +3204,15 @@ async fn drive(
2760 }
3204 }
2761 }
3205 }
2762 Some(CallCommand::EndMeeting) => {
3206 Some(CallCommand::EndMeeting) => {
3207 stop_local_publish(
3208 &mut local_video,
3209 &remote,
3210 &media_links,
3211 &mut media_description_request,
3212 control,
3213 timeline,
3214 )
3215 .await;
2763 if is_meeting {
3216 if is_meeting {
2764 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
3217 match remote.signaling.end_for_all(&remote.conversation, &remote.participant).await {
2765 Ok(()) => {
3218 Ok(()) => {
@@ -2773,6 +3226,16 @@ async fn drive(
2773 break;
3226 break;
2774 }
3227 }
2775 Some(CallCommand::Hangup) | None => {
3228 Some(CallCommand::Hangup) | None => {
3229 // Stop publishing before leave so remotes do not keep a frozen camera tile.
3230 stop_local_publish(
3231 &mut local_video,
3232 &remote,
3233 &media_links,
3234 &mut media_description_request,
3235 control,
3236 timeline,
3237 )
3238 .await;
2776 advance(state, CallSignal::LocalLeave, control);
3239 advance(state, CallSignal::LocalLeave, control);
2777 break;
3240 break;
2778 }
3241 }
@@ -2816,8 +3279,14 @@ async fn drive(
2816 if layout == Layout::Conference
3279 if layout == Layout::Conference
2817 && let Some(size) = local_video.camera_size()
3280 && let Some(size) = local_video.camera_size()
2818 && let Some(url) = media_links.get("applyChannelParameters").cloned()
3281 && let Some(url) = media_links.get("applyChannelParameters").cloned()
2819 && let Some(body) =
3282 && let Some(body) = send_capabilities.body_for_mid(
2820 send_capabilities.body_for(size, local_video.video_quality())
3283 local_video
3284 .camera_mid()
3285 .as_deref()
3286 .unwrap_or(CAMERA_MID),
3287 size,
3288 local_video.video_quality(),
3289 )
2821 {
3290 {
2822 let signaling = signaling.clone();
3291 let signaling = signaling.clone();
2823 let timeline = timeline.clone();
3292 let timeline = timeline.clone();
@@ -2864,6 +3333,28 @@ async fn drive(
2864 && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)
3333 && let Some(sample) = health_sampler.sample(std::time::Instant::now(), snapshot.health)
2865 {
3334 {
2866 let quality = quality_tracker.observe(std::time::Instant::now(), &sample);
3335 let quality = quality_tracker.observe(std::time::Instant::now(), &sample);
3336 if local_video.camera_on()
3337 && snapshot.camera_target_bitrate > 0
3338 && bitrate_governor.observe(
3339 std::time::Instant::now(),
3340 snapshot.video.remote_round_trip_ms,
3341 sample.loss_percent,
3342 snapshot.camera_target_bitrate,
3343 )
3344 {
3345 let cap = bitrate_governor.cap_bps();
3346 if let Err(error) = local_video.cap_camera_bitrate(cap) {
3347 timeline.record("bitrate cap failed", error.to_string());
3348 } else {
3349 timeline.record(
3350 "bitrate cap",
3351 match cap {
3352 Some(bps) => format!("{} kbit/s", bps / 1000),
3353 None => "cleared".into(),
3354 },
3355 );
3356 }
3357 }
2867 control.send(CallUpdate::Health(CallHealth {
3358 control.send(CallUpdate::Health(CallHealth {
2868 level: quality.level,
3359 level: quality.level,
2869 cpu_limited: quality.cpu_limited,
3360 cpu_limited: quality.cpu_limited,
@@ -3084,6 +3575,9 @@ async fn start_escalation(
3084 Ok(NextPeer {
3575 Ok(NextPeer {
3085 session,
3576 session,
3086 offered: Some(media),
3577 offered: Some(media),
3578 answered: None,
3579 leg_links: acceptance_links.clone(),
3580 remote_audio: None,
3087 reply_tags,
3581 reply_tags,
3088 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
3582 deadline: Some(Instant::now() + NEXT_PEER_LIMIT),
3089 connected: false,
3583 connected: false,
@@ -3133,34 +3627,56 @@ async fn escalate(
3133 }
3627 }
3134}
3628}
3135
3629
3630#[allow(clippy::too_many_arguments)]
3136async fn answer_on_new_peer(
3631async fn answer_on_new_peer(
3137 factory: &PeerConnectionFactory,
3632 factory: &PeerConnectionFactory,
3138 grant: &RelayGrant,
3633 grant: &RelayGrant,
3139 options: &CallOptions,
3634 options: &CallOptions,
3140 track: &RtcAudioTrack,
3635 track: &RtcAudioTrack,
3141 teams_offer: &str,
3636 teams_offer: &str,
3637 camera_on: bool,
3638 camera: Option<&RtcVideoTrack>,
3639 share: Option<&RtcVideoTrack>,
3142) -> Result<(PeerSession, AnsweredMedia)> {
3640) -> Result<(PeerSession, AnsweredMedia)> {
3143 let session = open_peer(factory, grant, &options.relay_host, false)?;
3641 let session = open_peer(factory, grant, &options.relay_host, false)?;
3144 let answered = answer_offer(
3642 // Keep every video mid from the mixer offer (camera, gallery, share).
3643 // Reject would stop them and leave set_track InvalidState after the new
3644 // peer replaces the old one. When the camera is already on, answer sendrecv
3645 // so the remote keeps receiving across the escalation.
3646 let video = match (camera_on, camera) {
3647 (true, Some(camera)) => AnswerVideo::Send(camera),
3648 _ => AnswerVideo::Receive,
3649 };
3650 let answered = answer_offer_with(
3145 &session.peer,
3651 &session.peer,
3146 Some(track),
3652 Some(track),
3147 teams_offer,
3653 teams_offer,
3148 AnswerVideo::Reject,
3654 video,
3149 None,
3655 None,
3150 false,
3656 share,
3657 camera_on,
3151 None,
3658 None,
3659 true,
3660 true,
3152 )
3661 )
3153 .await?;
3662 .await?;
3154 Ok((session, answered))
3663 Ok((session, answered))
3155}
3664}
3156
3665
3666fn video_lines_from_answer(peer: &PeerConnection, answered: &AnsweredMedia) -> Option<VideoLines> {
3667 let camera_mid = answered.camera_mid.as_deref()?;
3668 let camera = peer_transceiver(peer, camera_mid)?;
3669 let share = share_carrier_mid(&answered.remote).and_then(|mid| peer_transceiver(peer, &mid));
3670 Some(VideoLines { camera, share })
3671}
3672
3157async fn send_media_answer(
3673async fn send_media_answer(
3158 remote: &RemoteCall,
3674 remote: &RemoteCall,
3159 links: &CallbackLinks,
3675 links: &CallbackLinks,
3160 reply_links: &BTreeMap<String, String>,
3676 reply_links: &BTreeMap<String, String>,
3161 answered: &AnsweredMedia,
3677 answered: &AnsweredMedia,
3162 media_leg_id: &str,
3678 media_leg_id: &str,
3163) -> Result<()> {
3679) -> Result<(BTreeMap<String, String>, String)> {
3164 let url = reply_links
3680 let url = reply_links
3165 .get("mediaAnswer")
3681 .get("mediaAnswer")
3166 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
3682 .ok_or_else(|| Error::Signaling("renegotiation without a mediaAnswer link".into()))?;
@@ -3170,10 +3686,31 @@ async fn send_media_answer(
3170 &answered.answer_sdp,
3686 &answered.answer_sdp,
3171 media_leg_id,
3687 media_leg_id,
3172 );
3688 );
3173 remote
3689 let response = remote
3174 .signaling
3690 .signaling
3175 .post_json("POST mediaAnswer", url, body)
3691 .post_json_body("POST mediaAnswer", url, body)
3176 .await
3692 .await?;
3693 Ok((nested_links(&response), object_keys(&response)))
3694}
3695
3696fn absorb_answered_links(
3697 into: &mut BTreeMap<String, String>,
3698 extra: &BTreeMap<String, String>,
3699 timeline: &Timeline,
3700 response_keys: &str,
3701) {
3702 if extra.is_empty() {
3703 if !response_keys.is_empty() {
3704 timeline.record(
3705 "media answer links",
3706 format!("none, body keys {response_keys}"),
3707 );
3708 }
3709 return;
3710 }
3711 let names = extra.keys().cloned().collect::<Vec<_>>().join(",");
3712 timeline.record("media answer links", names);
3713 into.extend(extra.clone());
3177}
3714}
3178
3715
3179#[allow(clippy::too_many_arguments)]
3716#[allow(clippy::too_many_arguments)]
@@ -3188,7 +3725,32 @@ fn negotiate_video(
3188 links: &BTreeMap<String, String>,
3725 links: &BTreeMap<String, String>,
3189 roster: &Roster,
3726 roster: &Roster,
3190) {
3727) {
3191 let streams = match stream_lines(answer_sdp, &media.signaled.lines) {
3728 negotiate_video_lines(
3729 video,
3730 signaling,
3731 control,
3732 timeline,
3733 answer_sdp,
3734 &media.signaled.lines,
3735 from_mixer,
3736 links,
3737 roster,
3738 );
3739}
3740
3741#[allow(clippy::too_many_arguments)]
3742fn negotiate_video_lines(
3743 video: &mut VideoReceive,
3744 signaling: &Arc<Signaling>,
3745 control: &CallControl,
3746 timeline: &Timeline,
3747 teams_sdp: &str,
3748 lines: &[crate::sdp::SignaledLine],
3749 from_mixer: bool,
3750 links: &BTreeMap<String, String>,
3751 roster: &Roster,
3752) {
3753 let streams = match stream_lines(teams_sdp, lines) {
3192 Ok(streams) => streams,
3754 Ok(streams) => streams,
3193 Err(error) => {
3755 Err(error) => {
3194 timeline.record("video slots unknown", error.to_string());
3756 timeline.record("video slots unknown", error.to_string());
@@ -3221,6 +3783,47 @@ fn negotiate_video(
3221 send_receive_change(control, video.reselect(roster));
3783 send_receive_change(control, video.reselect(roster));
3222}
3784}
3223
3785
3786fn tell_bound_camera(
3787 remote: &RemoteCall,
3788 links: &BTreeMap<String, String>,
3789 local_video: &LocalVideo,
3790 request_id: &mut u32,
3791 timeline: &Timeline,
3792) {
3793 let mid = local_video
3794 .camera_mid()
3795 .unwrap_or_else(|| CAMERA_MID.to_owned());
3796 tell_media_descriptions(
3797 remote,
3798 links,
3799 MediaDescription::camera_line(mid, local_video.camera_on()),
3800 request_id,
3801 timeline,
3802 );
3803}
3804
3805fn tell_bound_share(
3806 remote: &RemoteCall,
3807 links: &BTreeMap<String, String>,
3808 local_video: &LocalVideo,
3809 request_id: &mut u32,
3810 timeline: &Timeline,
3811) {
3812 if !local_video.sharing() {
3813 return;
3814 }
3815 let mid = local_video
3816 .share_mid()
3817 .unwrap_or_else(|| SHARE_MID.to_owned());
3818 tell_media_descriptions(
3819 remote,
3820 links,
3821 MediaDescription::share_line(mid, true),
3822 request_id,
3823 timeline,
3824 );
3825}
3826
3224async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3827async fn camera_devices(mode: VideoMode) -> Vec<CameraDevice> {
3225 match mode {
3828 match mode {
3226 VideoMode::Pattern => vec![CameraDevice {
3829 VideoMode::Pattern => vec![CameraDevice {
@@ -4255,6 +4858,64 @@ fn sync_software_audio(
4255 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4858 crate::noise_stage::apply_for_outgoing(mic_settings, software_audio.is_none());
4256}
4859}
4257
4860
4861async fn stop_local_publish(
4862 local_video: &mut LocalVideo,
4863 remote: &RemoteCall,
4864 media_links: &BTreeMap<String, String>,
4865 request_id: &mut u32,
4866 control: &CallControl,
4867 timeline: &Timeline,
4868) {
4869 let camera_mid = local_video.camera_mid();
4870 let share_mid = local_video.share_mid();
4871 let was_sharing = local_video.sharing();
4872 let was_camera = local_video.camera_on() || local_video.camera_previewing();
4873 if was_sharing {
4874 local_video.stop_share();
4875 clear_share(control);
4876 }
4877 if was_camera {
4878 local_video.stop_camera();
4879 control.send(CallUpdate::Camera(false));
4880 }
4881 local_video.clear_lines();
4882 let Some(url) = media_links.get("updateMediaDescriptions").cloned() else {
4883 return;
4884 };
4885 let mut descriptions = Vec::new();
4886 if was_camera {
4887 descriptions.push(MediaDescription::camera_line(
4888 camera_mid.unwrap_or_else(|| CAMERA_MID.to_owned()),
4889 false,
4890 ));
4891 }
4892 if was_sharing {
4893 descriptions.push(MediaDescription::share_line(
4894 share_mid.unwrap_or_else(|| SHARE_MID.to_owned()),
4895 false,
4896 ));
4897 }
4898 if descriptions.is_empty() {
4899 return;
4900 }
4901 *request_id += 1;
4902 let id = *request_id;
4903 match remote
4904 .signaling
4905 .update_media_descriptions(&url, &descriptions, id)
4906 .await
4907 {
4908 Ok(()) => timeline.record(
4909 "updateMediaDescriptions",
4910 format!("publish off before leave, request {id}"),
4911 ),
4912 Err(error) => timeline.record(
4913 "updateMediaDescriptions failed",
4914 format!("publish off before leave: {error}"),
4915 ),
4916 }
4917}
4918
4258async fn tear_down(
4919async fn tear_down(
4259 mut live: Live,
4920 mut live: Live,
4260 inner: &Inner,
4921 inner: &Inner,
@@ -4266,13 +4927,15 @@ async fn tear_down(
4266 timeline.record("noise suppression", "DeepFilterNet too slow, WebRTC only");
4927 timeline.record("noise suppression", "DeepFilterNet too slow, WebRTC only");
4267 }
4928 }
4268 crate::noise_stage::clear();
4929 crate::noise_stage::clear();
4269 for peer in &live.peers {
4930 // Stop keep-alive / broker first so Teams does not see us as still present.
4270 peer.close();
4931 live.broker_running.store(false, Ordering::SeqCst);
4932 if let Some(broker) = live.broker.take() {
4933 broker.abort();
4271 }
4934 }
4272 if let Some(audio) = live.audio.take() {
4935 if let Some(audio) = live.audio.take() {
4273 audio.stop().await;
4936 audio.stop().await;
4274 }
4937 }
4275 live.broker_running.store(false, Ordering::SeqCst);
4938 // Leave and drop call legs while peers are still open, then close media.
4276 if !live.skip_leave
4939 if !live.skip_leave
4277 && let Some(remote) = &live.remote
4940 && let Some(remote) = &live.remote
4278 {
4941 {
@@ -4289,6 +4952,11 @@ async fn tear_down(
4289 Ok(()) => report.left_cleanly = true,
4952 Ok(()) => report.left_cleanly = true,
4290 Err(error) => timeline.record("leave failed", error.to_string()),
4953 Err(error) => timeline.record("leave failed", error.to_string()),
4291 }
4954 }
4955 for call_leg in &live.call_legs {
4956 if let Err(error) = remote.signaling.end_call_leg(call_leg).await {
4957 timeline.record("callLeg end failed", error.to_string());
4958 }
4959 }
4292 }
4960 }
4293 if report.end.is_none()
4961 if report.end.is_none()
4294 && let Some(callbacks) = live.callbacks.as_mut()
4962 && let Some(callbacks) = live.callbacks.as_mut()
@@ -4306,8 +4974,8 @@ async fn tear_down(
4306 .await;
4974 .await;
4307 report.end = waited.ok().flatten();
4975 report.end = waited.ok().flatten();
4308 }
4976 }
4309 if let Some(broker) = live.broker.take() {
4977 for peer in &live.peers {
4310 broker.abort();
4978 peer.close();
4311 }
4979 }
4312 for task in live.video_tasks.drain(..) {
4980 for task in live.video_tasks.drain(..) {
4313 task.abort();
4981 task.abort();
@@ -4345,6 +5013,14 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
4345 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
5013 | CallEvent::RetargetCompletion(body) => outcome_summary(body),
4346 CallEvent::ControlVideoStreaming(body) => parse_request(body)
5014 CallEvent::ControlVideoStreaming(body) => parse_request(body)
4347 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
5015 .map_or_else(|| "body not understood".to_owned(), |request| request.shape),
5016 CallEvent::MediaAcknowledgement(ack) => {
5017 let names = ack.links.keys().cloned().collect::<Vec<_>>().join(",");
5018 if names.is_empty() {
5019 format!("links=none keys={}", ack.keys)
5020 } else {
5021 format!("links={names}")
5022 }
5023 }
4348 _ => String::new(),
5024 _ => String::new(),
4349 };
5025 };
4350 timeline.record(format!("Trouter {}", event.name()), detail);
5026 timeline.record(format!("Trouter {}", event.name()), detail);
@@ -4352,7 +5028,21 @@ fn handle_callback(callback: &TrouterCallback, timeline: &Timeline) -> Result<Ca
4352 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
5028 CallEvent::Acceptance(acceptance) => timeline.record_sdp("remote answer", &acceptance.sdp),
4353 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
5029 CallEvent::MediaAnswer(answer) => timeline.record_sdp("remote answer", &answer.sdp),
4354 CallEvent::MediaRenegotiation(renegotiation) => {
5030 CallEvent::MediaRenegotiation(renegotiation) => {
4355 timeline.record_sdp("remote offer", &renegotiation.sdp)
5031 timeline.record_sdp("remote offer", &renegotiation.sdp);
5032 let names = renegotiation
5033 .links
5034 .keys()
5035 .cloned()
5036 .collect::<Vec<_>>()
5037 .join(",");
5038 timeline.record(
5039 "renegotiation links",
5040 if names.is_empty() {
5041 "none".to_owned()
5042 } else {
5043 names
5044 },
5045 );
4356 }
5046 }
4357 _ => {}
5047 _ => {}
4358 }
5048 }
@@ -4490,6 +5180,7 @@ struct StatsSnapshot {
4490 local_level: f64,
5180 local_level: f64,
4491 echo_return_loss_enhancement: f64,
5181 echo_return_loss_enhancement: f64,
4492 video: VideoReport,
5182 video: VideoReport,
5183 camera_target_bitrate: u64,
4493 share_inbound_packets: u64,
5184 share_inbound_packets: u64,
4494 share_outbound_packets: u64,
5185 share_outbound_packets: u64,
4495 share_receive: Option<ShareReceive>,
5186 share_receive: Option<ShareReceive>,
@@ -4604,6 +5295,10 @@ async fn collect_stats(peer: &PeerConnection, share_mids: &[String]) -> StatsSna
4604 snapshot.video.outbound_packets += outbound.sent.packets_sent;
5295 snapshot.video.outbound_packets += outbound.sent.packets_sent;
4605 if share_mids.contains(&outbound.outbound.mid) {
5296 if share_mids.contains(&outbound.outbound.mid) {
4606 snapshot.share_outbound_packets += outbound.sent.packets_sent;
5297 snapshot.share_outbound_packets += outbound.sent.packets_sent;
5298 } else if outbound.outbound.active {
5299 snapshot.camera_target_bitrate = snapshot
5300 .camera_target_bitrate
5301 .max(outbound.outbound.target_bitrate as u64);
4607 }
5302 }
4608 snapshot.video.outbound_frames_encoded +=
5303 snapshot.video.outbound_frames_encoded +=
4609 u64::from(outbound.outbound.frames_encoded);
5304 u64::from(outbound.outbound.frames_encoded);
@@ -4750,6 +5445,62 @@ mod tests {
4750 ));
5445 ));
4751 }
5446 }
4752
5447
5448 #[test]
5449 fn camera_does_not_start_while_a_peer_escalation_is_pending() {
5450 assert!(camera_may_start(true, false, true));
5451 assert!(!camera_may_start(true, true, true));
5452 assert!(!camera_may_start(false, false, true));
5453 assert!(!camera_may_start(true, false, false));
5454 }
5455
5456 #[test]
5457 fn leg_switch_keeps_mixer_control_links_when_renegotiation_omits_them() {
5458 let mut media_links = BTreeMap::from([
5459 (
5460 "updateMediaDescriptions".to_owned(),
5461 "https://m/update".to_owned(),
5462 ),
5463 (
5464 "applyChannelParameters".to_owned(),
5465 "https://m/apply".to_owned(),
5466 ),
5467 ("callLeg".to_owned(), "https://m/leg".to_owned()),
5468 ]);
5469 replace_leg_media_links(
5470 &mut media_links,
5471 &BTreeMap::from([("mediaAnswer".to_owned(), "https://m/answer".to_owned())]),
5472 );
5473 assert_eq!(
5474 media_links
5475 .get("updateMediaDescriptions")
5476 .map(String::as_str),
5477 Some("https://m/update")
5478 );
5479 assert_eq!(
5480 media_links
5481 .get("applyChannelParameters")
5482 .map(String::as_str),
5483 Some("https://m/apply")
5484 );
5485 assert_eq!(
5486 media_links.get("mediaAnswer").map(String::as_str),
5487 Some("https://m/answer")
5488 );
5489 replace_leg_media_links(
5490 &mut media_links,
5491 &BTreeMap::from([(
5492 "updateMediaDescriptions".to_owned(),
5493 "https://m/update-new".to_owned(),
5494 )]),
5495 );
5496 assert_eq!(
5497 media_links
5498 .get("updateMediaDescriptions")
5499 .map(String::as_str),
5500 Some("https://m/update-new")
5501 );
5502 }
5503
4753 #[test]
5504 #[test]
4754 fn keep_alive_fires_at_ninety_percent_of_the_interval() {
5505 fn keep_alive_fires_at_ninety_percent_of_the_interval() {
4755 assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430));
5506 assert_eq!(keep_alive_period(Some(2700)), Duration::from_secs(2430));
crates/calling/src/camera.rs +18 −12
@@ -213,8 +213,8 @@ fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<Camera
213 213
214 214 fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
215 215 match quality {
216 VideoQuality::P720 => vec![720, 540, 360],
217 VideoQuality::Auto | VideoQuality::P1080 => vec![1080, 720, 540, 360],
216 VideoQuality::Auto | VideoQuality::P720 => vec![720, 540, 360],
217 VideoQuality::P1080 => vec![1080, 720, 540, 360],
218 218 }
219 219 }
220 220
@@ -697,7 +697,7 @@ mod tests {
697 697 }
698 698
699 699 #[test]
700 fn a_c930e_like_list_picks_mjpeg_1080_for_auto() {
700 fn a_c930e_like_list_picks_mjpeg_720_for_auto() {
701 701 let formats = [
702 702 format(1920, 1080, FrameFormat::YUYV, 5),
703 703 format(1280, 720, FrameFormat::YUYV, 10),
@@ -708,16 +708,20 @@ mod tests {
708 708 ];
709 709 assert_eq!(
710 710 pick_format(&formats, VideoQuality::Auto),
711 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
711 Some(format(1280, 720, FrameFormat::MJPEG, 30))
712 712 );
713 713 assert_eq!(
714 714 pick_format(&formats, VideoQuality::P720),
715 715 Some(format(1280, 720, FrameFormat::MJPEG, 30))
716 716 );
717 assert_eq!(
718 pick_format(&formats, VideoQuality::P1080),
719 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
720 );
717 721 }
718 722
719 723 #[test]
720 fn auto_prefers_1080p_nv12_over_720p() {
724 fn auto_prefers_720p_nv12_over_1080p() {
721 725 let formats = [
722 726 format(1920, 1080, FrameFormat::NV12, 30),
723 727 format(640, 480, FrameFormat::NV12, 30),
@@ -726,7 +730,7 @@ mod tests {
726 730 ];
727 731 assert_eq!(
728 732 pick_format(&formats, VideoQuality::Auto),
729 Some(format(1920, 1080, FrameFormat::NV12, 30))
733 Some(format(1280, 720, FrameFormat::NV12, 30))
730 734 );
731 735 assert_eq!(
732 736 pick_format(&formats, VideoQuality::P720),
@@ -796,17 +800,19 @@ mod tests {
796 800 }
797 801
798 802 #[test]
799 fn auto_keeps_1080p_and_720_lock_scales_it_down() {
803 fn auto_and_720_scale_1080_down_while_1080_lock_keeps_it() {
800 804 assert_eq!(
801 805 fit_widescreen(gradient(1280, 720), VideoQuality::Auto).width(),
802 806 1280
803 807 );
804 let kept = fit_widescreen(gradient(1920, 1080), VideoQuality::Auto);
805 assert_eq!((kept.width(), kept.height()), (1920, 1080));
806 let scaled = fit_widescreen(gradient(1920, 1080), VideoQuality::P720);
807 assert_eq!((scaled.width(), scaled.height()), (1280, 720));
808 let auto = fit_widescreen(gradient(1920, 1080), VideoQuality::Auto);
809 assert_eq!((auto.width(), auto.height()), (1280, 720));
810 let locked = fit_widescreen(gradient(1920, 1080), VideoQuality::P720);
811 assert_eq!((locked.width(), locked.height()), (1280, 720));
812 let full = fit_widescreen(gradient(1920, 1080), VideoQuality::P1080);
813 assert_eq!((full.width(), full.height()), (1920, 1080));
808 814 let wide = fit_widescreen(gradient(2560, 1440), VideoQuality::Auto);
809 assert_eq!((wide.width(), wide.height()), (1920, 1080));
815 assert_eq!((wide.width(), wide.height()), (1280, 720));
810 816 let classic = fit_widescreen(gradient(640, 480), VideoQuality::Auto);
811 817 assert_eq!((classic.width(), classic.height()), (640, 360));
812 818 }
@@ -213,8 +213,8 @@ fn pick_format(formats: &[CameraFormat], quality: VideoQuality) -> Option<Camera
213
213
214fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
214fn candidate_heights(quality: VideoQuality) -> Vec<u32> {
215 match quality {
215 match quality {
216 VideoQuality::P720 => vec![720, 540, 360],
216 VideoQuality::Auto | VideoQuality::P720 => vec![720, 540, 360],
217 VideoQuality::Auto | VideoQuality::P1080 => vec![1080, 720, 540, 360],
217 VideoQuality::P1080 => vec![1080, 720, 540, 360],
218 }
218 }
219}
219}
220
220
@@ -697,7 +697,7 @@ mod tests {
697 }
697 }
698
698
699 #[test]
699 #[test]
700 fn a_c930e_like_list_picks_mjpeg_1080_for_auto() {
700 fn a_c930e_like_list_picks_mjpeg_720_for_auto() {
701 let formats = [
701 let formats = [
702 format(1920, 1080, FrameFormat::YUYV, 5),
702 format(1920, 1080, FrameFormat::YUYV, 5),
703 format(1280, 720, FrameFormat::YUYV, 10),
703 format(1280, 720, FrameFormat::YUYV, 10),
@@ -708,16 +708,20 @@ mod tests {
708 ];
708 ];
709 assert_eq!(
709 assert_eq!(
710 pick_format(&formats, VideoQuality::Auto),
710 pick_format(&formats, VideoQuality::Auto),
711 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
711 Some(format(1280, 720, FrameFormat::MJPEG, 30))
712 );
712 );
713 assert_eq!(
713 assert_eq!(
714 pick_format(&formats, VideoQuality::P720),
714 pick_format(&formats, VideoQuality::P720),
715 Some(format(1280, 720, FrameFormat::MJPEG, 30))
715 Some(format(1280, 720, FrameFormat::MJPEG, 30))
716 );
716 );
717 assert_eq!(
718 pick_format(&formats, VideoQuality::P1080),
719 Some(format(1920, 1080, FrameFormat::MJPEG, 30))
720 );
717 }
721 }
718
722
719 #[test]
723 #[test]
720 fn auto_prefers_1080p_nv12_over_720p() {
724 fn auto_prefers_720p_nv12_over_1080p() {
721 let formats = [
725 let formats = [
722 format(1920, 1080, FrameFormat::NV12, 30),
726 format(1920, 1080, FrameFormat::NV12, 30),
723 format(640, 480, FrameFormat::NV12, 30),
727 format(640, 480, FrameFormat::NV12, 30),
@@ -726,7 +730,7 @@ mod tests {
726 ];
730 ];
727 assert_eq!(
731 assert_eq!(
728 pick_format(&formats, VideoQuality::Auto),
732 pick_format(&formats, VideoQuality::Auto),
729 Some(format(1920, 1080, FrameFormat::NV12, 30))
733 Some(format(1280, 720, FrameFormat::NV12, 30))
730 );
734 );
731 assert_eq!(
735 assert_eq!(
732 pick_format(&formats, VideoQuality::P720),
736 pick_format(&formats, VideoQuality::P720),
@@ -796,17 +800,19 @@ mod tests {
796 }
800 }
797
801
798 #[test]
802 #[test]
799 fn auto_keeps_1080p_and_720_lock_scales_it_down() {
803 fn auto_and_720_scale_1080_down_while_1080_lock_keeps_it() {
800 assert_eq!(
804 assert_eq!(
801 fit_widescreen(gradient(1280, 720), VideoQuality::Auto).width(),
805 fit_widescreen(gradient(1280, 720), VideoQuality::Auto).width(),
802 1280
806 1280
803 );
807 );
804 let kept = fit_widescreen(gradient(1920, 1080), VideoQuality::Auto);
808 let auto = fit_widescreen(gradient(1920, 1080), VideoQuality::Auto);
805 assert_eq!((kept.width(), kept.height()), (1920, 1080));
809 assert_eq!((auto.width(), auto.height()), (1280, 720));
806 let scaled = fit_widescreen(gradient(1920, 1080), VideoQuality::P720);
810 let locked = fit_widescreen(gradient(1920, 1080), VideoQuality::P720);
807 assert_eq!((scaled.width(), scaled.height()), (1280, 720));
811 assert_eq!((locked.width(), locked.height()), (1280, 720));
812 let full = fit_widescreen(gradient(1920, 1080), VideoQuality::P1080);
813 assert_eq!((full.width(), full.height()), (1920, 1080));
808 let wide = fit_widescreen(gradient(2560, 1440), VideoQuality::Auto);
814 let wide = fit_widescreen(gradient(2560, 1440), VideoQuality::Auto);
809 assert_eq!((wide.width(), wide.height()), (1920, 1080));
815 assert_eq!((wide.width(), wide.height()), (1280, 720));
810 let classic = fit_widescreen(gradient(640, 480), VideoQuality::Auto);
816 let classic = fit_widescreen(gradient(640, 480), VideoQuality::Auto);
811 assert_eq!((classic.width(), classic.height()), (640, 360));
817 assert_eq!((classic.width(), classic.height()), (640, 360));
812 }
818 }
crates/calling/src/capture.rs +34 −9
@@ -1,5 +1,5 @@
1 use std::sync::Arc;
2 1 use std::sync::atomic::{AtomicBool, Ordering};
2 use std::sync::{Arc, Mutex};
3 3 use std::thread::JoinHandle;
4 4 use std::time::{Duration, Instant};
5 5
@@ -8,6 +8,30 @@ use tokio::task::JoinHandle as TaskHandle;
8 8 const STOP_WAIT: Duration = Duration::from_secs(2);
9 9 const STOP_POLL: Duration = Duration::from_millis(5);
10 10
11 static STOPPING: Mutex<Vec<JoinHandle<()>>> = Mutex::new(Vec::new());
12
13 fn wait_for_stopping_captures() {
14 let started = Instant::now();
15 loop {
16 let mut stopping = STOPPING
17 .lock()
18 .unwrap_or_else(|poisoned| poisoned.into_inner());
19 let (finished, running): (Vec<_>, Vec<_>) = std::mem::take(&mut *stopping)
20 .into_iter()
21 .partition(|thread| thread.is_finished());
22 *stopping = running;
23 let idle = stopping.is_empty();
24 drop(stopping);
25 for thread in finished {
26 let _ = thread.join();
27 }
28 if idle || started.elapsed() >= STOP_WAIT {
29 return;
30 }
31 std::thread::sleep(STOP_POLL);
32 }
33 }
34
11 35 /// A running frame source; dropping it stops the capture.
12 36 pub enum Capture {
13 37 Thread {
@@ -26,7 +50,10 @@ impl Capture {
26 50 let thread_stop = stop.clone();
27 51 let thread = std::thread::Builder::new()
28 52 .name(name.to_owned())
29 .spawn(move || body(thread_stop))?;
53 .spawn(move || {
54 wait_for_stopping_captures();
55 body(thread_stop)
56 })?;
30 57 Ok(Capture::Thread {
31 58 stop,
32 59 thread: Some(thread),
@@ -39,13 +66,11 @@ impl Drop for Capture {
39 66 match self {
40 67 Capture::Thread { stop, thread } => {
41 68 stop.store(true, Ordering::SeqCst);
42 let Some(thread) = thread.take() else { return };
43 let started = Instant::now();
44 while !thread.is_finished() && started.elapsed() < STOP_WAIT {
45 std::thread::sleep(STOP_POLL);
46 }
47 if thread.is_finished() {
48 let _ = thread.join();
69 if let Some(thread) = thread.take() {
70 STOPPING
71 .lock()
72 .unwrap_or_else(|poisoned| poisoned.into_inner())
73 .push(thread);
49 74 }
50 75 }
51 76 Capture::Task(task) => task.abort(),
@@ -1,5 +1,5 @@
1use std::sync::Arc;
2use std::sync::atomic::{AtomicBool, Ordering};
1use std::sync::atomic::{AtomicBool, Ordering};
2use std::sync::{Arc, Mutex};
3use std::thread::JoinHandle;
3use std::thread::JoinHandle;
4use std::time::{Duration, Instant};
4use std::time::{Duration, Instant};
5
5
@@ -8,6 +8,30 @@ use tokio::task::JoinHandle as TaskHandle;
8const STOP_WAIT: Duration = Duration::from_secs(2);
8const STOP_WAIT: Duration = Duration::from_secs(2);
9const STOP_POLL: Duration = Duration::from_millis(5);
9const STOP_POLL: Duration = Duration::from_millis(5);
10
10
11static STOPPING: Mutex<Vec<JoinHandle<()>>> = Mutex::new(Vec::new());
12
13fn wait_for_stopping_captures() {
14 let started = Instant::now();
15 loop {
16 let mut stopping = STOPPING
17 .lock()
18 .unwrap_or_else(|poisoned| poisoned.into_inner());
19 let (finished, running): (Vec<_>, Vec<_>) = std::mem::take(&mut *stopping)
20 .into_iter()
21 .partition(|thread| thread.is_finished());
22 *stopping = running;
23 let idle = stopping.is_empty();
24 drop(stopping);
25 for thread in finished {
26 let _ = thread.join();
27 }
28 if idle || started.elapsed() >= STOP_WAIT {
29 return;
30 }
31 std::thread::sleep(STOP_POLL);
32 }
33}
34
11/// A running frame source; dropping it stops the capture.
35/// A running frame source; dropping it stops the capture.
12pub enum Capture {
36pub enum Capture {
13 Thread {
37 Thread {
@@ -26,7 +50,10 @@ impl Capture {
26 let thread_stop = stop.clone();
50 let thread_stop = stop.clone();
27 let thread = std::thread::Builder::new()
51 let thread = std::thread::Builder::new()
28 .name(name.to_owned())
52 .name(name.to_owned())
29 .spawn(move || body(thread_stop))?;
53 .spawn(move || {
54 wait_for_stopping_captures();
55 body(thread_stop)
56 })?;
30 Ok(Capture::Thread {
57 Ok(Capture::Thread {
31 stop,
58 stop,
32 thread: Some(thread),
59 thread: Some(thread),
@@ -39,13 +66,11 @@ impl Drop for Capture {
39 match self {
66 match self {
40 Capture::Thread { stop, thread } => {
67 Capture::Thread { stop, thread } => {
41 stop.store(true, Ordering::SeqCst);
68 stop.store(true, Ordering::SeqCst);
42 let Some(thread) = thread.take() else { return };
69 if let Some(thread) = thread.take() {
43 let started = Instant::now();
70 STOPPING
44 while !thread.is_finished() && started.elapsed() < STOP_WAIT {
71 .lock()
45 std::thread::sleep(STOP_POLL);
72 .unwrap_or_else(|poisoned| poisoned.into_inner())
46 }
73 .push(thread);
47 if thread.is_finished() {
48 let _ = thread.join();
49 }
74 }
50 }
75 }
51 Capture::Task(task) => task.abort(),
76 Capture::Task(task) => task.abort(),
crates/calling/src/effects.rs +4 −1
@@ -294,7 +294,10 @@ impl Drop for EffectsThread {
294 294 fn drop(&mut self) {
295 295 self.frames.close();
296 296 if let Some(worker) = self.worker.take() {
297 let _ = worker.join();
297 // Join off the call task; a stuck effects worker must not block hangup.
298 std::thread::spawn(move || {
299 let _ = worker.join();
300 });
298 301 }
299 302 }
300 303 }
@@ -294,7 +294,10 @@ impl Drop for EffectsThread {
294 fn drop(&mut self) {
294 fn drop(&mut self) {
295 self.frames.close();
295 self.frames.close();
296 if let Some(worker) = self.worker.take() {
296 if let Some(worker) = self.worker.take() {
297 let _ = worker.join();
297 // Join off the call task; a stuck effects worker must not block hangup.
298 std::thread::spawn(move || {
299 let _ = worker.join();
300 });
298 }
301 }
299 }
302 }
300}
303}
crates/calling/src/sdp.rs +29 −16
@@ -471,34 +471,38 @@ fn signal_rtp_line(
471 471 .collect();
472 472 let simulcast = source.has("simulcast");
473 473 let receive_only = source.direction() == Some("recvonly");
474 let (range, ssrc_lines) = if multi_stream.is_some() {
474 let (range, ssrc_lines, copy_ssrc_groups) = if multi_stream.is_some() {
475 // Teams rejects x-ssrc-range / ssrc-group on x-multi-stream lines with SdpParsingFailure (301000).
475 476 (
476 477 None,
477 478 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
479 false,
478 480 )
479 481 } else if let Some(&first) = browser_ssrcs.first() {
480 482 let lines = source
481 483 .values("ssrc")
482 484 .map(|value| Attribute::new("ssrc", rewrite_ssrc_msid(value, &mid)))
483 485 .collect();
484 (Some((first, first)), lines)
486 (Some((first, first)), lines, true)
485 487 } else if simulcast {
486 488 let base = numbers.next_u32();
487 489 let lines = vec![Attribute::new(
488 490 "ssrc",
489 491 format!("{base} fake_attribute:fake_value"),
490 492 )];
491 (Some((base, base + SSRC_RANGE_SIZE - 1)), lines)
493 (Some((base, base + SSRC_RANGE_SIZE - 1)), lines, false)
492 494 } else if receive_only && role != LineRole::MainAudio {
493 495 (
494 496 Some((1, 1)),
495 497 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
498 false,
496 499 )
497 500 } else {
498 501 let base = numbers.next_u32();
499 502 (
500 503 Some((base, base)),
501 504 vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))],
505 false,
502 506 )
503 507 };
504 508 if let Some((first, last)) = range {
@@ -563,13 +567,15 @@ fn signal_rtp_line(
563 567 attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE));
564 568 }
565 569 attributes.extend(ssrc_lines);
566 attributes.extend(
567 source
568 .attributes
569 .iter()
570 .filter(|attribute| attribute.name == "ssrc-group")
571 .cloned(),
572 );
570 if copy_ssrc_groups {
571 attributes.extend(
572 source
573 .attributes
574 .iter()
575 .filter(|attribute| attribute.name == "ssrc-group")
576 .cloned(),
577 );
578 }
573 579 attributes.push(Attribute::new("label", role.label()));
574 580 if !source.has("rtcp-mux") {
575 581 attributes.push(Attribute::flag("rtcp-mux"));
@@ -754,12 +760,19 @@ pub fn stream_lines(teams_sdp: &str, lines: &[SignaledLine]) -> Result<Vec<Strea
754 760 role: line.role,
755 761 source_stream_id,
756 762 }),
757 folded => streams.extend(folded.iter().map(|browser_mid| StreamLine {
758 mid: mid.clone(),
759 browser_mid: browser_mid.clone(),
760 role: line.role,
761 source_stream_id: None,
762 })),
763 folded => {
764 let last = folded.len().saturating_sub(1);
765 streams.extend(folded.iter().enumerate().map(|(index, browser_mid)| {
766 StreamLine {
767 mid: mid.clone(),
768 browser_mid: browser_mid.clone(),
769 role: line.role,
770 source_stream_id: (line.role == LineRole::ScreenShare && index == last)
771 .then_some(source_stream_id)
772 .flatten(),
773 }
774 }))
775 }
763 776 }
764 777 }
765 778 Ok(streams)
@@ -471,34 +471,38 @@ fn signal_rtp_line(
471 .collect();
471 .collect();
472 let simulcast = source.has("simulcast");
472 let simulcast = source.has("simulcast");
473 let receive_only = source.direction() == Some("recvonly");
473 let receive_only = source.direction() == Some("recvonly");
474 let (range, ssrc_lines) = if multi_stream.is_some() {
474 let (range, ssrc_lines, copy_ssrc_groups) = if multi_stream.is_some() {
475 // Teams rejects x-ssrc-range / ssrc-group on x-multi-stream lines with SdpParsingFailure (301000).
475 (
476 (
476 None,
477 None,
477 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
478 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
479 false,
478 )
480 )
479 } else if let Some(&first) = browser_ssrcs.first() {
481 } else if let Some(&first) = browser_ssrcs.first() {
480 let lines = source
482 let lines = source
481 .values("ssrc")
483 .values("ssrc")
482 .map(|value| Attribute::new("ssrc", rewrite_ssrc_msid(value, &mid)))
484 .map(|value| Attribute::new("ssrc", rewrite_ssrc_msid(value, &mid)))
483 .collect();
485 .collect();
484 (Some((first, first)), lines)
486 (Some((first, first)), lines, true)
485 } else if simulcast {
487 } else if simulcast {
486 let base = numbers.next_u32();
488 let base = numbers.next_u32();
487 let lines = vec![Attribute::new(
489 let lines = vec![Attribute::new(
488 "ssrc",
490 "ssrc",
489 format!("{base} fake_attribute:fake_value"),
491 format!("{base} fake_attribute:fake_value"),
490 )];
492 )];
491 (Some((base, base + SSRC_RANGE_SIZE - 1)), lines)
493 (Some((base, base + SSRC_RANGE_SIZE - 1)), lines, false)
492 } else if receive_only && role != LineRole::MainAudio {
494 } else if receive_only && role != LineRole::MainAudio {
493 (
495 (
494 Some((1, 1)),
496 Some((1, 1)),
495 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
497 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
498 false,
496 )
499 )
497 } else {
500 } else {
498 let base = numbers.next_u32();
501 let base = numbers.next_u32();
499 (
502 (
500 Some((base, base)),
503 Some((base, base)),
501 vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))],
504 vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))],
505 false,
502 )
506 )
503 };
507 };
504 if let Some((first, last)) = range {
508 if let Some((first, last)) = range {
@@ -563,13 +567,15 @@ fn signal_rtp_line(
563 attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE));
567 attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE));
564 }
568 }
565 attributes.extend(ssrc_lines);
569 attributes.extend(ssrc_lines);
566 attributes.extend(
570 if copy_ssrc_groups {
567 source
571 attributes.extend(
568 .attributes
572 source
569 .iter()
573 .attributes
570 .filter(|attribute| attribute.name == "ssrc-group")
574 .iter()
571 .cloned(),
575 .filter(|attribute| attribute.name == "ssrc-group")
572 );
576 .cloned(),
577 );
578 }
573 attributes.push(Attribute::new("label", role.label()));
579 attributes.push(Attribute::new("label", role.label()));
574 if !source.has("rtcp-mux") {
580 if !source.has("rtcp-mux") {
575 attributes.push(Attribute::flag("rtcp-mux"));
581 attributes.push(Attribute::flag("rtcp-mux"));
@@ -754,12 +760,19 @@ pub fn stream_lines(teams_sdp: &str, lines: &[SignaledLine]) -> Result<Vec<Strea
754 role: line.role,
760 role: line.role,
755 source_stream_id,
761 source_stream_id,
756 }),
762 }),
757 folded => streams.extend(folded.iter().map(|browser_mid| StreamLine {
763 folded => {
758 mid: mid.clone(),
764 let last = folded.len().saturating_sub(1);
759 browser_mid: browser_mid.clone(),
765 streams.extend(folded.iter().enumerate().map(|(index, browser_mid)| {
760 role: line.role,
766 StreamLine {
761 source_stream_id: None,
767 mid: mid.clone(),
762 })),
768 browser_mid: browser_mid.clone(),
769 role: line.role,
770 source_stream_id: (line.role == LineRole::ScreenShare && index == last)
771 .then_some(source_stream_id)
772 .flatten(),
773 }
774 }))
775 }
763 }
776 }
764 }
777 }
765 Ok(streams)
778 Ok(streams)
crates/calling/src/send_control.rs +103 −0
@@ -1,4 +1,5 @@
1 1 use std::collections::{BTreeMap, HashMap};
2 use std::time::Instant;
2 3
3 4 use serde_json::Value;
4 5
@@ -253,8 +254,76 @@ pub fn capture_macroblocks(width: u32, height: u32) -> u32 {
253 254 macroblocks(f64::from(width), f64::from(height))
254 255 }
255 256
257 const GOVERNOR_STRESS_RTT_MS: f64 = 400.0;
258 const GOVERNOR_STRESS_LOSS_PCT: f64 = 5.0;
259 const GOVERNOR_RECOVER_RTT_MS: f64 = 150.0;
260 const GOVERNOR_FLOOR_BPS: u64 = 300_000;
261 const GOVERNOR_CUT: f64 = 0.7;
262 const GOVERNOR_RECOVER: f64 = 1.15;
263 const GOVERNOR_STRESS_SAMPLES: u8 = 2;
264 const GOVERNOR_RECOVER_WAIT_SECS: u64 = 4;
265
266 #[derive(Debug, Default)]
267 pub struct BitrateGovernor {
268 stress_streak: u8,
269 last_change: Option<Instant>,
270 cap_bps: Option<u64>,
271 }
272
273 impl BitrateGovernor {
274 pub fn observe(&mut self, now: Instant, rtt_ms: f64, loss_pct: f64, target_bps: u64) -> bool {
275 if target_bps == 0 {
276 return false;
277 }
278 let stressed = rtt_ms > GOVERNOR_STRESS_RTT_MS || loss_pct > GOVERNOR_STRESS_LOSS_PCT;
279 let recovering = rtt_ms < GOVERNOR_RECOVER_RTT_MS && loss_pct == 0.0;
280 if stressed {
281 self.stress_streak = self.stress_streak.saturating_add(1);
282 if self.stress_streak >= GOVERNOR_STRESS_SAMPLES {
283 let base = self.cap_bps.unwrap_or(target_bps);
284 let next = ((base as f64) * GOVERNOR_CUT).round() as u64;
285 let next = next.max(GOVERNOR_FLOOR_BPS).min(target_bps);
286 if self.cap_bps != Some(next) {
287 self.cap_bps = Some(next);
288 self.last_change = Some(now);
289 return true;
290 }
291 }
292 return false;
293 }
294 self.stress_streak = 0;
295 let Some(cap) = self.cap_bps else {
296 return false;
297 };
298 if !recovering {
299 return false;
300 }
301 let ready = self
302 .last_change
303 .is_none_or(|at| now.duration_since(at).as_secs() >= GOVERNOR_RECOVER_WAIT_SECS);
304 if !ready {
305 return false;
306 }
307 let next = ((cap as f64) * GOVERNOR_RECOVER).round() as u64;
308 if next >= target_bps {
309 self.cap_bps = None;
310 self.last_change = Some(now);
311 return true;
312 }
313 self.cap_bps = Some(next.max(GOVERNOR_FLOOR_BPS));
314 self.last_change = Some(now);
315 true
316 }
317
318 pub fn cap_bps(&self) -> Option<u64> {
319 self.cap_bps
320 }
321 }
322
256 323 #[cfg(test)]
257 324 mod tests {
325 use std::time::Duration;
326
258 327 use serde_json::json;
259 328
260 329 use super::*;
@@ -447,4 +516,38 @@ mod tests {
447 516 keyframe[2] = "max-fs=3600;max-fps=3000;max-br=1500;rid=3;ssrc=1113;KeyFrame=1";
448 517 assert!(filter.admit(&simulcast_request(5, keyframe)).is_some());
449 518 }
519
520 #[test]
521 fn bitrate_governor_cuts_after_two_stressed_samples() {
522 let mut governor = BitrateGovernor::default();
523 let start = Instant::now();
524 assert!(!governor.observe(start, 500.0, 0.0, 2_000_000));
525 assert!(governor.observe(start + Duration::from_secs(2), 500.0, 6.0, 2_000_000));
526 assert_eq!(governor.cap_bps(), Some(1_400_000));
527 }
528
529 #[test]
530 fn bitrate_governor_floors_at_300_kbps() {
531 let mut governor = BitrateGovernor::default();
532 let start = Instant::now();
533 assert!(!governor.observe(start, 500.0, 10.0, 400_000));
534 assert!(governor.observe(start + Duration::from_secs(2), 500.0, 10.0, 400_000));
535 assert_eq!(governor.cap_bps(), Some(300_000));
536 }
537
538 #[test]
539 fn bitrate_governor_recovers_after_clean_path() {
540 let mut governor = BitrateGovernor::default();
541 let start = Instant::now();
542 assert!(!governor.observe(start, 500.0, 8.0, 1_000_000));
543 assert!(governor.observe(start + Duration::from_secs(2), 500.0, 8.0, 1_000_000));
544 assert_eq!(governor.cap_bps(), Some(700_000));
545 assert!(!governor.observe(start + Duration::from_secs(3), 100.0, 0.0, 1_000_000));
546 assert!(governor.observe(start + Duration::from_secs(7), 100.0, 0.0, 1_000_000));
547 assert_eq!(governor.cap_bps(), Some(805_000));
548 assert!(governor.observe(start + Duration::from_secs(12), 100.0, 0.0, 1_000_000));
549 assert_eq!(governor.cap_bps(), Some(925_750));
550 assert!(governor.observe(start + Duration::from_secs(17), 100.0, 0.0, 1_000_000));
551 assert_eq!(governor.cap_bps(), None);
552 }
450 553 }
@@ -1,4 +1,5 @@
1use std::collections::{BTreeMap, HashMap};
1use std::collections::{BTreeMap, HashMap};
2use std::time::Instant;
2
3
3use serde_json::Value;
4use serde_json::Value;
4
5
@@ -253,8 +254,76 @@ pub fn capture_macroblocks(width: u32, height: u32) -> u32 {
253 macroblocks(f64::from(width), f64::from(height))
254 macroblocks(f64::from(width), f64::from(height))
254}
255}
255
256
257const GOVERNOR_STRESS_RTT_MS: f64 = 400.0;
258const GOVERNOR_STRESS_LOSS_PCT: f64 = 5.0;
259const GOVERNOR_RECOVER_RTT_MS: f64 = 150.0;
260const GOVERNOR_FLOOR_BPS: u64 = 300_000;
261const GOVERNOR_CUT: f64 = 0.7;
262const GOVERNOR_RECOVER: f64 = 1.15;
263const GOVERNOR_STRESS_SAMPLES: u8 = 2;
264const GOVERNOR_RECOVER_WAIT_SECS: u64 = 4;
265
266#[derive(Debug, Default)]
267pub struct BitrateGovernor {
268 stress_streak: u8,
269 last_change: Option<Instant>,
270 cap_bps: Option<u64>,
271}
272
273impl BitrateGovernor {
274 pub fn observe(&mut self, now: Instant, rtt_ms: f64, loss_pct: f64, target_bps: u64) -> bool {
275 if target_bps == 0 {
276 return false;
277 }
278 let stressed = rtt_ms > GOVERNOR_STRESS_RTT_MS || loss_pct > GOVERNOR_STRESS_LOSS_PCT;
279 let recovering = rtt_ms < GOVERNOR_RECOVER_RTT_MS && loss_pct == 0.0;
280 if stressed {
281 self.stress_streak = self.stress_streak.saturating_add(1);
282 if self.stress_streak >= GOVERNOR_STRESS_SAMPLES {
283 let base = self.cap_bps.unwrap_or(target_bps);
284 let next = ((base as f64) * GOVERNOR_CUT).round() as u64;
285 let next = next.max(GOVERNOR_FLOOR_BPS).min(target_bps);
286 if self.cap_bps != Some(next) {
287 self.cap_bps = Some(next);
288 self.last_change = Some(now);
289 return true;
290 }
291 }
292 return false;
293 }
294 self.stress_streak = 0;
295 let Some(cap) = self.cap_bps else {
296 return false;
297 };
298 if !recovering {
299 return false;
300 }
301 let ready = self
302 .last_change
303 .is_none_or(|at| now.duration_since(at).as_secs() >= GOVERNOR_RECOVER_WAIT_SECS);
304 if !ready {
305 return false;
306 }
307 let next = ((cap as f64) * GOVERNOR_RECOVER).round() as u64;
308 if next >= target_bps {
309 self.cap_bps = None;
310 self.last_change = Some(now);
311 return true;
312 }
313 self.cap_bps = Some(next.max(GOVERNOR_FLOOR_BPS));
314 self.last_change = Some(now);
315 true
316 }
317
318 pub fn cap_bps(&self) -> Option<u64> {
319 self.cap_bps
320 }
321}
322
256#[cfg(test)]
323#[cfg(test)]
257mod tests {
324mod tests {
325 use std::time::Duration;
326
258 use serde_json::json;
327 use serde_json::json;
259
328
260 use super::*;
329 use super::*;
@@ -447,4 +516,38 @@ mod tests {
447 keyframe[2] = "max-fs=3600;max-fps=3000;max-br=1500;rid=3;ssrc=1113;KeyFrame=1";
516 keyframe[2] = "max-fs=3600;max-fps=3000;max-br=1500;rid=3;ssrc=1113;KeyFrame=1";
448 assert!(filter.admit(&simulcast_request(5, keyframe)).is_some());
517 assert!(filter.admit(&simulcast_request(5, keyframe)).is_some());
449 }
518 }
519
520 #[test]
521 fn bitrate_governor_cuts_after_two_stressed_samples() {
522 let mut governor = BitrateGovernor::default();
523 let start = Instant::now();
524 assert!(!governor.observe(start, 500.0, 0.0, 2_000_000));
525 assert!(governor.observe(start + Duration::from_secs(2), 500.0, 6.0, 2_000_000));
526 assert_eq!(governor.cap_bps(), Some(1_400_000));
527 }
528
529 #[test]
530 fn bitrate_governor_floors_at_300_kbps() {
531 let mut governor = BitrateGovernor::default();
532 let start = Instant::now();
533 assert!(!governor.observe(start, 500.0, 10.0, 400_000));
534 assert!(governor.observe(start + Duration::from_secs(2), 500.0, 10.0, 400_000));
535 assert_eq!(governor.cap_bps(), Some(300_000));
536 }
537
538 #[test]
539 fn bitrate_governor_recovers_after_clean_path() {
540 let mut governor = BitrateGovernor::default();
541 let start = Instant::now();
542 assert!(!governor.observe(start, 500.0, 8.0, 1_000_000));
543 assert!(governor.observe(start + Duration::from_secs(2), 500.0, 8.0, 1_000_000));
544 assert_eq!(governor.cap_bps(), Some(700_000));
545 assert!(!governor.observe(start + Duration::from_secs(3), 100.0, 0.0, 1_000_000));
546 assert!(governor.observe(start + Duration::from_secs(7), 100.0, 0.0, 1_000_000));
547 assert_eq!(governor.cap_bps(), Some(805_000));
548 assert!(governor.observe(start + Duration::from_secs(12), 100.0, 0.0, 1_000_000));
549 assert_eq!(governor.cap_bps(), Some(925_750));
550 assert!(governor.observe(start + Duration::from_secs(17), 100.0, 0.0, 1_000_000));
551 assert_eq!(governor.cap_bps(), None);
552 }
450}
553}
crates/calling/src/signaling.rs +28 −0
@@ -334,6 +334,12 @@ impl Signaling {
334 334 .map(|_| ())
335 335 }
336 336
337 pub async fn post_json_body(&self, label: &str, url: &str, body: Value) -> Result<Value> {
338 self.send(label, Method::Post, url, Some(body))
339 .await
340 .map(|response| response.body)
341 }
342
337 343 pub async fn post_empty(&self, label: &str, url: &str) -> Result<()> {
338 344 self.send(label, Method::Post, url, None).await.map(|_| ())
339 345 }
@@ -947,6 +953,17 @@ impl Signaling {
947 953 .map(|_| ())
948 954 }
949 955
956 pub async fn end_call_leg(&self, call_leg_url: &str) -> Result<()> {
957 self.send(
958 "DELETE callLeg (hangup)",
959 Method::Delete,
960 call_leg_url,
961 Some(hangup_call_leg_body()),
962 )
963 .await
964 .map(|_| ())
965 }
966
950 967 pub async fn reject_renegotiation(
951 968 &self,
952 969 url: &str,
@@ -1185,6 +1202,10 @@ pub fn decline_body() -> Value {
1185 1202 json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
1186 1203 }
1187 1204
1205 pub fn hangup_call_leg_body() -> Value {
1206 json!({"callEnd": {"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
1207 }
1208
1188 1209 pub fn ringing_body(from: &Participant) -> Value {
1189 1210 json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}})
1190 1211 }
@@ -1840,6 +1861,13 @@ mod tests {
1840 1861 assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"]));
1841 1862 }
1842 1863
1864 #[test]
1865 fn hangup_call_leg_uses_success_end() {
1866 let body = hangup_call_leg_body();
1867 assert_eq!(body["callEnd"]["code"], 0);
1868 assert_eq!(body["callEnd"]["phrase"], "CallEndReasonLocalUserInitiated");
1869 }
1870
1843 1871 #[test]
1844 1872 fn attach_asks_for_media_and_joins_the_conversation() {
1845 1873 let from = from();
@@ -334,6 +334,12 @@ impl Signaling {
334 .map(|_| ())
334 .map(|_| ())
335 }
335 }
336
336
337 pub async fn post_json_body(&self, label: &str, url: &str, body: Value) -> Result<Value> {
338 self.send(label, Method::Post, url, Some(body))
339 .await
340 .map(|response| response.body)
341 }
342
337 pub async fn post_empty(&self, label: &str, url: &str) -> Result<()> {
343 pub async fn post_empty(&self, label: &str, url: &str) -> Result<()> {
338 self.send(label, Method::Post, url, None).await.map(|_| ())
344 self.send(label, Method::Post, url, None).await.map(|_| ())
339 }
345 }
@@ -947,6 +953,17 @@ impl Signaling {
947 .map(|_| ())
953 .map(|_| ())
948 }
954 }
949
955
956 pub async fn end_call_leg(&self, call_leg_url: &str) -> Result<()> {
957 self.send(
958 "DELETE callLeg (hangup)",
959 Method::Delete,
960 call_leg_url,
961 Some(hangup_call_leg_body()),
962 )
963 .await
964 .map(|_| ())
965 }
966
950 pub async fn reject_renegotiation(
967 pub async fn reject_renegotiation(
951 &self,
968 &self,
952 url: &str,
969 url: &str,
@@ -1185,6 +1202,10 @@ pub fn decline_body() -> Value {
1185 json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
1202 json!({"callEnd": {"code": DECLINE_CODE, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
1186}
1203}
1187
1204
1205pub fn hangup_call_leg_body() -> Value {
1206 json!({"callEnd": {"code": 0, "subCode": 0, "phrase": "CallEndReasonLocalUserInitiated", "resultCategories": ["Success"]}})
1207}
1208
1188pub fn ringing_body(from: &Participant) -> Value {
1209pub fn ringing_body(from: &Participant) -> Value {
1189 json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}})
1210 json!({"callProgress": {"sender": from.wire(), "status": "ringing", "phrase": "ringing"}})
1190}
1211}
@@ -1840,6 +1861,13 @@ mod tests {
1840 assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"]));
1861 assert_eq!(body["callEnd"]["resultCategories"], json!(["Success"]));
1841 }
1862 }
1842
1863
1864 #[test]
1865 fn hangup_call_leg_uses_success_end() {
1866 let body = hangup_call_leg_body();
1867 assert_eq!(body["callEnd"]["code"], 0);
1868 assert_eq!(body["callEnd"]["phrase"], "CallEndReasonLocalUserInitiated");
1869 }
1870
1843 #[test]
1871 #[test]
1844 fn attach_asks_for_media_and_joins_the_conversation() {
1872 fn attach_asks_for_media_and_joins_the_conversation() {
1845 let from = from();
1873 let from = from();
crates/calling/src/trouter_events.rs +137 −2
@@ -138,6 +138,12 @@ pub struct Renegotiation {
138 138 pub links: BTreeMap<String, String>,
139 139 }
140 140
141 #[derive(Debug, Clone, PartialEq, Eq)]
142 pub struct MediaAcknowledgement {
143 pub links: BTreeMap<String, String>,
144 pub keys: String,
145 }
146
141 147 #[derive(Debug, Clone, PartialEq)]
142 148 pub enum CallEvent {
143 149 ConversationUpdate(Value),
@@ -145,6 +151,7 @@ pub enum CallEvent {
145 151 Acceptance(Acceptance),
146 152 Progress(ProgressStatus),
147 153 MediaAnswer(MediaAnswer),
154 MediaAcknowledgement(MediaAcknowledgement),
148 155 MediaRenegotiation(Renegotiation),
149 156 Speakers(Vec<u32>),
150 157 ControlVideoStreaming(Value),
@@ -171,6 +178,7 @@ impl CallEvent {
171 178 CallEvent::Acceptance(_) => "call/acceptance".into(),
172 179 CallEvent::Progress(_) => "call/progress".into(),
173 180 CallEvent::MediaAnswer(_) => "call/mediaAnswer".into(),
181 CallEvent::MediaAcknowledgement(_) => "call/mediaAcknowledgement".into(),
174 182 CallEvent::MediaRenegotiation(_) => "call/mediaRenegotiation".into(),
175 183 CallEvent::Speakers(_) => "call/speakers".into(),
176 184 CallEvent::ControlVideoStreaming(_) => "call/controlVideoStreaming".into(),
@@ -212,6 +220,10 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
212 220 ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
213 221 ("call", "progress") => CallEvent::Progress(progress(&body)),
214 222 ("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),
223 ("call", "mediaAcknowledgement") => CallEvent::MediaAcknowledgement(MediaAcknowledgement {
224 links: nested_links(&body),
225 keys: object_keys(&body),
226 }),
215 227 ("call", "mediaRenegotiation") => CallEvent::MediaRenegotiation(renegotiation(&body)?),
216 228 ("call", "csrcInfo" | "dominantSpeakerInfo") => CallEvent::Speakers(speaker_sources(&body)),
217 229 ("call", "controlVideoStreaming") => CallEvent::ControlVideoStreaming(body),
@@ -265,18 +277,87 @@ pub fn acknowledgement_links(body: &Value) -> BTreeMap<String, String> {
265 277 string_links(&body["callAcceptanceAcknowledgement"]["links"])
266 278 }
267 279
280 const LEG_LINK_NAMES: &[&str] = &[
281 "mediaAnswer",
282 "rejection",
283 "mediaAcknowledgement",
284 "acknowledgement",
285 "updateMediaDescriptions",
286 "applyChannelParameters",
287 "controlVideoStreaming",
288 "callLeg",
289 "retargetCompletion",
290 "mediaRenegotiation",
291 "transfer",
292 "replacement",
293 "balanceUpdate",
294 ];
295
296 fn link_url(value: &Value) -> Option<String> {
297 value
298 .as_str()
299 .map(str::to_owned)
300 .or_else(|| value.get("href").and_then(Value::as_str).map(str::to_owned))
301 }
302
268 303 fn string_links(value: &Value) -> BTreeMap<String, String> {
269 304 value
270 305 .as_object()
271 306 .map(|links| {
272 307 links
273 308 .iter()
274 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
309 .filter_map(|(name, url)| Some((name.clone(), link_url(url)?)))
275 310 .collect()
276 311 })
277 312 .unwrap_or_default()
278 313 }
279 314
315 /// Every call-leg `links` object in the payload. Escalation offers often put
316 /// `updateMediaDescriptions` next to the media holder, not inside it; keeping
317 /// only the holder's `mediaAnswer` left us posting at the ended leg.
318 pub fn nested_links(value: &Value) -> BTreeMap<String, String> {
319 let mut links = BTreeMap::new();
320 collect_leg_links(value, 0, &mut links);
321 links
322 }
323
324 fn collect_leg_links(value: &Value, depth: usize, out: &mut BTreeMap<String, String>) {
325 if depth > 8 {
326 return;
327 }
328 match value {
329 Value::Object(map) => {
330 if let Some(links) = map.get("links") {
331 let parsed = string_links(links);
332 if parsed
333 .keys()
334 .any(|name| LEG_LINK_NAMES.contains(&name.as_str()))
335 {
336 out.extend(parsed);
337 }
338 }
339 for child in map.values() {
340 collect_leg_links(child, depth + 1, out);
341 }
342 }
343 Value::Array(items) => {
344 for item in items {
345 collect_leg_links(item, depth + 1, out);
346 }
347 }
348 _ => {}
349 }
350 }
351
352 pub fn object_keys(value: &Value) -> String {
353 let Some(map) = value.as_object() else {
354 return String::new();
355 };
356 let mut keys: Vec<&str> = map.keys().map(String::as_str).collect();
357 keys.sort_unstable();
358 keys.join(",")
359 }
360
280 361 fn acceptance(body: &Value) -> Result<Acceptance> {
281 362 let accepted = &body["callAcceptance"];
282 363 let media = &accepted["mediaContent"];
@@ -346,6 +427,8 @@ fn renegotiation(body: &Value) -> Result<Renegotiation> {
346 427 .as_str()
347 428 .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent.blob".into()))?
348 429 .to_owned();
430 let mut links = nested_links(body);
431 links.extend(string_links(&holder["links"]));
349 432 Ok(Renegotiation {
350 433 sdp,
351 434 new_offer: media["newOffer"].as_bool().unwrap_or(false),
@@ -353,7 +436,7 @@ fn renegotiation(body: &Value) -> Result<Renegotiation> {
353 436 || media["isTwoPartyToMultiPartyEscalation"]
354 437 .as_bool()
355 438 .unwrap_or(false),
356 links: string_links(&holder["links"]),
439 links,
357 440 })
358 441 }
359 442
@@ -659,6 +742,58 @@ mod tests {
659 742 assert!(classify("callAgent/abc/1/call/mediaRenegotiation/", json!({"x": 1})).is_err());
660 743 }
661 744
745 #[test]
746 fn renegotiation_keeps_leg_links_that_sit_beside_the_offer() {
747 let body = json!({
748 "mediaRenegotiation": {
749 "mediaContent": {"blob": "v=0\r\n", "newOffer": true, "escalationOccurring": true},
750 "links": {"mediaAnswer": "https://cc/answer", "rejection": "https://cc/reject"}
751 },
752 "links": {
753 "updateMediaDescriptions": {"href": "https://cc/new/update"},
754 "applyChannelParameters": "https://cc/new/apply",
755 "callLeg": "https://cc/new/leg"
756 }
757 });
758 let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", body).unwrap();
759 let CallEvent::MediaRenegotiation(renegotiation) = event else {
760 panic!("not a renegotiation")
761 };
762 assert_eq!(renegotiation.links["mediaAnswer"], "https://cc/answer");
763 assert_eq!(
764 renegotiation.links["updateMediaDescriptions"],
765 "https://cc/new/update"
766 );
767 assert_eq!(
768 renegotiation.links["applyChannelParameters"],
769 "https://cc/new/apply"
770 );
771 assert_eq!(renegotiation.links["callLeg"], "https://cc/new/leg");
772 }
773
774 #[test]
775 fn media_acknowledgement_harvests_new_mixer_leg_links() {
776 let body = json!({
777 "mediaAcknowledgement": {
778 "links": {
779 "updateMediaDescriptions": "https://cc/leg2/update",
780 "applyChannelParameters": "https://cc/leg2/apply",
781 "callLeg": "https://cc/leg2"
782 }
783 }
784 });
785 let (_, event) = classify("callAgent/abc/1/call/mediaAcknowledgement/", body).unwrap();
786 let CallEvent::MediaAcknowledgement(ack) = event else {
787 panic!("not a media acknowledgement")
788 };
789 assert_eq!(
790 ack.links["updateMediaDescriptions"],
791 "https://cc/leg2/update"
792 );
793 assert_eq!(ack.links["applyChannelParameters"], "https://cc/leg2/apply");
794 assert_eq!(ack.links["callLeg"], "https://cc/leg2");
795 }
796
662 797 #[test]
663 798 fn speaker_sources_come_from_known_list_keys() {
664 799 assert_eq!(
@@ -138,6 +138,12 @@ pub struct Renegotiation {
138 pub links: BTreeMap<String, String>,
138 pub links: BTreeMap<String, String>,
139}
139}
140
140
141#[derive(Debug, Clone, PartialEq, Eq)]
142pub struct MediaAcknowledgement {
143 pub links: BTreeMap<String, String>,
144 pub keys: String,
145}
146
141#[derive(Debug, Clone, PartialEq)]
147#[derive(Debug, Clone, PartialEq)]
142pub enum CallEvent {
148pub enum CallEvent {
143 ConversationUpdate(Value),
149 ConversationUpdate(Value),
@@ -145,6 +151,7 @@ pub enum CallEvent {
145 Acceptance(Acceptance),
151 Acceptance(Acceptance),
146 Progress(ProgressStatus),
152 Progress(ProgressStatus),
147 MediaAnswer(MediaAnswer),
153 MediaAnswer(MediaAnswer),
154 MediaAcknowledgement(MediaAcknowledgement),
148 MediaRenegotiation(Renegotiation),
155 MediaRenegotiation(Renegotiation),
149 Speakers(Vec<u32>),
156 Speakers(Vec<u32>),
150 ControlVideoStreaming(Value),
157 ControlVideoStreaming(Value),
@@ -171,6 +178,7 @@ impl CallEvent {
171 CallEvent::Acceptance(_) => "call/acceptance".into(),
178 CallEvent::Acceptance(_) => "call/acceptance".into(),
172 CallEvent::Progress(_) => "call/progress".into(),
179 CallEvent::Progress(_) => "call/progress".into(),
173 CallEvent::MediaAnswer(_) => "call/mediaAnswer".into(),
180 CallEvent::MediaAnswer(_) => "call/mediaAnswer".into(),
181 CallEvent::MediaAcknowledgement(_) => "call/mediaAcknowledgement".into(),
174 CallEvent::MediaRenegotiation(_) => "call/mediaRenegotiation".into(),
182 CallEvent::MediaRenegotiation(_) => "call/mediaRenegotiation".into(),
175 CallEvent::Speakers(_) => "call/speakers".into(),
183 CallEvent::Speakers(_) => "call/speakers".into(),
176 CallEvent::ControlVideoStreaming(_) => "call/controlVideoStreaming".into(),
184 CallEvent::ControlVideoStreaming(_) => "call/controlVideoStreaming".into(),
@@ -212,6 +220,10 @@ pub fn classify(path: &str, body: Value) -> Result<(String, CallEvent)> {
212 ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
220 ("call", "acceptance") => CallEvent::Acceptance(acceptance(&body)?),
213 ("call", "progress") => CallEvent::Progress(progress(&body)),
221 ("call", "progress") => CallEvent::Progress(progress(&body)),
214 ("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),
222 ("call", "mediaAnswer") => CallEvent::MediaAnswer(media_answer(&body)?),
223 ("call", "mediaAcknowledgement") => CallEvent::MediaAcknowledgement(MediaAcknowledgement {
224 links: nested_links(&body),
225 keys: object_keys(&body),
226 }),
215 ("call", "mediaRenegotiation") => CallEvent::MediaRenegotiation(renegotiation(&body)?),
227 ("call", "mediaRenegotiation") => CallEvent::MediaRenegotiation(renegotiation(&body)?),
216 ("call", "csrcInfo" | "dominantSpeakerInfo") => CallEvent::Speakers(speaker_sources(&body)),
228 ("call", "csrcInfo" | "dominantSpeakerInfo") => CallEvent::Speakers(speaker_sources(&body)),
217 ("call", "controlVideoStreaming") => CallEvent::ControlVideoStreaming(body),
229 ("call", "controlVideoStreaming") => CallEvent::ControlVideoStreaming(body),
@@ -265,18 +277,87 @@ pub fn acknowledgement_links(body: &Value) -> BTreeMap<String, String> {
265 string_links(&body["callAcceptanceAcknowledgement"]["links"])
277 string_links(&body["callAcceptanceAcknowledgement"]["links"])
266}
278}
267
279
280const LEG_LINK_NAMES: &[&str] = &[
281 "mediaAnswer",
282 "rejection",
283 "mediaAcknowledgement",
284 "acknowledgement",
285 "updateMediaDescriptions",
286 "applyChannelParameters",
287 "controlVideoStreaming",
288 "callLeg",
289 "retargetCompletion",
290 "mediaRenegotiation",
291 "transfer",
292 "replacement",
293 "balanceUpdate",
294];
295
296fn link_url(value: &Value) -> Option<String> {
297 value
298 .as_str()
299 .map(str::to_owned)
300 .or_else(|| value.get("href").and_then(Value::as_str).map(str::to_owned))
301}
302
268fn string_links(value: &Value) -> BTreeMap<String, String> {
303fn string_links(value: &Value) -> BTreeMap<String, String> {
269 value
304 value
270 .as_object()
305 .as_object()
271 .map(|links| {
306 .map(|links| {
272 links
307 links
273 .iter()
308 .iter()
274 .filter_map(|(name, url)| Some((name.clone(), url.as_str()?.to_owned())))
309 .filter_map(|(name, url)| Some((name.clone(), link_url(url)?)))
275 .collect()
310 .collect()
276 })
311 })
277 .unwrap_or_default()
312 .unwrap_or_default()
278}
313}
279
314
315/// Every call-leg `links` object in the payload. Escalation offers often put
316/// `updateMediaDescriptions` next to the media holder, not inside it; keeping
317/// only the holder's `mediaAnswer` left us posting at the ended leg.
318pub fn nested_links(value: &Value) -> BTreeMap<String, String> {
319 let mut links = BTreeMap::new();
320 collect_leg_links(value, 0, &mut links);
321 links
322}
323
324fn collect_leg_links(value: &Value, depth: usize, out: &mut BTreeMap<String, String>) {
325 if depth > 8 {
326 return;
327 }
328 match value {
329 Value::Object(map) => {
330 if let Some(links) = map.get("links") {
331 let parsed = string_links(links);
332 if parsed
333 .keys()
334 .any(|name| LEG_LINK_NAMES.contains(&name.as_str()))
335 {
336 out.extend(parsed);
337 }
338 }
339 for child in map.values() {
340 collect_leg_links(child, depth + 1, out);
341 }
342 }
343 Value::Array(items) => {
344 for item in items {
345 collect_leg_links(item, depth + 1, out);
346 }
347 }
348 _ => {}
349 }
350}
351
352pub fn object_keys(value: &Value) -> String {
353 let Some(map) = value.as_object() else {
354 return String::new();
355 };
356 let mut keys: Vec<&str> = map.keys().map(String::as_str).collect();
357 keys.sort_unstable();
358 keys.join(",")
359}
360
280fn acceptance(body: &Value) -> Result<Acceptance> {
361fn acceptance(body: &Value) -> Result<Acceptance> {
281 let accepted = &body["callAcceptance"];
362 let accepted = &body["callAcceptance"];
282 let media = &accepted["mediaContent"];
363 let media = &accepted["mediaContent"];
@@ -346,6 +427,8 @@ fn renegotiation(body: &Value) -> Result<Renegotiation> {
346 .as_str()
427 .as_str()
347 .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent.blob".into()))?
428 .ok_or_else(|| Error::Callback("mediaRenegotiation without mediaContent.blob".into()))?
348 .to_owned();
429 .to_owned();
430 let mut links = nested_links(body);
431 links.extend(string_links(&holder["links"]));
349 Ok(Renegotiation {
432 Ok(Renegotiation {
350 sdp,
433 sdp,
351 new_offer: media["newOffer"].as_bool().unwrap_or(false),
434 new_offer: media["newOffer"].as_bool().unwrap_or(false),
@@ -353,7 +436,7 @@ fn renegotiation(body: &Value) -> Result<Renegotiation> {
353 || media["isTwoPartyToMultiPartyEscalation"]
436 || media["isTwoPartyToMultiPartyEscalation"]
354 .as_bool()
437 .as_bool()
355 .unwrap_or(false),
438 .unwrap_or(false),
356 links: string_links(&holder["links"]),
439 links,
357 })
440 })
358}
441}
359
442
@@ -659,6 +742,58 @@ mod tests {
659 assert!(classify("callAgent/abc/1/call/mediaRenegotiation/", json!({"x": 1})).is_err());
742 assert!(classify("callAgent/abc/1/call/mediaRenegotiation/", json!({"x": 1})).is_err());
660 }
743 }
661
744
745 #[test]
746 fn renegotiation_keeps_leg_links_that_sit_beside_the_offer() {
747 let body = json!({
748 "mediaRenegotiation": {
749 "mediaContent": {"blob": "v=0\r\n", "newOffer": true, "escalationOccurring": true},
750 "links": {"mediaAnswer": "https://cc/answer", "rejection": "https://cc/reject"}
751 },
752 "links": {
753 "updateMediaDescriptions": {"href": "https://cc/new/update"},
754 "applyChannelParameters": "https://cc/new/apply",
755 "callLeg": "https://cc/new/leg"
756 }
757 });
758 let (_, event) = classify("callAgent/abc/1/call/mediaRenegotiation/", body).unwrap();
759 let CallEvent::MediaRenegotiation(renegotiation) = event else {
760 panic!("not a renegotiation")
761 };
762 assert_eq!(renegotiation.links["mediaAnswer"], "https://cc/answer");
763 assert_eq!(
764 renegotiation.links["updateMediaDescriptions"],
765 "https://cc/new/update"
766 );
767 assert_eq!(
768 renegotiation.links["applyChannelParameters"],
769 "https://cc/new/apply"
770 );
771 assert_eq!(renegotiation.links["callLeg"], "https://cc/new/leg");
772 }
773
774 #[test]
775 fn media_acknowledgement_harvests_new_mixer_leg_links() {
776 let body = json!({
777 "mediaAcknowledgement": {
778 "links": {
779 "updateMediaDescriptions": "https://cc/leg2/update",
780 "applyChannelParameters": "https://cc/leg2/apply",
781 "callLeg": "https://cc/leg2"
782 }
783 }
784 });
785 let (_, event) = classify("callAgent/abc/1/call/mediaAcknowledgement/", body).unwrap();
786 let CallEvent::MediaAcknowledgement(ack) = event else {
787 panic!("not a media acknowledgement")
788 };
789 assert_eq!(
790 ack.links["updateMediaDescriptions"],
791 "https://cc/leg2/update"
792 );
793 assert_eq!(ack.links["applyChannelParameters"], "https://cc/leg2/apply");
794 assert_eq!(ack.links["callLeg"], "https://cc/leg2");
795 }
796
662 #[test]
797 #[test]
663 fn speaker_sources_come_from_known_list_keys() {
798 fn speaker_sources_come_from_known_list_keys() {
664 assert_eq!(
799 assert_eq!(
crates/calling/src/video_layout.rs +38 −6
@@ -235,21 +235,29 @@ pub fn add_one_to_one_lines(
235 235 /// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
236 236 #[derive(Debug, Clone, PartialEq, Eq)]
237 237 pub struct MediaDescription {
238 pub mid: &'static str,
238 pub mid: String,
239 239 pub direction: &'static str,
240 240 pub label: Option<&'static str>,
241 241 }
242 242
243 243 impl MediaDescription {
244 244 pub fn camera(sending: bool) -> Self {
245 Self::line(CAMERA_MID, sending, CAMERA_LINE_LABEL)
245 Self::camera_line(CAMERA_MID, sending)
246 246 }
247 247
248 248 pub fn share(sending: bool) -> Self {
249 Self::line(SHARE_MID, sending, SHARE_LINE_LABEL)
249 Self::share_line(SHARE_MID, sending)
250 }
251
252 pub fn camera_line(mid: impl Into<String>, sending: bool) -> Self {
253 Self::line(mid.into(), sending, CAMERA_LINE_LABEL)
254 }
255
256 pub fn share_line(mid: impl Into<String>, sending: bool) -> Self {
257 Self::line(mid.into(), sending, SHARE_LINE_LABEL)
250 258 }
251 259
252 fn line(mid: &'static str, sending: bool, label: &'static str) -> Self {
260 fn line(mid: String, sending: bool, label: &'static str) -> Self {
253 261 if sending {
254 262 MediaDescription {
255 263 mid,
@@ -465,6 +473,16 @@ pub fn send_capabilities_body(
465 473 height: u32,
466 474 sequence_number: u64,
467 475 quality: VideoQuality,
476 ) -> Value {
477 send_capabilities_body_for(CAMERA_MID, width, height, sequence_number, quality)
478 }
479
480 pub fn send_capabilities_body_for(
481 camera_mid: &str,
482 width: u32,
483 height: u32,
484 sequence_number: u64,
485 quality: VideoQuality,
468 486 ) -> Value {
469 487 let ceiling = quality.capture_height().max(quality.capture_width());
470 488 let width = width.min(ceiling);
@@ -488,7 +506,7 @@ pub fn send_capabilities_body(
488 506 json!({
489 507 "applyChannelParameters": {
490 508 "multiChannelParameter": {
491 "mids": [CAMERA_MID],
509 "mids": [camera_mid],
492 510 "mediaParameter": capabilities.to_string(),
493 511 },
494 512 },
@@ -505,13 +523,23 @@ pub struct SendCapabilityReporter {
505 523
506 524 impl SendCapabilityReporter {
507 525 pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> {
526 self.body_for_mid(CAMERA_MID, size, quality)
527 }
528
529 pub fn body_for_mid(
530 &mut self,
531 camera_mid: &str,
532 size: (u32, u32),
533 quality: VideoQuality,
534 ) -> Option<Value> {
508 535 if self.last_size == Some(size) && self.last_quality == Some(quality) {
509 536 return None;
510 537 }
511 538 self.last_size.replace(size);
512 539 self.last_quality.replace(quality);
513 540 self.sequence_number += 1;
514 Some(send_capabilities_body(
541 Some(send_capabilities_body_for(
542 camera_mid,
515 543 size.0,
516 544 size.1,
517 545 self.sequence_number,
@@ -842,6 +870,10 @@ mod tests {
842 870 MediaDescription::share(true).wire(),
843 871 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
844 872 );
873 assert_eq!(
874 MediaDescription::camera_line("7", true).wire(),
875 json!({"mid": "7", "direction": "sendrecv", "label": "main-video"})
876 );
845 877 }
846 878
847 879 #[test]
@@ -235,21 +235,29 @@ pub fn add_one_to_one_lines(
235/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
235/// Per-line direction told to the mixer through `updateMediaDescriptions`; no SDP renegotiation.
236#[derive(Debug, Clone, PartialEq, Eq)]
236#[derive(Debug, Clone, PartialEq, Eq)]
237pub struct MediaDescription {
237pub struct MediaDescription {
238 pub mid: &'static str,
238 pub mid: String,
239 pub direction: &'static str,
239 pub direction: &'static str,
240 pub label: Option<&'static str>,
240 pub label: Option<&'static str>,
241}
241}
242
242
243impl MediaDescription {
243impl MediaDescription {
244 pub fn camera(sending: bool) -> Self {
244 pub fn camera(sending: bool) -> Self {
245 Self::line(CAMERA_MID, sending, CAMERA_LINE_LABEL)
245 Self::camera_line(CAMERA_MID, sending)
246 }
246 }
247
247
248 pub fn share(sending: bool) -> Self {
248 pub fn share(sending: bool) -> Self {
249 Self::line(SHARE_MID, sending, SHARE_LINE_LABEL)
249 Self::share_line(SHARE_MID, sending)
250 }
251
252 pub fn camera_line(mid: impl Into<String>, sending: bool) -> Self {
253 Self::line(mid.into(), sending, CAMERA_LINE_LABEL)
254 }
255
256 pub fn share_line(mid: impl Into<String>, sending: bool) -> Self {
257 Self::line(mid.into(), sending, SHARE_LINE_LABEL)
250 }
258 }
251
259
252 fn line(mid: &'static str, sending: bool, label: &'static str) -> Self {
260 fn line(mid: String, sending: bool, label: &'static str) -> Self {
253 if sending {
261 if sending {
254 MediaDescription {
262 MediaDescription {
255 mid,
263 mid,
@@ -465,6 +473,16 @@ pub fn send_capabilities_body(
465 height: u32,
473 height: u32,
466 sequence_number: u64,
474 sequence_number: u64,
467 quality: VideoQuality,
475 quality: VideoQuality,
476) -> Value {
477 send_capabilities_body_for(CAMERA_MID, width, height, sequence_number, quality)
478}
479
480pub fn send_capabilities_body_for(
481 camera_mid: &str,
482 width: u32,
483 height: u32,
484 sequence_number: u64,
485 quality: VideoQuality,
468) -> Value {
486) -> Value {
469 let ceiling = quality.capture_height().max(quality.capture_width());
487 let ceiling = quality.capture_height().max(quality.capture_width());
470 let width = width.min(ceiling);
488 let width = width.min(ceiling);
@@ -488,7 +506,7 @@ pub fn send_capabilities_body(
488 json!({
506 json!({
489 "applyChannelParameters": {
507 "applyChannelParameters": {
490 "multiChannelParameter": {
508 "multiChannelParameter": {
491 "mids": [CAMERA_MID],
509 "mids": [camera_mid],
492 "mediaParameter": capabilities.to_string(),
510 "mediaParameter": capabilities.to_string(),
493 },
511 },
494 },
512 },
@@ -505,13 +523,23 @@ pub struct SendCapabilityReporter {
505
523
506impl SendCapabilityReporter {
524impl SendCapabilityReporter {
507 pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> {
525 pub fn body_for(&mut self, size: (u32, u32), quality: VideoQuality) -> Option<Value> {
526 self.body_for_mid(CAMERA_MID, size, quality)
527 }
528
529 pub fn body_for_mid(
530 &mut self,
531 camera_mid: &str,
532 size: (u32, u32),
533 quality: VideoQuality,
534 ) -> Option<Value> {
508 if self.last_size == Some(size) && self.last_quality == Some(quality) {
535 if self.last_size == Some(size) && self.last_quality == Some(quality) {
509 return None;
536 return None;
510 }
537 }
511 self.last_size.replace(size);
538 self.last_size.replace(size);
512 self.last_quality.replace(quality);
539 self.last_quality.replace(quality);
513 self.sequence_number += 1;
540 self.sequence_number += 1;
514 Some(send_capabilities_body(
541 Some(send_capabilities_body_for(
542 camera_mid,
515 size.0,
543 size.0,
516 size.1,
544 size.1,
517 self.sequence_number,
545 self.sequence_number,
@@ -842,6 +870,10 @@ mod tests {
842 MediaDescription::share(true).wire(),
870 MediaDescription::share(true).wire(),
843 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
871 json!({"mid": "11", "direction": "sendrecv", "label": "applicationsharing-video"})
844 );
872 );
873 assert_eq!(
874 MediaDescription::camera_line("7", true).wire(),
875 json!({"mid": "7", "direction": "sendrecv", "label": "main-video"})
876 );
845 }
877 }
846
878
847 #[test]
879 #[test]
crates/calling/src/video_quality.rs +10 −10
@@ -8,11 +8,10 @@ pub enum VideoQuality {
8 8 }
9 9
10 10 impl VideoQuality {
11 /// Preferred capture height for this choice (Auto prefers 1080).
12 11 pub fn capture_height(self) -> u32 {
13 12 match self {
14 Self::P720 => 720,
15 Self::Auto | Self::P1080 => 1080,
13 Self::Auto | Self::P720 => 720,
14 Self::P1080 => 1080,
16 15 }
17 16 }
18 17
@@ -23,8 +22,8 @@ impl VideoQuality {
23 22 /// Highest sensor height we may open before downscaling to the capture ceiling.
24 23 pub fn largest_sensor_height(self) -> u32 {
25 24 match self {
26 Self::P720 => 1080,
27 Self::Auto | Self::P1080 => 1440,
25 Self::Auto | Self::P720 => 1080,
26 Self::P1080 => 1440,
28 27 }
29 28 }
30 29
@@ -50,12 +49,13 @@ mod tests {
50 49 use super::*;
51 50
52 51 #[test]
53 fn auto_and_1080_share_a_1080_capture_ceiling() {
54 assert_eq!(VideoQuality::Auto.capture_height(), 1080);
55 assert_eq!(VideoQuality::P1080.capture_height(), 1080);
52 fn auto_and_720_share_a_720_capture_ceiling() {
53 assert_eq!(VideoQuality::Auto.capture_height(), 720);
56 54 assert_eq!(VideoQuality::P720.capture_height(), 720);
57 assert_eq!(VideoQuality::Auto.capture_width(), 1920);
58 assert_eq!(VideoQuality::P720.capture_width(), 1280);
55 assert_eq!(VideoQuality::P1080.capture_height(), 1080);
56 assert_eq!(VideoQuality::Auto.capture_width(), 1280);
57 assert_eq!(VideoQuality::P1080.capture_width(), 1920);
58 assert_eq!(VideoQuality::Auto.largest_sensor_height(), 1080);
59 59 }
60 60
61 61 #[test]
@@ -8,11 +8,10 @@ pub enum VideoQuality {
8}
8}
9
9
10impl VideoQuality {
10impl VideoQuality {
11 /// Preferred capture height for this choice (Auto prefers 1080).
12 pub fn capture_height(self) -> u32 {
11 pub fn capture_height(self) -> u32 {
13 match self {
12 match self {
14 Self::P720 => 720,
13 Self::Auto | Self::P720 => 720,
15 Self::Auto | Self::P1080 => 1080,
14 Self::P1080 => 1080,
16 }
15 }
17 }
16 }
18
17
@@ -23,8 +22,8 @@ impl VideoQuality {
23 /// Highest sensor height we may open before downscaling to the capture ceiling.
22 /// Highest sensor height we may open before downscaling to the capture ceiling.
24 pub fn largest_sensor_height(self) -> u32 {
23 pub fn largest_sensor_height(self) -> u32 {
25 match self {
24 match self {
26 Self::P720 => 1080,
25 Self::Auto | Self::P720 => 1080,
27 Self::Auto | Self::P1080 => 1440,
26 Self::P1080 => 1440,
28 }
27 }
29 }
28 }
30
29
@@ -50,12 +49,13 @@ mod tests {
50 use super::*;
49 use super::*;
51
50
52 #[test]
51 #[test]
53 fn auto_and_1080_share_a_1080_capture_ceiling() {
52 fn auto_and_720_share_a_720_capture_ceiling() {
54 assert_eq!(VideoQuality::Auto.capture_height(), 1080);
53 assert_eq!(VideoQuality::Auto.capture_height(), 720);
55 assert_eq!(VideoQuality::P1080.capture_height(), 1080);
56 assert_eq!(VideoQuality::P720.capture_height(), 720);
54 assert_eq!(VideoQuality::P720.capture_height(), 720);
57 assert_eq!(VideoQuality::Auto.capture_width(), 1920);
55 assert_eq!(VideoQuality::P1080.capture_height(), 1080);
58 assert_eq!(VideoQuality::P720.capture_width(), 1280);
56 assert_eq!(VideoQuality::Auto.capture_width(), 1280);
57 assert_eq!(VideoQuality::P1080.capture_width(), 1920);
58 assert_eq!(VideoQuality::Auto.largest_sensor_height(), 1080);
59 }
59 }
60
60
61 #[test]
61 #[test]
crates/calling/src/video_receive.rs +6 −0
@@ -186,6 +186,12 @@ impl VideoReceive {
186 186 self.table = table;
187 187 }
188 188
189 pub fn replace_requester(&mut self, requester: SourceRequester) {
190 self.requester = Some(requester);
191 self.held.fill(None);
192 self.screen_held = None;
193 }
194
189 195 pub fn is_ready(&self) -> bool {
190 196 self.requester.is_some() && !self.table.is_empty()
191 197 }
@@ -186,6 +186,12 @@ impl VideoReceive {
186 self.table = table;
186 self.table = table;
187 }
187 }
188
188
189 pub fn replace_requester(&mut self, requester: SourceRequester) {
190 self.requester = Some(requester);
191 self.held.fill(None);
192 self.screen_held = None;
193 }
194
189 pub fn is_ready(&self) -> bool {
195 pub fn is_ready(&self) -> bool {
190 self.requester.is_some() && !self.table.is_empty()
196 self.requester.is_some() && !self.table.is_empty()
191 }
197 }
crates/calling/src/video_send.rs +143 −9
@@ -215,6 +215,7 @@ pub struct LocalVideo {
215 215 /// The desktop dialog already bound the PipeWire stream. Later `StartShare`
216 216 /// commands must attach that capturer, not replace it.
217 217 portal_bound: bool,
218 camera_bitrate_cap: Option<u64>,
218 219 }
219 220
220 221 impl LocalVideo {
@@ -245,6 +246,7 @@ impl LocalVideo {
245 246 portal_armed: false,
246 247 portal_keep: false,
247 248 portal_bound: false,
249 camera_bitrate_cap: None,
248 250 }
249 251 }
250 252
@@ -340,7 +342,10 @@ impl LocalVideo {
340 342 .map(|encoding| encoding.rid)
341 343 .collect();
342 344 if rids.len() > 1 {
343 let plans = plan_layers(limits, frame, &rids);
345 let mut plans = plan_layers(limits, frame, &rids);
346 if source == SendSource::Camera {
347 Self::apply_bitrate_cap_to_plans(&mut plans, self.camera_bitrate_cap);
348 }
344 349 if plans.iter().any(|plan| plan.keyframe) {
345 350 Self::set_layers(&sender, &plans, KEYFRAME_NUDGE)?;
346 351 }
@@ -350,7 +355,12 @@ impl LocalVideo {
350 355 let Some(limit) = limits.first() else {
351 356 return Ok(None);
352 357 };
353 let encoder = encoder_limits(limit, frame);
358 let mut encoder = encoder_limits(limit, frame);
359 if source == SendSource::Camera
360 && let Some(cap) = self.camera_bitrate_cap
361 {
362 encoder.max_bitrate = Some(encoder.max_bitrate.map_or(cap, |max| max.min(cap)));
363 }
354 364 if limit.keyframe {
355 365 Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
356 366 }
@@ -363,6 +373,15 @@ impl LocalVideo {
363 373 }]))
364 374 }
365 375
376 fn apply_bitrate_cap_to_plans(plans: &mut [LayerPlan], cap: Option<u64>) {
377 let Some(cap) = cap else { return };
378 for plan in plans {
379 if let Some(limits) = plan.limits.as_mut() {
380 limits.max_bitrate = Some(limits.max_bitrate.map_or(cap, |max| max.min(cap)));
381 }
382 }
383 }
384
366 385 /// The mixer sends its limits once, often before the first frame tells the size to scale from.
367 386 pub fn refresh_send_limits(&mut self) -> Vec<(SendSource, Result<Option<Vec<LayerPlan>>>)> {
368 387 let mut refreshed = Vec::new();
@@ -437,6 +456,10 @@ impl LocalVideo {
437 456 self.camera.track.clone()
438 457 }
439 458
459 pub fn share_track(&self) -> RtcVideoTrack {
460 self.screen.track.clone()
461 }
462
440 463 pub fn take_effects_failure(&self) -> bool {
441 464 self.blur.take_unavailable()
442 465 }
@@ -455,6 +478,21 @@ impl LocalVideo {
455 478 self.lines.is_some()
456 479 }
457 480
481 pub fn clear_lines(&mut self) {
482 if let Some(lines) = self.lines.take() {
483 let _ = lines.camera.sender().set_track(None);
484 let _ = Self::set_active(&lines.camera.sender(), false);
485 if let Some(share) = lines.share {
486 let _ = share.sender().set_track(None);
487 let _ = Self::set_active(&share.sender(), false);
488 }
489 }
490 }
491
492 pub fn camera_mid(&self) -> Option<String> {
493 self.lines.as_ref().and_then(|lines| lines.camera.mid())
494 }
495
458 496 pub fn share_mid(&self) -> Option<String> {
459 497 self.lines
460 498 .as_ref()
@@ -520,26 +558,81 @@ impl LocalVideo {
520 558 }
521 559
522 560 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
561 self.clear_lines();
523 562 if self.camera_on() {
524 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
563 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
525 564 }
526 565 if self.sharing()
527 566 && let Some(share) = &lines.share
528 567 {
529 Self::begin_sending(&share.sender(), &self.screen.track)?;
568 Self::begin_sending_on(share, &self.screen.track)?;
530 569 }
531 570 self.lines = Some(lines);
532 571 Ok(())
533 572 }
534 573
574 fn ensure_send_direction(transceiver: &RtpTransceiver) -> Result<()> {
575 match transceiver.direction() {
576 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly => Ok(()),
577 RtpTransceiverDirection::RecvOnly | RtpTransceiverDirection::Inactive => transceiver
578 .set_direction(RtpTransceiverDirection::SendRecv)
579 .map_err(|error| Error::Webrtc(error.to_string())),
580 RtpTransceiverDirection::Stopped => Err(Error::Webrtc("video line is stopped".into())),
581 }
582 }
583
584 fn begin_sending_on(transceiver: &RtpTransceiver, track: &RtcVideoTrack) -> Result<()> {
585 Self::ensure_send_direction(transceiver)?;
586 Self::begin_sending(&transceiver.sender(), track)
587 }
588
535 589 fn begin_sending(sender: &RtpSender, track: &RtcVideoTrack) -> Result<()> {
536 590 sender
537 591 .set_track(Some(MediaStreamTrack::Video(track.clone())))
538 592 .map_err(|error| Error::Webrtc(error.to_string()))?;
593 // Prefer dropping resolution over framerate when the uplink is tight.
594 let mut parameters = sender.parameters();
595 parameters.set_degradation_preference(DegradationPreference::MaintainFramerate);
596 sender
597 .set_parameters(parameters)
598 .map_err(|error| Error::Webrtc(error.to_string()))?;
539 599 Self::set_active(sender, true)
540 600 }
541 601
542 fn set_active(sender: &RtpSender, active: bool) -> Result<()> {
602 pub fn cap_camera_bitrate(&mut self, cap: Option<u64>) -> Result<()> {
603 if self.camera_bitrate_cap == cap {
604 return Ok(());
605 }
606 self.camera_bitrate_cap = cap;
607 if let Some(limits) = self
608 .camera
609 .requested
610 .as_ref()
611 .map(|requested| requested.limits.clone())
612 {
613 let _ = self.apply_send_limit(SendSource::Camera, &limits)?;
614 return Ok(());
615 }
616 let Some(sender) = self
617 .sender_of(SendSource::Camera)
618 .filter(|_| self.camera_on())
619 else {
620 return Ok(());
621 };
622 let mut parameters = sender.parameters();
623 for encoding in &mut parameters.encodings {
624 encoding.max_bitrate = match (encoding.max_bitrate, cap) {
625 (Some(max), Some(cap)) => Some(max.min(cap)),
626 (None, Some(cap)) => Some(cap),
627 (max, None) => max,
628 };
629 }
630 sender
631 .set_parameters(parameters)
632 .map_err(|error| Error::Webrtc(error.to_string()))
633 }
634
635 pub(crate) fn set_sender_active(sender: &RtpSender, active: bool) -> Result<()> {
543 636 let mut parameters = sender.parameters();
544 637 for encoding in &mut parameters.encodings {
545 638 encoding.active = active;
@@ -549,6 +642,10 @@ impl LocalVideo {
549 642 .map_err(|error| Error::Webrtc(error.to_string()))
550 643 }
551 644
645 fn set_active(sender: &RtpSender, active: bool) -> Result<()> {
646 Self::set_sender_active(sender, active)
647 }
648
552 649 fn camera_sink(&self) -> LocalSink {
553 650 LocalSink::new(
554 651 self.camera.source.clone(),
@@ -607,12 +704,11 @@ impl LocalVideo {
607 704 if !self.is_available() {
608 705 return Err(Error::Webrtc("video is switched off".into()));
609 706 }
610 let sender = lines.camera.sender();
611 707 if !self.camera_previewing() {
612 708 self.camera.capture = None;
613 709 self.camera.capture = Some(self.capture_camera(choice)?);
614 710 }
615 Self::begin_sending(&sender, &self.camera.track)?;
711 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
616 712 self.camera_preview = false;
617 713 Ok(())
618 714 }
@@ -665,7 +761,7 @@ impl LocalVideo {
665 761 self.camera_preview = preview;
666 762 if !preview {
667 763 if let Some(lines) = self.lines.as_ref() {
668 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
764 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
669 765 }
670 766 }
671 767 Ok(())
@@ -778,7 +874,7 @@ impl LocalVideo {
778 874 };
779 875 self.screen.capture = Some(capture);
780 876 }
781 Self::begin_sending(&share.sender(), &self.screen.track)?;
877 Self::begin_sending_on(&share, &self.screen.track)?;
782 878 let _ = self.tune_share(&share.sender());
783 879 Ok(())
784 880 }
@@ -805,6 +901,9 @@ impl LocalVideo {
805 901 #[cfg(test)]
806 902 mod tests {
807 903 use super::*;
904 use libwebrtc::MediaType;
905 use libwebrtc::peer_connection_factory::RtcConfiguration;
906 use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};
808 907
809 908 #[tokio::test]
810 909 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
@@ -827,6 +926,41 @@ mod tests {
827 926 assert!(!video.camera_previewing() && !video.camera_on());
828 927 }
829 928
929 #[tokio::test]
930 async fn clearing_a_sender_track_does_not_crash() {
931 let factory = crate::devices::shared_factory();
932 let peer = factory
933 .create_peer_connection(RtcConfiguration::default())
934 .expect("peer");
935 let transceiver = peer
936 .add_transceiver_for_media(
937 MediaType::Video,
938 RtpTransceiverInit {
939 direction: RtpTransceiverDirection::SendRecv,
940 stream_ids: vec!["camera".into()],
941 send_encodings: Vec::new(),
942 },
943 )
944 .expect("transceiver");
945 let (updates, _) = tokio::sync::mpsc::unbounded_channel();
946 let video = LocalVideo::new(
947 &factory,
948 VideoMode::Pattern,
949 VideoHub::new(updates.clone()),
950 updates,
951 );
952 let sender = transceiver.sender();
953 sender
954 .set_track(Some(
955 libwebrtc::media_stream_track::MediaStreamTrack::Video(video.camera_track()),
956 ))
957 .expect("attach");
958 // Do not call sender.track() afterwards: the FFI track() wrapper crashes on a null
959 // webrtc track (get_or_create_media_stream_track).
960 sender.set_track(None).expect("detach must accept nullptr");
961 peer.close();
962 }
963
830 964 #[test]
831 965 fn frame_sizes_survive_packing() {
832 966 assert_eq!(unpack_size(pack_size(1280, 720)), Some((1280, 720)));
@@ -215,6 +215,7 @@ pub struct LocalVideo {
215 /// The desktop dialog already bound the PipeWire stream. Later `StartShare`
215 /// The desktop dialog already bound the PipeWire stream. Later `StartShare`
216 /// commands must attach that capturer, not replace it.
216 /// commands must attach that capturer, not replace it.
217 portal_bound: bool,
217 portal_bound: bool,
218 camera_bitrate_cap: Option<u64>,
218}
219}
219
220
220impl LocalVideo {
221impl LocalVideo {
@@ -245,6 +246,7 @@ impl LocalVideo {
245 portal_armed: false,
246 portal_armed: false,
246 portal_keep: false,
247 portal_keep: false,
247 portal_bound: false,
248 portal_bound: false,
249 camera_bitrate_cap: None,
248 }
250 }
249 }
251 }
250
252
@@ -340,7 +342,10 @@ impl LocalVideo {
340 .map(|encoding| encoding.rid)
342 .map(|encoding| encoding.rid)
341 .collect();
343 .collect();
342 if rids.len() > 1 {
344 if rids.len() > 1 {
343 let plans = plan_layers(limits, frame, &rids);
345 let mut plans = plan_layers(limits, frame, &rids);
346 if source == SendSource::Camera {
347 Self::apply_bitrate_cap_to_plans(&mut plans, self.camera_bitrate_cap);
348 }
344 if plans.iter().any(|plan| plan.keyframe) {
349 if plans.iter().any(|plan| plan.keyframe) {
345 Self::set_layers(&sender, &plans, KEYFRAME_NUDGE)?;
350 Self::set_layers(&sender, &plans, KEYFRAME_NUDGE)?;
346 }
351 }
@@ -350,7 +355,12 @@ impl LocalVideo {
350 let Some(limit) = limits.first() else {
355 let Some(limit) = limits.first() else {
351 return Ok(None);
356 return Ok(None);
352 };
357 };
353 let encoder = encoder_limits(limit, frame);
358 let mut encoder = encoder_limits(limit, frame);
359 if source == SendSource::Camera
360 && let Some(cap) = self.camera_bitrate_cap
361 {
362 encoder.max_bitrate = Some(encoder.max_bitrate.map_or(cap, |max| max.min(cap)));
363 }
354 if limit.keyframe {
364 if limit.keyframe {
355 Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
365 Self::set_limits(&sender, &encoder, KEYFRAME_NUDGE)?;
356 }
366 }
@@ -363,6 +373,15 @@ impl LocalVideo {
363 }]))
373 }]))
364 }
374 }
365
375
376 fn apply_bitrate_cap_to_plans(plans: &mut [LayerPlan], cap: Option<u64>) {
377 let Some(cap) = cap else { return };
378 for plan in plans {
379 if let Some(limits) = plan.limits.as_mut() {
380 limits.max_bitrate = Some(limits.max_bitrate.map_or(cap, |max| max.min(cap)));
381 }
382 }
383 }
384
366 /// The mixer sends its limits once, often before the first frame tells the size to scale from.
385 /// The mixer sends its limits once, often before the first frame tells the size to scale from.
367 pub fn refresh_send_limits(&mut self) -> Vec<(SendSource, Result<Option<Vec<LayerPlan>>>)> {
386 pub fn refresh_send_limits(&mut self) -> Vec<(SendSource, Result<Option<Vec<LayerPlan>>>)> {
368 let mut refreshed = Vec::new();
387 let mut refreshed = Vec::new();
@@ -437,6 +456,10 @@ impl LocalVideo {
437 self.camera.track.clone()
456 self.camera.track.clone()
438 }
457 }
439
458
459 pub fn share_track(&self) -> RtcVideoTrack {
460 self.screen.track.clone()
461 }
462
440 pub fn take_effects_failure(&self) -> bool {
463 pub fn take_effects_failure(&self) -> bool {
441 self.blur.take_unavailable()
464 self.blur.take_unavailable()
442 }
465 }
@@ -455,6 +478,21 @@ impl LocalVideo {
455 self.lines.is_some()
478 self.lines.is_some()
456 }
479 }
457
480
481 pub fn clear_lines(&mut self) {
482 if let Some(lines) = self.lines.take() {
483 let _ = lines.camera.sender().set_track(None);
484 let _ = Self::set_active(&lines.camera.sender(), false);
485 if let Some(share) = lines.share {
486 let _ = share.sender().set_track(None);
487 let _ = Self::set_active(&share.sender(), false);
488 }
489 }
490 }
491
492 pub fn camera_mid(&self) -> Option<String> {
493 self.lines.as_ref().and_then(|lines| lines.camera.mid())
494 }
495
458 pub fn share_mid(&self) -> Option<String> {
496 pub fn share_mid(&self) -> Option<String> {
459 self.lines
497 self.lines
460 .as_ref()
498 .as_ref()
@@ -520,26 +558,81 @@ impl LocalVideo {
520 }
558 }
521
559
522 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
560 pub fn set_lines(&mut self, lines: VideoLines) -> Result<()> {
561 self.clear_lines();
523 if self.camera_on() {
562 if self.camera_on() {
524 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
563 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
525 }
564 }
526 if self.sharing()
565 if self.sharing()
527 && let Some(share) = &lines.share
566 && let Some(share) = &lines.share
528 {
567 {
529 Self::begin_sending(&share.sender(), &self.screen.track)?;
568 Self::begin_sending_on(share, &self.screen.track)?;
530 }
569 }
531 self.lines = Some(lines);
570 self.lines = Some(lines);
532 Ok(())
571 Ok(())
533 }
572 }
534
573
574 fn ensure_send_direction(transceiver: &RtpTransceiver) -> Result<()> {
575 match transceiver.direction() {
576 RtpTransceiverDirection::SendRecv | RtpTransceiverDirection::SendOnly => Ok(()),
577 RtpTransceiverDirection::RecvOnly | RtpTransceiverDirection::Inactive => transceiver
578 .set_direction(RtpTransceiverDirection::SendRecv)
579 .map_err(|error| Error::Webrtc(error.to_string())),
580 RtpTransceiverDirection::Stopped => Err(Error::Webrtc("video line is stopped".into())),
581 }
582 }
583
584 fn begin_sending_on(transceiver: &RtpTransceiver, track: &RtcVideoTrack) -> Result<()> {
585 Self::ensure_send_direction(transceiver)?;
586 Self::begin_sending(&transceiver.sender(), track)
587 }
588
535 fn begin_sending(sender: &RtpSender, track: &RtcVideoTrack) -> Result<()> {
589 fn begin_sending(sender: &RtpSender, track: &RtcVideoTrack) -> Result<()> {
536 sender
590 sender
537 .set_track(Some(MediaStreamTrack::Video(track.clone())))
591 .set_track(Some(MediaStreamTrack::Video(track.clone())))
538 .map_err(|error| Error::Webrtc(error.to_string()))?;
592 .map_err(|error| Error::Webrtc(error.to_string()))?;
593 // Prefer dropping resolution over framerate when the uplink is tight.
594 let mut parameters = sender.parameters();
595 parameters.set_degradation_preference(DegradationPreference::MaintainFramerate);
596 sender
597 .set_parameters(parameters)
598 .map_err(|error| Error::Webrtc(error.to_string()))?;
539 Self::set_active(sender, true)
599 Self::set_active(sender, true)
540 }
600 }
541
601
542 fn set_active(sender: &RtpSender, active: bool) -> Result<()> {
602 pub fn cap_camera_bitrate(&mut self, cap: Option<u64>) -> Result<()> {
603 if self.camera_bitrate_cap == cap {
604 return Ok(());
605 }
606 self.camera_bitrate_cap = cap;
607 if let Some(limits) = self
608 .camera
609 .requested
610 .as_ref()
611 .map(|requested| requested.limits.clone())
612 {
613 let _ = self.apply_send_limit(SendSource::Camera, &limits)?;
614 return Ok(());
615 }
616 let Some(sender) = self
617 .sender_of(SendSource::Camera)
618 .filter(|_| self.camera_on())
619 else {
620 return Ok(());
621 };
622 let mut parameters = sender.parameters();
623 for encoding in &mut parameters.encodings {
624 encoding.max_bitrate = match (encoding.max_bitrate, cap) {
625 (Some(max), Some(cap)) => Some(max.min(cap)),
626 (None, Some(cap)) => Some(cap),
627 (max, None) => max,
628 };
629 }
630 sender
631 .set_parameters(parameters)
632 .map_err(|error| Error::Webrtc(error.to_string()))
633 }
634
635 pub(crate) fn set_sender_active(sender: &RtpSender, active: bool) -> Result<()> {
543 let mut parameters = sender.parameters();
636 let mut parameters = sender.parameters();
544 for encoding in &mut parameters.encodings {
637 for encoding in &mut parameters.encodings {
545 encoding.active = active;
638 encoding.active = active;
@@ -549,6 +642,10 @@ impl LocalVideo {
549 .map_err(|error| Error::Webrtc(error.to_string()))
642 .map_err(|error| Error::Webrtc(error.to_string()))
550 }
643 }
551
644
645 fn set_active(sender: &RtpSender, active: bool) -> Result<()> {
646 Self::set_sender_active(sender, active)
647 }
648
552 fn camera_sink(&self) -> LocalSink {
649 fn camera_sink(&self) -> LocalSink {
553 LocalSink::new(
650 LocalSink::new(
554 self.camera.source.clone(),
651 self.camera.source.clone(),
@@ -607,12 +704,11 @@ impl LocalVideo {
607 if !self.is_available() {
704 if !self.is_available() {
608 return Err(Error::Webrtc("video is switched off".into()));
705 return Err(Error::Webrtc("video is switched off".into()));
609 }
706 }
610 let sender = lines.camera.sender();
611 if !self.camera_previewing() {
707 if !self.camera_previewing() {
612 self.camera.capture = None;
708 self.camera.capture = None;
613 self.camera.capture = Some(self.capture_camera(choice)?);
709 self.camera.capture = Some(self.capture_camera(choice)?);
614 }
710 }
615 Self::begin_sending(&sender, &self.camera.track)?;
711 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
616 self.camera_preview = false;
712 self.camera_preview = false;
617 Ok(())
713 Ok(())
618 }
714 }
@@ -665,7 +761,7 @@ impl LocalVideo {
665 self.camera_preview = preview;
761 self.camera_preview = preview;
666 if !preview {
762 if !preview {
667 if let Some(lines) = self.lines.as_ref() {
763 if let Some(lines) = self.lines.as_ref() {
668 Self::begin_sending(&lines.camera.sender(), &self.camera.track)?;
764 Self::begin_sending_on(&lines.camera, &self.camera.track)?;
669 }
765 }
670 }
766 }
671 Ok(())
767 Ok(())
@@ -778,7 +874,7 @@ impl LocalVideo {
778 };
874 };
779 self.screen.capture = Some(capture);
875 self.screen.capture = Some(capture);
780 }
876 }
781 Self::begin_sending(&share.sender(), &self.screen.track)?;
877 Self::begin_sending_on(&share, &self.screen.track)?;
782 let _ = self.tune_share(&share.sender());
878 let _ = self.tune_share(&share.sender());
783 Ok(())
879 Ok(())
784 }
880 }
@@ -805,6 +901,9 @@ impl LocalVideo {
805#[cfg(test)]
901#[cfg(test)]
806mod tests {
902mod tests {
807 use super::*;
903 use super::*;
904 use libwebrtc::MediaType;
905 use libwebrtc::peer_connection_factory::RtcConfiguration;
906 use libwebrtc::rtp_transceiver::{RtpTransceiverDirection, RtpTransceiverInit};
808
907
809 #[tokio::test]
908 #[tokio::test]
810 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
909 async fn a_camera_preview_runs_without_a_line_and_stops_cleanly() {
@@ -827,6 +926,41 @@ mod tests {
827 assert!(!video.camera_previewing() && !video.camera_on());
926 assert!(!video.camera_previewing() && !video.camera_on());
828 }
927 }
829
928
929 #[tokio::test]
930 async fn clearing_a_sender_track_does_not_crash() {
931 let factory = crate::devices::shared_factory();
932 let peer = factory
933 .create_peer_connection(RtcConfiguration::default())
934 .expect("peer");
935 let transceiver = peer
936 .add_transceiver_for_media(
937 MediaType::Video,
938 RtpTransceiverInit {
939 direction: RtpTransceiverDirection::SendRecv,
940 stream_ids: vec!["camera".into()],
941 send_encodings: Vec::new(),
942 },
943 )
944 .expect("transceiver");
945 let (updates, _) = tokio::sync::mpsc::unbounded_channel();
946 let video = LocalVideo::new(
947 &factory,
948 VideoMode::Pattern,
949 VideoHub::new(updates.clone()),
950 updates,
951 );
952 let sender = transceiver.sender();
953 sender
954 .set_track(Some(
955 libwebrtc::media_stream_track::MediaStreamTrack::Video(video.camera_track()),
956 ))
957 .expect("attach");
958 // Do not call sender.track() afterwards: the FFI track() wrapper crashes on a null
959 // webrtc track (get_or_create_media_stream_track).
960 sender.set_track(None).expect("detach must accept nullptr");
961 peer.close();
962 }
963
830 #[test]
964 #[test]
831 fn frame_sizes_survive_packing() {
965 fn frame_sizes_survive_packing() {
832 assert_eq!(unpack_size(pack_size(1280, 720)), Some((1280, 720)));
966 assert_eq!(unpack_size(pack_size(1280, 720)), Some((1280, 720)));
docs/research/internal-endpoints.md +1 −1
@@ -146,7 +146,7 @@ Token audiences (not requests): `crates/session/src/scope.rs` - `ic3.teams.offic
146 146 | `api-emea.flightproxy.teams.microsoft.com/api/v2/epconv` | POST | `crates/calling/src/signaling.rs` | create conversation, subscribe meeting, resolve meeting id | W | no - `/communications/calls` is app-only (bot registration), not a user client |
147 147 | `api.flightproxy.teams.microsoft.com/api/v2/ep/{cc or conv host}/{path}` | as link | `crates/calling/src/signaling.rs` (`routed_url`) | transport for every `*.cc.skype.com` / `*.conv.skype.com` link | R/W | no |
148 148 | conversation controller links (server-provided): join, end for all, broker poll, updateEndpointState, publishState, removeState, sendMessage, addParticipant(AndModality), updateEndpointMetadata, admit, removeParticipant, mute, updateMeetingSettings, updateParticipantRole, notificationLinks, leave, transfer | POST, PUT, GET, DELETE | `crates/calling/src/signaling.rs` | meeting join, roster, hand raise, spotlight, reactions, invite, lobby, mute, lock, roles, keep-alive, leave, transfer | R/W | no - no user-token call control in Graph; `updateMeetingSettings` partly via onlineMeeting PATCH |
149 | call leg links (server-provided, `*.cc.skype.com`): attach, progress, acceptance, callLeg, rejection, mediaAcknowledgement, applyChannelParameters, controlVideoStreaming, mediaAnswer, updateMediaDescriptions | POST, DELETE | `crates/calling/src/signaling.rs`, `crates/calling/src/call.rs`, `crates/calling/src/push.rs`, `crates/calling/src/engine.rs` | incoming call, SDP offer / answer, ringing, decline, keep-alive, renegotiation, video layout | W | no |
149 | call leg links (server-provided, `*.cc.skype.com`): attach, progress, acceptance, callLeg, rejection, mediaAcknowledgement, applyChannelParameters, controlVideoStreaming, mediaAnswer, updateMediaDescriptions | POST, DELETE | `crates/calling/src/signaling.rs`, `crates/calling/src/call.rs`, `crates/calling/src/push.rs`, `crates/calling/src/engine.rs` | incoming call, SDP offer / answer, ringing, decline, hangup, keep-alive, renegotiation, video layout | W | no |
150 150 | recording / caption bot command URL (from roster) | POST | `crates/calling/src/signaling.rs`, `crates/calling/assets/caption_command.js` | recording start / stop, captions on / off, caption language | W | no - Graph only has post-meeting recordings and transcripts |
151 151 | `teams.cloud.microsoft/api/authsvc/v1.0/authz` | POST | `crates/calling/assets/caption_command.js` | Skype token for the bot command | R | no |
152 152 | `teams.microsoft.com/trap/tokens` | GET | `crates/calling/src/relay.rs` | TURN credentials | R | no |
@@ -146,7 +146,7 @@ Token audiences (not requests): `crates/session/src/scope.rs` - `ic3.teams.offic
146| `api-emea.flightproxy.teams.microsoft.com/api/v2/epconv` | POST | `crates/calling/src/signaling.rs` | create conversation, subscribe meeting, resolve meeting id | W | no - `/communications/calls` is app-only (bot registration), not a user client |
146| `api-emea.flightproxy.teams.microsoft.com/api/v2/epconv` | POST | `crates/calling/src/signaling.rs` | create conversation, subscribe meeting, resolve meeting id | W | no - `/communications/calls` is app-only (bot registration), not a user client |
147| `api.flightproxy.teams.microsoft.com/api/v2/ep/{cc or conv host}/{path}` | as link | `crates/calling/src/signaling.rs` (`routed_url`) | transport for every `*.cc.skype.com` / `*.conv.skype.com` link | R/W | no |
147| `api.flightproxy.teams.microsoft.com/api/v2/ep/{cc or conv host}/{path}` | as link | `crates/calling/src/signaling.rs` (`routed_url`) | transport for every `*.cc.skype.com` / `*.conv.skype.com` link | R/W | no |
148| conversation controller links (server-provided): join, end for all, broker poll, updateEndpointState, publishState, removeState, sendMessage, addParticipant(AndModality), updateEndpointMetadata, admit, removeParticipant, mute, updateMeetingSettings, updateParticipantRole, notificationLinks, leave, transfer | POST, PUT, GET, DELETE | `crates/calling/src/signaling.rs` | meeting join, roster, hand raise, spotlight, reactions, invite, lobby, mute, lock, roles, keep-alive, leave, transfer | R/W | no - no user-token call control in Graph; `updateMeetingSettings` partly via onlineMeeting PATCH |
148| conversation controller links (server-provided): join, end for all, broker poll, updateEndpointState, publishState, removeState, sendMessage, addParticipant(AndModality), updateEndpointMetadata, admit, removeParticipant, mute, updateMeetingSettings, updateParticipantRole, notificationLinks, leave, transfer | POST, PUT, GET, DELETE | `crates/calling/src/signaling.rs` | meeting join, roster, hand raise, spotlight, reactions, invite, lobby, mute, lock, roles, keep-alive, leave, transfer | R/W | no - no user-token call control in Graph; `updateMeetingSettings` partly via onlineMeeting PATCH |
149| call leg links (server-provided, `*.cc.skype.com`): attach, progress, acceptance, callLeg, rejection, mediaAcknowledgement, applyChannelParameters, controlVideoStreaming, mediaAnswer, updateMediaDescriptions | POST, DELETE | `crates/calling/src/signaling.rs`, `crates/calling/src/call.rs`, `crates/calling/src/push.rs`, `crates/calling/src/engine.rs` | incoming call, SDP offer / answer, ringing, decline, keep-alive, renegotiation, video layout | W | no |
149| call leg links (server-provided, `*.cc.skype.com`): attach, progress, acceptance, callLeg, rejection, mediaAcknowledgement, applyChannelParameters, controlVideoStreaming, mediaAnswer, updateMediaDescriptions | POST, DELETE | `crates/calling/src/signaling.rs`, `crates/calling/src/call.rs`, `crates/calling/src/push.rs`, `crates/calling/src/engine.rs` | incoming call, SDP offer / answer, ringing, decline, hangup, keep-alive, renegotiation, video layout | W | no |
150| recording / caption bot command URL (from roster) | POST | `crates/calling/src/signaling.rs`, `crates/calling/assets/caption_command.js` | recording start / stop, captions on / off, caption language | W | no - Graph only has post-meeting recordings and transcripts |
150| recording / caption bot command URL (from roster) | POST | `crates/calling/src/signaling.rs`, `crates/calling/assets/caption_command.js` | recording start / stop, captions on / off, caption language | W | no - Graph only has post-meeting recordings and transcripts |
151| `teams.cloud.microsoft/api/authsvc/v1.0/authz` | POST | `crates/calling/assets/caption_command.js` | Skype token for the bot command | R | no |
151| `teams.cloud.microsoft/api/authsvc/v1.0/authz` | POST | `crates/calling/assets/caption_command.js` | Skype token for the bot command | R | no |
152| `teams.microsoft.com/trap/tokens` | GET | `crates/calling/src/relay.rs` | TURN credentials | R | no |
152| `teams.microsoft.com/trap/tokens` | GET | `crates/calling/src/relay.rs` | TURN credentials | R | no |
vendor/libwebrtc/src/native/rtp_transceiver.rs +6 −0
@@ -78,6 +78,12 @@ impl RtpTransceiver {
78 78 self.sys_handle.direction().into()
79 79 }
80 80
81 pub fn set_direction(&self, direction: RtpTransceiverDirection) -> Result<(), RtcError> {
82 self.sys_handle
83 .set_direction(direction.into())
84 .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() })
85 }
86
81 87 pub fn sender(&self) -> rtp_sender::RtpSender {
82 88 rtp_sender::RtpSender { handle: RtpSender { sys_handle: self.sys_handle.sender() } }
83 89 }
@@ -78,6 +78,12 @@ impl RtpTransceiver {
78 self.sys_handle.direction().into()
78 self.sys_handle.direction().into()
79 }
79 }
80
80
81 pub fn set_direction(&self, direction: RtpTransceiverDirection) -> Result<(), RtcError> {
82 self.sys_handle
83 .set_direction(direction.into())
84 .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() })
85 }
86
81 pub fn sender(&self) -> rtp_sender::RtpSender {
87 pub fn sender(&self) -> rtp_sender::RtpSender {
82 rtp_sender::RtpSender { handle: RtpSender { sys_handle: self.sys_handle.sender() } }
88 rtp_sender::RtpSender { handle: RtpSender { sys_handle: self.sys_handle.sender() } }
83 }
89 }
vendor/libwebrtc/src/rtp_transceiver.rs +4 −0
@@ -56,6 +56,10 @@ impl RtpTransceiver {
56 56 self.handle.direction()
57 57 }
58 58
59 pub fn set_direction(&self, direction: RtpTransceiverDirection) -> Result<(), RtcError> {
60 self.handle.set_direction(direction)
61 }
62
59 63 pub fn sender(&self) -> RtpSender {
60 64 self.handle.sender()
61 65 }
@@ -56,6 +56,10 @@ impl RtpTransceiver {
56 self.handle.direction()
56 self.handle.direction()
57 }
57 }
58
58
59 pub fn set_direction(&self, direction: RtpTransceiverDirection) -> Result<(), RtcError> {
60 self.handle.set_direction(direction)
61 }
62
59 pub fn sender(&self) -> RtpSender {
63 pub fn sender(&self) -> RtpSender {
60 self.handle.sender()
64 self.handle.sender()
61 }
65 }
vendor/webrtc-sys/src/rtp_sender.cpp +2 −1
@@ -149,7 +149,8 @@ RtpSender::RtpSender(
149 149 peer_connection_(std::move(peer_connection)) {}
150 150
151 151 bool RtpSender::set_track(std::shared_ptr<MediaStreamTrack> track) const {
152 return sender_->SetTrack(track->rtc_track().get());
152 // An empty track clears the sender (clear_lines on a peer switch).
153 return sender_->SetTrack(track ? track->rtc_track().get() : nullptr);
153 154 }
154 155
155 156 std::shared_ptr<MediaStreamTrack> RtpSender::track() const {
@@ -149,7 +149,8 @@ RtpSender::RtpSender(
149 peer_connection_(std::move(peer_connection)) {}
149 peer_connection_(std::move(peer_connection)) {}
150
150
151bool RtpSender::set_track(std::shared_ptr<MediaStreamTrack> track) const {
151bool RtpSender::set_track(std::shared_ptr<MediaStreamTrack> track) const {
152 return sender_->SetTrack(track->rtc_track().get());
152 // An empty track clears the sender (clear_lines on a peer switch).
153 return sender_->SetTrack(track ? track->rtc_track().get() : nullptr);
153}
154}
154
155
155std::shared_ptr<MediaStreamTrack> RtpSender::track() const {
156std::shared_ptr<MediaStreamTrack> RtpSender::track() const {