BlueGit

ict rusty-teams

Files

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

sdp.rs

sdp.rs 50.1 KiB Download Raw
1use std::collections::{HashMap, HashSet};
2
3use crate::error::{Error, Result};
4
5const SIGNALED_PORT: &str = "1234";
6const SIGNALED_PROTO: &str = "RTP/SAVP";
7const SESSION_BANDWIDTH: &str = "CT:4000";
8const PLACEHOLDER_CANDIDATE: &str = "1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host";
9const PLACEHOLDER_CONNECTION: &str = "IN IP4 10.10.10.10";
10const SSRC_RANGE_SIZE: u32 = 100;
11const BACKSLASHED_EXTENSIONS: [&str; 2] = [
12 "http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time",
13 "http://www.ietf.org/id/draft-holmer-rmcat-transport-wide-cc-extensions-01",
14];
15const DROPPED_EXTENSIONS: [&str; 1] = ["http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"];
16const LAYERS_ALLOCATION: &str = "http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00";
17const NOT_ADVERTISED_SUFFIX: &str = "-non-advertised";
18const DIRECTIONS: [&str; 4] = ["sendrecv", "sendonly", "recvonly", "inactive"];
19
20#[derive(Debug, Clone, PartialEq, Eq)]
21pub struct Attribute {
22 pub name: String,
23 pub value: Option<String>,
24}
25
26impl Attribute {
27 fn new(name: &str, value: impl Into<String>) -> Self {
28 Attribute {
29 name: name.to_owned(),
30 value: Some(value.into()),
31 }
32 }
33
34 fn flag(name: &str) -> Self {
35 Attribute {
36 name: name.to_owned(),
37 value: None,
38 }
39 }
40
41 fn render(&self) -> String {
42 match &self.value {
43 Some(value) => format!("a={}:{value}", self.name),
44 None => format!("a={}", self.name),
45 }
46 }
47}
48
49#[derive(Debug, Clone, Default)]
50pub struct Session {
51 pub version: String,
52 pub origin: String,
53 pub name: String,
54 pub connection: Option<String>,
55 pub bandwidths: Vec<String>,
56 pub timing: String,
57 pub attributes: Vec<Attribute>,
58}
59
60#[derive(Debug, Clone)]
61pub struct Media {
62 pub kind: String,
63 pub port: String,
64 pub proto: String,
65 pub formats: Vec<String>,
66 pub connection: Option<String>,
67 pub bandwidths: Vec<String>,
68 pub attributes: Vec<Attribute>,
69}
70
71#[derive(Debug, Clone)]
72pub struct SessionDescription {
73 pub session: Session,
74 pub media: Vec<Media>,
75}
76
77impl Media {
78 pub fn values<'a>(&'a self, name: &str) -> impl Iterator<Item = &'a str> + 'a {
79 let name = name.to_owned();
80 self.attributes
81 .iter()
82 .filter(move |attribute| attribute.name == name)
83 .filter_map(|attribute| attribute.value.as_deref())
84 }
85
86 pub fn value(&self, name: &str) -> Option<&str> {
87 self.values(name).next()
88 }
89
90 pub fn has(&self, name: &str) -> bool {
91 self.attributes.iter().any(|attribute| attribute.name == name)
92 }
93
94 pub fn mid(&self) -> Option<&str> {
95 self.value("mid")
96 }
97
98 pub fn direction(&self) -> Option<&str> {
99 self.attributes
100 .iter()
101 .find(|attribute| DIRECTIONS.contains(&attribute.name.as_str()))
102 .map(|attribute| attribute.name.as_str())
103 }
104
105 fn rtpmap(&self) -> HashMap<String, String> {
106 self.values("rtpmap")
107 .filter_map(|value| value.split_once(' '))
108 .map(|(payload, encoding)| (payload.to_owned(), encoding.to_owned()))
109 .collect()
110 }
111}
112
113pub fn parse(text: &str) -> Result<SessionDescription> {
114 let mut session = Session::default();
115 let mut media: Vec<Media> = Vec::new();
116 for raw in text.split('\n') {
117 let line = raw.trim_end_matches('\r');
118 if line.is_empty() {
119 continue;
120 }
121 let (kind, value) = line
122 .split_once('=')
123 .ok_or_else(|| Error::Sdp(format!("line without '=': {line}")))?;
124 if kind == "m" {
125 let mut parts = value.split(' ');
126 let (Some(media_kind), Some(port), Some(proto)) = (parts.next(), parts.next(), parts.next()) else {
127 return Err(Error::Sdp(format!("short m-line: {line}")));
128 };
129 media.push(Media {
130 kind: media_kind.to_owned(),
131 port: port.to_owned(),
132 proto: proto.to_owned(),
133 formats: parts.map(str::to_owned).collect(),
134 connection: None,
135 bandwidths: Vec::new(),
136 attributes: Vec::new(),
137 });
138 continue;
139 }
140 let attribute = || {
141 let (name, value) = match value.split_once(':') {
142 Some((name, value)) => (name, Some(value.to_owned())),
143 None => (value, None),
144 };
145 Attribute {
146 name: name.to_owned(),
147 value,
148 }
149 };
150 match (media.last_mut(), kind) {
151 (None, "v") => session.version = value.to_owned(),
152 (None, "o") => session.origin = value.to_owned(),
153 (None, "s") => session.name = value.to_owned(),
154 (None, "c") => session.connection = Some(value.to_owned()),
155 (None, "b") => session.bandwidths.push(value.to_owned()),
156 (None, "t") => session.timing = value.to_owned(),
157 (None, "a") => session.attributes.push(attribute()),
158 (Some(current), "c") => current.connection = Some(value.to_owned()),
159 (Some(current), "b") => current.bandwidths.push(value.to_owned()),
160 (Some(current), "a") => current.attributes.push(attribute()),
161 _ => {}
162 }
163 }
164 Ok(SessionDescription { session, media })
165}
166
167fn session_rank(name: &str) -> usize {
168 match name {
169 "x-mediabw" => 0,
170 "extmap-allow-mixed" => 1,
171 "msid-semantic" => 2,
172 "group" => 3,
173 _ => 99,
174 }
175}
176
177fn media_rank(name: &str) -> usize {
178 match name {
179 "x-multi-stream" => 0,
180 "x-data-protocol" => 1,
181 "x-signaling-fb" => 2,
182 "x-ssrc-range" => 3,
183 "x-source-streamid" => 4,
184 "rtpmap" => 10,
185 "fmtp" => 11,
186 "rtcp" => 12,
187 "rtcp-fb" => 13,
188 "extmap" => 14,
189 "extmap-allow-mixed" => 15,
190 "setup" => 16,
191 "mid" => 17,
192 "msid" => 18,
193 "ptime" => 19,
194 "maxptime" => 20,
195 "sendrecv" | "sendonly" | "recvonly" | "inactive" => 21,
196 "ice-ufrag" => 22,
197 "ice-pwd" => 23,
198 "fingerprint" => 24,
199 "candidate" => 25,
200 "end-of-candidates" => 26,
201 "ice-options" => 27,
202 "ssrc" => 28,
203 "ssrc-group" => 29,
204 "rtcp-mux" => 30,
205 "rtcp-rsize" => 31,
206 "rid" => 32,
207 "simulcast" => 33,
208 "label" => 34,
209 "sctp-port" => 35,
210 "max-message-size" => 36,
211 _ => 99,
212 }
213}
214
215pub fn write(description: &SessionDescription) -> String {
216 let session = &description.session;
217 let mut lines = vec![
218 format!("v={}", session.version),
219 format!("o={}", session.origin),
220 format!("s={}", session.name),
221 ];
222 lines.extend(session.connection.iter().map(|connection| format!("c={connection}")));
223 lines.extend(session.bandwidths.iter().map(|bandwidth| format!("b={bandwidth}")));
224 lines.push(format!("t={}", session.timing));
225 let mut session_attributes: Vec<&Attribute> = session.attributes.iter().collect();
226 session_attributes.sort_by_key(|attribute| session_rank(&attribute.name));
227 lines.extend(session_attributes.into_iter().map(Attribute::render));
228 for media in &description.media {
229 let mut header = vec![media.kind.clone(), media.port.clone(), media.proto.clone()];
230 header.extend(media.formats.iter().cloned());
231 lines.push(format!("m={}", header.join(" ")));
232 lines.extend(media.connection.iter().map(|connection| format!("c={connection}")));
233 lines.extend(media.bandwidths.iter().map(|bandwidth| format!("b={bandwidth}")));
234 let mut attributes: Vec<&Attribute> = media.attributes.iter().collect();
235 attributes.sort_by_key(|attribute| media_rank(&attribute.name));
236 lines.extend(attributes.into_iter().map(Attribute::render));
237 }
238 let mut text = lines.join("\r\n");
239 text.push_str("\r\n");
240 text
241}
242
243#[derive(Debug, Clone, Copy, PartialEq, Eq)]
244pub enum LineRole {
245 MainAudio,
246 MainVideo,
247 ScreenShare,
248 Data,
249}
250
251impl LineRole {
252 fn label(self) -> &'static str {
253 match self {
254 LineRole::MainAudio => "main-audio",
255 LineRole::MainVideo => "main-video",
256 LineRole::ScreenShare => "applicationsharing-video",
257 LineRole::Data => "data",
258 }
259 }
260
261 fn stream_prefix(self) -> &'static str {
262 match self {
263 LineRole::MainAudio => "mainAudio",
264 LineRole::MainVideo => "mainVideo",
265 LineRole::ScreenShare => "applicationsharingVideo",
266 LineRole::Data => "data",
267 }
268 }
269}
270
271/// Which browser m-lines play which Teams role; `gallery_mids` are folded into one `x-multi-stream` line.
272#[derive(Debug, Clone, Default)]
273pub struct OfferPlan {
274 pub screen_share_mids: Vec<String>,
275 pub gallery_mids: Vec<String>,
276}
277
278#[derive(Debug, Clone, PartialEq, Eq)]
279pub struct SignaledLine {
280 pub browser_mids: Vec<String>,
281 pub role: LineRole,
282}
283
284#[derive(Debug, Clone)]
285pub struct SignaledOffer {
286 pub sdp: String,
287 pub lines: Vec<SignaledLine>,
288}
289
290/// Random numbers for SSRCs; injected so tests stay deterministic.
291pub trait NumberSource {
292 fn next_u32(&mut self) -> u32;
293}
294
295impl<F: FnMut() -> u32> NumberSource for F {
296 fn next_u32(&mut self) -> u32 {
297 self()
298 }
299}
300
301pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl NumberSource) -> Result<SignaledOffer> {
302 let browser = parse(browser_sdp)?;
303 let cname = browser
304 .media
305 .iter()
306 .flat_map(|media| media.values("ssrc"))
307 .find_map(|value| value.split_once(" cname:").map(|(_, cname)| cname.to_owned()))
308 .unwrap_or_else(|| format!("{:08x}{:08x}", numbers.next_u32(), numbers.next_u32()));
309 let gallery_carrier = plan.gallery_mids.last().cloned();
310 let mut lines = Vec::new();
311 let mut media = Vec::new();
312 for source in &browser.media {
313 let mid = source.mid().unwrap_or_default().to_owned();
314 if plan.gallery_mids.contains(&mid) && Some(&mid) != gallery_carrier.as_ref() {
315 continue;
316 }
317 let role = match source.kind.as_str() {
318 "audio" => LineRole::MainAudio,
319 "application" => LineRole::Data,
320 _ if plan.screen_share_mids.contains(&mid) => LineRole::ScreenShare,
321 _ => LineRole::MainVideo,
322 };
323 let multi_stream = (Some(&mid) == gallery_carrier.as_ref()).then_some(plan.gallery_mids.len());
324 let is_first = media.is_empty();
325 let signaled = if source.port == "0" {
326 signal_rejected_line(source, role)
327 } else if role == LineRole::Data {
328 signal_data_line(source, numbers)
329 } else {
330 signal_rtp_line(source, role, multi_stream, &cname, is_first, numbers)
331 };
332 media.push(signaled);
333 lines.push(SignaledLine {
334 browser_mids: match multi_stream {
335 Some(_) => plan.gallery_mids.clone(),
336 None => vec![mid],
337 },
338 role,
339 });
340 }
341 let mut session = browser.session.clone();
342 session.bandwidths = vec![SESSION_BANDWIDTH.to_owned()];
343 for attribute in &mut session.attributes {
344 match attribute.name.as_str() {
345 "msid-semantic" => attribute.value = Some(" WMS *".to_owned()),
346 "group" if attribute.value.as_deref().is_some_and(|value| value.starts_with("BUNDLE")) => {
347 let mids: Vec<&str> = media.iter().filter(|line| line.port != "0").filter_map(Media::mid).collect();
348 attribute.value = Some(format!("BUNDLE {}", mids.join(" ")));
349 }
350 _ => {}
351 }
352 }
353 let description = SessionDescription { session, media };
354 Ok(SignaledOffer {
355 sdp: write(&description),
356 lines,
357 })
358}
359
360fn signal_rejected_line(source: &Media, role: LineRole) -> Media {
361 let attributes = vec![
362 Attribute::new("mid", source.mid().unwrap_or_default()),
363 Attribute::flag("inactive"),
364 Attribute::new("label", role.label()),
365 ];
366 Media {
367 kind: if role == LineRole::Data { "x-data".to_owned() } else { source.kind.clone() },
368 port: "0".to_owned(),
369 proto: SIGNALED_PROTO.to_owned(),
370 formats: source.formats.clone(),
371 connection: Some(PLACEHOLDER_CONNECTION.to_owned()),
372 bandwidths: Vec::new(),
373 attributes,
374 }
375}
376
377fn signal_rtp_line(
378 source: &Media,
379 role: LineRole,
380 multi_stream: Option<usize>,
381 cname: &str,
382 carries_candidate: bool,
383 numbers: &mut impl NumberSource,
384) -> Media {
385 let mut media = source.clone();
386 media.port = SIGNALED_PORT.to_owned();
387 media.proto = SIGNALED_PROTO.to_owned();
388 media.connection = Some(PLACEHOLDER_CONNECTION.to_owned());
389 let rtpmap = source.rtpmap();
390 let is_rtx = |payload: &str| rtpmap.get(payload).is_some_and(|encoding| encoding.starts_with("rtx/"));
391 let mid = source.mid().unwrap_or_default().to_owned();
392
393 let mut attributes = Vec::new();
394 if let Some(count) = multi_stream {
395 attributes.push(Attribute::new("x-multi-stream", format!("{count} 1 1 1")));
396 }
397 attributes.push(Attribute::new(
398 "x-signaling-fb",
399 match role {
400 LineRole::MainAudio => "* x-message app recv:dsh",
401 _ => "* x-message app send:src recv:src,vc",
402 },
403 ));
404 let browser_ssrcs: Vec<u32> = source
405 .values("ssrc")
406 .filter_map(|value| value.split(' ').next()?.parse().ok())
407 .collect();
408 let simulcast = source.has("simulcast");
409 let receive_only = source.direction() == Some("recvonly");
410 let (range, ssrc_lines) = if multi_stream.is_some() {
411 (None, vec![Attribute::new("ssrc", format!("1 cname:{cname}"))])
412 } else if let Some(&first) = browser_ssrcs.first() {
413 let lines = source
414 .values("ssrc")
415 .map(|value| Attribute::new("ssrc", rewrite_ssrc_msid(value, &mid)))
416 .collect();
417 (Some((first, first)), lines)
418 } else if simulcast {
419 let base = numbers.next_u32();
420 let lines = vec![Attribute::new("ssrc", format!("{base} fake_attribute:fake_value"))];
421 (Some((base, base + SSRC_RANGE_SIZE - 1)), lines)
422 } else if receive_only && role != LineRole::MainAudio {
423 (Some((1, 1)), vec![Attribute::new("ssrc", format!("1 cname:{cname}"))])
424 } else {
425 let base = numbers.next_u32();
426 (Some((base, base)), vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))])
427 };
428 if let Some((first, last)) = range {
429 attributes.push(Attribute::new("x-ssrc-range", format!("{first}-{last}")));
430 }
431
432 let video = source.kind == "video";
433 let feedback_by_payload = feedback_by_payload(source);
434 let shared_feedback = shared_feedback(&feedback_by_payload, source, &is_rtx);
435 let mut fmtp: Vec<(usize, Attribute)> = Vec::new();
436 for attribute in &source.attributes {
437 let value = attribute.value.as_deref().unwrap_or_default();
438 match attribute.name.as_str() {
439 "ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" | "candidate" | "end-of-candidates" => {}
440 "rtpmap" => attributes.push(Attribute::new("rtpmap", signal_rtpmap(value))),
441 "fmtp" => {
442 let payload = value.split(' ').next().unwrap_or_default();
443 let position = source.formats.iter().position(|format| format == payload).unwrap_or(usize::MAX);
444 let cleaned = if video {
445 value.replace(";sps-pps-idr-in-keyframe=1", "")
446 } else {
447 value.to_owned()
448 };
449 fmtp.push((position, Attribute::new("fmtp", cleaned)));
450 }
451 "rtcp" => attributes.push(Attribute::new("rtcp", SIGNALED_PORT)),
452 "extmap" => {
453 if let Some(signaled) = signal_extmap(value) {
454 attributes.push(Attribute::new("extmap", signaled));
455 }
456 }
457 _ => attributes.push(attribute.clone()),
458 }
459 }
460 fmtp.sort_by_key(|(position, _)| *position);
461 attributes.extend(fmtp.into_iter().map(|(_, attribute)| attribute));
462 match shared_feedback {
463 Some(feedback) => attributes.extend(feedback.iter().map(|kind| Attribute::new("rtcp-fb", format!("* {kind}")))),
464 None => attributes.extend(source.attributes.iter().filter(|attribute| attribute.name == "rtcp-fb").cloned()),
465 }
466 if carries_candidate {
467 attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE));
468 }
469 attributes.extend(ssrc_lines);
470 attributes.extend(source.attributes.iter().filter(|attribute| attribute.name == "ssrc-group").cloned());
471 attributes.push(Attribute::new("label", role.label()));
472 if !source.has("rtcp-mux") {
473 attributes.push(Attribute::flag("rtcp-mux"));
474 }
475 media.attributes = attributes;
476 media
477}
478
479fn rewrite_ssrc_msid(value: &str, mid: &str) -> String {
480 match value.split_once(" msid:") {
481 Some((ssrc, msid)) => {
482 let stream = msid.split(' ').next().unwrap_or("-");
483 format!("{ssrc} msid:{stream} {mid}")
484 }
485 None => value.to_owned(),
486 }
487}
488
489fn signal_rtpmap(value: &str) -> String {
490 match value.split_once(' ') {
491 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/48000/2") => format!("{payload} RED/8000"),
492 _ => value.to_owned(),
493 }
494}
495
496fn signal_extmap(value: &str) -> Option<String> {
497 let (identifier, uri) = value.split_once(' ')?;
498 if DROPPED_EXTENSIONS.contains(&uri) {
499 return None;
500 }
501 if BACKSLASHED_EXTENSIONS.contains(&uri) {
502 return Some(format!("{identifier} {}", uri.replace('/', "\\")));
503 }
504 if uri == LAYERS_ALLOCATION {
505 return Some(format!("{identifier} {uri}{NOT_ADVERTISED_SUFFIX}"));
506 }
507 Some(value.to_owned())
508}
509
510fn feedback_by_payload(source: &Media) -> HashMap<String, Vec<String>> {
511 let mut map: HashMap<String, Vec<String>> = HashMap::new();
512 for value in source.values("rtcp-fb") {
513 if let Some((payload, kind)) = value.split_once(' ') {
514 map.entry(payload.to_owned()).or_default().push(kind.to_owned());
515 }
516 }
517 map
518}
519
520fn shared_feedback(
521 by_payload: &HashMap<String, Vec<String>>,
522 source: &Media,
523 is_rtx: &impl Fn(&str) -> bool,
524) -> Option<Vec<String>> {
525 let mut codecs = source.formats.iter().filter(|payload| !is_rtx(payload));
526 let first = by_payload.get(codecs.next()?)?;
527 codecs.all(|payload| by_payload.get(payload) == Some(first)).then(|| first.clone())
528}
529
530fn signal_data_line(source: &Media, numbers: &mut impl NumberSource) -> Media {
531 let ssrc = numbers.next_u32();
532 let mut attributes = vec![
533 Attribute::new("x-data-protocol", "sctp"),
534 Attribute::new("x-ssrc-range", format!("{ssrc}-{ssrc}")),
535 Attribute::new("rtpmap", "127 x-data/90000"),
536 Attribute::new("rtpmap", "126 rtx/90000"),
537 Attribute::new("fmtp", "126 apt=127"),
538 Attribute::flag("sendrecv"),
539 Attribute::flag("rtcp-mux"),
540 Attribute::new("label", LineRole::Data.label()),
541 ];
542 attributes.extend(source.attributes.iter().cloned());
543 Media {
544 kind: "x-data".to_owned(),
545 port: SIGNALED_PORT.to_owned(),
546 proto: SIGNALED_PROTO.to_owned(),
547 formats: vec!["127".to_owned(), "126".to_owned()],
548 connection: Some(PLACEHOLDER_CONNECTION.to_owned()),
549 bandwidths: Vec::new(),
550 attributes,
551 }
552}
553
554pub fn to_browser_answer(teams_sdp: &str, offer: &SignaledOffer, browser_offer_sdp: &str) -> Result<String> {
555 let answer = parse(teams_sdp)?;
556 let browser_offer = parse(browser_offer_sdp)?;
557 if answer.media.len() != offer.lines.len() {
558 return Err(Error::Sdp(format!(
559 "answer has {} m-lines, offer signaled {}",
560 answer.media.len(),
561 offer.lines.len()
562 )));
563 }
564 let offered: HashMap<&str, &Media> = browser_offer
565 .media
566 .iter()
567 .filter_map(|media| Some((media.mid()?, media)))
568 .collect();
569 let mut media = Vec::new();
570 for (index, (teams_line, signaled)) in answer.media.iter().zip(&offer.lines).enumerate() {
571 for (stream_index, browser_mid) in signaled.browser_mids.iter().enumerate() {
572 let offered_line = offered
573 .get(browser_mid.as_str())
574 .ok_or_else(|| Error::Sdp(format!("offer has no mid {browser_mid}")))?;
575 let section = if signaled.role == LineRole::Data {
576 browser_data_line(teams_line, offered_line, &answer.session)
577 } else {
578 browser_rtp_line(teams_line, offered_line, signaled.role, stream_index as u32, index == 0, &answer.session)
579 };
580 media.push(section);
581 }
582 }
583 let mut session = answer.session.clone();
584 session.attributes.retain(|attribute| attribute.name.starts_with("x-"));
585 session.attributes.push(Attribute::flag("extmap-allow-mixed"));
586 session.attributes.push(Attribute::new("msid-semantic", " WMS *"));
587 let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect();
588 session.attributes.push(Attribute::new("group", format!("BUNDLE {}", mids.join(" "))));
589 Ok(write(&SessionDescription { session, media }))
590}
591
592#[derive(Debug, Clone, PartialEq, Eq)]
593pub struct StreamLine {
594 pub mid: String,
595 pub browser_mid: String,
596 pub role: LineRole,
597 pub source_stream_id: Option<u32>,
598}
599
600pub fn stream_lines(teams_sdp: &str, lines: &[SignaledLine]) -> Result<Vec<StreamLine>> {
601 let teams = parse(teams_sdp)?;
602 if teams.media.len() != lines.len() {
603 return Err(Error::Sdp(format!("sdp has {} m-lines, {} were signaled", teams.media.len(), lines.len())));
604 }
605 let mut streams = Vec::new();
606 for (media, line) in teams.media.iter().zip(lines) {
607 let source_stream_id = media.value("x-source-streamid").and_then(|value| value.trim().parse().ok());
608 let mid = media.mid().unwrap_or_default().to_owned();
609 match line.browser_mids.as_slice() {
610 [browser_mid] => streams.push(StreamLine {
611 mid,
612 browser_mid: browser_mid.clone(),
613 role: line.role,
614 source_stream_id,
615 }),
616 folded => streams.extend(folded.iter().map(|browser_mid| StreamLine {
617 mid: mid.clone(),
618 browser_mid: browser_mid.clone(),
619 role: line.role,
620 source_stream_id: None,
621 })),
622 }
623 }
624 Ok(streams)
625}
626
627fn transport_attributes(teams_line: &Media, session: &Session) -> Vec<Attribute> {
628 ["setup", "ice-ufrag", "ice-pwd", "fingerprint"]
629 .into_iter()
630 .filter_map(|name| {
631 teams_line
632 .attributes
633 .iter()
634 .chain(&session.attributes)
635 .find(|attribute| attribute.name == name)
636 .cloned()
637 })
638 .collect()
639}
640
641fn browser_rtp_line(
642 teams_line: &Media,
643 offered: &Media,
644 role: LineRole,
645 stream_index: u32,
646 carries_candidates: bool,
647 session: &Session,
648) -> Media {
649 let offered_rtpmap = offered.rtpmap();
650 let offered_codecs: HashMap<String, String> = offered_rtpmap
651 .values()
652 .filter_map(|encoding| {
653 let (name, rest) = encoding.split_once('/')?;
654 Some((name.to_ascii_lowercase(), rest.to_owned()))
655 })
656 .collect();
657 let answer_rtpmap = teams_line.rtpmap();
658 let kept: Vec<String> = teams_line
659 .formats
660 .iter()
661 .filter(|payload| {
662 answer_rtpmap
663 .get(*payload)
664 .and_then(|encoding| encoding.split('/').next())
665 .is_some_and(|name| offered_codecs.contains_key(&name.to_ascii_lowercase()))
666 })
667 .cloned()
668 .collect();
669 let kept_set: HashSet<&str> = kept.iter().map(String::as_str).collect();
670 let payload_of = |value: &str| value.split(' ').next().unwrap_or_default().to_owned();
671 let codec_payload = |codec: &str| {
672 kept.iter().find(|payload| {
673 answer_rtpmap
674 .get(*payload)
675 .is_some_and(|encoding| encoding.to_ascii_lowercase().starts_with(&format!("{codec}/")))
676 })
677 };
678
679 let mut attributes = Vec::new();
680 attributes.extend(teams_line.values("x-source-streamid").map(|value| Attribute::new("x-source-streamid", value)));
681 for value in teams_line.values("rtpmap") {
682 let payload = payload_of(value);
683 if !kept_set.contains(payload.as_str()) {
684 continue;
685 }
686 let encoding = answer_rtpmap.get(&payload).cloned().unwrap_or_default();
687 let name = encoding.split('/').next().unwrap_or_default();
688 let offered_rest = offered_codecs.get(&name.to_ascii_lowercase());
689 let rewritten = match offered_rest {
690 Some(rest) if name.eq_ignore_ascii_case("red") => format!("{payload} {name}/{rest}"),
691 _ => value.to_owned(),
692 };
693 attributes.push(Attribute::new("rtpmap", rewritten));
694 }
695 let mut fmtp_payloads = HashSet::new();
696 for value in teams_line.values("fmtp") {
697 let payload = payload_of(value);
698 if !kept_set.contains(payload.as_str()) {
699 continue;
700 }
701 fmtp_payloads.insert(payload);
702 let cleaned = value
703 .split(';')
704 .filter(|parameter| !parameter.starts_with("rtx-time="))
705 .collect::<Vec<_>>()
706 .join(";");
707 attributes.push(Attribute::new("fmtp", cleaned));
708 }
709 if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) {
710 attributes.push(Attribute::new("fmtp", format!("{opus} usedtx=1")));
711 }
712 if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus"))
713 && !fmtp_payloads.contains(red)
714 {
715 attributes.push(Attribute::new("fmtp", format!("{red} {opus}/{opus}")));
716 }
717 attributes.extend(teams_line.values("rtcp").map(|value| Attribute::new("rtcp", value)));
718 let answer_feedback: Vec<&str> = teams_line
719 .values("rtcp-fb")
720 .filter(|value| !value.contains("x-message"))
721 .collect();
722 if answer_feedback.is_empty() && !teams_line.has("rtcp-fb") {
723 attributes.extend(
724 offered
725 .values("rtcp-fb")
726 .filter(|value| kept_set.contains(payload_of(value).as_str()))
727 .map(|value| Attribute::new("rtcp-fb", value)),
728 );
729 } else {
730 attributes.extend(answer_feedback.into_iter().map(|value| Attribute::new("rtcp-fb", value)));
731 }
732 for value in teams_line.values("extmap") {
733 let restored = value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "");
734 attributes.push(Attribute::new("extmap", restored));
735 }
736 attributes.extend(transport_attributes(teams_line, session));
737 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
738 attributes.extend(teams_line.values("ptime").map(|value| Attribute::new("ptime", value)));
739 if let Some(direction) = teams_line.direction() {
740 attributes.push(Attribute::flag(direction));
741 }
742 if carries_candidates {
743 attributes.extend(teams_line.values("candidate").map(|value| Attribute::new("candidate", browser_candidate(value))));
744 }
745 let (primary, retransmission) = stream_ssrcs(teams_line, stream_index);
746 if let Some(primary) = primary {
747 let stream = format!("{}-{primary}", role.stream_prefix());
748 for ssrc in [Some(primary), retransmission].into_iter().flatten() {
749 attributes.push(Attribute::new("ssrc", format!("{ssrc} cname:{}", stream_cname(primary))));
750 attributes.push(Attribute::new("ssrc", format!("{ssrc} msid:{stream} {stream}")));
751 }
752 if let Some(retransmission) = retransmission {
753 attributes.push(Attribute::new("ssrc-group", format!("FID {primary} {retransmission}")));
754 }
755 }
756 attributes.push(Attribute::flag("rtcp-mux"));
757 if teams_line.has("rtcp-rsize") {
758 attributes.push(Attribute::flag("rtcp-rsize"));
759 }
760 if let Some(simulcast) = offered.value("simulcast").and_then(|value| value.strip_prefix("send ")) {
761 let rids: Vec<String> = simulcast.split(';').map(|rid| rid.trim_start_matches('~').to_owned()).collect();
762 attributes.extend(rids.iter().map(|rid| Attribute::new("rid", format!("{rid} recv"))));
763 attributes.push(Attribute::new("simulcast", format!("recv {}", rids.join(";"))));
764 }
765 Media {
766 kind: offered.kind.clone(),
767 port: teams_line.port.clone(),
768 proto: offered.proto.clone(),
769 formats: kept,
770 connection: teams_line.connection.clone().or_else(|| session.connection.clone()),
771 bandwidths: teams_line.bandwidths.clone(),
772 attributes,
773 }
774}
775
776fn stream_cname(primary: u32) -> String {
777 format!("teams{primary}")
778}
779
780fn stream_ssrcs(teams_line: &Media, stream_index: u32) -> (Option<u32>, Option<u32>) {
781 let offset = stream_index * SSRC_RANGE_SIZE;
782 if let Some(group) = teams_line.value("ssrc-group").and_then(|value| value.strip_prefix("FID ")) {
783 let mut ssrcs = group.split(' ').filter_map(|value| value.parse::<u32>().ok());
784 let primary = ssrcs.next().map(|ssrc| ssrc + offset);
785 return (primary, ssrcs.next().map(|ssrc| ssrc + offset));
786 }
787 let first = teams_line
788 .value("x-ssrc-range")
789 .and_then(|range| range.split('-').next()?.parse::<u32>().ok())
790 .map(|ssrc| ssrc + offset);
791 (first, None)
792}
793
794fn browser_candidate(value: &str) -> String {
795 let mut parts: Vec<&str> = value.split(' ').collect();
796 if let Some(position) = parts.iter().position(|part| *part == "MTURNID") {
797 parts.truncate(position);
798 }
799 let tcp_type = match parts.get(2).map(|transport| transport.to_ascii_lowercase()).as_deref() {
800 Some("tcp-pass") => Some("passive"),
801 Some("tcp-act") => Some("active"),
802 _ => None,
803 };
804 if tcp_type.is_some() {
805 parts[2] = "tcp";
806 }
807 let mut candidate = parts.join(" ");
808 if let Some(tcp_type) = tcp_type {
809 candidate.push_str(" tcptype ");
810 candidate.push_str(tcp_type);
811 }
812 candidate
813}
814
815fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) -> Media {
816 let mut attributes = Vec::new();
817 attributes.extend(teams_line.values("x-source-streamid").map(|value| Attribute::new("x-source-streamid", value)));
818 attributes.extend(transport_attributes(teams_line, session));
819 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
820 attributes.extend(offered.values("sctp-port").map(|value| Attribute::new("sctp-port", value)));
821 Media {
822 kind: offered.kind.clone(),
823 port: teams_line.port.clone(),
824 proto: offered.proto.clone(),
825 formats: offered.formats.clone(),
826 connection: teams_line.connection.clone().or_else(|| session.connection.clone()),
827 bandwidths: Vec::new(),
828 attributes,
829 }
830}
831
832const BROWSER_PORT: &str = "9";
833const BROWSER_PROTO: &str = "UDP/TLS/RTP/SAVPF";
834const BROWSER_CONNECTION: &str = "IN IP4 0.0.0.0";
835const BROWSER_RTCP: &str = "9 IN IP4 0.0.0.0";
836const BROWSER_DATA_PROTO: &str = "UDP/DTLS/SCTP";
837const BROWSER_DATA_FORMAT: &str = "webrtc-datachannel";
838const SCTP_PORT: &str = "5000";
839const SCTP_MAX_MESSAGE_SIZE: &str = "262144";
840const PLACEHOLDER_CANDIDATE_TAIL: &str = " 1234 typ host";
841const TEAMS_ONLY_ATTRIBUTES: [&str; 6] = [
842 "x-multi-stream",
843 "x-signaling-fb",
844 "x-ssrc-range",
845 "x-source-streamid",
846 "x-data-protocol",
847 "label",
848];
849const TRANSPORT_ATTRIBUTES: [&str; 5] = ["setup", "ice-ufrag", "ice-pwd", "fingerprint", "ice-options"];
850
851/// A Teams offer translated for libwebrtc; `lines` remembers which browser mids each signaled line stands for.
852#[derive(Debug, Clone)]
853pub struct RemoteOffer {
854 pub browser_sdp: String,
855 pub lines: Vec<SignaledLine>,
856}
857
858impl RemoteOffer {
859 pub fn plan(&self) -> OfferPlan {
860 let mut plan = OfferPlan::default();
861 for line in &self.lines {
862 match line.role {
863 LineRole::ScreenShare => plan.screen_share_mids.extend(line.browser_mids.iter().cloned()),
864 _ if line.browser_mids.len() > 1 => plan.gallery_mids.extend(line.browser_mids.iter().cloned()),
865 _ => {}
866 }
867 }
868 plan
869 }
870}
871
872fn role_of_teams_line(line: &Media) -> LineRole {
873 match line.value("label") {
874 Some("main-audio") => LineRole::MainAudio,
875 Some("main-video") => LineRole::MainVideo,
876 Some("applicationsharing-video") => LineRole::ScreenShare,
877 Some("data") => LineRole::Data,
878 _ => match line.kind.as_str() {
879 "audio" => LineRole::MainAudio,
880 "x-data" | "application" => LineRole::Data,
881 _ => LineRole::MainVideo,
882 },
883 }
884}
885
886/// Folded gallery lines get the mids just below the carrier line's own mid.
887fn folded_mids(carrier: &str, count: usize) -> Vec<String> {
888 match carrier.parse::<usize>() {
889 Ok(last) if last + 1 >= count => (last + 1 - count..=last).map(|mid| mid.to_string()).collect(),
890 _ => (0..count)
891 .map(|index| if index + 1 == count { carrier.to_owned() } else { format!("{carrier}-{index}") })
892 .collect(),
893 }
894}
895
896pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
897 let teams = parse(teams_sdp)?;
898 let mut media = Vec::new();
899 let mut lines = Vec::new();
900 for source in &teams.media {
901 let role = role_of_teams_line(source);
902 let carrier = source.mid().unwrap_or_default().to_owned();
903 let folded = source
904 .value("x-multi-stream")
905 .and_then(|value| value.split(' ').next()?.parse::<usize>().ok())
906 .filter(|count| *count > 1);
907 let mids = match folded {
908 Some(count) => folded_mids(&carrier, count),
909 None => vec![carrier.clone()],
910 };
911 for (index, mid) in mids.iter().enumerate() {
912 let converted = if role == LineRole::Data {
913 browser_data_from_teams(source, mid, &teams.session)
914 } else {
915 browser_rtp_from_teams(source, mid, folded.is_some(), index == 0 && lines.is_empty(), &teams.session)
916 };
917 media.push(converted);
918 }
919 lines.push(SignaledLine {
920 browser_mids: mids,
921 role,
922 });
923 }
924 let mut session = teams.session.clone();
925 session.bandwidths.clear();
926 session.connection = None;
927 session.attributes.retain(|attribute| matches!(attribute.name.as_str(), "extmap-allow-mixed" | "msid-semantic"));
928 let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect();
929 session.attributes.push(Attribute::new("group", format!("BUNDLE {}", mids.join(" "))));
930 Ok(RemoteOffer {
931 browser_sdp: write(&SessionDescription { session, media }),
932 lines,
933 })
934}
935
936fn transport_from_teams(source: &Media, session: &Session) -> Vec<Attribute> {
937 TRANSPORT_ATTRIBUTES
938 .iter()
939 .filter_map(|name| {
940 source
941 .attributes
942 .iter()
943 .chain(&session.attributes)
944 .find(|attribute| attribute.name == *name)
945 .cloned()
946 })
947 .collect()
948}
949
950fn browser_data_from_teams(source: &Media, mid: &str, session: &Session) -> Media {
951 let mut attributes = transport_from_teams(source, session);
952 attributes.push(Attribute::new("mid", mid));
953 attributes.push(Attribute::new("sctp-port", SCTP_PORT));
954 attributes.push(Attribute::new("max-message-size", SCTP_MAX_MESSAGE_SIZE));
955 Media {
956 kind: "application".to_owned(),
957 port: BROWSER_PORT.to_owned(),
958 proto: BROWSER_DATA_PROTO.to_owned(),
959 formats: vec![BROWSER_DATA_FORMAT.to_owned()],
960 connection: Some(BROWSER_CONNECTION.to_owned()),
961 bandwidths: Vec::new(),
962 attributes,
963 }
964}
965
966fn browser_rtp_from_teams(source: &Media, mid: &str, folded: bool, carries_candidate: bool, session: &Session) -> Media {
967 let rtpmap = source.rtpmap();
968 let is_rtx = |payload: &str| rtpmap.get(payload).is_some_and(|encoding| encoding.starts_with("rtx/"));
969 let mut attributes = Vec::new();
970 let mut expanded_feedback: Vec<Attribute> = Vec::new();
971 for attribute in &source.attributes {
972 let value = attribute.value.as_deref().unwrap_or_default();
973 match attribute.name.as_str() {
974 name if TEAMS_ONLY_ATTRIBUTES.contains(&name) => {}
975 name if name.starts_with("x-") => {}
976 "mid" | "rtcp-mux" => {}
977 name if TRANSPORT_ATTRIBUTES.contains(&name) => {}
978 "candidate" => {
979 if carries_candidate && !value.contains(PLACEHOLDER_CANDIDATE_TAIL) {
980 attributes.push(Attribute::new("candidate", browser_candidate(value)));
981 }
982 }
983 "ssrc" => {
984 let placeholder = value.contains("fake_attribute") || value.starts_with("1 ");
985 if !folded && !placeholder {
986 attributes.push(attribute.clone());
987 }
988 }
989 "ssrc-group" => {
990 if !folded {
991 attributes.push(attribute.clone());
992 }
993 }
994 "rtcp" => attributes.push(Attribute::new("rtcp", BROWSER_RTCP)),
995 "rtpmap" => attributes.push(Attribute::new("rtpmap", browser_rtpmap(value))),
996 "extmap" => attributes.push(Attribute::new("extmap", browser_extmap(value))),
997 "rtcp-fb" => match value.strip_prefix("* ") {
998 Some(kind) => expanded_feedback.extend(
999 source
1000 .formats
1001 .iter()
1002 .filter(|payload| !is_rtx(payload))
1003 .map(|payload| Attribute::new("rtcp-fb", format!("{payload} {kind}"))),
1004 ),
1005 None => attributes.push(attribute.clone()),
1006 },
1007 _ => attributes.push(attribute.clone()),
1008 }
1009 }
1010 attributes.extend(expanded_feedback);
1011 attributes.extend(transport_from_teams(source, session));
1012 attributes.push(Attribute::new("mid", mid));
1013 attributes.push(Attribute::flag("rtcp-mux"));
1014 Media {
1015 kind: source.kind.clone(),
1016 port: BROWSER_PORT.to_owned(),
1017 proto: BROWSER_PROTO.to_owned(),
1018 formats: source.formats.clone(),
1019 connection: Some(BROWSER_CONNECTION.to_owned()),
1020 bandwidths: Vec::new(),
1021 attributes,
1022 }
1023}
1024
1025fn browser_rtpmap(value: &str) -> String {
1026 match value.split_once(' ') {
1027 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => format!("{payload} red/48000/2"),
1028 _ => value.to_owned(),
1029 }
1030}
1031
1032fn browser_extmap(value: &str) -> String {
1033 value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "")
1034}
1035
1036/// libwebrtc answers every offered line in the offer's order and with its mids, so the offer's plan applies unchanged.
1037pub fn to_teams_answer(browser_answer_sdp: &str, remote: &RemoteOffer, numbers: &mut impl NumberSource) -> Result<SignaledOffer> {
1038 to_teams_offer(browser_answer_sdp, &remote.plan(), numbers)
1039}
1040
1041#[cfg(test)]
1042mod tests {
1043 use super::*;
1044
1045 fn counter() -> impl FnMut() -> u32 {
1046 let mut next = 1000u32;
1047 move || {
1048 next += 1;
1049 next
1050 }
1051 }
1052
1053 const AUDIO_ONLY_OFFER: &str = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\na=extmap-allow-mixed\r\na=msid-semantic: WMS stream\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\r\nc=IN IP4 0.0.0.0\r\na=rtcp:9 IN IP4 0.0.0.0\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=ice-options:trickle\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=mid:0\r\na=extmap:1 urn:ietf:params:rtp-hdrext:ssrc-audio-level\r\na=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\r\na=sendrecv\r\na=msid:stream track\r\na=rtcp-mux\r\na=rtpmap:111 opus/48000/2\r\na=rtcp-fb:111 transport-cc\r\na=fmtp:111 minptime=10;useinbandfec=1\r\na=rtpmap:63 red/48000/2\r\na=fmtp:63 111/111\r\na=rtpmap:9 G722/8000\r\na=rtpmap:0 PCMU/8000\r\na=rtpmap:8 PCMA/8000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:110 telephone-event/48000\r\na=rtpmap:126 telephone-event/8000\r\na=ssrc:42 cname:abc\r\na=ssrc:42 msid:stream track\r\n";
1054
1055 #[test]
1056 fn audio_only_offer_gets_the_teams_shape() {
1057 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1058 let text = offer.sdp.replace("\r\n", "\n");
1059 assert!(text.contains("\nb=CT:4000\n"));
1060 assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\n"));
1061 assert!(text.contains("a=x-signaling-fb:* x-message app recv:dsh\n"));
1062 assert!(text.contains("a=x-ssrc-range:42-42\n"));
1063 assert!(text.contains("a=rtpmap:63 RED/8000\n"));
1064 assert!(text.contains("a=rtcp:1234\n"));
1065 assert!(text.contains("a=extmap:2 http:\\\\www.webrtc.org\\experiments\\rtp-hdrext\\abs-send-time\n"));
1066 assert!(text.contains("a=ssrc:42 msid:stream 0\n"));
1067 assert!(text.contains("a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\n"));
1068 assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\nc=IN IP4 10.10.10.10\n"));
1069 assert!(text.ends_with("a=label:main-audio\n"));
1070 assert_eq!(offer.lines, vec![SignaledLine { browser_mids: vec!["0".into()], role: LineRole::MainAudio }]);
1071 }
1072
1073 #[test]
1074 fn a_renegotiation_signals_only_the_placeholder_candidate() {
1075 let gathered = AUDIO_ONLY_OFFER.replace(
1076 "a=mid:0\r\n",
1077 "a=mid:0\r\na=candidate:1 1 udp 2121998079 192.0.2.1 45325 typ host generation 0 network-id 1\r\na=candidate:2 1 tcp 1518018303 2001:db8::1 47585 typ host tcptype passive generation 0 network-id 2\r\na=end-of-candidates\r\n",
1078 );
1079 let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter()).unwrap().sdp;
1080 let candidates: Vec<&str> = text.lines().filter(|line| line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")).collect();
1081 assert_eq!(candidates, vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]);
1082 }
1083
1084 #[test]
1085 fn answer_candidates_lose_teams_extensions() {
1086 assert_eq!(
1087 browser_candidate("1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 158"),
1088 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480"
1089 );
1090 assert_eq!(
1091 browser_candidate("3 1 tcp-pass 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478"),
1092 "3 1 tcp 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478 tcptype passive"
1093 );
1094 assert_eq!(
1095 browser_candidate("10 1 TCP-ACT 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009"),
1096 "10 1 tcp 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009 tcptype active"
1097 );
1098 }
1099
1100 #[test]
1101 fn audio_answer_maps_back_to_the_browser_mid_and_codecs() {
1102 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1103 let answer = "v=0\r\no=- 7 0 IN IP4 52.112.0.1\r\ns=session\r\nc=IN IP4 52.112.0.1\r\nb=CT:10000000\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=audio 3480 RTP/SAVP 109 111 97 13 101\r\nc=IN IP4 52.112.0.1\r\na=x-source-streamid:201\r\na=rtcp:3480\r\na=setup:passive\r\na=ice-ufrag:U\r\na=ice-pwd:P\r\na=rtcp-mux\r\na=candidate:1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 9\r\na=label:main-audio\r\na=mid:0\r\na=rtpmap:109 SATINFB/48000/2\r\na=rtpmap:111 OPUS/48000/2\r\na=rtpmap:97 RED/8000\r\na=rtpmap:13 CN/8000\r\na=rtpmap:101 telephone-event/8000\r\na=fmtp:101 0-16\r\na=fingerprint:sha-256 BB\r\na=x-ssrc-range:1000-1000\r\n";
1104 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER).unwrap().replace("\r\n", "\n");
1105 assert!(browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"), "{browser}");
1106 assert!(browser.contains("a=rtpmap:97 RED/48000/2\n"));
1107 assert!(browser.contains("a=fmtp:111 usedtx=1\n"));
1108 assert!(browser.contains("a=fmtp:97 111/111\n"));
1109 assert!(browser.contains("a=rtcp-fb:111 transport-cc\n"));
1110 assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n"));
1111 assert!(browser.contains("a=group:BUNDLE 0\n"));
1112 assert!(!browser.contains("SATINFB") && !browser.contains("MTURNID") && !browser.contains("label"));
1113 }
1114 #[test]
1115 fn an_audio_offer_from_teams_gets_the_browser_shape_back() {
1116 let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1117 let remote = from_teams_offer(&offer.sdp).unwrap();
1118 let text = remote.browser_sdp.replace("\r\n", "\n");
1119 assert!(text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"), "{text}");
1120 assert!(text.contains("c=IN IP4 0.0.0.0\n"));
1121 assert!(text.contains("a=rtcp:9 IN IP4 0.0.0.0\n"));
1122 assert!(text.contains("a=rtpmap:63 red/48000/2\n"));
1123 assert!(text.contains("a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"));
1124 assert!(text.contains("a=ice-ufrag:u\n") && text.contains("a=fingerprint:sha-256 AA\n") && text.contains("a=setup:actpass\n"));
1125 assert!(text.contains("a=mid:0\n") && text.contains("a=group:BUNDLE 0\n"));
1126 assert!(!text.contains("10.10.10.10") && !text.contains("x-ssrc-range") && !text.contains("label") && !text.contains("1234"));
1127 assert_eq!(remote.lines, offer.lines);
1128 }
1129
1130 #[test]
1131 fn shared_video_feedback_is_spelled_out_per_codec_again() {
1132 let teams = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=video 1234 RTP/SAVP 102 103\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=rtpmap:103 rtx/90000\r\na=fmtp:103 apt=102\r\na=rtcp-fb:* nack\r\na=rtcp-fb:* nack pli\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=label:main-video\r\n";
1133 let remote = from_teams_offer(teams).unwrap();
1134 let text = remote.browser_sdp.replace("\r\n", "\n");
1135 assert!(text.contains("a=rtcp-fb:102 nack\n") && text.contains("a=rtcp-fb:102 nack pli\n"));
1136 assert!(!text.contains("a=rtcp-fb:103") && !text.contains("a=rtcp-fb:*"));
1137 }
1138
1139 #[test]
1140 fn a_rejected_video_line_stays_rejected_and_out_of_the_bundle() {
1141 let audio_and_video = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=label:main-audio\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\n";
1142 let remote = from_teams_offer(audio_and_video).unwrap();
1143 let answer = "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 BB\r\na=setup:active\r\na=ssrc:7 cname:x\r\nm=video 0 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na=inactive\r\n";
1144 let signaled = to_teams_answer(answer, &remote, &mut counter()).unwrap();
1145 let text = signaled.sdp.replace("\r\n", "\n");
1146 assert!(text.contains("m=video 0 RTP/SAVP 102\n"), "{text}");
1147 assert!(text.contains("a=group:BUNDLE 0\n"));
1148 let parsed = parse(&signaled.sdp).unwrap();
1149 assert_eq!(parsed.media.len(), 2);
1150 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1151 assert_eq!(parsed.media[1].direction(), Some("inactive"));
1152 }
1153
1154 const ONE_TO_ONE_VIDEO_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 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=label:main-audio\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\nm=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na=sendrecv\r\na=label:applicationsharing-video\r\n";
1155
1156 fn browser_answer(camera_direction: &str, share_port: &str, share_direction: &str) -> String {
1157 format!("v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 0 1\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:111 opus/48000/2\r\na=mid:0\r\na=sendrecv\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 BB\r\na=setup:active\r\na=ssrc:7 cname:x\r\nm=video 9 UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:1\r\na={camera_direction}\r\na=ssrc:8 cname:x\r\nm=video {share_port} UDP/TLS/RTP/SAVPF 102\r\nc=IN IP4 0.0.0.0\r\na=rtpmap:102 H264/90000\r\na=mid:2\r\na={share_direction}\r\n")
1158 }
1159
1160 #[test]
1161 fn a_one_to_one_offer_keeps_a_camera_line_and_a_sharing_line() {
1162 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1163 let roles: Vec<LineRole> = remote.lines.iter().map(|line| line.role).collect();
1164 assert_eq!(roles, vec![LineRole::MainAudio, LineRole::MainVideo, LineRole::ScreenShare]);
1165 assert_eq!(remote.plan().screen_share_mids, vec!["2".to_owned()]);
1166 assert!(remote.plan().gallery_mids.is_empty());
1167 assert_eq!(parse(&remote.browser_sdp).unwrap().media.iter().filter(|media| media.kind == "video").count(), 2);
1168 }
1169
1170 #[test]
1171 fn accepting_with_audio_answers_the_video_line_receive_only_and_with_video_sending() {
1172 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1173 for (camera_direction, expected) in [("recvonly", "recvonly"), ("sendrecv", "sendrecv")] {
1174 let answer = to_teams_answer(&browser_answer(camera_direction, "0", "inactive"), &remote, &mut counter()).unwrap();
1175 let parsed = parse(&answer.sdp).unwrap();
1176 assert_eq!(parsed.media.len(), 3);
1177 assert_eq!(parsed.media[1].port, "1234");
1178 assert_eq!(parsed.media[1].direction(), Some(expected));
1179 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1180 assert_eq!(parsed.media[2].port, "0");
1181 assert_eq!(parsed.media[2].value("label"), Some("applicationsharing-video"));
1182 }
1183 }
1184
1185 #[test]
1186 fn folded_gallery_lines_expand_below_their_carrier_mid() {
1187 assert_eq!(folded_mids("17", 8), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>());
1188 assert_eq!(folded_mids("x", 2), vec!["x-0".to_owned(), "x".to_owned()]);
1189 }
1190}