BlueGit

ict rusty-teams

Files

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

hold.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
hold.rs 11.1 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 {
50 kind,
51 mid: String::new(),
52 direction_line: None,
53 });
54 } else if let Some(section) = found.last_mut() {
55 if let Some(mid) = line.strip_prefix("a=mid:") {
56 section.mid = mid.to_owned();
57 } else if line
58 .strip_prefix("a=")
59 .is_some_and(|name| DIRECTIONS.contains(&name))
60 {
61 section.direction_line = Some(index);
62 }
63 }
64 }
65 found
66}
67
68pub fn rewrite_directions(
69 sdp: &str,
70 pick: impl Fn(MediaLine<'_>) -> Option<&'static str>,
71) -> String {
72 let newline = if sdp.contains("\r\n") { "\r\n" } else { "\n" };
73 let mut lines: Vec<String> = sdp
74 .split('\n')
75 .map(|line| line.trim_end_matches('\r').to_owned())
76 .collect();
77 for section in sections(&lines) {
78 let Some(direction_line) = section.direction_line else {
79 continue;
80 };
81 if let Some(direction) = pick(MediaLine {
82 kind: &section.kind,
83 mid: &section.mid,
84 }) {
85 lines[direction_line] = format!("a={direction}");
86 }
87 }
88 lines.join(newline)
89}
90
91pub fn direction_of(sdp: &str, mid: &str) -> Option<String> {
92 let lines: Vec<String> = sdp
93 .split('\n')
94 .map(|line| line.trim_end_matches('\r').to_owned())
95 .collect();
96 sections(&lines)
97 .into_iter()
98 .find(|section| section.mid == mid)
99 .and_then(|section| section.direction_line)
100 .and_then(|line| lines[line].strip_prefix("a=").map(str::to_owned))
101}
102
103pub fn stop_sending_on(sdp: &str, mid: &str) -> String {
104 let newline = if sdp.contains("\r\n") { "\r\n" } else { "\n" };
105 let mut lines: Vec<String> = sdp
106 .split('\n')
107 .map(|line| line.trim_end_matches('\r').to_owned())
108 .collect();
109 for section in sections(&lines) {
110 let Some(direction_line) = section.direction_line else {
111 continue;
112 };
113 if section.mid != mid {
114 continue;
115 }
116 let receive_only = match lines[direction_line].as_str() {
117 "a=sendrecv" => "recvonly",
118 "a=sendonly" => INACTIVE,
119 _ => continue,
120 };
121 lines[direction_line] = format!("a={receive_only}");
122 }
123 lines.join(newline)
124}
125
126fn mirrored(direction: &str) -> &'static str {
127 match direction {
128 "sendonly" => "recvonly",
129 "recvonly" => "sendonly",
130 "inactive" => INACTIVE,
131 _ => "sendrecv",
132 }
133}
134
135pub fn keep_media_running(browser_answer: &str, browser_offer: &str) -> String {
136 let offer_lines: Vec<String> = browser_offer
137 .split('\n')
138 .map(|line| line.trim_end_matches('\r').to_owned())
139 .collect();
140 let offered: HashMap<String, &'static str> = sections(&offer_lines)
141 .into_iter()
142 .filter_map(|section| {
143 let direction = offer_lines[section.direction_line?].strip_prefix("a=")?;
144 Some((section.mid, mirrored(direction)))
145 })
146 .collect();
147 rewrite_directions(browser_answer, |line| offered.get(line.mid).copied())
148}
149
150pub fn all_inactive(sdp: &str) -> String {
151 rewrite_directions(sdp, |_| Some(INACTIVE))
152}
153
154pub fn is_hold(teams_sdp: &str) -> Result<bool> {
155 let description = parse(teams_sdp)?;
156 let mut media = description
157 .media
158 .iter()
159 .filter(|line| line.port != REJECTED_PORT && !DATA_KINDS.contains(&line.kind.as_str()))
160 .peekable();
161 if media.peek().is_none() {
162 return Ok(false);
163 }
164 Ok(media.all(|line| line.direction() == Some(INACTIVE)))
165}
166
167pub fn offer_sends_video(teams_sdp: &str) -> bool {
168 parse(teams_sdp).is_ok_and(|description| {
169 description.media.iter().any(|line| {
170 line.kind == "video"
171 && line.port != REJECTED_PORT
172 && line
173 .value("label")
174 .is_none_or(|label| label == MAIN_VIDEO_LABEL)
175 && matches!(line.direction(), None | Some("sendrecv" | "sendonly"))
176 })
177 })
178}
179
180pub fn offer_modalities(video: bool, sharing: bool) -> Vec<String> {
181 let mut modalities = accepted_modalities(video);
182 if sharing {
183 modalities.push(SCREEN_SHARER.to_owned());
184 }
185 modalities
186}
187
188const SCREEN_SHARER: &str = "ScreenSharer";
189
190pub fn accepted_modalities(video: bool) -> Vec<String> {
191 let mut modalities = vec!["Audio".to_owned()];
192 if video {
193 modalities.push("Video".to_owned());
194 }
195 modalities
196}
197
198#[cfg(test)]
199mod tests {
200 #[test]
201 fn the_direction_of_a_line_is_read_by_mid() {
202 let sdp = "v=0\r\nm=audio 9 RTP 0\r\na=mid:0\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:2\r\na=recvonly\r\n";
203 assert_eq!(super::direction_of(sdp, "2").as_deref(), Some("recvonly"));
204 assert_eq!(super::direction_of(sdp, "7"), None);
205 }
206
207 #[test]
208 fn a_line_that_stops_sending_keeps_receiving() {
209 let sdp = "v=0\r\nm=audio 9 RTP 0\r\na=mid:0\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:1\r\na=sendrecv\r\nm=video 9 RTP 96\r\na=mid:2\r\na=sendonly\r\n";
210 let camera_off = super::stop_sending_on(sdp, "1");
211 assert!(camera_off.contains("a=mid:1\r\na=recvonly"));
212 assert!(camera_off.contains("a=mid:0\r\na=sendrecv"));
213 assert!(super::stop_sending_on(sdp, "2").contains("a=mid:2\r\na=inactive"));
214 }
215
216 use super::*;
217
218 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";
219
220 fn directions(sdp: &str) -> Vec<String> {
221 parse(sdp)
222 .unwrap()
223 .media
224 .iter()
225 .map(|line| line.direction().unwrap_or("none").to_owned())
226 .collect()
227 }
228
229 #[test]
230 fn holding_puts_every_line_on_inactive_and_nothing_else_changes() {
231 let held = all_inactive(OFFER);
232 assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);
233 assert_eq!(held.lines().count(), OFFER.lines().count());
234 assert!(held.contains("a=mid:2\r\na=inactive\r\n"));
235 assert!(held.ends_with("\r\n"));
236 }
237
238 #[test]
239 fn resuming_keeps_the_offer_as_libwebrtc_wrote_it() {
240 let resumed = rewrite_directions(OFFER, |_| None);
241 assert_eq!(resumed, OFFER);
242 assert_eq!(
243 directions(&resumed),
244 vec!["sendrecv", "sendrecv", "recvonly"]
245 );
246 }
247
248 #[test]
249 fn single_lines_can_be_picked_by_kind_and_mid() {
250 let picked = rewrite_directions(OFFER, |line| match (line.kind, line.mid) {
251 ("video", "1") => Some("inactive"),
252 ("video", "2") => Some("sendonly"),
253 _ => None,
254 });
255 assert_eq!(
256 directions(&picked),
257 vec!["sendrecv", "inactive", "sendonly"]
258 );
259 }
260
261 #[test]
262 fn plain_line_feeds_survive() {
263 let unix = OFFER.replace("\r\n", "\n");
264 let held = all_inactive(&unix);
265 assert!(!held.contains('\r'));
266 assert_eq!(directions(&held), vec!["inactive", "inactive", "inactive"]);
267 }
268
269 #[test]
270 fn a_hold_answer_mirrors_our_offer_so_nothing_stops_locally() {
271 let answer = all_inactive(&OFFER.replace("a=setup:actpass", "a=setup:passive"));
272 let kept = keep_media_running(&answer, OFFER);
273 assert_eq!(directions(&kept), vec!["sendrecv", "sendrecv", "sendonly"]);
274 assert_eq!(kept.lines().count(), answer.lines().count());
275 }
276
277 #[test]
278 fn a_hold_is_every_audio_and_video_line_inactive() {
279 assert!(is_hold(&all_inactive(OFFER)).unwrap());
280 assert!(!is_hold(OFFER).unwrap());
281 let sendonly_audio = rewrite_directions(&all_inactive(OFFER), |line| {
282 (line.kind == "audio").then_some("sendonly")
283 });
284 assert!(!is_hold(&sendonly_audio).unwrap());
285 }
286
287 #[test]
288 fn rejected_and_data_lines_do_not_stop_a_hold() {
289 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";
290 assert!(is_hold(teams).unwrap());
291 assert!(!is_hold("v=0\r\ns=-\r\nt=0 0\r\n").unwrap());
292 }
293
294 #[test]
295 fn an_offer_with_a_sending_main_video_line_is_a_video_call() {
296 let teams = |direction: &str, label: &str| {
297 format!(
298 "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"
299 )
300 };
301 assert!(offer_sends_video(&teams("sendrecv", "main-video")));
302 assert!(offer_sends_video(&teams("sendonly", "main-video")));
303 assert!(!offer_sends_video(&teams("recvonly", "main-video")));
304 assert!(!offer_sends_video(&teams("inactive", "main-video")));
305 assert!(!offer_sends_video(&teams(
306 "sendrecv",
307 "applicationsharing-video"
308 )));
309 }
310
311 #[test]
312 fn the_hold_state_prefers_your_own_hold() {
313 assert_eq!(HoldState::from_flags(false, false), HoldState::Active);
314 assert_eq!(HoldState::from_flags(true, true), HoldState::Local);
315 assert_eq!(HoldState::from_flags(false, true), HoldState::Remote);
316 }
317
318 #[test]
319 fn accepting_with_video_adds_the_modality() {
320 assert_eq!(accepted_modalities(false), vec!["Audio"]);
321 assert_eq!(accepted_modalities(true), vec!["Audio", "Video"]);
322 assert_eq!(
323 super::offer_modalities(false, true),
324 vec!["Audio", "ScreenSharer"]
325 );
326 assert_eq!(
327 super::offer_modalities(true, true),
328 vec!["Audio", "Video", "ScreenSharer"]
329 );
330 }
331}