BlueGit

ict rusty-teams

Files

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

hold.rs

hold.rs 8.2 KiB Download Raw
1use std::collections::HashMap;
2
3use crate::error::Result;
4use crate::sdp::parse;
5
6const DIRECTIONS: [&str; 4] = ["sendrecv", "sendonly", "recvonly", "inactive"];
7pub const INACTIVE: &str = "inactive";
8const REJECTED_PORT: &str = "0";
9const DATA_KINDS: [&str; 2] = ["x-data", "application"];
10const MAIN_VIDEO_LABEL: &str = "main-video";
11
12#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)]
13pub enum HoldState {
14 #[default]
15 Active,
16 Local,
17 Remote,
18}
19
20impl HoldState {
21 pub fn from_flags(local: bool, remote: bool) -> HoldState {
22 if local {
23 HoldState::Local
24 } else if remote {
25 HoldState::Remote
26 } else {
27 HoldState::Active
28 }
29 }
30}
31
32#[derive(Debug, Clone, Copy)]
33pub struct MediaLine<'a> {
34 pub kind: &'a str,
35 pub mid: &'a str,
36}
37
38struct Section {
39 kind: String,
40 mid: String,
41 direction_line: Option<usize>,
42}
43
44fn sections(lines: &[String]) -> Vec<Section> {
45 let mut found: Vec<Section> = Vec::new();
46 for (index, line) in lines.iter().enumerate() {
47 if let Some(rest) = line.strip_prefix("m=") {
48 let kind = rest.split(' ').next().unwrap_or_default().to_owned();
49 found.push(Section { kind, mid: String::new(), direction_line: None });
50 } else if let Some(section) = found.last_mut() {
51 if let Some(mid) = line.strip_prefix("a=mid:") {
52 section.mid = mid.to_owned();
53 } else if line.strip_prefix("a=").is_some_and(|name| DIRECTIONS.contains(&name)) {
54 section.direction_line = Some(index);
55 }
56 }
57 }
58 found
59}
60
61pub fn rewrite_directions(sdp: &str, pick: impl Fn(MediaLine<'_>) -> Option<&'static str>) -> String {
62 let newline = if sdp.contains("\r\n") { "\r\n" } else { "\n" };
63 let mut lines: Vec<String> = sdp.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();
64 for section in sections(&lines) {
65 let Some(direction_line) = section.direction_line else { continue };
66 if let Some(direction) = pick(MediaLine { kind: &section.kind, mid: &section.mid }) {
67 lines[direction_line] = format!("a={direction}");
68 }
69 }
70 lines.join(newline)
71}
72
73fn mirrored(direction: &str) -> &'static str {
74 match direction {
75 "sendonly" => "recvonly",
76 "recvonly" => "sendonly",
77 "inactive" => INACTIVE,
78 _ => "sendrecv",
79 }
80}
81
82pub fn keep_media_running(browser_answer: &str, browser_offer: &str) -> String {
83 let offer_lines: Vec<String> = browser_offer.split('\n').map(|line| line.trim_end_matches('\r').to_owned()).collect();
84 let offered: HashMap<String, &'static str> = sections(&offer_lines)
85 .into_iter()
86 .filter_map(|section| {
87 let direction = offer_lines[section.direction_line?].strip_prefix("a=")?;
88 Some((section.mid, mirrored(direction)))
89 })
90 .collect();
91 rewrite_directions(browser_answer, |line| offered.get(line.mid).copied())
92}
93
94pub fn all_inactive(sdp: &str) -> String {
95 rewrite_directions(sdp, |_| Some(INACTIVE))
96}
97
98pub fn is_hold(teams_sdp: &str) -> Result<bool> {
99 let description = parse(teams_sdp)?;
100 let mut media = description
101 .media
102 .iter()
103 .filter(|line| line.port != REJECTED_PORT && !DATA_KINDS.contains(&line.kind.as_str()))
104 .peekable();
105 if media.peek().is_none() {
106 return Ok(false);
107 }
108 Ok(media.all(|line| line.direction() == Some(INACTIVE)))
109}
110
111pub fn offer_sends_video(teams_sdp: &str) -> bool {
112 parse(teams_sdp).is_ok_and(|description| {
113 description.media.iter().any(|line| {
114 line.kind == "video"
115 && line.port != REJECTED_PORT
116 && line.value("label").is_none_or(|label| label == MAIN_VIDEO_LABEL)
117 && matches!(line.direction(), None | Some("sendrecv" | "sendonly"))
118 })
119 })
120}
121
122pub fn accepted_modalities(video: bool) -> Vec<String> {
123 let mut modalities = vec!["Audio".to_owned()];
124 if video {
125 modalities.push("Video".to_owned());
126 }
127 modalities
128}
129
130#[cfg(test)]
131mod tests {
132 use super::*;
133
134 const OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1 2\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=mid:0\r\na=sendrecv\r\na=rtpmap:111 opus/48000/2\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:1\r\na=sendrecv\r\na=rtpmap:102 H264/90000\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=mid:2\r\na=recvonly\r\na=rtpmap:102 H264/90000\r\n";
135
136 fn directions(sdp: &str) -> Vec<String> {
137 parse(sdp).unwrap().media.iter().map(|line| line.direction().unwrap_or("none").to_owned()).collect()
138 }
139
140 #[test]
141 fn holding_puts_every_line_on_inactive_and_nothing_else_changes() {
142 let held = all_inactive(OFFER);
143 assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);
144 assert_eq!(held.lines().count(), OFFER.lines().count());
145 assert!(held.contains("a=mid:2\r\na=inactive\r\n"));
146 assert!(held.ends_with("\r\n"));
147 }
148
149 #[test]
150 fn resuming_keeps_the_offer_as_libwebrtc_wrote_it() {
151 let resumed = rewrite_directions(OFFER, |_| None);
152 assert_eq!(resumed, OFFER);
153 assert_eq!(directions(&resumed), vec!["sendrecv", "sendrecv", "recvonly"]);
154 }
155
156 #[test]
157 fn single_lines_can_be_picked_by_kind_and_mid() {
158 let picked = rewrite_directions(OFFER, |line| match (line.kind, line.mid) {
159 ("video", "1") => Some("inactive"),
160 ("video", "2") => Some("sendonly"),
161 _ => None,
162 });
163 assert_eq!(directions(&picked), vec!["sendrecv", "inactive", "sendonly"]);
164 }
165
166 #[test]
167 fn plain_line_feeds_survive() {
168 let unix = OFFER.replace("\r\n", "\n");
169 let held = all_inactive(&unix);
170 assert!(!held.contains('\r'));
171 assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);
172 }
173
174 #[test]
175 fn a_hold_answer_mirrors_our_offer_so_nothing_stops_locally() {
176 let answer = all_inactive(&OFFER.replace("a=setup:actpass", "a=setup:passive"));
177 let kept = keep_media_running(&answer, OFFER);
178 assert_eq!(directions(&kept), vec!["sendrecv", "sendrecv", "sendonly"]);
179 assert_eq!(kept.lines().count(), answer.lines().count());
180 }
181
182 #[test]
183 fn a_hold_is_every_audio_and_video_line_inactive() {
184 assert!(is_hold(&all_inactive(OFFER)).unwrap());
185 assert!(!is_hold(OFFER).unwrap());
186 let sendonly_audio = rewrite_directions(&all_inactive(OFFER), |line| (line.kind == "audio").then_some("sendonly"));
187 assert!(!is_hold(&sendonly_audio).unwrap());
188 }
189
190 #[test]
191 fn rejected_and_data_lines_do_not_stop_a_hold() {
192 let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\na=mid:0\r\na=inactive\r\nm=video 0 RTP/SAVP 102\r\na=mid:1\r\na=inactive\r\nm=x-data 1234 RTP/SAVP 127\r\na=mid:2\r\na=sendrecv\r\n";
193 assert!(is_hold(teams).unwrap());
194 assert!(!is_hold("v=0\r\ns=-\r\nt=0 0\r\n").unwrap());
195 }
196
197 #[test]
198 fn an_offer_with_a_sending_main_video_line_is_a_video_call() {
199 let teams = |direction: &str, label: &str| format!("v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\nm=audio 1234 RTP/SAVP 111\r\na=mid:0\r\na=sendrecv\r\nm=video 1234 RTP/SAVP 102\r\na=mid:1\r\na={direction}\r\na=label:{label}\r\n");
200 assert!(offer_sends_video(&teams("sendrecv", "main-video")));
201 assert!(offer_sends_video(&teams("sendonly", "main-video")));
202 assert!(!offer_sends_video(&teams("recvonly", "main-video")));
203 assert!(!offer_sends_video(&teams("inactive", "main-video")));
204 assert!(!offer_sends_video(&teams("sendrecv", "applicationsharing-video")));
205 }
206
207 #[test]
208 fn the_hold_state_prefers_your_own_hold() {
209 assert_eq!(HoldState::from_flags(false, false), HoldState::Active);
210 assert_eq!(HoldState::from_flags(true, true), HoldState::Local);
211 assert_eq!(HoldState::from_flags(false, true), HoldState::Remote);
212 }
213
214 #[test]
215 fn accepting_with_video_adds_the_modality() {
216 assert_eq!(accepted_modalities(false), vec!["Audio"]);
217 assert_eq!(accepted_modalities(true), vec!["Audio", "Video"]);
218 }
219}