BlueGit

ict rusty-teams

Files

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

sdp.rs

chore: cargo fmt the workspace
metis Daniel Däschle · pushed by metis · 2 weeks ago
a6592765 History
sdp.rs 60.5 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] =
16 ["http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"];
17const LAYERS_ALLOCATION: &str =
18 "http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00";
19const NOT_ADVERTISED_SUFFIX: &str = "-non-advertised";
20const DIRECTIONS: [&str; 4] = ["sendrecv", "sendonly", "recvonly", "inactive"];
21
22#[derive(Debug, Clone, PartialEq, Eq)]
23pub struct Attribute {
24 pub name: String,
25 pub value: Option<String>,
26}
27
28impl Attribute {
29 pub fn with_value(name: &str, value: impl Into<String>) -> Self {
30 Attribute::new(name, value)
31 }
32
33 fn new(name: &str, value: impl Into<String>) -> Self {
34 Attribute {
35 name: name.to_owned(),
36 value: Some(value.into()),
37 }
38 }
39
40 fn flag(name: &str) -> Self {
41 Attribute {
42 name: name.to_owned(),
43 value: None,
44 }
45 }
46
47 fn render(&self) -> String {
48 match &self.value {
49 Some(value) => format!("a={}:{value}", self.name),
50 None => format!("a={}", self.name),
51 }
52 }
53}
54
55#[derive(Debug, Clone, Default)]
56pub struct Session {
57 pub version: String,
58 pub origin: String,
59 pub name: String,
60 pub connection: Option<String>,
61 pub bandwidths: Vec<String>,
62 pub timing: String,
63 pub attributes: Vec<Attribute>,
64}
65
66#[derive(Debug, Clone)]
67pub struct Media {
68 pub kind: String,
69 pub port: String,
70 pub proto: String,
71 pub formats: Vec<String>,
72 pub connection: Option<String>,
73 pub bandwidths: Vec<String>,
74 pub attributes: Vec<Attribute>,
75}
76
77#[derive(Debug, Clone)]
78pub struct SessionDescription {
79 pub session: Session,
80 pub media: Vec<Media>,
81}
82
83impl Media {
84 pub fn values<'a>(&'a self, name: &str) -> impl Iterator<Item = &'a str> + 'a {
85 let name = name.to_owned();
86 self.attributes
87 .iter()
88 .filter(move |attribute| attribute.name == name)
89 .filter_map(|attribute| attribute.value.as_deref())
90 }
91
92 pub fn value(&self, name: &str) -> Option<&str> {
93 self.values(name).next()
94 }
95
96 pub fn has(&self, name: &str) -> bool {
97 self.attributes
98 .iter()
99 .any(|attribute| attribute.name == name)
100 }
101
102 pub fn mid(&self) -> Option<&str> {
103 self.value("mid")
104 }
105
106 pub fn direction(&self) -> Option<&str> {
107 self.attributes
108 .iter()
109 .find(|attribute| DIRECTIONS.contains(&attribute.name.as_str()))
110 .map(|attribute| attribute.name.as_str())
111 }
112
113 fn rtpmap(&self) -> HashMap<String, String> {
114 self.values("rtpmap")
115 .filter_map(|value| value.split_once(' '))
116 .map(|(payload, encoding)| (payload.to_owned(), encoding.to_owned()))
117 .collect()
118 }
119}
120
121pub fn parse(text: &str) -> Result<SessionDescription> {
122 let mut session = Session::default();
123 let mut media: Vec<Media> = Vec::new();
124 for raw in text.split('\n') {
125 let line = raw.trim_end_matches('\r');
126 if line.is_empty() {
127 continue;
128 }
129 let (kind, value) = line
130 .split_once('=')
131 .ok_or_else(|| Error::Sdp(format!("line without '=': {line}")))?;
132 if kind == "m" {
133 let mut parts = value.split(' ');
134 let (Some(media_kind), Some(port), Some(proto)) =
135 (parts.next(), parts.next(), parts.next())
136 else {
137 return Err(Error::Sdp(format!("short m-line: {line}")));
138 };
139 media.push(Media {
140 kind: media_kind.to_owned(),
141 port: port.to_owned(),
142 proto: proto.to_owned(),
143 formats: parts.map(str::to_owned).collect(),
144 connection: None,
145 bandwidths: Vec::new(),
146 attributes: Vec::new(),
147 });
148 continue;
149 }
150 let attribute = || {
151 let (name, value) = match value.split_once(':') {
152 Some((name, value)) => (name, Some(value.to_owned())),
153 None => (value, None),
154 };
155 Attribute {
156 name: name.to_owned(),
157 value,
158 }
159 };
160 match (media.last_mut(), kind) {
161 (None, "v") => session.version = value.to_owned(),
162 (None, "o") => session.origin = value.to_owned(),
163 (None, "s") => session.name = value.to_owned(),
164 (None, "c") => session.connection = Some(value.to_owned()),
165 (None, "b") => session.bandwidths.push(value.to_owned()),
166 (None, "t") => session.timing = value.to_owned(),
167 (None, "a") => session.attributes.push(attribute()),
168 (Some(current), "c") => current.connection = Some(value.to_owned()),
169 (Some(current), "b") => current.bandwidths.push(value.to_owned()),
170 (Some(current), "a") => current.attributes.push(attribute()),
171 _ => {}
172 }
173 }
174 Ok(SessionDescription { session, media })
175}
176
177fn session_rank(name: &str) -> usize {
178 match name {
179 "x-mediabw" => 0,
180 "extmap-allow-mixed" => 1,
181 "msid-semantic" => 2,
182 "group" => 3,
183 _ => 99,
184 }
185}
186
187fn media_rank(name: &str) -> usize {
188 match name {
189 "x-multi-stream" => 0,
190 "x-data-protocol" => 1,
191 "x-signaling-fb" => 2,
192 "x-ssrc-range" => 3,
193 "x-source-streamid" => 4,
194 "rtpmap" => 10,
195 "fmtp" => 11,
196 "rtcp" => 12,
197 "rtcp-fb" => 13,
198 "extmap" => 14,
199 "extmap-allow-mixed" => 15,
200 "setup" => 16,
201 "mid" => 17,
202 "msid" => 18,
203 "ptime" => 19,
204 "maxptime" => 20,
205 "sendrecv" | "sendonly" | "recvonly" | "inactive" => 21,
206 "ice-ufrag" => 22,
207 "ice-pwd" => 23,
208 "fingerprint" => 24,
209 "candidate" => 25,
210 "end-of-candidates" => 26,
211 "ice-options" => 27,
212 "ssrc" => 28,
213 "ssrc-group" => 29,
214 "rtcp-mux" => 30,
215 "rtcp-rsize" => 31,
216 "rid" => 32,
217 "simulcast" => 33,
218 "label" => 34,
219 "sctp-port" => 35,
220 "max-message-size" => 36,
221 _ => 99,
222 }
223}
224
225pub fn write(description: &SessionDescription) -> String {
226 let session = &description.session;
227 let mut lines = vec![
228 format!("v={}", session.version),
229 format!("o={}", session.origin),
230 format!("s={}", session.name),
231 ];
232 lines.extend(
233 session
234 .connection
235 .iter()
236 .map(|connection| format!("c={connection}")),
237 );
238 lines.extend(
239 session
240 .bandwidths
241 .iter()
242 .map(|bandwidth| format!("b={bandwidth}")),
243 );
244 lines.push(format!("t={}", session.timing));
245 let mut session_attributes: Vec<&Attribute> = session.attributes.iter().collect();
246 session_attributes.sort_by_key(|attribute| session_rank(&attribute.name));
247 lines.extend(session_attributes.into_iter().map(Attribute::render));
248 for media in &description.media {
249 let mut header = vec![media.kind.clone(), media.port.clone(), media.proto.clone()];
250 header.extend(media.formats.iter().cloned());
251 lines.push(format!("m={}", header.join(" ")));
252 lines.extend(
253 media
254 .connection
255 .iter()
256 .map(|connection| format!("c={connection}")),
257 );
258 lines.extend(
259 media
260 .bandwidths
261 .iter()
262 .map(|bandwidth| format!("b={bandwidth}")),
263 );
264 let mut attributes: Vec<&Attribute> = media.attributes.iter().collect();
265 attributes.sort_by_key(|attribute| media_rank(&attribute.name));
266 lines.extend(attributes.into_iter().map(Attribute::render));
267 }
268 let mut text = lines.join("\r\n");
269 text.push_str("\r\n");
270 text
271}
272
273#[derive(Debug, Clone, Copy, PartialEq, Eq)]
274pub enum LineRole {
275 MainAudio,
276 MainVideo,
277 ScreenShare,
278 Data,
279}
280
281impl LineRole {
282 fn label(self) -> &'static str {
283 match self {
284 LineRole::MainAudio => "main-audio",
285 LineRole::MainVideo => "main-video",
286 LineRole::ScreenShare => "applicationsharing-video",
287 LineRole::Data => "data",
288 }
289 }
290
291 fn stream_prefix(self) -> &'static str {
292 match self {
293 LineRole::MainAudio => "mainAudio",
294 LineRole::MainVideo => "mainVideo",
295 LineRole::ScreenShare => "applicationsharingVideo",
296 LineRole::Data => "data",
297 }
298 }
299}
300
301/// Which browser m-lines play which Teams role; `gallery_mids` are folded into one `x-multi-stream` line.
302#[derive(Debug, Clone, Default)]
303pub struct OfferPlan {
304 pub screen_share_mids: Vec<String>,
305 pub gallery_mids: Vec<String>,
306}
307
308#[derive(Debug, Clone, PartialEq, Eq)]
309pub struct SignaledLine {
310 pub browser_mids: Vec<String>,
311 pub role: LineRole,
312}
313
314#[derive(Debug, Clone)]
315pub struct SignaledOffer {
316 pub sdp: String,
317 pub lines: Vec<SignaledLine>,
318}
319
320/// Random numbers for SSRCs; injected so tests stay deterministic.
321pub trait NumberSource {
322 fn next_u32(&mut self) -> u32;
323}
324
325impl<F: FnMut() -> u32> NumberSource for F {
326 fn next_u32(&mut self) -> u32 {
327 self()
328 }
329}
330
331pub fn to_teams_offer(
332 browser_sdp: &str,
333 plan: &OfferPlan,
334 numbers: &mut impl NumberSource,
335) -> Result<SignaledOffer> {
336 let browser = parse(browser_sdp)?;
337 let cname = browser
338 .media
339 .iter()
340 .flat_map(|media| media.values("ssrc"))
341 .find_map(|value| {
342 value
343 .split_once(" cname:")
344 .map(|(_, cname)| cname.to_owned())
345 })
346 .unwrap_or_else(|| format!("{:08x}{:08x}", numbers.next_u32(), numbers.next_u32()));
347 let gallery_carrier = plan.gallery_mids.last().cloned();
348 let mut lines = Vec::new();
349 let mut media = Vec::new();
350 for source in &browser.media {
351 let mid = source.mid().unwrap_or_default().to_owned();
352 if plan.gallery_mids.contains(&mid) && Some(&mid) != gallery_carrier.as_ref() {
353 continue;
354 }
355 let role = match source.kind.as_str() {
356 "audio" => LineRole::MainAudio,
357 "application" => LineRole::Data,
358 _ if plan.screen_share_mids.contains(&mid) => LineRole::ScreenShare,
359 _ => LineRole::MainVideo,
360 };
361 let multi_stream =
362 (Some(&mid) == gallery_carrier.as_ref()).then_some(plan.gallery_mids.len());
363 let is_first = media.is_empty();
364 let signaled = if source.port == "0" {
365 signal_rejected_line(source, role)
366 } else if role == LineRole::Data {
367 signal_data_line(source, numbers)
368 } else {
369 signal_rtp_line(source, role, multi_stream, &cname, is_first, numbers)
370 };
371 media.push(signaled);
372 lines.push(SignaledLine {
373 browser_mids: match multi_stream {
374 Some(_) => plan.gallery_mids.clone(),
375 None => vec![mid],
376 },
377 role,
378 });
379 }
380 let mut session = browser.session.clone();
381 session.bandwidths = vec![SESSION_BANDWIDTH.to_owned()];
382 for attribute in &mut session.attributes {
383 match attribute.name.as_str() {
384 "msid-semantic" => attribute.value = Some(" WMS *".to_owned()),
385 "group"
386 if attribute
387 .value
388 .as_deref()
389 .is_some_and(|value| value.starts_with("BUNDLE")) =>
390 {
391 let mids: Vec<&str> = media
392 .iter()
393 .filter(|line| line.port != "0")
394 .filter_map(Media::mid)
395 .collect();
396 attribute.value = Some(format!("BUNDLE {}", mids.join(" ")));
397 }
398 _ => {}
399 }
400 }
401 let description = SessionDescription { session, media };
402 Ok(SignaledOffer {
403 sdp: write(&description),
404 lines,
405 })
406}
407
408fn signal_rejected_line(source: &Media, role: LineRole) -> Media {
409 let attributes = vec![
410 Attribute::new("mid", source.mid().unwrap_or_default()),
411 Attribute::flag("inactive"),
412 Attribute::new("label", role.label()),
413 ];
414 Media {
415 kind: if role == LineRole::Data {
416 "x-data".to_owned()
417 } else {
418 source.kind.clone()
419 },
420 port: "0".to_owned(),
421 proto: SIGNALED_PROTO.to_owned(),
422 formats: source.formats.clone(),
423 connection: Some(PLACEHOLDER_CONNECTION.to_owned()),
424 bandwidths: Vec::new(),
425 attributes,
426 }
427}
428
429fn signal_rtp_line(
430 source: &Media,
431 role: LineRole,
432 multi_stream: Option<usize>,
433 cname: &str,
434 carries_candidate: bool,
435 numbers: &mut impl NumberSource,
436) -> Media {
437 let mut media = source.clone();
438 media.port = SIGNALED_PORT.to_owned();
439 media.proto = SIGNALED_PROTO.to_owned();
440 media.connection = Some(PLACEHOLDER_CONNECTION.to_owned());
441 let rtpmap = source.rtpmap();
442 let is_rtx = |payload: &str| {
443 rtpmap
444 .get(payload)
445 .is_some_and(|encoding| encoding.starts_with("rtx/"))
446 };
447 let mid = source.mid().unwrap_or_default().to_owned();
448
449 let mut attributes = Vec::new();
450 if let Some(count) = multi_stream {
451 attributes.push(Attribute::new("x-multi-stream", format!("{count} 1 1 1")));
452 }
453 attributes.push(Attribute::new(
454 "x-signaling-fb",
455 match role {
456 LineRole::MainAudio => "* x-message app recv:dsh",
457 _ => "* x-message app send:src recv:src,vc",
458 },
459 ));
460 let browser_ssrcs: Vec<u32> = source
461 .values("ssrc")
462 .filter_map(|value| value.split(' ').next()?.parse().ok())
463 .collect();
464 let simulcast = source.has("simulcast");
465 let receive_only = source.direction() == Some("recvonly");
466 let (range, ssrc_lines) = if multi_stream.is_some() {
467 (
468 None,
469 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
470 )
471 } else if let Some(&first) = browser_ssrcs.first() {
472 let lines = source
473 .values("ssrc")
474 .map(|value| Attribute::new("ssrc", rewrite_ssrc_msid(value, &mid)))
475 .collect();
476 (Some((first, first)), lines)
477 } else if simulcast {
478 let base = numbers.next_u32();
479 let lines = vec![Attribute::new(
480 "ssrc",
481 format!("{base} fake_attribute:fake_value"),
482 )];
483 (Some((base, base + SSRC_RANGE_SIZE - 1)), lines)
484 } else if receive_only && role != LineRole::MainAudio {
485 (
486 Some((1, 1)),
487 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
488 )
489 } else {
490 let base = numbers.next_u32();
491 (
492 Some((base, base)),
493 vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))],
494 )
495 };
496 if let Some((first, last)) = range {
497 attributes.push(Attribute::new("x-ssrc-range", format!("{first}-{last}")));
498 }
499
500 let video = source.kind == "video";
501 let feedback_by_payload = feedback_by_payload(source);
502 let shared_feedback = shared_feedback(&feedback_by_payload, source, &is_rtx);
503 let mut fmtp: Vec<(usize, Attribute)> = Vec::new();
504 for attribute in &source.attributes {
505 let value = attribute.value.as_deref().unwrap_or_default();
506 match attribute.name.as_str() {
507 "ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" | "candidate"
508 | "end-of-candidates" => {}
509 "rtpmap" => attributes.push(Attribute::new("rtpmap", signal_rtpmap(value))),
510 "fmtp" => {
511 let payload = value.split(' ').next().unwrap_or_default();
512 let position = source
513 .formats
514 .iter()
515 .position(|format| format == payload)
516 .unwrap_or(usize::MAX);
517 let is_opus = rtpmap
518 .get(payload)
519 .is_some_and(|encoding| encoding.to_ascii_lowercase().starts_with("opus/"));
520 let cleaned = if video {
521 value.replace(";sps-pps-idr-in-keyframe=1", "")
522 } else if is_opus {
523 with_fmtp_parameters(value, &OPUS_RECEIVE_FULLBAND)
524 } else {
525 value.to_owned()
526 };
527 fmtp.push((position, Attribute::new("fmtp", cleaned)));
528 }
529 "rtcp" => attributes.push(Attribute::new("rtcp", SIGNALED_PORT)),
530 "extmap" => {
531 if let Some(signaled) = signal_extmap(value) {
532 attributes.push(Attribute::new("extmap", signaled));
533 }
534 }
535 _ => attributes.push(attribute.clone()),
536 }
537 }
538 fmtp.sort_by_key(|(position, _)| *position);
539 attributes.extend(fmtp.into_iter().map(|(_, attribute)| attribute));
540 match shared_feedback {
541 Some(feedback) => attributes.extend(
542 feedback
543 .iter()
544 .map(|kind| Attribute::new("rtcp-fb", format!("* {kind}"))),
545 ),
546 None => attributes.extend(
547 source
548 .attributes
549 .iter()
550 .filter(|attribute| attribute.name == "rtcp-fb")
551 .cloned(),
552 ),
553 }
554 if carries_candidate {
555 attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE));
556 }
557 attributes.extend(ssrc_lines);
558 attributes.extend(
559 source
560 .attributes
561 .iter()
562 .filter(|attribute| attribute.name == "ssrc-group")
563 .cloned(),
564 );
565 attributes.push(Attribute::new("label", role.label()));
566 if !source.has("rtcp-mux") {
567 attributes.push(Attribute::flag("rtcp-mux"));
568 }
569 media.attributes = attributes;
570 media
571}
572
573fn rewrite_ssrc_msid(value: &str, mid: &str) -> String {
574 match value.split_once(" msid:") {
575 Some((ssrc, msid)) => {
576 let stream = msid.split(' ').next().unwrap_or("-");
577 format!("{ssrc} msid:{stream} {mid}")
578 }
579 None => value.to_owned(),
580 }
581}
582
583fn signal_rtpmap(value: &str) -> String {
584 match value.split_once(' ') {
585 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/48000/2") => {
586 format!("{payload} RED/8000")
587 }
588 _ => value.to_owned(),
589 }
590}
591
592fn signal_extmap(value: &str) -> Option<String> {
593 let (identifier, uri) = value.split_once(' ')?;
594 if DROPPED_EXTENSIONS.contains(&uri) {
595 return None;
596 }
597 if BACKSLASHED_EXTENSIONS.contains(&uri) {
598 return Some(format!("{identifier} {}", uri.replace('/', "\\")));
599 }
600 if uri == LAYERS_ALLOCATION {
601 return Some(format!("{identifier} {uri}{NOT_ADVERTISED_SUFFIX}"));
602 }
603 Some(value.to_owned())
604}
605
606fn feedback_by_payload(source: &Media) -> HashMap<String, Vec<String>> {
607 let mut map: HashMap<String, Vec<String>> = HashMap::new();
608 for value in source.values("rtcp-fb") {
609 if let Some((payload, kind)) = value.split_once(' ') {
610 map.entry(payload.to_owned())
611 .or_default()
612 .push(kind.to_owned());
613 }
614 }
615 map
616}
617
618fn shared_feedback(
619 by_payload: &HashMap<String, Vec<String>>,
620 source: &Media,
621 is_rtx: &impl Fn(&str) -> bool,
622) -> Option<Vec<String>> {
623 let mut codecs = source.formats.iter().filter(|payload| !is_rtx(payload));
624 let first = by_payload.get(codecs.next()?)?;
625 codecs
626 .all(|payload| by_payload.get(payload) == Some(first))
627 .then(|| first.clone())
628}
629
630fn signal_data_line(source: &Media, numbers: &mut impl NumberSource) -> Media {
631 let ssrc = numbers.next_u32();
632 let mut attributes = vec![
633 Attribute::new("x-data-protocol", "sctp"),
634 Attribute::new("x-ssrc-range", format!("{ssrc}-{ssrc}")),
635 Attribute::new("rtpmap", "127 x-data/90000"),
636 Attribute::new("rtpmap", "126 rtx/90000"),
637 Attribute::new("fmtp", "126 apt=127"),
638 Attribute::flag("sendrecv"),
639 Attribute::flag("rtcp-mux"),
640 Attribute::new("label", LineRole::Data.label()),
641 ];
642 attributes.extend(source.attributes.iter().cloned());
643 Media {
644 kind: "x-data".to_owned(),
645 port: SIGNALED_PORT.to_owned(),
646 proto: SIGNALED_PROTO.to_owned(),
647 formats: vec!["127".to_owned(), "126".to_owned()],
648 connection: Some(PLACEHOLDER_CONNECTION.to_owned()),
649 bandwidths: Vec::new(),
650 attributes,
651 }
652}
653
654pub fn to_browser_answer(
655 teams_sdp: &str,
656 offer: &SignaledOffer,
657 browser_offer_sdp: &str,
658) -> Result<String> {
659 let answer = parse(teams_sdp)?;
660 let browser_offer = parse(browser_offer_sdp)?;
661 if answer.media.len() != offer.lines.len() {
662 return Err(Error::Sdp(format!(
663 "answer has {} m-lines, offer signaled {}",
664 answer.media.len(),
665 offer.lines.len()
666 )));
667 }
668 let offered: HashMap<&str, &Media> = browser_offer
669 .media
670 .iter()
671 .filter_map(|media| Some((media.mid()?, media)))
672 .collect();
673 let mut media = Vec::new();
674 for (index, (teams_line, signaled)) in answer.media.iter().zip(&offer.lines).enumerate() {
675 for (stream_index, browser_mid) in signaled.browser_mids.iter().enumerate() {
676 let offered_line = offered
677 .get(browser_mid.as_str())
678 .ok_or_else(|| Error::Sdp(format!("offer has no mid {browser_mid}")))?;
679 let section = if signaled.role == LineRole::Data {
680 browser_data_line(teams_line, offered_line, &answer.session)
681 } else {
682 browser_rtp_line(
683 teams_line,
684 offered_line,
685 signaled.role,
686 stream_index as u32,
687 index == 0,
688 &answer.session,
689 )
690 };
691 media.push(section);
692 }
693 }
694 let mut session = answer.session.clone();
695 session
696 .attributes
697 .retain(|attribute| attribute.name.starts_with("x-"));
698 session
699 .attributes
700 .push(Attribute::flag("extmap-allow-mixed"));
701 session
702 .attributes
703 .push(Attribute::new("msid-semantic", " WMS *"));
704 session.attributes.push(Attribute::new(
705 "group",
706 bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))),
707 ));
708 Ok(write(&SessionDescription { session, media }))
709}
710
711fn bundle_group<'a>(lines: impl Iterator<Item = (&'a str, Option<&'a str>)>) -> String {
712 let mids: Vec<&str> = lines
713 .filter(|(port, _)| *port != "0")
714 .filter_map(|(_, mid)| mid)
715 .collect();
716 format!("BUNDLE {}", mids.join(" "))
717}
718
719#[derive(Debug, Clone, PartialEq, Eq)]
720pub struct StreamLine {
721 pub mid: String,
722 pub browser_mid: String,
723 pub role: LineRole,
724 pub source_stream_id: Option<u32>,
725}
726
727pub fn stream_lines(teams_sdp: &str, lines: &[SignaledLine]) -> Result<Vec<StreamLine>> {
728 let teams = parse(teams_sdp)?;
729 if teams.media.len() != lines.len() {
730 return Err(Error::Sdp(format!(
731 "sdp has {} m-lines, {} were signaled",
732 teams.media.len(),
733 lines.len()
734 )));
735 }
736 let mut streams = Vec::new();
737 for (media, line) in teams.media.iter().zip(lines) {
738 let source_stream_id = media
739 .value("x-source-streamid")
740 .and_then(|value| value.trim().parse().ok());
741 let mid = media.mid().unwrap_or_default().to_owned();
742 match line.browser_mids.as_slice() {
743 [browser_mid] => streams.push(StreamLine {
744 mid,
745 browser_mid: browser_mid.clone(),
746 role: line.role,
747 source_stream_id,
748 }),
749 folded => streams.extend(folded.iter().map(|browser_mid| StreamLine {
750 mid: mid.clone(),
751 browser_mid: browser_mid.clone(),
752 role: line.role,
753 source_stream_id: None,
754 })),
755 }
756 }
757 Ok(streams)
758}
759
760fn transport_attributes(teams_line: &Media, session: &Session) -> Vec<Attribute> {
761 ["setup", "ice-ufrag", "ice-pwd", "fingerprint"]
762 .into_iter()
763 .filter_map(|name| {
764 teams_line
765 .attributes
766 .iter()
767 .chain(&session.attributes)
768 .find(|attribute| attribute.name == name)
769 .cloned()
770 })
771 .collect()
772}
773
774const OPUS_SEND_QUALITY: [(&str, &str); 2] =
775 [("maxaveragebitrate", "40000"), ("maxplaybackrate", "48000")];
776
777const OPUS_RECEIVE_FULLBAND: [(&str, &str); 2] = [
778 ("maxplaybackrate", "48000"),
779 ("sprop-maxcapturerate", "48000"),
780];
781
782/// libwebrtc sizes its Opus encoder from these remote fmtp parameters; without them it picks its own bitrate.
783fn with_opus_send_quality(fmtp: &str) -> String {
784 with_fmtp_parameters(fmtp, &OPUS_SEND_QUALITY)
785}
786
787fn with_fmtp_parameters(fmtp: &str, parameters: &[(&str, &str)]) -> String {
788 let mut value = fmtp.to_owned();
789 for &(name, setting) in parameters {
790 if value
791 .split([' ', ';'])
792 .any(|parameter| parameter.split('=').next() == Some(name))
793 {
794 continue;
795 }
796 if !value.ends_with(' ') {
797 value.push(if value.contains(' ') { ';' } else { ' ' });
798 }
799 value.push_str(&format!("{name}={setting}"));
800 }
801 value
802}
803
804fn browser_rtp_line(
805 teams_line: &Media,
806 offered: &Media,
807 role: LineRole,
808 stream_index: u32,
809 carries_candidates: bool,
810 session: &Session,
811) -> Media {
812 let offered_rtpmap = offered.rtpmap();
813 let offered_codecs: HashMap<String, String> = offered_rtpmap
814 .values()
815 .filter_map(|encoding| {
816 let (name, rest) = encoding.split_once('/')?;
817 Some((name.to_ascii_lowercase(), rest.to_owned()))
818 })
819 .collect();
820 let answer_rtpmap = teams_line.rtpmap();
821 let kept: Vec<String> = teams_line
822 .formats
823 .iter()
824 .filter(|payload| {
825 answer_rtpmap
826 .get(*payload)
827 .and_then(|encoding| encoding.split('/').next())
828 .is_some_and(|name| offered_codecs.contains_key(&name.to_ascii_lowercase()))
829 })
830 .cloned()
831 .collect();
832 let kept_set: HashSet<&str> = kept.iter().map(String::as_str).collect();
833 let payload_of = |value: &str| value.split(' ').next().unwrap_or_default().to_owned();
834 let codec_payload = |codec: &str| {
835 kept.iter().find(|payload| {
836 answer_rtpmap.get(*payload).is_some_and(|encoding| {
837 encoding
838 .to_ascii_lowercase()
839 .starts_with(&format!("{codec}/"))
840 })
841 })
842 };
843
844 let mut attributes = Vec::new();
845 attributes.extend(
846 teams_line
847 .values("x-source-streamid")
848 .map(|value| Attribute::new("x-source-streamid", value)),
849 );
850 for value in teams_line.values("rtpmap") {
851 let payload = payload_of(value);
852 if !kept_set.contains(payload.as_str()) {
853 continue;
854 }
855 let encoding = answer_rtpmap.get(&payload).cloned().unwrap_or_default();
856 let name = encoding.split('/').next().unwrap_or_default();
857 let offered_rest = offered_codecs.get(&name.to_ascii_lowercase());
858 let rewritten = match offered_rest {
859 Some(rest) if name.eq_ignore_ascii_case("red") => format!("{payload} {name}/{rest}"),
860 _ => value.to_owned(),
861 };
862 attributes.push(Attribute::new("rtpmap", rewritten));
863 }
864 let mut fmtp_payloads = HashSet::new();
865 for value in teams_line.values("fmtp") {
866 let payload = payload_of(value);
867 if !kept_set.contains(payload.as_str()) {
868 continue;
869 }
870 let cleaned = value
871 .split(';')
872 .filter(|parameter| !parameter.starts_with("rtx-time="))
873 .collect::<Vec<_>>()
874 .join(";");
875 let is_opus = codec_payload("opus").is_some_and(|opus| *opus == payload);
876 fmtp_payloads.insert(payload);
877 attributes.push(Attribute::new(
878 "fmtp",
879 if is_opus {
880 with_opus_send_quality(&cleaned)
881 } else {
882 cleaned
883 },
884 ));
885 }
886 if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) {
887 attributes.push(Attribute::new(
888 "fmtp",
889 with_opus_send_quality(&format!("{opus} usedtx=1")),
890 ));
891 }
892 if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus"))
893 && !fmtp_payloads.contains(red)
894 {
895 attributes.push(Attribute::new("fmtp", format!("{red} {opus}/{opus}")));
896 }
897 attributes.extend(
898 teams_line
899 .values("rtcp")
900 .map(|value| Attribute::new("rtcp", value)),
901 );
902 let answer_feedback: Vec<&str> = teams_line
903 .values("rtcp-fb")
904 .filter(|value| !value.contains("x-message"))
905 .collect();
906 if answer_feedback.is_empty() && !teams_line.has("rtcp-fb") {
907 attributes.extend(
908 offered
909 .values("rtcp-fb")
910 .filter(|value| kept_set.contains(payload_of(value).as_str()))
911 .map(|value| Attribute::new("rtcp-fb", value)),
912 );
913 } else {
914 attributes.extend(
915 answer_feedback
916 .into_iter()
917 .map(|value| Attribute::new("rtcp-fb", value)),
918 );
919 }
920 for value in teams_line.values("extmap") {
921 let restored = value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "");
922 attributes.push(Attribute::new("extmap", restored));
923 }
924 attributes.extend(transport_attributes(teams_line, session));
925 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
926 attributes.extend(
927 teams_line
928 .values("ptime")
929 .map(|value| Attribute::new("ptime", value)),
930 );
931 if let Some(direction) = teams_line.direction() {
932 attributes.push(Attribute::flag(direction));
933 }
934 if carries_candidates {
935 attributes.extend(
936 teams_line
937 .values("candidate")
938 .chain(teams_line.values("x-candidate-ipv6"))
939 .map(|value| Attribute::new("candidate", browser_candidate(value))),
940 );
941 }
942 attributes.extend(stream_ssrc_attributes(teams_line, stream_index, role));
943 attributes.push(Attribute::flag("rtcp-mux"));
944 if teams_line.has("rtcp-rsize") {
945 attributes.push(Attribute::flag("rtcp-rsize"));
946 }
947 if let Some(simulcast) = offered
948 .value("simulcast")
949 .and_then(|value| value.strip_prefix("send "))
950 {
951 let rids: Vec<String> = simulcast
952 .split(';')
953 .map(|rid| rid.trim_start_matches('~').to_owned())
954 .collect();
955 attributes.extend(
956 rids.iter()
957 .map(|rid| Attribute::new("rid", format!("{rid} recv"))),
958 );
959 attributes.push(Attribute::new(
960 "simulcast",
961 format!("recv {}", rids.join(";")),
962 ));
963 }
964 Media {
965 kind: offered.kind.clone(),
966 port: teams_line.port.clone(),
967 proto: offered.proto.clone(),
968 formats: kept,
969 connection: teams_line
970 .connection
971 .clone()
972 .or_else(|| session.connection.clone()),
973 bandwidths: teams_line.bandwidths.clone(),
974 attributes,
975 }
976}
977
978fn stream_ssrc_attributes(teams_line: &Media, stream_index: u32, role: LineRole) -> Vec<Attribute> {
979 let (Some(primary), retransmission) = stream_ssrcs(teams_line, stream_index) else {
980 return Vec::new();
981 };
982 let stream = format!("{}-{primary}", role.stream_prefix());
983 let mut attributes = Vec::new();
984 for ssrc in [Some(primary), retransmission].into_iter().flatten() {
985 attributes.push(Attribute::new(
986 "ssrc",
987 format!("{ssrc} cname:{}", stream_cname(primary)),
988 ));
989 attributes.push(Attribute::new(
990 "ssrc",
991 format!("{ssrc} msid:{stream} {stream}"),
992 ));
993 }
994 if let Some(retransmission) = retransmission {
995 attributes.push(Attribute::new(
996 "ssrc-group",
997 format!("FID {primary} {retransmission}"),
998 ));
999 }
1000 attributes
1001}
1002
1003fn stream_cname(primary: u32) -> String {
1004 format!("teams{primary}")
1005}
1006
1007fn stream_ssrcs(teams_line: &Media, stream_index: u32) -> (Option<u32>, Option<u32>) {
1008 let offset = stream_index * SSRC_RANGE_SIZE;
1009 if let Some(group) = teams_line
1010 .value("ssrc-group")
1011 .and_then(|value| value.strip_prefix("FID "))
1012 {
1013 let mut ssrcs = group
1014 .split(' ')
1015 .filter_map(|value| value.parse::<u32>().ok());
1016 let primary = ssrcs.next().map(|ssrc| ssrc + offset);
1017 return (primary, ssrcs.next().map(|ssrc| ssrc + offset));
1018 }
1019 let first = teams_line
1020 .value("x-ssrc-range")
1021 .and_then(|range| range.split('-').next()?.parse::<u32>().ok())
1022 .map(|ssrc| ssrc + offset);
1023 (first, None)
1024}
1025
1026fn browser_candidate(value: &str) -> String {
1027 let mut parts: Vec<&str> = value.split(' ').collect();
1028 if let Some(position) = parts.iter().position(|part| *part == "MTURNID") {
1029 parts.truncate(position);
1030 }
1031 let tcp_type = match parts
1032 .get(2)
1033 .map(|transport| transport.to_ascii_lowercase())
1034 .as_deref()
1035 {
1036 Some("tcp-pass") => Some("passive"),
1037 Some("tcp-act") => Some("active"),
1038 Some("tcp-so") => Some("so"),
1039 _ => None,
1040 };
1041 if tcp_type.is_some() {
1042 parts[2] = "tcp";
1043 }
1044 let mut candidate = parts.join(" ");
1045 if let Some(tcp_type) = tcp_type {
1046 candidate.push_str(" tcptype ");
1047 candidate.push_str(tcp_type);
1048 }
1049 candidate
1050}
1051
1052fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) -> Media {
1053 let mut attributes = Vec::new();
1054 attributes.extend(
1055 teams_line
1056 .values("x-source-streamid")
1057 .map(|value| Attribute::new("x-source-streamid", value)),
1058 );
1059 attributes.extend(transport_attributes(teams_line, session));
1060 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
1061 attributes.extend(
1062 offered
1063 .values("sctp-port")
1064 .map(|value| Attribute::new("sctp-port", value)),
1065 );
1066 Media {
1067 kind: offered.kind.clone(),
1068 port: teams_line.port.clone(),
1069 proto: offered.proto.clone(),
1070 formats: offered.formats.clone(),
1071 connection: teams_line
1072 .connection
1073 .clone()
1074 .or_else(|| session.connection.clone()),
1075 bandwidths: Vec::new(),
1076 attributes,
1077 }
1078}
1079
1080const BROWSER_PORT: &str = "9";
1081const BROWSER_PROTO: &str = "UDP/TLS/RTP/SAVPF";
1082const BROWSER_CONNECTION: &str = "IN IP4 0.0.0.0";
1083const BROWSER_RTCP: &str = "9 IN IP4 0.0.0.0";
1084const BROWSER_DATA_PROTO: &str = "UDP/DTLS/SCTP";
1085const BROWSER_DATA_FORMAT: &str = "webrtc-datachannel";
1086const SCTP_PORT: &str = "5000";
1087const SCTP_MAX_MESSAGE_SIZE: &str = "262144";
1088const PLACEHOLDER_CANDIDATE_TAIL: &str = " 1234 typ host";
1089const TEAMS_ONLY_ATTRIBUTES: [&str; 6] = [
1090 "x-multi-stream",
1091 "x-signaling-fb",
1092 "x-ssrc-range",
1093 "x-source-streamid",
1094 "x-data-protocol",
1095 "label",
1096];
1097const TRANSPORT_ATTRIBUTES: [&str; 5] = [
1098 "setup",
1099 "ice-ufrag",
1100 "ice-pwd",
1101 "fingerprint",
1102 "ice-options",
1103];
1104
1105/// A Teams offer translated for libwebrtc; `lines` remembers which browser mids each signaled line stands for.
1106#[derive(Debug, Clone)]
1107pub struct RemoteOffer {
1108 pub browser_sdp: String,
1109 pub lines: Vec<SignaledLine>,
1110}
1111
1112impl RemoteOffer {
1113 pub fn plan(&self) -> OfferPlan {
1114 let mut plan = OfferPlan::default();
1115 for line in &self.lines {
1116 match line.role {
1117 LineRole::ScreenShare => plan
1118 .screen_share_mids
1119 .extend(line.browser_mids.iter().cloned()),
1120 _ if line.browser_mids.len() > 1 => {
1121 plan.gallery_mids.extend(line.browser_mids.iter().cloned())
1122 }
1123 _ => {}
1124 }
1125 }
1126 plan
1127 }
1128}
1129
1130fn role_of_teams_line(line: &Media) -> LineRole {
1131 match line.value("label") {
1132 Some("main-audio") => LineRole::MainAudio,
1133 Some("main-video") => LineRole::MainVideo,
1134 Some("applicationsharing-video") => LineRole::ScreenShare,
1135 Some("data") => LineRole::Data,
1136 _ => match line.kind.as_str() {
1137 "audio" => LineRole::MainAudio,
1138 "x-data" | "application" => LineRole::Data,
1139 _ => LineRole::MainVideo,
1140 },
1141 }
1142}
1143
1144/// Folded gallery lines get the mids just below the carrier line's own mid, unless another line already uses one of them.
1145fn folded_mids(carrier: &str, count: usize, taken: &[String]) -> Vec<String> {
1146 let below = match carrier.parse::<usize>() {
1147 Ok(last) if last + 1 >= count => Some(
1148 (last + 1 - count..=last)
1149 .map(|mid| mid.to_string())
1150 .collect::<Vec<_>>(),
1151 ),
1152 _ => None,
1153 };
1154 match below.filter(|mids| {
1155 mids.iter()
1156 .all(|mid| mid == carrier || !taken.contains(mid))
1157 }) {
1158 Some(mids) => mids,
1159 None => (0..count)
1160 .map(|index| {
1161 if index + 1 == count {
1162 carrier.to_owned()
1163 } else {
1164 format!("{carrier}-{index}")
1165 }
1166 })
1167 .collect(),
1168 }
1169}
1170
1171pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
1172 let teams = parse(teams_sdp)?;
1173 let mut media = Vec::new();
1174 let mut lines = Vec::new();
1175 let mut taken: Vec<String> = teams
1176 .media
1177 .iter()
1178 .filter_map(|line| line.mid().map(str::to_owned))
1179 .collect();
1180 for source in &teams.media {
1181 let role = role_of_teams_line(source);
1182 let carrier = source.mid().unwrap_or_default().to_owned();
1183 let folded = source
1184 .value("x-multi-stream")
1185 .and_then(|value| value.split(' ').next()?.parse::<usize>().ok())
1186 .filter(|count| *count > 1);
1187 let mids = match folded {
1188 Some(count) => folded_mids(&carrier, count, &taken),
1189 None => vec![carrier.clone()],
1190 };
1191 taken.extend(mids.iter().cloned());
1192 for (index, mid) in mids.iter().enumerate() {
1193 let converted = if role == LineRole::Data {
1194 browser_data_from_teams(source, mid, &teams.session)
1195 } else {
1196 browser_rtp_from_teams(
1197 source,
1198 mid,
1199 role,
1200 folded.is_some(),
1201 index == 0 && lines.is_empty(),
1202 &teams.session,
1203 )
1204 };
1205 media.push(converted);
1206 }
1207 lines.push(SignaledLine {
1208 browser_mids: mids,
1209 role,
1210 });
1211 }
1212 let mut session = teams.session.clone();
1213 session.bandwidths.clear();
1214 session.connection = None;
1215 session.attributes.retain(|attribute| {
1216 matches!(
1217 attribute.name.as_str(),
1218 "extmap-allow-mixed" | "msid-semantic"
1219 )
1220 });
1221 session.attributes.push(Attribute::new(
1222 "group",
1223 bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))),
1224 ));
1225 Ok(RemoteOffer {
1226 browser_sdp: write(&SessionDescription { session, media }),
1227 lines,
1228 })
1229}
1230
1231fn transport_from_teams(source: &Media, session: &Session) -> Vec<Attribute> {
1232 TRANSPORT_ATTRIBUTES
1233 .iter()
1234 .filter_map(|name| {
1235 source
1236 .attributes
1237 .iter()
1238 .chain(&session.attributes)
1239 .find(|attribute| attribute.name == *name)
1240 .cloned()
1241 })
1242 .collect()
1243}
1244
1245fn browser_data_from_teams(source: &Media, mid: &str, session: &Session) -> Media {
1246 let mut attributes = transport_from_teams(source, session);
1247 attributes.push(Attribute::new("mid", mid));
1248 attributes.push(Attribute::new("sctp-port", SCTP_PORT));
1249 attributes.push(Attribute::new("max-message-size", SCTP_MAX_MESSAGE_SIZE));
1250 Media {
1251 kind: "application".to_owned(),
1252 port: BROWSER_PORT.to_owned(),
1253 proto: BROWSER_DATA_PROTO.to_owned(),
1254 formats: vec![BROWSER_DATA_FORMAT.to_owned()],
1255 connection: Some(BROWSER_CONNECTION.to_owned()),
1256 bandwidths: Vec::new(),
1257 attributes,
1258 }
1259}
1260
1261fn browser_rtp_from_teams(
1262 source: &Media,
1263 mid: &str,
1264 role: LineRole,
1265 folded: bool,
1266 carries_candidate: bool,
1267 session: &Session,
1268) -> Media {
1269 let rtpmap = source.rtpmap();
1270 let is_rtx = |payload: &str| {
1271 rtpmap
1272 .get(payload)
1273 .is_some_and(|encoding| encoding.starts_with("rtx/"))
1274 };
1275 let mut attributes = Vec::new();
1276 let mut expanded_feedback: Vec<Attribute> = Vec::new();
1277 let mut signals_ssrc = false;
1278 let mut ssrc_groups = Vec::new();
1279 for attribute in &source.attributes {
1280 let value = attribute.value.as_deref().unwrap_or_default();
1281 match attribute.name.as_str() {
1282 name if TEAMS_ONLY_ATTRIBUTES.contains(&name) => {}
1283 "x-candidate-ipv6" => {
1284 if carries_candidate {
1285 attributes.push(Attribute::new("candidate", browser_candidate(value)));
1286 }
1287 }
1288 name if name.starts_with("x-") => {}
1289 "mid" | "rtcp-mux" => {}
1290 name if TRANSPORT_ATTRIBUTES.contains(&name) => {}
1291 "candidate" => {
1292 if carries_candidate && !value.contains(PLACEHOLDER_CANDIDATE_TAIL) {
1293 attributes.push(Attribute::new("candidate", browser_candidate(value)));
1294 }
1295 }
1296 "ssrc" => {
1297 let placeholder = value.contains("fake_attribute") || value.starts_with("1 ");
1298 if !folded && !placeholder {
1299 signals_ssrc = true;
1300 attributes.push(attribute.clone());
1301 }
1302 }
1303 "ssrc-group" => {
1304 if !folded {
1305 ssrc_groups.push(attribute.clone());
1306 }
1307 }
1308 "rtcp" => attributes.push(Attribute::new("rtcp", BROWSER_RTCP)),
1309 "rtpmap" => attributes.push(Attribute::new("rtpmap", browser_rtpmap(value))),
1310 "extmap" => attributes.push(Attribute::new("extmap", browser_extmap(value))),
1311 "rtcp-fb" => match value.strip_prefix("* ") {
1312 Some(kind) => expanded_feedback.extend(
1313 source
1314 .formats
1315 .iter()
1316 .filter(|payload| !is_rtx(payload))
1317 .map(|payload| Attribute::new("rtcp-fb", format!("{payload} {kind}"))),
1318 ),
1319 None => attributes.push(attribute.clone()),
1320 },
1321 _ => attributes.push(attribute.clone()),
1322 }
1323 }
1324 attributes.extend(expanded_feedback);
1325 attributes.extend(transport_from_teams(source, session));
1326 attributes.push(Attribute::new("mid", mid));
1327 if signals_ssrc {
1328 attributes.extend(ssrc_groups);
1329 } else if !folded {
1330 attributes.extend(stream_ssrc_attributes(source, 0, role));
1331 }
1332 attributes.push(Attribute::flag("rtcp-mux"));
1333 Media {
1334 kind: source.kind.clone(),
1335 port: BROWSER_PORT.to_owned(),
1336 proto: BROWSER_PROTO.to_owned(),
1337 formats: source.formats.clone(),
1338 connection: Some(BROWSER_CONNECTION.to_owned()),
1339 bandwidths: Vec::new(),
1340 attributes,
1341 }
1342}
1343
1344fn browser_rtpmap(value: &str) -> String {
1345 match value.split_once(' ') {
1346 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => {
1347 format!("{payload} red/48000/2")
1348 }
1349 _ => value.to_owned(),
1350 }
1351}
1352
1353fn browser_extmap(value: &str) -> String {
1354 value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "")
1355}
1356
1357/// libwebrtc answers every offered line in the offer's order and with its mids, so the offer's plan applies unchanged.
1358pub fn to_teams_answer(
1359 browser_answer_sdp: &str,
1360 remote: &RemoteOffer,
1361 numbers: &mut impl NumberSource,
1362) -> Result<SignaledOffer> {
1363 to_teams_offer(browser_answer_sdp, &remote.plan(), numbers)
1364}
1365
1366#[cfg(test)]
1367mod tests {
1368 use super::*;
1369
1370 fn counter() -> impl FnMut() -> u32 {
1371 let mut next = 1000u32;
1372 move || {
1373 next += 1;
1374 next
1375 }
1376 }
1377
1378 #[test]
1379 fn rejected_lines_stay_out_of_the_bundle() {
1380 let lines = [("9", Some("0")), ("0", Some("1")), ("9", Some("2"))];
1381 assert_eq!(bundle_group(lines.into_iter()), "BUNDLE 0 2");
1382 }
1383
1384 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";
1385
1386 #[test]
1387 fn audio_only_offer_gets_the_teams_shape() {
1388 let offer =
1389 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1390 let text = offer.sdp.replace("\r\n", "\n");
1391 assert!(text.contains("\nb=CT:4000\n"));
1392 assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\n"));
1393 assert!(text.contains("a=x-signaling-fb:* x-message app recv:dsh\n"));
1394 assert!(text.contains("a=x-ssrc-range:42-42\n"));
1395 assert!(text.contains("a=rtpmap:63 RED/8000\n"));
1396 assert!(text.contains("a=fmtp:111 minptime=10;useinbandfec=1;maxplaybackrate=48000;sprop-maxcapturerate=48000\n"));
1397 assert!(text.contains("a=rtcp:1234\n"));
1398 assert!(text.contains(
1399 "a=extmap:2 http:\\\\www.webrtc.org\\experiments\\rtp-hdrext\\abs-send-time\n"
1400 ));
1401 assert!(text.contains("a=ssrc:42 msid:stream 0\n"));
1402 assert!(
1403 text.contains("a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\n")
1404 );
1405 assert!(
1406 text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\nc=IN IP4 10.10.10.10\n")
1407 );
1408 assert!(text.ends_with("a=label:main-audio\n"));
1409 assert_eq!(
1410 offer.lines,
1411 vec![SignaledLine {
1412 browser_mids: vec!["0".into()],
1413 role: LineRole::MainAudio
1414 }]
1415 );
1416 }
1417
1418 #[test]
1419 fn a_renegotiation_signals_only_the_placeholder_candidate() {
1420 let gathered = AUDIO_ONLY_OFFER.replace(
1421 "a=mid:0\r\n",
1422 "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",
1423 );
1424 let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter())
1425 .unwrap()
1426 .sdp;
1427 let candidates: Vec<&str> = text
1428 .lines()
1429 .filter(|line| {
1430 line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")
1431 })
1432 .collect();
1433 assert_eq!(
1434 candidates,
1435 vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]
1436 );
1437 }
1438
1439 #[test]
1440 fn answer_candidates_lose_teams_extensions() {
1441 assert_eq!(
1442 browser_candidate(
1443 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 158"
1444 ),
1445 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480"
1446 );
1447 assert_eq!(
1448 browser_candidate(
1449 "3 1 tcp-pass 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478"
1450 ),
1451 "3 1 tcp 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478 tcptype passive"
1452 );
1453 assert_eq!(
1454 browser_candidate(
1455 "10 1 TCP-ACT 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009"
1456 ),
1457 "10 1 tcp 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009 tcptype active"
1458 );
1459 }
1460
1461 #[test]
1462 fn audio_answer_maps_back_to_the_browser_mid_and_codecs() {
1463 let offer =
1464 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1465 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";
1466 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER)
1467 .unwrap()
1468 .replace("\r\n", "\n");
1469 assert!(
1470 browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"),
1471 "{browser}"
1472 );
1473 assert!(browser.contains("a=rtpmap:97 RED/48000/2\n"));
1474 assert!(
1475 browser.contains("a=fmtp:111 usedtx=1;maxaveragebitrate=40000;maxplaybackrate=48000\n")
1476 );
1477 assert!(browser.contains("a=fmtp:97 111/111\n"));
1478 assert!(browser.contains("a=rtcp-fb:111 transport-cc\n"));
1479 assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n"));
1480 assert!(browser.contains("a=group:BUNDLE 0\n"));
1481 assert!(
1482 !browser.contains("SATINFB")
1483 && !browser.contains("MTURNID")
1484 && !browser.contains("label")
1485 );
1486 }
1487 #[test]
1488 fn an_audio_offer_from_teams_gets_the_browser_shape_back() {
1489 let offer =
1490 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1491 let remote = from_teams_offer(&offer.sdp).unwrap();
1492 let text = remote.browser_sdp.replace("\r\n", "\n");
1493 assert!(
1494 text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"),
1495 "{text}"
1496 );
1497 assert!(text.contains("c=IN IP4 0.0.0.0\n"));
1498 assert!(text.contains("a=rtcp:9 IN IP4 0.0.0.0\n"));
1499 assert!(text.contains("a=rtpmap:63 red/48000/2\n"));
1500 assert!(
1501 text.contains(
1502 "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"
1503 )
1504 );
1505 assert!(
1506 text.contains("a=ice-ufrag:u\n")
1507 && text.contains("a=fingerprint:sha-256 AA\n")
1508 && text.contains("a=setup:actpass\n")
1509 );
1510 assert!(text.contains("a=mid:0\n") && text.contains("a=group:BUNDLE 0\n"));
1511 assert!(
1512 !text.contains("10.10.10.10")
1513 && !text.contains("x-ssrc-range")
1514 && !text.contains("label")
1515 && !text.contains("1234")
1516 );
1517 assert_eq!(remote.lines, offer.lines);
1518 }
1519
1520 #[test]
1521 fn shared_video_feedback_is_spelled_out_per_codec_again() {
1522 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";
1523 let remote = from_teams_offer(teams).unwrap();
1524 let text = remote.browser_sdp.replace("\r\n", "\n");
1525 assert!(text.contains("a=rtcp-fb:102 nack\n") && text.contains("a=rtcp-fb:102 nack pli\n"));
1526 assert!(!text.contains("a=rtcp-fb:103") && !text.contains("a=rtcp-fb:*"));
1527 }
1528
1529 #[test]
1530 fn a_peer_offer_with_only_ssrc_ranges_signals_the_streams_it_sends() {
1531 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 1\r\nm=audio 1234 RTP/SAVP 111\r\nc=IN IP4 10.10.10.10\r\na=x-ssrc-range:40475-40475\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 103 104\r\nc=IN IP4 10.10.10.10\r\na=x-ssrc-range:40476-40575\r\na=rtpmap:103 H264/90000\r\na=rtpmap:104 rtx/90000\r\na=fmtp:104 apt=103\r\na=ssrc-group:FID 40476 40526\r\na=mid:1\r\na=sendrecv\r\na=label:main-video\r\n";
1532 let remote = from_teams_offer(teams).unwrap();
1533 let parsed = parse(&remote.browser_sdp).unwrap();
1534 let audio: Vec<&str> = parsed.media[0].values("ssrc").collect();
1535 assert!(
1536 audio.iter().any(|value| value.starts_with("40475 cname:")),
1537 "{audio:?}"
1538 );
1539 assert_eq!(
1540 parsed.media[1].values("ssrc-group").collect::<Vec<_>>(),
1541 vec!["FID 40476 40526"]
1542 );
1543 let video: Vec<&str> = parsed.media[1].values("ssrc").collect();
1544 assert!(
1545 video.iter().any(|value| value.starts_with("40476 cname:"))
1546 && video.iter().any(|value| value.starts_with("40526 cname:")),
1547 "{video:?}"
1548 );
1549 }
1550
1551 #[test]
1552 fn a_rejected_video_line_stays_rejected_and_out_of_the_bundle() {
1553 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";
1554 let remote = from_teams_offer(audio_and_video).unwrap();
1555 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";
1556 let signaled = to_teams_answer(answer, &remote, &mut counter()).unwrap();
1557 let text = signaled.sdp.replace("\r\n", "\n");
1558 assert!(text.contains("m=video 0 RTP/SAVP 102\n"), "{text}");
1559 assert!(text.contains("a=group:BUNDLE 0\n"));
1560 let parsed = parse(&signaled.sdp).unwrap();
1561 assert_eq!(parsed.media.len(), 2);
1562 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1563 assert_eq!(parsed.media[1].direction(), Some("inactive"));
1564 }
1565
1566 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";
1567
1568 fn browser_answer(camera_direction: &str, share_port: &str, share_direction: &str) -> String {
1569 format!(
1570 "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"
1571 )
1572 }
1573
1574 #[test]
1575 fn a_folded_line_never_reuses_the_mid_of_another_line() {
1576 let folded = "m=video 1234 RTP/SAVP 102\r\nc=IN IP4 10.10.10.10\r\na=rtpmap:102 H264/90000\r\na=mid:3\r\na=sendrecv\r\na=x-multi-stream:2 1 1 1\r\n";
1577 let teams = format!(
1578 "{}{folded}",
1579 ONE_TO_ONE_VIDEO_OFFER.replace("BUNDLE 0 1 2", "BUNDLE 0 1 2 3")
1580 );
1581 let remote = from_teams_offer(&teams).unwrap();
1582 let mids: Vec<String> = parse(&remote.browser_sdp)
1583 .unwrap()
1584 .media
1585 .iter()
1586 .filter_map(|line| line.mid().map(str::to_owned))
1587 .collect();
1588 let mut unique = mids.clone();
1589 unique.sort();
1590 unique.dedup();
1591 assert_eq!(unique.len(), mids.len(), "{mids:?}");
1592 assert_eq!(
1593 remote.lines.last().unwrap().browser_mids,
1594 vec!["3-0".to_owned(), "3".to_owned()]
1595 );
1596 }
1597
1598 #[test]
1599 fn a_one_to_one_offer_keeps_a_camera_line_and_a_sharing_line() {
1600 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1601 let roles: Vec<LineRole> = remote.lines.iter().map(|line| line.role).collect();
1602 assert_eq!(
1603 roles,
1604 vec![
1605 LineRole::MainAudio,
1606 LineRole::MainVideo,
1607 LineRole::ScreenShare
1608 ]
1609 );
1610 assert_eq!(remote.plan().screen_share_mids, vec!["2".to_owned()]);
1611 assert!(remote.plan().gallery_mids.is_empty());
1612 assert_eq!(
1613 parse(&remote.browser_sdp)
1614 .unwrap()
1615 .media
1616 .iter()
1617 .filter(|media| media.kind == "video")
1618 .count(),
1619 2
1620 );
1621 }
1622
1623 #[test]
1624 fn accepting_with_audio_answers_the_video_line_receive_only_and_with_video_sending() {
1625 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1626 for (camera_direction, expected) in [("recvonly", "recvonly"), ("sendrecv", "sendrecv")] {
1627 let answer = to_teams_answer(
1628 &browser_answer(camera_direction, "0", "inactive"),
1629 &remote,
1630 &mut counter(),
1631 )
1632 .unwrap();
1633 let parsed = parse(&answer.sdp).unwrap();
1634 assert_eq!(parsed.media.len(), 3);
1635 assert_eq!(parsed.media[1].port, "1234");
1636 assert_eq!(parsed.media[1].direction(), Some(expected));
1637 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1638 assert_eq!(parsed.media[2].port, "0");
1639 assert_eq!(
1640 parsed.media[2].value("label"),
1641 Some("applicationsharing-video")
1642 );
1643 }
1644 }
1645
1646 #[test]
1647 fn folded_gallery_lines_expand_below_their_carrier_mid_unless_those_are_taken() {
1648 let taken = ["0".to_owned(), "1".to_owned(), "17".to_owned()];
1649 assert_eq!(
1650 folded_mids("17", 8, &taken),
1651 (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>()
1652 );
1653 assert_eq!(
1654 folded_mids("x", 2, &taken),
1655 vec!["x-0".to_owned(), "x".to_owned()]
1656 );
1657 assert_eq!(
1658 folded_mids("2", 2, &taken),
1659 vec!["2-0".to_owned(), "2".to_owned()]
1660 );
1661 }
1662
1663 #[test]
1664 fn opus_fmtp_gets_the_send_quality_without_overriding_teams() {
1665 assert_eq!(
1666 with_opus_send_quality("111 minptime=10;useinbandfec=1"),
1667 "111 minptime=10;useinbandfec=1;maxaveragebitrate=40000;maxplaybackrate=48000"
1668 );
1669 assert_eq!(
1670 with_opus_send_quality("111 maxplaybackrate=16000"),
1671 "111 maxplaybackrate=16000;maxaveragebitrate=40000"
1672 );
1673 assert_eq!(
1674 with_opus_send_quality("111"),
1675 "111 maxaveragebitrate=40000;maxplaybackrate=48000"
1676 );
1677 }
1678}