BlueGit

ict rusty-teams

Files

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

sdp.rs

sdp.rs 71.4 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.
302/// `gallery_mids` / `fold_groups` collapse several browser mids into one Teams `x-multi-stream` line.
303#[derive(Debug, Clone, Default)]
304pub struct OfferPlan {
305 pub screen_share_mids: Vec<String>,
306 pub gallery_mids: Vec<String>,
307 /// Each group is one Teams line; the last mid is the carrier written back to Teams.
308 pub fold_groups: Vec<Vec<String>>,
309}
310
311#[derive(Debug, Clone, PartialEq, Eq)]
312pub struct SignaledLine {
313 pub browser_mids: Vec<String>,
314 pub role: LineRole,
315}
316
317#[derive(Debug, Clone)]
318pub struct SignaledOffer {
319 pub sdp: String,
320 pub lines: Vec<SignaledLine>,
321}
322
323/// Random numbers for SSRCs; injected so tests stay deterministic.
324pub trait NumberSource {
325 fn next_u32(&mut self) -> u32;
326}
327
328impl<F: FnMut() -> u32> NumberSource for F {
329 fn next_u32(&mut self) -> u32 {
330 self()
331 }
332}
333
334pub fn to_teams_offer(
335 browser_sdp: &str,
336 plan: &OfferPlan,
337 numbers: &mut impl NumberSource,
338) -> Result<SignaledOffer> {
339 let browser = parse(browser_sdp)?;
340 let cname = browser
341 .media
342 .iter()
343 .flat_map(|media| media.values("ssrc"))
344 .find_map(|value| {
345 value
346 .split_once(" cname:")
347 .map(|(_, cname)| cname.to_owned())
348 })
349 .unwrap_or_else(|| format!("{:08x}{:08x}", numbers.next_u32(), numbers.next_u32()));
350 let fold_groups = effective_fold_groups(plan);
351 let mut lines = Vec::new();
352 let mut media = Vec::new();
353 for source in &browser.media {
354 let mid = source.mid().unwrap_or_default().to_owned();
355 let fold_group = fold_groups
356 .iter()
357 .find(|group| group.iter().any(|entry| entry == &mid));
358 let fold_carrier = fold_group.and_then(|group| group.last());
359 if fold_group.is_some() && Some(&mid) != fold_carrier {
360 continue;
361 }
362 let role = match source.kind.as_str() {
363 "audio" => LineRole::MainAudio,
364 "application" => LineRole::Data,
365 _ if plan.screen_share_mids.contains(&mid) => LineRole::ScreenShare,
366 _ => LineRole::MainVideo,
367 };
368 let multi_stream = fold_group.map(|group| group.len());
369 let is_first = media.is_empty();
370 let signaled = if source.port == "0" {
371 signal_rejected_line(source, role, multi_stream)
372 } else if role == LineRole::Data {
373 signal_data_line(source, numbers)
374 } else {
375 signal_rtp_line(source, role, multi_stream, &cname, is_first, numbers)
376 };
377 media.push(signaled);
378 lines.push(SignaledLine {
379 browser_mids: match fold_group {
380 Some(group) => group.clone(),
381 None => vec![mid],
382 },
383 role,
384 });
385 }
386 let mut session = browser.session.clone();
387 session.bandwidths = vec![SESSION_BANDWIDTH.to_owned()];
388 for attribute in &mut session.attributes {
389 match attribute.name.as_str() {
390 "msid-semantic" => attribute.value = Some(" WMS *".to_owned()),
391 "group"
392 if attribute
393 .value
394 .as_deref()
395 .is_some_and(|value| value.starts_with("BUNDLE")) =>
396 {
397 let mids: Vec<&str> = media
398 .iter()
399 .filter(|line| line.port != "0")
400 .filter_map(Media::mid)
401 .collect();
402 attribute.value = Some(format!("BUNDLE {}", mids.join(" ")));
403 }
404 _ => {}
405 }
406 }
407 let description = SessionDescription { session, media };
408 Ok(SignaledOffer {
409 sdp: write(&description),
410 lines,
411 })
412}
413
414fn signal_rejected_line(source: &Media, role: LineRole, multi_stream: Option<usize>) -> Media {
415 let mut attributes = Vec::new();
416 if let Some(count) = multi_stream {
417 attributes.push(Attribute::new("x-multi-stream", format!("{count} 1 1 1")));
418 }
419 attributes.push(Attribute::new("mid", source.mid().unwrap_or_default()));
420 attributes.push(Attribute::flag("inactive"));
421 attributes.push(Attribute::new("label", role.label()));
422 Media {
423 kind: if role == LineRole::Data {
424 "x-data".to_owned()
425 } else {
426 source.kind.clone()
427 },
428 port: "0".to_owned(),
429 proto: SIGNALED_PROTO.to_owned(),
430 formats: source.formats.clone(),
431 connection: Some(PLACEHOLDER_CONNECTION.to_owned()),
432 bandwidths: Vec::new(),
433 attributes,
434 }
435}
436
437fn signal_rtp_line(
438 source: &Media,
439 role: LineRole,
440 multi_stream: Option<usize>,
441 cname: &str,
442 carries_candidate: bool,
443 numbers: &mut impl NumberSource,
444) -> Media {
445 let mut media = source.clone();
446 media.port = SIGNALED_PORT.to_owned();
447 media.proto = SIGNALED_PROTO.to_owned();
448 media.connection = Some(PLACEHOLDER_CONNECTION.to_owned());
449 let rtpmap = source.rtpmap();
450 let is_rtx = |payload: &str| {
451 rtpmap
452 .get(payload)
453 .is_some_and(|encoding| encoding.starts_with("rtx/"))
454 };
455 let mid = source.mid().unwrap_or_default().to_owned();
456
457 let mut attributes = Vec::new();
458 if let Some(count) = multi_stream {
459 attributes.push(Attribute::new("x-multi-stream", format!("{count} 1 1 1")));
460 }
461 attributes.push(Attribute::new(
462 "x-signaling-fb",
463 match role {
464 LineRole::MainAudio => "* x-message app recv:dsh",
465 _ => "* x-message app send:src recv:src,vc",
466 },
467 ));
468 let browser_ssrcs: Vec<u32> = source
469 .values("ssrc")
470 .filter_map(|value| value.split(' ').next()?.parse().ok())
471 .collect();
472 let simulcast = source.has("simulcast");
473 let receive_only = source.direction() == Some("recvonly");
474 let (range, ssrc_lines, copy_ssrc_groups) = if multi_stream.is_some() {
475 // Teams rejects x-ssrc-range / ssrc-group on x-multi-stream lines with SdpParsingFailure (301000).
476 (
477 None,
478 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
479 false,
480 )
481 } else if let Some(&first) = browser_ssrcs.first() {
482 let lines = source
483 .values("ssrc")
484 .map(|value| Attribute::new("ssrc", rewrite_ssrc_msid(value, &mid)))
485 .collect();
486 (Some((first, first)), lines, true)
487 } else if simulcast {
488 let base = numbers.next_u32();
489 let lines = vec![Attribute::new(
490 "ssrc",
491 format!("{base} fake_attribute:fake_value"),
492 )];
493 (Some((base, base + SSRC_RANGE_SIZE - 1)), lines, false)
494 } else if receive_only && role != LineRole::MainAudio {
495 (
496 Some((1, 1)),
497 vec![Attribute::new("ssrc", format!("1 cname:{cname}"))],
498 false,
499 )
500 } else {
501 let base = numbers.next_u32();
502 (
503 Some((base, base)),
504 vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))],
505 false,
506 )
507 };
508 if let Some((first, last)) = range {
509 attributes.push(Attribute::new("x-ssrc-range", format!("{first}-{last}")));
510 }
511
512 let video = source.kind == "video";
513 let feedback_by_payload = feedback_by_payload(source);
514 let shared_feedback = shared_feedback(&feedback_by_payload, source, &is_rtx);
515 let mut fmtp: Vec<(usize, Attribute)> = Vec::new();
516 for attribute in &source.attributes {
517 let value = attribute.value.as_deref().unwrap_or_default();
518 match attribute.name.as_str() {
519 "ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" | "candidate"
520 | "end-of-candidates" => {}
521 "rtpmap" => attributes.push(Attribute::new("rtpmap", signal_rtpmap(value))),
522 "fmtp" => {
523 let payload = value.split(' ').next().unwrap_or_default();
524 let position = source
525 .formats
526 .iter()
527 .position(|format| format == payload)
528 .unwrap_or(usize::MAX);
529 let is_opus = rtpmap
530 .get(payload)
531 .is_some_and(|encoding| encoding.to_ascii_lowercase().starts_with("opus/"));
532 let cleaned = if video {
533 without_fmtp_parameter(
534 &value.replace(";sps-pps-idr-in-keyframe=1", ""),
535 H264_SEND_START[0].0,
536 )
537 } else if is_opus {
538 with_fmtp_parameters(value, &OPUS_RECEIVE_FULLBAND)
539 } else {
540 value.to_owned()
541 };
542 fmtp.push((position, Attribute::new("fmtp", cleaned)));
543 }
544 "rtcp" => attributes.push(Attribute::new("rtcp", SIGNALED_PORT)),
545 "extmap" => {
546 if let Some(signaled) = signal_extmap(value) {
547 attributes.push(Attribute::new("extmap", signaled));
548 }
549 }
550 _ => attributes.push(attribute.clone()),
551 }
552 }
553 fmtp.sort_by_key(|(position, _)| *position);
554 attributes.extend(fmtp.into_iter().map(|(_, attribute)| attribute));
555 match shared_feedback {
556 Some(feedback) => attributes.extend(
557 feedback
558 .iter()
559 .map(|kind| Attribute::new("rtcp-fb", format!("* {kind}"))),
560 ),
561 None => attributes.extend(
562 source
563 .attributes
564 .iter()
565 .filter(|attribute| attribute.name == "rtcp-fb")
566 .cloned(),
567 ),
568 }
569 if carries_candidate {
570 attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE));
571 }
572 attributes.extend(ssrc_lines);
573 if copy_ssrc_groups {
574 attributes.extend(
575 source
576 .attributes
577 .iter()
578 .filter(|attribute| attribute.name == "ssrc-group")
579 .cloned(),
580 );
581 }
582 attributes.push(Attribute::new("label", role.label()));
583 if !source.has("rtcp-mux") {
584 attributes.push(Attribute::flag("rtcp-mux"));
585 }
586 media.attributes = attributes;
587 media
588}
589
590fn rewrite_ssrc_msid(value: &str, mid: &str) -> String {
591 match value.split_once(" msid:") {
592 Some((ssrc, msid)) => {
593 let stream = msid.split(' ').next().unwrap_or("-");
594 format!("{ssrc} msid:{stream} {mid}")
595 }
596 None => value.to_owned(),
597 }
598}
599
600fn signal_rtpmap(value: &str) -> String {
601 match value.split_once(' ') {
602 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/48000/2") => {
603 format!("{payload} RED/8000")
604 }
605 _ => value.to_owned(),
606 }
607}
608
609fn signal_extmap(value: &str) -> Option<String> {
610 let (identifier, uri) = value.split_once(' ')?;
611 if DROPPED_EXTENSIONS.contains(&uri) {
612 return None;
613 }
614 if BACKSLASHED_EXTENSIONS.contains(&uri) {
615 return Some(format!("{identifier} {}", uri.replace('/', "\\")));
616 }
617 if uri == LAYERS_ALLOCATION {
618 return Some(format!("{identifier} {uri}{NOT_ADVERTISED_SUFFIX}"));
619 }
620 Some(value.to_owned())
621}
622
623fn feedback_by_payload(source: &Media) -> HashMap<String, Vec<String>> {
624 let mut map: HashMap<String, Vec<String>> = HashMap::new();
625 for value in source.values("rtcp-fb") {
626 if let Some((payload, kind)) = value.split_once(' ') {
627 map.entry(payload.to_owned())
628 .or_default()
629 .push(kind.to_owned());
630 }
631 }
632 map
633}
634
635fn shared_feedback(
636 by_payload: &HashMap<String, Vec<String>>,
637 source: &Media,
638 is_rtx: &impl Fn(&str) -> bool,
639) -> Option<Vec<String>> {
640 let mut codecs = source.formats.iter().filter(|payload| !is_rtx(payload));
641 let first = by_payload.get(codecs.next()?)?;
642 codecs
643 .all(|payload| by_payload.get(payload) == Some(first))
644 .then(|| first.clone())
645}
646
647fn signal_data_line(source: &Media, numbers: &mut impl NumberSource) -> Media {
648 let ssrc = numbers.next_u32();
649 let mut attributes = vec![
650 Attribute::new("x-data-protocol", "sctp"),
651 Attribute::new("x-ssrc-range", format!("{ssrc}-{ssrc}")),
652 Attribute::new("rtpmap", "127 x-data/90000"),
653 Attribute::new("rtpmap", "126 rtx/90000"),
654 Attribute::new("fmtp", "126 apt=127"),
655 Attribute::flag("sendrecv"),
656 Attribute::flag("rtcp-mux"),
657 Attribute::new("label", LineRole::Data.label()),
658 ];
659 attributes.extend(source.attributes.iter().cloned());
660 Media {
661 kind: "x-data".to_owned(),
662 port: SIGNALED_PORT.to_owned(),
663 proto: SIGNALED_PROTO.to_owned(),
664 formats: vec!["127".to_owned(), "126".to_owned()],
665 connection: Some(PLACEHOLDER_CONNECTION.to_owned()),
666 bandwidths: Vec::new(),
667 attributes,
668 }
669}
670
671pub fn to_browser_answer(
672 teams_sdp: &str,
673 offer: &SignaledOffer,
674 browser_offer_sdp: &str,
675) -> Result<String> {
676 let answer = parse(teams_sdp)?;
677 let browser_offer = parse(browser_offer_sdp)?;
678 if answer.media.len() != offer.lines.len() {
679 return Err(Error::Sdp(format!(
680 "answer has {} m-lines, offer signaled {}",
681 answer.media.len(),
682 offer.lines.len()
683 )));
684 }
685 let offered: HashMap<&str, &Media> = browser_offer
686 .media
687 .iter()
688 .filter_map(|media| Some((media.mid()?, media)))
689 .collect();
690 let mut media = Vec::new();
691 for (index, (teams_line, signaled)) in answer.media.iter().zip(&offer.lines).enumerate() {
692 for (stream_index, browser_mid) in signaled.browser_mids.iter().enumerate() {
693 let offered_line = offered
694 .get(browser_mid.as_str())
695 .ok_or_else(|| Error::Sdp(format!("offer has no mid {browser_mid}")))?;
696 let section = if signaled.role == LineRole::Data {
697 browser_data_line(teams_line, offered_line, &answer.session)
698 } else {
699 browser_rtp_line(
700 teams_line,
701 offered_line,
702 signaled.role,
703 stream_index as u32,
704 index == 0,
705 &answer.session,
706 )
707 };
708 media.push(section);
709 }
710 }
711 let mut session = answer.session.clone();
712 session
713 .attributes
714 .retain(|attribute| attribute.name.starts_with("x-"));
715 session
716 .attributes
717 .push(Attribute::flag("extmap-allow-mixed"));
718 session
719 .attributes
720 .push(Attribute::new("msid-semantic", " WMS *"));
721 session.attributes.push(Attribute::new(
722 "group",
723 bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))),
724 ));
725 Ok(write(&SessionDescription { session, media }))
726}
727
728fn bundle_group<'a>(lines: impl Iterator<Item = (&'a str, Option<&'a str>)>) -> String {
729 let mids: Vec<&str> = lines
730 .filter(|(port, _)| *port != "0")
731 .filter_map(|(_, mid)| mid)
732 .collect();
733 format!("BUNDLE {}", mids.join(" "))
734}
735
736#[derive(Debug, Clone, PartialEq, Eq)]
737pub struct StreamLine {
738 pub mid: String,
739 pub browser_mid: String,
740 pub role: LineRole,
741 pub source_stream_id: Option<u32>,
742}
743
744pub fn stream_lines(teams_sdp: &str, lines: &[SignaledLine]) -> Result<Vec<StreamLine>> {
745 let teams = parse(teams_sdp)?;
746 if teams.media.len() != lines.len() {
747 return Err(Error::Sdp(format!(
748 "sdp has {} m-lines, {} were signaled",
749 teams.media.len(),
750 lines.len()
751 )));
752 }
753 let mut streams = Vec::new();
754 for (media, line) in teams.media.iter().zip(lines) {
755 let source_stream_id = media
756 .value("x-source-streamid")
757 .and_then(|value| value.trim().parse().ok());
758 let mid = media.mid().unwrap_or_default().to_owned();
759 match line.browser_mids.as_slice() {
760 [browser_mid] => streams.push(StreamLine {
761 mid,
762 browser_mid: browser_mid.clone(),
763 role: line.role,
764 source_stream_id,
765 }),
766 folded => {
767 let last = folded.len().saturating_sub(1);
768 streams.extend(folded.iter().enumerate().map(|(index, browser_mid)| {
769 StreamLine {
770 mid: mid.clone(),
771 browser_mid: browser_mid.clone(),
772 role: line.role,
773 source_stream_id: (line.role == LineRole::ScreenShare && index == last)
774 .then_some(source_stream_id)
775 .flatten(),
776 }
777 }))
778 }
779 }
780 }
781 Ok(streams)
782}
783
784fn transport_attributes(teams_line: &Media, session: &Session) -> Vec<Attribute> {
785 ["setup", "ice-ufrag", "ice-pwd", "fingerprint"]
786 .into_iter()
787 .filter_map(|name| {
788 teams_line
789 .attributes
790 .iter()
791 .chain(&session.attributes)
792 .find(|attribute| attribute.name == name)
793 .cloned()
794 })
795 .collect()
796}
797
798const OPUS_SEND_QUALITY: [(&str, &str); 2] =
799 [("maxaveragebitrate", "40000"), ("maxplaybackrate", "48000")];
800
801const OPUS_RECEIVE_FULLBAND: [(&str, &str); 2] = [
802 ("maxplaybackrate", "48000"),
803 ("sprop-maxcapturerate", "48000"),
804];
805
806/// libwebrtc sizes its Opus encoder from these remote fmtp parameters; without them it picks its own bitrate.
807fn with_opus_send_quality(fmtp: &str) -> String {
808 with_fmtp_parameters(fmtp, &OPUS_SEND_QUALITY)
809}
810
811/// libwebrtc starts its bandwidth estimate at 300 kbit/s, which opens a 720p camera at 320x180.
812const H264_SEND_START: [(&str, &str); 1] = [("x-google-start-bitrate", "1500")];
813const H264_PROFILE_LEVEL_ID: &str = "profile-level-id=";
814const H264_LEVEL_4_0: u8 = 0x28;
815const FULL_HD_MAX_FS: u32 = 8160;
816const FULL_HD_MAX_MBPS: u32 = 244_800;
817
818/// Only touches H264 lines, the sole codec here that carries a `profile-level-id`.
819fn with_h264_send_quality(fmtp: &str) -> String {
820 if !fmtp.contains(H264_PROFILE_LEVEL_ID) {
821 return fmtp.to_owned();
822 }
823 with_fmtp_parameters(&with_full_hd_level(fmtp), &H264_SEND_START)
824}
825
826/// Teams answers level 3.1 even when its `max-fs` and `max-mbps` allow 1080p, and the encoder
827/// stalls at 1080p on that level. The explicit limits are what the peer can really receive.
828fn with_full_hd_level(fmtp: &str) -> String {
829 let limit = |name: &str| {
830 fmtp.split([' ', ';'])
831 .find_map(|parameter| parameter.strip_prefix(name)?.strip_prefix('='))
832 .and_then(|value| value.parse::<u32>().ok())
833 };
834 let allows_full_hd = limit("max-fs").is_some_and(|max_fs| max_fs >= FULL_HD_MAX_FS)
835 && limit("max-mbps").is_some_and(|max_mbps| max_mbps >= FULL_HD_MAX_MBPS);
836 let level = fmtp
837 .find(H264_PROFILE_LEVEL_ID)
838 .map(|start| start + H264_PROFILE_LEVEL_ID.len() + 4)
839 .map(|start| start..start + 2)
840 .filter(|range| {
841 fmtp.get(range.clone())
842 .and_then(|level| u8::from_str_radix(level, 16).ok())
843 .is_some_and(|level| level < H264_LEVEL_4_0)
844 });
845 let mut raised = fmtp.to_owned();
846 if let Some(range) = level.filter(|_| allows_full_hd) {
847 raised.replace_range(range, &format!("{H264_LEVEL_4_0:02x}"));
848 }
849 raised
850}
851
852fn without_fmtp_parameter(fmtp: &str, name: &str) -> String {
853 let Some((payload, parameters)) = fmtp.split_once(' ') else {
854 return fmtp.to_owned();
855 };
856 let kept: Vec<&str> = parameters
857 .split(';')
858 .filter(|parameter| parameter.split('=').next() != Some(name))
859 .collect();
860 format!("{payload} {}", kept.join(";"))
861}
862
863fn with_fmtp_parameters(fmtp: &str, parameters: &[(&str, &str)]) -> String {
864 let mut value = fmtp.to_owned();
865 for &(name, setting) in parameters {
866 if value
867 .split([' ', ';'])
868 .any(|parameter| parameter.split('=').next() == Some(name))
869 {
870 continue;
871 }
872 if !value.ends_with(' ') {
873 value.push(if value.contains(' ') { ';' } else { ' ' });
874 }
875 value.push_str(&format!("{name}={setting}"));
876 }
877 value
878}
879
880fn browser_rtp_line(
881 teams_line: &Media,
882 offered: &Media,
883 role: LineRole,
884 stream_index: u32,
885 carries_candidates: bool,
886 session: &Session,
887) -> Media {
888 let offered_rtpmap = offered.rtpmap();
889 let offered_codecs: HashMap<String, String> = offered_rtpmap
890 .values()
891 .filter_map(|encoding| {
892 let (name, rest) = encoding.split_once('/')?;
893 Some((name.to_ascii_lowercase(), rest.to_owned()))
894 })
895 .collect();
896 let answer_rtpmap = teams_line.rtpmap();
897 let kept: Vec<String> = teams_line
898 .formats
899 .iter()
900 .filter(|payload| {
901 answer_rtpmap
902 .get(*payload)
903 .and_then(|encoding| encoding.split('/').next())
904 .is_some_and(|name| offered_codecs.contains_key(&name.to_ascii_lowercase()))
905 })
906 .cloned()
907 .collect();
908 let kept_set: HashSet<&str> = kept.iter().map(String::as_str).collect();
909 let payload_of = |value: &str| value.split(' ').next().unwrap_or_default().to_owned();
910 let codec_payload = |codec: &str| {
911 kept.iter().find(|payload| {
912 answer_rtpmap.get(*payload).is_some_and(|encoding| {
913 encoding
914 .to_ascii_lowercase()
915 .starts_with(&format!("{codec}/"))
916 })
917 })
918 };
919
920 let mut attributes = Vec::new();
921 attributes.extend(
922 teams_line
923 .values("x-source-streamid")
924 .map(|value| Attribute::new("x-source-streamid", value)),
925 );
926 for value in teams_line.values("rtpmap") {
927 let payload = payload_of(value);
928 if !kept_set.contains(payload.as_str()) {
929 continue;
930 }
931 let encoding = answer_rtpmap.get(&payload).cloned().unwrap_or_default();
932 let name = encoding.split('/').next().unwrap_or_default();
933 let offered_rest = offered_codecs.get(&name.to_ascii_lowercase());
934 let rewritten = match offered_rest {
935 Some(rest) if name.eq_ignore_ascii_case("red") => format!("{payload} {name}/{rest}"),
936 _ => value.to_owned(),
937 };
938 attributes.push(Attribute::new("rtpmap", rewritten));
939 }
940 let mut fmtp_payloads = HashSet::new();
941 for value in teams_line.values("fmtp") {
942 let payload = payload_of(value);
943 if !kept_set.contains(payload.as_str()) {
944 continue;
945 }
946 let cleaned = value
947 .split(';')
948 .filter(|parameter| !parameter.starts_with("rtx-time="))
949 .collect::<Vec<_>>()
950 .join(";");
951 let is_opus = codec_payload("opus").is_some_and(|opus| *opus == payload);
952 fmtp_payloads.insert(payload);
953 attributes.push(Attribute::new(
954 "fmtp",
955 if is_opus {
956 with_opus_send_quality(&cleaned)
957 } else {
958 with_h264_send_quality(&cleaned)
959 },
960 ));
961 }
962 if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) {
963 attributes.push(Attribute::new(
964 "fmtp",
965 with_opus_send_quality(&format!("{opus} usedtx=1")),
966 ));
967 }
968 if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus"))
969 && !fmtp_payloads.contains(red)
970 {
971 attributes.push(Attribute::new("fmtp", format!("{red} {opus}/{opus}")));
972 }
973 attributes.extend(
974 teams_line
975 .values("rtcp")
976 .map(|value| Attribute::new("rtcp", value)),
977 );
978 let answer_feedback: Vec<&str> = teams_line
979 .values("rtcp-fb")
980 .filter(|value| !value.contains("x-message"))
981 .collect();
982 if answer_feedback.is_empty() && !teams_line.has("rtcp-fb") {
983 attributes.extend(
984 offered
985 .values("rtcp-fb")
986 .filter(|value| kept_set.contains(payload_of(value).as_str()))
987 .map(|value| Attribute::new("rtcp-fb", value)),
988 );
989 } else {
990 attributes.extend(
991 answer_feedback
992 .into_iter()
993 .map(|value| Attribute::new("rtcp-fb", value)),
994 );
995 }
996 for value in teams_line.values("extmap") {
997 let restored = value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "");
998 attributes.push(Attribute::new("extmap", restored));
999 }
1000 attributes.extend(transport_attributes(teams_line, session));
1001 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
1002 attributes.extend(
1003 teams_line
1004 .values("ptime")
1005 .map(|value| Attribute::new("ptime", value)),
1006 );
1007 if let Some(direction) = teams_line.direction() {
1008 attributes.push(Attribute::flag(direction));
1009 }
1010 if carries_candidates {
1011 attributes.extend(
1012 teams_line
1013 .values("candidate")
1014 .chain(teams_line.values("x-candidate-ipv6"))
1015 .map(|value| Attribute::new("candidate", browser_candidate(value))),
1016 );
1017 }
1018 attributes.extend(stream_ssrc_attributes(teams_line, stream_index, role));
1019 attributes.push(Attribute::flag("rtcp-mux"));
1020 if teams_line.has("rtcp-rsize") {
1021 attributes.push(Attribute::flag("rtcp-rsize"));
1022 }
1023 if let Some(simulcast) = offered
1024 .value("simulcast")
1025 .and_then(|value| value.strip_prefix("send "))
1026 {
1027 let rids: Vec<String> = simulcast
1028 .split(';')
1029 .map(|rid| rid.trim_start_matches('~').to_owned())
1030 .collect();
1031 attributes.extend(
1032 rids.iter()
1033 .map(|rid| Attribute::new("rid", format!("{rid} recv"))),
1034 );
1035 attributes.push(Attribute::new(
1036 "simulcast",
1037 format!("recv {}", rids.join(";")),
1038 ));
1039 }
1040 // A rejected line still needs a format. Teams rejects with a static payload
1041 // such as `34` that has no rtpmap, so fall back to the offered payload.
1042 let formats = if kept.is_empty() && teams_line.port == "0" {
1043 offered.formats.iter().take(1).cloned().collect()
1044 } else {
1045 kept
1046 };
1047 Media {
1048 kind: offered.kind.clone(),
1049 port: teams_line.port.clone(),
1050 proto: offered.proto.clone(),
1051 formats,
1052 connection: teams_line
1053 .connection
1054 .clone()
1055 .or_else(|| session.connection.clone()),
1056 bandwidths: teams_line.bandwidths.clone(),
1057 attributes,
1058 }
1059}
1060
1061fn stream_ssrc_attributes(teams_line: &Media, stream_index: u32, role: LineRole) -> Vec<Attribute> {
1062 let (Some(primary), retransmission) = stream_ssrcs(teams_line, stream_index) else {
1063 return Vec::new();
1064 };
1065 let stream = format!("{}-{primary}", role.stream_prefix());
1066 let mut attributes = Vec::new();
1067 for ssrc in [Some(primary), retransmission].into_iter().flatten() {
1068 attributes.push(Attribute::new(
1069 "ssrc",
1070 format!("{ssrc} cname:{}", stream_cname(primary)),
1071 ));
1072 attributes.push(Attribute::new(
1073 "ssrc",
1074 format!("{ssrc} msid:{stream} {stream}"),
1075 ));
1076 }
1077 if let Some(retransmission) = retransmission {
1078 attributes.push(Attribute::new(
1079 "ssrc-group",
1080 format!("FID {primary} {retransmission}"),
1081 ));
1082 }
1083 attributes
1084}
1085
1086fn stream_cname(primary: u32) -> String {
1087 format!("teams{primary}")
1088}
1089
1090fn stream_ssrcs(teams_line: &Media, stream_index: u32) -> (Option<u32>, Option<u32>) {
1091 let offset = stream_index * SSRC_RANGE_SIZE;
1092 if let Some(group) = teams_line
1093 .value("ssrc-group")
1094 .and_then(|value| value.strip_prefix("FID "))
1095 {
1096 let mut ssrcs = group
1097 .split(' ')
1098 .filter_map(|value| value.parse::<u32>().ok());
1099 let primary = ssrcs.next().map(|ssrc| ssrc + offset);
1100 return (primary, ssrcs.next().map(|ssrc| ssrc + offset));
1101 }
1102 let first = teams_line
1103 .value("x-ssrc-range")
1104 .and_then(|range| range.split('-').next()?.parse::<u32>().ok())
1105 .map(|ssrc| ssrc + offset);
1106 (first, None)
1107}
1108
1109fn browser_candidate(value: &str) -> String {
1110 let mut parts: Vec<&str> = value.split(' ').collect();
1111 if let Some(position) = parts.iter().position(|part| *part == "MTURNID") {
1112 parts.truncate(position);
1113 }
1114 let tcp_type = match parts
1115 .get(2)
1116 .map(|transport| transport.to_ascii_lowercase())
1117 .as_deref()
1118 {
1119 Some("tcp-pass") => Some("passive"),
1120 Some("tcp-act") => Some("active"),
1121 Some("tcp-so") => Some("so"),
1122 _ => None,
1123 };
1124 if tcp_type.is_some() {
1125 parts[2] = "tcp";
1126 }
1127 let mut candidate = parts.join(" ");
1128 if let Some(tcp_type) = tcp_type {
1129 candidate.push_str(" tcptype ");
1130 candidate.push_str(tcp_type);
1131 }
1132 candidate
1133}
1134
1135fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) -> Media {
1136 let mut attributes = Vec::new();
1137 attributes.extend(
1138 teams_line
1139 .values("x-source-streamid")
1140 .map(|value| Attribute::new("x-source-streamid", value)),
1141 );
1142 attributes.extend(transport_attributes(teams_line, session));
1143 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
1144 attributes.extend(
1145 offered
1146 .values("sctp-port")
1147 .map(|value| Attribute::new("sctp-port", value)),
1148 );
1149 Media {
1150 kind: offered.kind.clone(),
1151 port: teams_line.port.clone(),
1152 proto: offered.proto.clone(),
1153 formats: offered.formats.clone(),
1154 connection: teams_line
1155 .connection
1156 .clone()
1157 .or_else(|| session.connection.clone()),
1158 bandwidths: Vec::new(),
1159 attributes,
1160 }
1161}
1162
1163const BROWSER_PORT: &str = "9";
1164const BROWSER_PROTO: &str = "UDP/TLS/RTP/SAVPF";
1165const BROWSER_CONNECTION: &str = "IN IP4 0.0.0.0";
1166const BROWSER_RTCP: &str = "9 IN IP4 0.0.0.0";
1167const BROWSER_DATA_PROTO: &str = "UDP/DTLS/SCTP";
1168const BROWSER_DATA_FORMAT: &str = "webrtc-datachannel";
1169const SCTP_PORT: &str = "5000";
1170const SCTP_MAX_MESSAGE_SIZE: &str = "262144";
1171const PLACEHOLDER_CANDIDATE_TAIL: &str = " 1234 typ host";
1172const TEAMS_ONLY_ATTRIBUTES: [&str; 6] = [
1173 "x-multi-stream",
1174 "x-signaling-fb",
1175 "x-ssrc-range",
1176 "x-source-streamid",
1177 "x-data-protocol",
1178 "label",
1179];
1180const TRANSPORT_ATTRIBUTES: [&str; 5] = [
1181 "setup",
1182 "ice-ufrag",
1183 "ice-pwd",
1184 "fingerprint",
1185 "ice-options",
1186];
1187
1188/// A Teams offer translated for libwebrtc; `lines` remembers which browser mids each signaled line stands for.
1189#[derive(Debug, Clone)]
1190pub struct RemoteOffer {
1191 pub browser_sdp: String,
1192 pub lines: Vec<SignaledLine>,
1193}
1194
1195impl RemoteOffer {
1196 pub fn plan(&self) -> OfferPlan {
1197 let mut plan = OfferPlan::default();
1198 for line in &self.lines {
1199 match line.role {
1200 LineRole::ScreenShare => plan
1201 .screen_share_mids
1202 .extend(line.browser_mids.iter().cloned()),
1203 _ => {}
1204 }
1205 if line.browser_mids.len() > 1 {
1206 plan.gallery_mids.extend(line.browser_mids.iter().cloned());
1207 plan.fold_groups.push(line.browser_mids.clone());
1208 }
1209 }
1210 plan
1211 }
1212}
1213
1214fn effective_fold_groups(plan: &OfferPlan) -> Vec<Vec<String>> {
1215 if !plan.fold_groups.is_empty() {
1216 return plan.fold_groups.clone();
1217 }
1218 if plan.gallery_mids.len() > 1 {
1219 vec![plan.gallery_mids.clone()]
1220 } else {
1221 Vec::new()
1222 }
1223}
1224
1225fn role_of_teams_line(line: &Media) -> LineRole {
1226 match line.value("label") {
1227 Some("main-audio") => LineRole::MainAudio,
1228 Some("main-video") => LineRole::MainVideo,
1229 Some("applicationsharing-video") => LineRole::ScreenShare,
1230 Some("data") => LineRole::Data,
1231 _ => match line.kind.as_str() {
1232 "audio" => LineRole::MainAudio,
1233 "x-data" | "application" => LineRole::Data,
1234 _ => LineRole::MainVideo,
1235 },
1236 }
1237}
1238
1239/// Folded gallery lines get the mids just below the carrier line's own mid, unless another line already uses one of them.
1240fn folded_mids(carrier: &str, count: usize, taken: &[String]) -> Vec<String> {
1241 let below = match carrier.parse::<usize>() {
1242 Ok(last) if last + 1 >= count => Some(
1243 (last + 1 - count..=last)
1244 .map(|mid| mid.to_string())
1245 .collect::<Vec<_>>(),
1246 ),
1247 _ => None,
1248 };
1249 match below.filter(|mids| {
1250 mids.iter()
1251 .all(|mid| mid == carrier || !taken.contains(mid))
1252 }) {
1253 Some(mids) => mids,
1254 None => (0..count)
1255 .map(|index| {
1256 if index + 1 == count {
1257 carrier.to_owned()
1258 } else {
1259 format!("{carrier}-{index}")
1260 }
1261 })
1262 .collect(),
1263 }
1264}
1265
1266pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
1267 let teams = parse(teams_sdp)?;
1268 let mut media = Vec::new();
1269 let mut lines = Vec::new();
1270 let mut taken: Vec<String> = teams
1271 .media
1272 .iter()
1273 .filter_map(|line| line.mid().map(str::to_owned))
1274 .collect();
1275 for source in &teams.media {
1276 let role = role_of_teams_line(source);
1277 let carrier = source.mid().unwrap_or_default().to_owned();
1278 let folded = source
1279 .value("x-multi-stream")
1280 .and_then(|value| value.split(' ').next()?.parse::<usize>().ok())
1281 .filter(|count| *count > 1);
1282 let mids = match folded {
1283 Some(count) => folded_mids(&carrier, count, &taken),
1284 None => vec![carrier.clone()],
1285 };
1286 taken.extend(mids.iter().cloned());
1287 for (index, mid) in mids.iter().enumerate() {
1288 let converted = if role == LineRole::Data {
1289 browser_data_from_teams(source, mid, &teams.session)
1290 } else {
1291 browser_rtp_from_teams(
1292 source,
1293 mid,
1294 role,
1295 folded.is_some(),
1296 index == 0 && lines.is_empty(),
1297 &teams.session,
1298 )
1299 };
1300 media.push(converted);
1301 }
1302 lines.push(SignaledLine {
1303 browser_mids: mids,
1304 role,
1305 });
1306 }
1307 let mut session = teams.session.clone();
1308 session.bandwidths.clear();
1309 session.connection = None;
1310 session.attributes.retain(|attribute| {
1311 matches!(
1312 attribute.name.as_str(),
1313 "extmap-allow-mixed" | "msid-semantic"
1314 )
1315 });
1316 session.attributes.push(Attribute::new(
1317 "group",
1318 bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))),
1319 ));
1320 Ok(RemoteOffer {
1321 browser_sdp: write(&SessionDescription { session, media }),
1322 lines,
1323 })
1324}
1325
1326fn transport_from_teams(source: &Media, session: &Session) -> Vec<Attribute> {
1327 TRANSPORT_ATTRIBUTES
1328 .iter()
1329 .filter_map(|name| {
1330 source
1331 .attributes
1332 .iter()
1333 .chain(&session.attributes)
1334 .find(|attribute| attribute.name == *name)
1335 .cloned()
1336 })
1337 .collect()
1338}
1339
1340fn browser_data_from_teams(source: &Media, mid: &str, session: &Session) -> Media {
1341 let mut attributes = transport_from_teams(source, session);
1342 attributes.push(Attribute::new("mid", mid));
1343 attributes.push(Attribute::new("sctp-port", SCTP_PORT));
1344 attributes.push(Attribute::new("max-message-size", SCTP_MAX_MESSAGE_SIZE));
1345 Media {
1346 kind: "application".to_owned(),
1347 port: BROWSER_PORT.to_owned(),
1348 proto: BROWSER_DATA_PROTO.to_owned(),
1349 formats: vec![BROWSER_DATA_FORMAT.to_owned()],
1350 connection: Some(BROWSER_CONNECTION.to_owned()),
1351 bandwidths: Vec::new(),
1352 attributes,
1353 }
1354}
1355
1356fn browser_rtp_from_teams(
1357 source: &Media,
1358 mid: &str,
1359 role: LineRole,
1360 folded: bool,
1361 carries_candidate: bool,
1362 session: &Session,
1363) -> Media {
1364 let rtpmap = source.rtpmap();
1365 let is_rtx = |payload: &str| {
1366 rtpmap
1367 .get(payload)
1368 .is_some_and(|encoding| encoding.starts_with("rtx/"))
1369 };
1370 let mut attributes = Vec::new();
1371 let mut expanded_feedback: Vec<Attribute> = Vec::new();
1372 let mut signals_ssrc = false;
1373 let mut ssrc_groups = Vec::new();
1374 for attribute in &source.attributes {
1375 let value = attribute.value.as_deref().unwrap_or_default();
1376 match attribute.name.as_str() {
1377 name if TEAMS_ONLY_ATTRIBUTES.contains(&name) => {}
1378 "x-candidate-ipv6" => {
1379 if carries_candidate {
1380 attributes.push(Attribute::new("candidate", browser_candidate(value)));
1381 }
1382 }
1383 name if name.starts_with("x-") => {}
1384 "mid" | "rtcp-mux" => {}
1385 name if TRANSPORT_ATTRIBUTES.contains(&name) => {}
1386 "candidate" => {
1387 if carries_candidate && !value.contains(PLACEHOLDER_CANDIDATE_TAIL) {
1388 attributes.push(Attribute::new("candidate", browser_candidate(value)));
1389 }
1390 }
1391 "ssrc" => {
1392 let placeholder = value.contains("fake_attribute") || value.starts_with("1 ");
1393 if !folded && !placeholder {
1394 signals_ssrc = true;
1395 attributes.push(attribute.clone());
1396 }
1397 }
1398 "ssrc-group" => {
1399 if !folded {
1400 ssrc_groups.push(attribute.clone());
1401 }
1402 }
1403 "rtcp" => attributes.push(Attribute::new("rtcp", BROWSER_RTCP)),
1404 "rtpmap" => attributes.push(Attribute::new("rtpmap", browser_rtpmap(value))),
1405 "extmap" => attributes.push(Attribute::new("extmap", browser_extmap(value))),
1406 "fmtp" => attributes.push(Attribute::new("fmtp", with_h264_send_quality(value))),
1407 "rtcp-fb" => match value.strip_prefix("* ") {
1408 Some(kind) => expanded_feedback.extend(
1409 source
1410 .formats
1411 .iter()
1412 .filter(|payload| !is_rtx(payload))
1413 .map(|payload| Attribute::new("rtcp-fb", format!("{payload} {kind}"))),
1414 ),
1415 None => attributes.push(attribute.clone()),
1416 },
1417 _ => attributes.push(attribute.clone()),
1418 }
1419 }
1420 attributes.extend(expanded_feedback);
1421 attributes.extend(transport_from_teams(source, session));
1422 attributes.push(Attribute::new("mid", mid));
1423 if signals_ssrc {
1424 attributes.extend(ssrc_groups);
1425 } else if !folded {
1426 attributes.extend(stream_ssrc_attributes(source, 0, role));
1427 }
1428 attributes.push(Attribute::flag("rtcp-mux"));
1429 Media {
1430 kind: source.kind.clone(),
1431 port: BROWSER_PORT.to_owned(),
1432 proto: BROWSER_PROTO.to_owned(),
1433 formats: source.formats.clone(),
1434 connection: Some(BROWSER_CONNECTION.to_owned()),
1435 bandwidths: Vec::new(),
1436 attributes,
1437 }
1438}
1439
1440fn browser_rtpmap(value: &str) -> String {
1441 match value.split_once(' ') {
1442 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => {
1443 format!("{payload} red/48000/2")
1444 }
1445 _ => value.to_owned(),
1446 }
1447}
1448
1449fn browser_extmap(value: &str) -> String {
1450 value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "")
1451}
1452
1453/// libwebrtc answers every offered line in the offer's order and with its mids, so the offer's plan applies unchanged.
1454pub fn to_teams_answer(
1455 browser_answer_sdp: &str,
1456 remote: &RemoteOffer,
1457 numbers: &mut impl NumberSource,
1458) -> Result<SignaledOffer> {
1459 to_teams_offer(browser_answer_sdp, &remote.plan(), numbers)
1460}
1461
1462#[cfg(test)]
1463mod tests {
1464 use super::*;
1465
1466 fn counter() -> impl FnMut() -> u32 {
1467 let mut next = 1000u32;
1468 move || {
1469 next += 1;
1470 next
1471 }
1472 }
1473
1474 #[test]
1475 fn h264_sends_start_high_and_use_the_level_the_peer_limits_allow() {
1476 let full_hd = "98 packetization-mode=1;profile-level-id=42e01f;max-fs=8160;max-mbps=244800";
1477 assert_eq!(
1478 with_h264_send_quality(full_hd),
1479 "98 packetization-mode=1;profile-level-id=42e028;max-fs=8160;max-mbps=244800;x-google-start-bitrate=1500"
1480 );
1481 let hd = "98 profile-level-id=42e01f;max-fs=3600;max-mbps=108000";
1482 assert_eq!(
1483 with_h264_send_quality(hd),
1484 "98 profile-level-id=42e01f;max-fs=3600;max-mbps=108000;x-google-start-bitrate=1500"
1485 );
1486 assert_eq!(with_h264_send_quality("99 apt=98"), "99 apt=98");
1487 assert_eq!(
1488 without_fmtp_parameter(
1489 "98 profile-level-id=42e01f;x-google-start-bitrate=1500",
1490 "x-google-start-bitrate"
1491 ),
1492 "98 profile-level-id=42e01f"
1493 );
1494 }
1495
1496 #[test]
1497 fn rejected_lines_stay_out_of_the_bundle() {
1498 let lines = [("9", Some("0")), ("0", Some("1")), ("9", Some("2"))];
1499 assert_eq!(bundle_group(lines.into_iter()), "BUNDLE 0 2");
1500 }
1501
1502 const ONE_TO_ONE_BROWSER_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\r\na=msid-semantic: WMS stream\r\nm=audio 9 UDP/TLS/RTP/SAVPF 111\r\nc=IN IP4 0.0.0.0\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\r\na=mid:0\r\na=sendrecv\r\na=msid:stream track\r\na=rtcp-mux\r\na=rtpmap:111 opus/48000/2\r\na=ssrc:42 cname:abc\r\nm=video 9 UDP/TLS/RTP/SAVPF 102 103\r\nc=IN IP4 0.0.0.0\r\na=mid:1\r\na=inactive\r\na=rtcp-mux\r\na=rtpmap:102 H264/90000\r\na=rtpmap:103 rtx/90000\r\na=fmtp:103 apt=102\r\n";
1503 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";
1504
1505 #[test]
1506 fn audio_only_offer_gets_the_teams_shape() {
1507 let offer =
1508 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1509 let text = offer.sdp.replace("\r\n", "\n");
1510 assert!(text.contains("\nb=CT:4000\n"));
1511 assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\n"));
1512 assert!(text.contains("a=x-signaling-fb:* x-message app recv:dsh\n"));
1513 assert!(text.contains("a=x-ssrc-range:42-42\n"));
1514 assert!(text.contains("a=rtpmap:63 RED/8000\n"));
1515 assert!(text.contains("a=fmtp:111 minptime=10;useinbandfec=1;maxplaybackrate=48000;sprop-maxcapturerate=48000\n"));
1516 assert!(text.contains("a=rtcp:1234\n"));
1517 assert!(text.contains(
1518 "a=extmap:2 http:\\\\www.webrtc.org\\experiments\\rtp-hdrext\\abs-send-time\n"
1519 ));
1520 assert!(text.contains("a=ssrc:42 msid:stream 0\n"));
1521 assert!(
1522 text.contains("a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\n")
1523 );
1524 assert!(
1525 text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\nc=IN IP4 10.10.10.10\n")
1526 );
1527 assert!(text.ends_with("a=label:main-audio\n"));
1528 assert_eq!(
1529 offer.lines,
1530 vec![SignaledLine {
1531 browser_mids: vec!["0".into()],
1532 role: LineRole::MainAudio
1533 }]
1534 );
1535 }
1536
1537 #[test]
1538 fn a_renegotiation_signals_only_the_placeholder_candidate() {
1539 let gathered = AUDIO_ONLY_OFFER.replace(
1540 "a=mid:0\r\n",
1541 "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",
1542 );
1543 let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter())
1544 .unwrap()
1545 .sdp;
1546 let candidates: Vec<&str> = text
1547 .lines()
1548 .filter(|line| {
1549 line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")
1550 })
1551 .collect();
1552 assert_eq!(
1553 candidates,
1554 vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]
1555 );
1556 }
1557
1558 #[test]
1559 fn answer_candidates_lose_teams_extensions() {
1560 assert_eq!(
1561 browser_candidate(
1562 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 158"
1563 ),
1564 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480"
1565 );
1566 assert_eq!(
1567 browser_candidate(
1568 "3 1 tcp-pass 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478"
1569 ),
1570 "3 1 tcp 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478 tcptype passive"
1571 );
1572 assert_eq!(
1573 browser_candidate(
1574 "10 1 TCP-ACT 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009"
1575 ),
1576 "10 1 tcp 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009 tcptype active"
1577 );
1578 }
1579
1580 #[test]
1581 fn audio_answer_maps_back_to_the_browser_mid_and_codecs() {
1582 let offer =
1583 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1584 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";
1585 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER)
1586 .unwrap()
1587 .replace("\r\n", "\n");
1588 assert!(
1589 browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"),
1590 "{browser}"
1591 );
1592 assert!(browser.contains("a=rtpmap:97 RED/48000/2\n"));
1593 assert!(
1594 browser.contains("a=fmtp:111 usedtx=1;maxaveragebitrate=40000;maxplaybackrate=48000\n")
1595 );
1596 assert!(browser.contains("a=fmtp:97 111/111\n"));
1597 assert!(browser.contains("a=rtcp-fb:111 transport-cc\n"));
1598 assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n"));
1599 assert!(browser.contains("a=group:BUNDLE 0\n"));
1600 assert!(
1601 !browser.contains("SATINFB")
1602 && !browser.contains("MTURNID")
1603 && !browser.contains("label")
1604 );
1605 }
1606 #[test]
1607 fn a_rejected_answer_line_without_rtpmap_keeps_an_offered_format() {
1608 let offer = to_teams_offer(
1609 ONE_TO_ONE_BROWSER_OFFER,
1610 &OfferPlan::default(),
1611 &mut counter(),
1612 )
1613 .unwrap();
1614 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\nt=0 0\r\na=group:BUNDLE 0\r\nm=audio 3480 RTP/SAVP 111\r\nc=IN IP4 52.112.0.1\r\na=setup:passive\r\na=ice-ufrag:U\r\na=ice-pwd:P\r\na=rtcp-mux\r\na=mid:0\r\na=rtpmap:111 OPUS/48000/2\r\na=fingerprint:sha-256 BB\r\na=x-ssrc-range:1000-1000\r\nm=video 0 RTP/SAVP 34\r\na=mid:1\r\n";
1615 let browser = to_browser_answer(answer, &offer, ONE_TO_ONE_BROWSER_OFFER)
1616 .unwrap()
1617 .replace("\r\n", "\n");
1618 assert!(
1619 browser.contains("m=video 0 UDP/TLS/RTP/SAVPF 102\n"),
1620 "{browser}"
1621 );
1622 assert!(browser.contains("a=group:BUNDLE 0\n"));
1623 }
1624
1625 #[test]
1626 fn an_audio_offer_from_teams_gets_the_browser_shape_back() {
1627 let offer =
1628 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1629 let remote = from_teams_offer(&offer.sdp).unwrap();
1630 let text = remote.browser_sdp.replace("\r\n", "\n");
1631 assert!(
1632 text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"),
1633 "{text}"
1634 );
1635 assert!(text.contains("c=IN IP4 0.0.0.0\n"));
1636 assert!(text.contains("a=rtcp:9 IN IP4 0.0.0.0\n"));
1637 assert!(text.contains("a=rtpmap:63 red/48000/2\n"));
1638 assert!(
1639 text.contains(
1640 "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"
1641 )
1642 );
1643 assert!(
1644 text.contains("a=ice-ufrag:u\n")
1645 && text.contains("a=fingerprint:sha-256 AA\n")
1646 && text.contains("a=setup:actpass\n")
1647 );
1648 assert!(text.contains("a=mid:0\n") && text.contains("a=group:BUNDLE 0\n"));
1649 assert!(
1650 !text.contains("10.10.10.10")
1651 && !text.contains("x-ssrc-range")
1652 && !text.contains("label")
1653 && !text.contains("1234")
1654 );
1655 assert_eq!(remote.lines, offer.lines);
1656 }
1657
1658 #[test]
1659 fn shared_video_feedback_is_spelled_out_per_codec_again() {
1660 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";
1661 let remote = from_teams_offer(teams).unwrap();
1662 let text = remote.browser_sdp.replace("\r\n", "\n");
1663 assert!(text.contains("a=rtcp-fb:102 nack\n") && text.contains("a=rtcp-fb:102 nack pli\n"));
1664 assert!(!text.contains("a=rtcp-fb:103") && !text.contains("a=rtcp-fb:*"));
1665 }
1666
1667 #[test]
1668 fn a_peer_offer_with_only_ssrc_ranges_signals_the_streams_it_sends() {
1669 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";
1670 let remote = from_teams_offer(teams).unwrap();
1671 let parsed = parse(&remote.browser_sdp).unwrap();
1672 let audio: Vec<&str> = parsed.media[0].values("ssrc").collect();
1673 assert!(
1674 audio.iter().any(|value| value.starts_with("40475 cname:")),
1675 "{audio:?}"
1676 );
1677 assert_eq!(
1678 parsed.media[1].values("ssrc-group").collect::<Vec<_>>(),
1679 vec!["FID 40476 40526"]
1680 );
1681 let video: Vec<&str> = parsed.media[1].values("ssrc").collect();
1682 assert!(
1683 video.iter().any(|value| value.starts_with("40476 cname:"))
1684 && video.iter().any(|value| value.starts_with("40526 cname:")),
1685 "{video:?}"
1686 );
1687 }
1688
1689 #[test]
1690 fn a_rejected_video_line_stays_rejected_and_out_of_the_bundle() {
1691 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";
1692 let remote = from_teams_offer(audio_and_video).unwrap();
1693 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";
1694 let signaled = to_teams_answer(answer, &remote, &mut counter()).unwrap();
1695 let text = signaled.sdp.replace("\r\n", "\n");
1696 assert!(text.contains("m=video 0 RTP/SAVP 102\n"), "{text}");
1697 assert!(text.contains("a=group:BUNDLE 0\n"));
1698 let parsed = parse(&signaled.sdp).unwrap();
1699 assert_eq!(parsed.media.len(), 2);
1700 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1701 assert_eq!(parsed.media[1].direction(), Some("inactive"));
1702 }
1703
1704 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";
1705
1706 fn browser_answer(camera_direction: &str, share_port: &str, share_direction: &str) -> String {
1707 format!(
1708 "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"
1709 )
1710 }
1711
1712 #[test]
1713 fn a_folded_line_never_reuses_the_mid_of_another_line() {
1714 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";
1715 let teams = format!(
1716 "{}{folded}",
1717 ONE_TO_ONE_VIDEO_OFFER.replace("BUNDLE 0 1 2", "BUNDLE 0 1 2 3")
1718 );
1719 let remote = from_teams_offer(&teams).unwrap();
1720 let mids: Vec<String> = parse(&remote.browser_sdp)
1721 .unwrap()
1722 .media
1723 .iter()
1724 .filter_map(|line| line.mid().map(str::to_owned))
1725 .collect();
1726 let mut unique = mids.clone();
1727 unique.sort();
1728 unique.dedup();
1729 assert_eq!(unique.len(), mids.len(), "{mids:?}");
1730 assert_eq!(
1731 remote.lines.last().unwrap().browser_mids,
1732 vec!["3-0".to_owned(), "3".to_owned()]
1733 );
1734 }
1735
1736 #[test]
1737 fn a_one_to_one_offer_keeps_a_camera_line_and_a_sharing_line() {
1738 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1739 let roles: Vec<LineRole> = remote.lines.iter().map(|line| line.role).collect();
1740 assert_eq!(
1741 roles,
1742 vec![
1743 LineRole::MainAudio,
1744 LineRole::MainVideo,
1745 LineRole::ScreenShare
1746 ]
1747 );
1748 assert_eq!(remote.plan().screen_share_mids, vec!["2".to_owned()]);
1749 assert!(remote.plan().gallery_mids.is_empty());
1750 assert_eq!(
1751 parse(&remote.browser_sdp)
1752 .unwrap()
1753 .media
1754 .iter()
1755 .filter(|media| media.kind == "video")
1756 .count(),
1757 2
1758 );
1759 }
1760
1761 #[test]
1762 fn accepting_with_audio_answers_the_video_line_receive_only_and_with_video_sending() {
1763 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1764 for (camera_direction, expected) in [("recvonly", "recvonly"), ("sendrecv", "sendrecv")] {
1765 let answer = to_teams_answer(
1766 &browser_answer(camera_direction, "0", "inactive"),
1767 &remote,
1768 &mut counter(),
1769 )
1770 .unwrap();
1771 let parsed = parse(&answer.sdp).unwrap();
1772 assert_eq!(parsed.media.len(), 3);
1773 assert_eq!(parsed.media[1].port, "1234");
1774 assert_eq!(parsed.media[1].direction(), Some(expected));
1775 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1776 assert_eq!(parsed.media[2].port, "0");
1777 assert_eq!(
1778 parsed.media[2].value("label"),
1779 Some("applicationsharing-video")
1780 );
1781 }
1782 }
1783
1784 #[test]
1785 fn folded_gallery_lines_expand_below_their_carrier_mid_unless_those_are_taken() {
1786 let taken = ["0".to_owned(), "1".to_owned(), "17".to_owned()];
1787 assert_eq!(
1788 folded_mids("17", 8, &taken),
1789 (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>()
1790 );
1791 assert_eq!(
1792 folded_mids("x", 2, &taken),
1793 vec!["x-0".to_owned(), "x".to_owned()]
1794 );
1795 assert_eq!(
1796 folded_mids("2", 2, &taken),
1797 vec!["2-0".to_owned(), "2".to_owned()]
1798 );
1799 }
1800
1801 /// Mid 2 is already taken, so mid 3 with x-multi-stream:2 folds to 3-0 + 3 (as in the Hyprland 1:1 call report).
1802 fn folded_carrier_neighbor_taken(label: &str) -> String {
1803 format!(
1804 "v=0\r\no=- 1 2 IN IP4 127.0.0.1\r\ns=-\r\nt=0 0\r\na=group:BUNDLE 1 2 5 3 4\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:1\r\na=sendrecv\r\na=label:main-audio\r\na=ice-ufrag:u\r\na=ice-pwd:p\r\na=fingerprint:sha-256 AA\r\na=setup:actpass\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: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:5\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:3\r\na=sendrecv\r\na=label:{label}\r\na=x-multi-stream:2 1 1 1\r\nm=x-data 1234 RTP/SAVP 127\r\nc=IN IP4 10.10.10.10\r\na=mid:4\r\na=sendrecv\r\na=label:data\r\n"
1805 )
1806 }
1807
1808 #[test]
1809 fn a_folded_answer_keeps_one_teams_line_when_carrier_neighbors_are_taken() {
1810 for label in ["main-video", "applicationsharing-video"] {
1811 let offer = folded_carrier_neighbor_taken(label);
1812 let remote = from_teams_offer(&offer).unwrap();
1813 let folded = remote
1814 .lines
1815 .iter()
1816 .find(|line| line.browser_mids.len() > 1)
1817 .expect("folded line");
1818 assert_eq!(folded.browser_mids, vec!["3-0".to_owned(), "3".to_owned()]);
1819 assert_eq!(
1820 remote.plan().fold_groups,
1821 vec![vec!["3-0".to_owned(), "3".to_owned()]]
1822 );
1823 let offer_lines = parse(&offer).unwrap().media.len();
1824 let browser = parse(&remote.browser_sdp).unwrap();
1825 assert_eq!(browser.media.len(), offer_lines + 1);
1826 for port in ["0", "9"] {
1827 let answer_browser = write(&SessionDescription {
1828 session: browser.session.clone(),
1829 media: browser
1830 .media
1831 .iter()
1832 .map(|line| {
1833 let mut line = line.clone();
1834 line.port = if line.kind == "audio" || line.kind == "application" {
1835 "9".to_owned()
1836 } else {
1837 port.to_owned()
1838 };
1839 line.attributes.retain(|attribute| {
1840 !matches!(
1841 attribute.name.as_str(),
1842 "sendrecv" | "recvonly" | "sendonly" | "inactive"
1843 )
1844 });
1845 if line.kind == "audio" || line.kind == "application" {
1846 line.attributes.push(Attribute::flag("sendrecv"));
1847 } else {
1848 line.attributes.push(Attribute::flag("inactive"));
1849 }
1850 line
1851 })
1852 .collect(),
1853 });
1854 let answer = to_teams_answer(&answer_browser, &remote, &mut counter()).unwrap();
1855 let parsed = parse(&answer.sdp).unwrap();
1856 let mids: Vec<_> = parsed.media.iter().filter_map(|line| line.mid()).collect();
1857 assert_eq!(
1858 parsed.media.len(),
1859 offer_lines,
1860 "{label} port {port}: answer mids {mids:?} must match the offer line count"
1861 );
1862 assert!(
1863 !mids.iter().any(|mid| *mid == "3-0"),
1864 "{label} port {port}: signaled answer must not expose the internal fold mid: {mids:?}"
1865 );
1866 assert!(mids.iter().any(|mid| *mid == "3"), "{label} port {port}");
1867 let carrier = parsed
1868 .media
1869 .iter()
1870 .find(|line| line.mid() == Some("3"))
1871 .unwrap();
1872 assert_eq!(
1873 carrier
1874 .value("x-multi-stream")
1875 .and_then(|value| value.split(' ').next().map(str::to_owned)),
1876 Some("2".to_owned()),
1877 "{label} port {port}: carrier must keep x-multi-stream"
1878 );
1879 assert_eq!(carrier.value("label"), Some(label));
1880 }
1881 }
1882 }
1883
1884 #[test]
1885 fn opus_fmtp_gets_the_send_quality_without_overriding_teams() {
1886 assert_eq!(
1887 with_opus_send_quality("111 minptime=10;useinbandfec=1"),
1888 "111 minptime=10;useinbandfec=1;maxaveragebitrate=40000;maxplaybackrate=48000"
1889 );
1890 assert_eq!(
1891 with_opus_send_quality("111 maxplaybackrate=16000"),
1892 "111 maxplaybackrate=16000;maxaveragebitrate=40000"
1893 );
1894 assert_eq!(
1895 with_opus_send_quality("111"),
1896 "111 maxaveragebitrate=40000;maxplaybackrate=48000"
1897 );
1898 }
1899}