BlueGit

ict rusty-teams

Files

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

sdp.rs

sdp.rs 72.8 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=";
814
815/// Only touches H264 lines, the sole codec here that carries a `profile-level-id`.
816fn with_h264_send_quality(fmtp: &str) -> String {
817 if !fmtp.contains(H264_PROFILE_LEVEL_ID) {
818 return fmtp.to_owned();
819 }
820 with_fmtp_parameters(&with_full_hd_level(fmtp), &H264_SEND_START)
821}
822
823/// Teams answers a level below the frame size its own `max-fs` and `max-mbps` allow, and the
824/// encoder stalls on every layer larger than that level. The explicit limits are what the peer
825/// can really receive. The level is never lowered, and an answer without both limits stays as it is.
826fn with_full_hd_level(fmtp: &str) -> String {
827 let limit = |name: &str| {
828 fmtp.split([' ', ';'])
829 .find_map(|parameter| parameter.strip_prefix(name)?.strip_prefix('='))
830 .and_then(|value| value.parse::<u32>().ok())
831 };
832 let (Some(max_fs), Some(max_mbps)) = (limit("max-fs"), limit("max-mbps")) else {
833 return fmtp.to_owned();
834 };
835 let Some(needed) = h264_level_for(max_fs, max_mbps) else {
836 return fmtp.to_owned();
837 };
838 let range = fmtp
839 .find(H264_PROFILE_LEVEL_ID)
840 .map(|start| start + H264_PROFILE_LEVEL_ID.len() + 4)
841 .map(|start| start..start + 2)
842 .filter(|range| range.end <= fmtp.len());
843 let Some(range) = range else {
844 return fmtp.to_owned();
845 };
846 let current = fmtp
847 .get(range.clone())
848 .and_then(|level| u8::from_str_radix(level, 16).ok());
849 if current.is_some_and(|level| level >= needed) {
850 return fmtp.to_owned();
851 }
852 let mut raised = fmtp.to_owned();
853 raised.replace_range(range, &format!("{needed:02x}"));
854 raised
855}
856
857/// H.264 Table A-1, lowest level whose MaxFS and MaxMBPS cover the peer limits.
858fn h264_level_for(max_fs: u32, max_mbps: u32) -> Option<u8> {
859 const LEVELS: [(u8, u32, u32); 16] = [
860 (0x0a, 99, 1_485),
861 (0x0b, 396, 3_000),
862 (0x0c, 396, 6_000),
863 (0x0d, 396, 11_880),
864 (0x14, 396, 11_880),
865 (0x15, 792, 19_800),
866 (0x16, 1_620, 20_250),
867 (0x1e, 1_620, 40_500),
868 (0x1f, 3_600, 108_000),
869 (0x20, 5_120, 216_000),
870 (0x28, 8_192, 245_760),
871 (0x29, 8_192, 245_760),
872 (0x2a, 8_704, 522_240),
873 (0x32, 22_080, 589_824),
874 (0x33, 36_864, 983_040),
875 (0x34, 36_864, 2_073_600),
876 ];
877 LEVELS
878 .into_iter()
879 .find(|(_, fs, mbps)| *fs >= max_fs && *mbps >= max_mbps)
880 .map(|(level, _, _)| level)
881}
882
883fn without_fmtp_parameter(fmtp: &str, name: &str) -> String {
884 let Some((payload, parameters)) = fmtp.split_once(' ') else {
885 return fmtp.to_owned();
886 };
887 let kept: Vec<&str> = parameters
888 .split(';')
889 .filter(|parameter| parameter.split('=').next() != Some(name))
890 .collect();
891 format!("{payload} {}", kept.join(";"))
892}
893
894fn with_fmtp_parameters(fmtp: &str, parameters: &[(&str, &str)]) -> String {
895 let mut value = fmtp.to_owned();
896 for &(name, setting) in parameters {
897 if value
898 .split([' ', ';'])
899 .any(|parameter| parameter.split('=').next() == Some(name))
900 {
901 continue;
902 }
903 if !value.ends_with(' ') {
904 value.push(if value.contains(' ') { ';' } else { ' ' });
905 }
906 value.push_str(&format!("{name}={setting}"));
907 }
908 value
909}
910
911fn browser_rtp_line(
912 teams_line: &Media,
913 offered: &Media,
914 role: LineRole,
915 stream_index: u32,
916 carries_candidates: bool,
917 session: &Session,
918) -> Media {
919 let offered_rtpmap = offered.rtpmap();
920 let offered_codecs: HashMap<String, String> = offered_rtpmap
921 .values()
922 .filter_map(|encoding| {
923 let (name, rest) = encoding.split_once('/')?;
924 Some((name.to_ascii_lowercase(), rest.to_owned()))
925 })
926 .collect();
927 let answer_rtpmap = teams_line.rtpmap();
928 let kept: Vec<String> = teams_line
929 .formats
930 .iter()
931 .filter(|payload| {
932 answer_rtpmap
933 .get(*payload)
934 .and_then(|encoding| encoding.split('/').next())
935 .is_some_and(|name| offered_codecs.contains_key(&name.to_ascii_lowercase()))
936 })
937 .cloned()
938 .collect();
939 let kept_set: HashSet<&str> = kept.iter().map(String::as_str).collect();
940 let payload_of = |value: &str| value.split(' ').next().unwrap_or_default().to_owned();
941 let codec_payload = |codec: &str| {
942 kept.iter().find(|payload| {
943 answer_rtpmap.get(*payload).is_some_and(|encoding| {
944 encoding
945 .to_ascii_lowercase()
946 .starts_with(&format!("{codec}/"))
947 })
948 })
949 };
950
951 let mut attributes = Vec::new();
952 attributes.extend(
953 teams_line
954 .values("x-source-streamid")
955 .map(|value| Attribute::new("x-source-streamid", value)),
956 );
957 for value in teams_line.values("rtpmap") {
958 let payload = payload_of(value);
959 if !kept_set.contains(payload.as_str()) {
960 continue;
961 }
962 let encoding = answer_rtpmap.get(&payload).cloned().unwrap_or_default();
963 let name = encoding.split('/').next().unwrap_or_default();
964 let offered_rest = offered_codecs.get(&name.to_ascii_lowercase());
965 let rewritten = match offered_rest {
966 Some(rest) if name.eq_ignore_ascii_case("red") => format!("{payload} {name}/{rest}"),
967 _ => value.to_owned(),
968 };
969 attributes.push(Attribute::new("rtpmap", rewritten));
970 }
971 let mut fmtp_payloads = HashSet::new();
972 for value in teams_line.values("fmtp") {
973 let payload = payload_of(value);
974 if !kept_set.contains(payload.as_str()) {
975 continue;
976 }
977 let cleaned = value
978 .split(';')
979 .filter(|parameter| !parameter.starts_with("rtx-time="))
980 .collect::<Vec<_>>()
981 .join(";");
982 let is_opus = codec_payload("opus").is_some_and(|opus| *opus == payload);
983 fmtp_payloads.insert(payload);
984 attributes.push(Attribute::new(
985 "fmtp",
986 if is_opus {
987 with_opus_send_quality(&cleaned)
988 } else {
989 with_h264_send_quality(&cleaned)
990 },
991 ));
992 }
993 if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) {
994 attributes.push(Attribute::new(
995 "fmtp",
996 with_opus_send_quality(&format!("{opus} usedtx=1")),
997 ));
998 }
999 if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus"))
1000 && !fmtp_payloads.contains(red)
1001 {
1002 attributes.push(Attribute::new("fmtp", format!("{red} {opus}/{opus}")));
1003 }
1004 attributes.extend(
1005 teams_line
1006 .values("rtcp")
1007 .map(|value| Attribute::new("rtcp", value)),
1008 );
1009 let answer_feedback: Vec<&str> = teams_line
1010 .values("rtcp-fb")
1011 .filter(|value| !value.contains("x-message"))
1012 .collect();
1013 if answer_feedback.is_empty() && !teams_line.has("rtcp-fb") {
1014 attributes.extend(
1015 offered
1016 .values("rtcp-fb")
1017 .filter(|value| kept_set.contains(payload_of(value).as_str()))
1018 .map(|value| Attribute::new("rtcp-fb", value)),
1019 );
1020 } else {
1021 attributes.extend(
1022 answer_feedback
1023 .into_iter()
1024 .map(|value| Attribute::new("rtcp-fb", value)),
1025 );
1026 }
1027 for value in teams_line.values("extmap") {
1028 let restored = value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "");
1029 attributes.push(Attribute::new("extmap", restored));
1030 }
1031 attributes.extend(transport_attributes(teams_line, session));
1032 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
1033 attributes.extend(
1034 teams_line
1035 .values("ptime")
1036 .map(|value| Attribute::new("ptime", value)),
1037 );
1038 if let Some(direction) = teams_line.direction() {
1039 attributes.push(Attribute::flag(direction));
1040 }
1041 if carries_candidates {
1042 attributes.extend(
1043 teams_line
1044 .values("candidate")
1045 .chain(teams_line.values("x-candidate-ipv6"))
1046 .map(|value| Attribute::new("candidate", browser_candidate(value))),
1047 );
1048 }
1049 attributes.extend(stream_ssrc_attributes(teams_line, stream_index, role));
1050 attributes.push(Attribute::flag("rtcp-mux"));
1051 if teams_line.has("rtcp-rsize") {
1052 attributes.push(Attribute::flag("rtcp-rsize"));
1053 }
1054 if let Some(simulcast) = offered
1055 .value("simulcast")
1056 .and_then(|value| value.strip_prefix("send "))
1057 {
1058 let rids: Vec<String> = simulcast
1059 .split(';')
1060 .map(|rid| rid.trim_start_matches('~').to_owned())
1061 .collect();
1062 attributes.extend(
1063 rids.iter()
1064 .map(|rid| Attribute::new("rid", format!("{rid} recv"))),
1065 );
1066 attributes.push(Attribute::new(
1067 "simulcast",
1068 format!("recv {}", rids.join(";")),
1069 ));
1070 }
1071 // A rejected line still needs a format. Teams rejects with a static payload
1072 // such as `34` that has no rtpmap, so fall back to the offered payload.
1073 let formats = if kept.is_empty() && teams_line.port == "0" {
1074 offered.formats.iter().take(1).cloned().collect()
1075 } else {
1076 kept
1077 };
1078 Media {
1079 kind: offered.kind.clone(),
1080 port: teams_line.port.clone(),
1081 proto: offered.proto.clone(),
1082 formats,
1083 connection: teams_line
1084 .connection
1085 .clone()
1086 .or_else(|| session.connection.clone()),
1087 bandwidths: teams_line.bandwidths.clone(),
1088 attributes,
1089 }
1090}
1091
1092fn stream_ssrc_attributes(teams_line: &Media, stream_index: u32, role: LineRole) -> Vec<Attribute> {
1093 let (Some(primary), retransmission) = stream_ssrcs(teams_line, stream_index) else {
1094 return Vec::new();
1095 };
1096 let stream = format!("{}-{primary}", role.stream_prefix());
1097 let mut attributes = Vec::new();
1098 for ssrc in [Some(primary), retransmission].into_iter().flatten() {
1099 attributes.push(Attribute::new(
1100 "ssrc",
1101 format!("{ssrc} cname:{}", stream_cname(primary)),
1102 ));
1103 attributes.push(Attribute::new(
1104 "ssrc",
1105 format!("{ssrc} msid:{stream} {stream}"),
1106 ));
1107 }
1108 if let Some(retransmission) = retransmission {
1109 attributes.push(Attribute::new(
1110 "ssrc-group",
1111 format!("FID {primary} {retransmission}"),
1112 ));
1113 }
1114 attributes
1115}
1116
1117fn stream_cname(primary: u32) -> String {
1118 format!("teams{primary}")
1119}
1120
1121fn stream_ssrcs(teams_line: &Media, stream_index: u32) -> (Option<u32>, Option<u32>) {
1122 let offset = stream_index * SSRC_RANGE_SIZE;
1123 if let Some(group) = teams_line
1124 .value("ssrc-group")
1125 .and_then(|value| value.strip_prefix("FID "))
1126 {
1127 let mut ssrcs = group
1128 .split(' ')
1129 .filter_map(|value| value.parse::<u32>().ok());
1130 let primary = ssrcs.next().map(|ssrc| ssrc + offset);
1131 return (primary, ssrcs.next().map(|ssrc| ssrc + offset));
1132 }
1133 let first = teams_line
1134 .value("x-ssrc-range")
1135 .and_then(|range| range.split('-').next()?.parse::<u32>().ok())
1136 .map(|ssrc| ssrc + offset);
1137 (first, None)
1138}
1139
1140fn browser_candidate(value: &str) -> String {
1141 let mut parts: Vec<&str> = value.split(' ').collect();
1142 if let Some(position) = parts.iter().position(|part| *part == "MTURNID") {
1143 parts.truncate(position);
1144 }
1145 let tcp_type = match parts
1146 .get(2)
1147 .map(|transport| transport.to_ascii_lowercase())
1148 .as_deref()
1149 {
1150 Some("tcp-pass") => Some("passive"),
1151 Some("tcp-act") => Some("active"),
1152 Some("tcp-so") => Some("so"),
1153 _ => None,
1154 };
1155 if tcp_type.is_some() {
1156 parts[2] = "tcp";
1157 }
1158 let mut candidate = parts.join(" ");
1159 if let Some(tcp_type) = tcp_type {
1160 candidate.push_str(" tcptype ");
1161 candidate.push_str(tcp_type);
1162 }
1163 candidate
1164}
1165
1166fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) -> Media {
1167 let mut attributes = Vec::new();
1168 attributes.extend(
1169 teams_line
1170 .values("x-source-streamid")
1171 .map(|value| Attribute::new("x-source-streamid", value)),
1172 );
1173 attributes.extend(transport_attributes(teams_line, session));
1174 attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default()));
1175 attributes.extend(
1176 offered
1177 .values("sctp-port")
1178 .map(|value| Attribute::new("sctp-port", value)),
1179 );
1180 Media {
1181 kind: offered.kind.clone(),
1182 port: teams_line.port.clone(),
1183 proto: offered.proto.clone(),
1184 formats: offered.formats.clone(),
1185 connection: teams_line
1186 .connection
1187 .clone()
1188 .or_else(|| session.connection.clone()),
1189 bandwidths: Vec::new(),
1190 attributes,
1191 }
1192}
1193
1194const BROWSER_PORT: &str = "9";
1195const BROWSER_PROTO: &str = "UDP/TLS/RTP/SAVPF";
1196const BROWSER_CONNECTION: &str = "IN IP4 0.0.0.0";
1197const BROWSER_RTCP: &str = "9 IN IP4 0.0.0.0";
1198const BROWSER_DATA_PROTO: &str = "UDP/DTLS/SCTP";
1199const BROWSER_DATA_FORMAT: &str = "webrtc-datachannel";
1200const SCTP_PORT: &str = "5000";
1201const SCTP_MAX_MESSAGE_SIZE: &str = "262144";
1202const PLACEHOLDER_CANDIDATE_TAIL: &str = " 1234 typ host";
1203const TEAMS_ONLY_ATTRIBUTES: [&str; 6] = [
1204 "x-multi-stream",
1205 "x-signaling-fb",
1206 "x-ssrc-range",
1207 "x-source-streamid",
1208 "x-data-protocol",
1209 "label",
1210];
1211const TRANSPORT_ATTRIBUTES: [&str; 5] = [
1212 "setup",
1213 "ice-ufrag",
1214 "ice-pwd",
1215 "fingerprint",
1216 "ice-options",
1217];
1218
1219/// A Teams offer translated for libwebrtc; `lines` remembers which browser mids each signaled line stands for.
1220#[derive(Debug, Clone)]
1221pub struct RemoteOffer {
1222 pub browser_sdp: String,
1223 pub lines: Vec<SignaledLine>,
1224}
1225
1226impl RemoteOffer {
1227 pub fn plan(&self) -> OfferPlan {
1228 let mut plan = OfferPlan::default();
1229 for line in &self.lines {
1230 match line.role {
1231 LineRole::ScreenShare => plan
1232 .screen_share_mids
1233 .extend(line.browser_mids.iter().cloned()),
1234 _ => {}
1235 }
1236 if line.browser_mids.len() > 1 {
1237 plan.gallery_mids.extend(line.browser_mids.iter().cloned());
1238 plan.fold_groups.push(line.browser_mids.clone());
1239 }
1240 }
1241 plan
1242 }
1243}
1244
1245fn effective_fold_groups(plan: &OfferPlan) -> Vec<Vec<String>> {
1246 if !plan.fold_groups.is_empty() {
1247 return plan.fold_groups.clone();
1248 }
1249 if plan.gallery_mids.len() > 1 {
1250 vec![plan.gallery_mids.clone()]
1251 } else {
1252 Vec::new()
1253 }
1254}
1255
1256fn role_of_teams_line(line: &Media) -> LineRole {
1257 match line.value("label") {
1258 Some("main-audio") => LineRole::MainAudio,
1259 Some("main-video") => LineRole::MainVideo,
1260 Some("applicationsharing-video") => LineRole::ScreenShare,
1261 Some("data") => LineRole::Data,
1262 _ => match line.kind.as_str() {
1263 "audio" => LineRole::MainAudio,
1264 "x-data" | "application" => LineRole::Data,
1265 _ => LineRole::MainVideo,
1266 },
1267 }
1268}
1269
1270/// Folded gallery lines get the mids just below the carrier line's own mid, unless another line already uses one of them.
1271fn folded_mids(carrier: &str, count: usize, taken: &[String]) -> Vec<String> {
1272 let below = match carrier.parse::<usize>() {
1273 Ok(last) if last + 1 >= count => Some(
1274 (last + 1 - count..=last)
1275 .map(|mid| mid.to_string())
1276 .collect::<Vec<_>>(),
1277 ),
1278 _ => None,
1279 };
1280 match below.filter(|mids| {
1281 mids.iter()
1282 .all(|mid| mid == carrier || !taken.contains(mid))
1283 }) {
1284 Some(mids) => mids,
1285 None => (0..count)
1286 .map(|index| {
1287 if index + 1 == count {
1288 carrier.to_owned()
1289 } else {
1290 format!("{carrier}-{index}")
1291 }
1292 })
1293 .collect(),
1294 }
1295}
1296
1297pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> {
1298 let teams = parse(teams_sdp)?;
1299 let mut media = Vec::new();
1300 let mut lines = Vec::new();
1301 let mut taken: Vec<String> = teams
1302 .media
1303 .iter()
1304 .filter_map(|line| line.mid().map(str::to_owned))
1305 .collect();
1306 for source in &teams.media {
1307 let role = role_of_teams_line(source);
1308 let carrier = source.mid().unwrap_or_default().to_owned();
1309 let folded = source
1310 .value("x-multi-stream")
1311 .and_then(|value| value.split(' ').next()?.parse::<usize>().ok())
1312 .filter(|count| *count > 1);
1313 let mids = match folded {
1314 Some(count) => folded_mids(&carrier, count, &taken),
1315 None => vec![carrier.clone()],
1316 };
1317 taken.extend(mids.iter().cloned());
1318 for (index, mid) in mids.iter().enumerate() {
1319 let converted = if role == LineRole::Data {
1320 browser_data_from_teams(source, mid, &teams.session)
1321 } else {
1322 browser_rtp_from_teams(
1323 source,
1324 mid,
1325 role,
1326 folded.is_some(),
1327 index == 0 && lines.is_empty(),
1328 &teams.session,
1329 )
1330 };
1331 media.push(converted);
1332 }
1333 lines.push(SignaledLine {
1334 browser_mids: mids,
1335 role,
1336 });
1337 }
1338 let mut session = teams.session.clone();
1339 session.bandwidths.clear();
1340 session.connection = None;
1341 session.attributes.retain(|attribute| {
1342 matches!(
1343 attribute.name.as_str(),
1344 "extmap-allow-mixed" | "msid-semantic"
1345 )
1346 });
1347 session.attributes.push(Attribute::new(
1348 "group",
1349 bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))),
1350 ));
1351 Ok(RemoteOffer {
1352 browser_sdp: write(&SessionDescription { session, media }),
1353 lines,
1354 })
1355}
1356
1357fn transport_from_teams(source: &Media, session: &Session) -> Vec<Attribute> {
1358 TRANSPORT_ATTRIBUTES
1359 .iter()
1360 .filter_map(|name| {
1361 source
1362 .attributes
1363 .iter()
1364 .chain(&session.attributes)
1365 .find(|attribute| attribute.name == *name)
1366 .cloned()
1367 })
1368 .collect()
1369}
1370
1371fn browser_data_from_teams(source: &Media, mid: &str, session: &Session) -> Media {
1372 let mut attributes = transport_from_teams(source, session);
1373 attributes.push(Attribute::new("mid", mid));
1374 attributes.push(Attribute::new("sctp-port", SCTP_PORT));
1375 attributes.push(Attribute::new("max-message-size", SCTP_MAX_MESSAGE_SIZE));
1376 Media {
1377 kind: "application".to_owned(),
1378 port: BROWSER_PORT.to_owned(),
1379 proto: BROWSER_DATA_PROTO.to_owned(),
1380 formats: vec![BROWSER_DATA_FORMAT.to_owned()],
1381 connection: Some(BROWSER_CONNECTION.to_owned()),
1382 bandwidths: Vec::new(),
1383 attributes,
1384 }
1385}
1386
1387fn browser_rtp_from_teams(
1388 source: &Media,
1389 mid: &str,
1390 role: LineRole,
1391 folded: bool,
1392 carries_candidate: bool,
1393 session: &Session,
1394) -> Media {
1395 let rtpmap = source.rtpmap();
1396 let is_rtx = |payload: &str| {
1397 rtpmap
1398 .get(payload)
1399 .is_some_and(|encoding| encoding.starts_with("rtx/"))
1400 };
1401 let mut attributes = Vec::new();
1402 let mut expanded_feedback: Vec<Attribute> = Vec::new();
1403 let mut signals_ssrc = false;
1404 let mut ssrc_groups = Vec::new();
1405 for attribute in &source.attributes {
1406 let value = attribute.value.as_deref().unwrap_or_default();
1407 match attribute.name.as_str() {
1408 name if TEAMS_ONLY_ATTRIBUTES.contains(&name) => {}
1409 "x-candidate-ipv6" => {
1410 if carries_candidate {
1411 attributes.push(Attribute::new("candidate", browser_candidate(value)));
1412 }
1413 }
1414 name if name.starts_with("x-") => {}
1415 "mid" | "rtcp-mux" => {}
1416 name if TRANSPORT_ATTRIBUTES.contains(&name) => {}
1417 "candidate" => {
1418 if carries_candidate && !value.contains(PLACEHOLDER_CANDIDATE_TAIL) {
1419 attributes.push(Attribute::new("candidate", browser_candidate(value)));
1420 }
1421 }
1422 "ssrc" => {
1423 let placeholder = value.contains("fake_attribute") || value.starts_with("1 ");
1424 if !folded && !placeholder {
1425 signals_ssrc = true;
1426 attributes.push(attribute.clone());
1427 }
1428 }
1429 "ssrc-group" => {
1430 if !folded {
1431 ssrc_groups.push(attribute.clone());
1432 }
1433 }
1434 "rtcp" => attributes.push(Attribute::new("rtcp", BROWSER_RTCP)),
1435 "rtpmap" => attributes.push(Attribute::new("rtpmap", browser_rtpmap(value))),
1436 "extmap" => attributes.push(Attribute::new("extmap", browser_extmap(value))),
1437 "fmtp" => attributes.push(Attribute::new("fmtp", with_h264_send_quality(value))),
1438 "rtcp-fb" => match value.strip_prefix("* ") {
1439 Some(kind) => expanded_feedback.extend(
1440 source
1441 .formats
1442 .iter()
1443 .filter(|payload| !is_rtx(payload))
1444 .map(|payload| Attribute::new("rtcp-fb", format!("{payload} {kind}"))),
1445 ),
1446 None => attributes.push(attribute.clone()),
1447 },
1448 _ => attributes.push(attribute.clone()),
1449 }
1450 }
1451 attributes.extend(expanded_feedback);
1452 attributes.extend(transport_from_teams(source, session));
1453 attributes.push(Attribute::new("mid", mid));
1454 if signals_ssrc {
1455 attributes.extend(ssrc_groups);
1456 } else if !folded {
1457 attributes.extend(stream_ssrc_attributes(source, 0, role));
1458 }
1459 attributes.push(Attribute::flag("rtcp-mux"));
1460 Media {
1461 kind: source.kind.clone(),
1462 port: BROWSER_PORT.to_owned(),
1463 proto: BROWSER_PROTO.to_owned(),
1464 formats: source.formats.clone(),
1465 connection: Some(BROWSER_CONNECTION.to_owned()),
1466 bandwidths: Vec::new(),
1467 attributes,
1468 }
1469}
1470
1471fn browser_rtpmap(value: &str) -> String {
1472 match value.split_once(' ') {
1473 Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => {
1474 format!("{payload} red/48000/2")
1475 }
1476 _ => value.to_owned(),
1477 }
1478}
1479
1480fn browser_extmap(value: &str) -> String {
1481 value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "")
1482}
1483
1484/// libwebrtc answers every offered line in the offer's order and with its mids, so the offer's plan applies unchanged.
1485pub fn to_teams_answer(
1486 browser_answer_sdp: &str,
1487 remote: &RemoteOffer,
1488 numbers: &mut impl NumberSource,
1489) -> Result<SignaledOffer> {
1490 to_teams_offer(browser_answer_sdp, &remote.plan(), numbers)
1491}
1492
1493#[cfg(test)]
1494mod tests {
1495 use super::*;
1496
1497 fn counter() -> impl FnMut() -> u32 {
1498 let mut next = 1000u32;
1499 move || {
1500 next += 1;
1501 next
1502 }
1503 }
1504
1505 #[test]
1506 fn h264_sends_start_high_and_use_the_level_the_peer_limits_allow() {
1507 let full_hd = "98 packetization-mode=1;profile-level-id=42e01f;max-fs=8160;max-mbps=244800";
1508 assert_eq!(
1509 with_h264_send_quality(full_hd),
1510 "98 packetization-mode=1;profile-level-id=42e028;max-fs=8160;max-mbps=244800;x-google-start-bitrate=1500"
1511 );
1512 let hd = "98 profile-level-id=42e01f;max-fs=3600;max-mbps=108000";
1513 assert_eq!(
1514 with_h264_send_quality(hd),
1515 "98 profile-level-id=42e01f;max-fs=3600;max-mbps=108000;x-google-start-bitrate=1500"
1516 );
1517 let level_30 = "98 profile-level-id=42C01E;max-fs=3600;max-mbps=108000";
1518 assert_eq!(
1519 with_h264_send_quality(level_30),
1520 "98 profile-level-id=42C01f;max-fs=3600;max-mbps=108000;x-google-start-bitrate=1500"
1521 );
1522 assert_eq!(
1523 with_h264_send_quality("98 profile-level-id=42C01E"),
1524 "98 profile-level-id=42C01E;x-google-start-bitrate=1500"
1525 );
1526 assert_eq!(with_h264_send_quality("99 apt=98"), "99 apt=98");
1527 assert_eq!(
1528 without_fmtp_parameter(
1529 "98 profile-level-id=42e01f;x-google-start-bitrate=1500",
1530 "x-google-start-bitrate"
1531 ),
1532 "98 profile-level-id=42e01f"
1533 );
1534 }
1535
1536 #[test]
1537 fn rejected_lines_stay_out_of_the_bundle() {
1538 let lines = [("9", Some("0")), ("0", Some("1")), ("9", Some("2"))];
1539 assert_eq!(bundle_group(lines.into_iter()), "BUNDLE 0 2");
1540 }
1541
1542 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";
1543 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";
1544
1545 #[test]
1546 fn audio_only_offer_gets_the_teams_shape() {
1547 let offer =
1548 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1549 let text = offer.sdp.replace("\r\n", "\n");
1550 assert!(text.contains("\nb=CT:4000\n"));
1551 assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\n"));
1552 assert!(text.contains("a=x-signaling-fb:* x-message app recv:dsh\n"));
1553 assert!(text.contains("a=x-ssrc-range:42-42\n"));
1554 assert!(text.contains("a=rtpmap:63 RED/8000\n"));
1555 assert!(text.contains("a=fmtp:111 minptime=10;useinbandfec=1;maxplaybackrate=48000;sprop-maxcapturerate=48000\n"));
1556 assert!(text.contains("a=rtcp:1234\n"));
1557 assert!(text.contains(
1558 "a=extmap:2 http:\\\\www.webrtc.org\\experiments\\rtp-hdrext\\abs-send-time\n"
1559 ));
1560 assert!(text.contains("a=ssrc:42 msid:stream 0\n"));
1561 assert!(
1562 text.contains("a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\n")
1563 );
1564 assert!(
1565 text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\nc=IN IP4 10.10.10.10\n")
1566 );
1567 assert!(text.ends_with("a=label:main-audio\n"));
1568 assert_eq!(
1569 offer.lines,
1570 vec![SignaledLine {
1571 browser_mids: vec!["0".into()],
1572 role: LineRole::MainAudio
1573 }]
1574 );
1575 }
1576
1577 #[test]
1578 fn a_renegotiation_signals_only_the_placeholder_candidate() {
1579 let gathered = AUDIO_ONLY_OFFER.replace(
1580 "a=mid:0\r\n",
1581 "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",
1582 );
1583 let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter())
1584 .unwrap()
1585 .sdp;
1586 let candidates: Vec<&str> = text
1587 .lines()
1588 .filter(|line| {
1589 line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")
1590 })
1591 .collect();
1592 assert_eq!(
1593 candidates,
1594 vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]
1595 );
1596 }
1597
1598 #[test]
1599 fn answer_candidates_lose_teams_extensions() {
1600 assert_eq!(
1601 browser_candidate(
1602 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 158"
1603 ),
1604 "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480"
1605 );
1606 assert_eq!(
1607 browser_candidate(
1608 "3 1 tcp-pass 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478"
1609 ),
1610 "3 1 tcp 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478 tcptype passive"
1611 );
1612 assert_eq!(
1613 browser_candidate(
1614 "10 1 TCP-ACT 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009"
1615 ),
1616 "10 1 tcp 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009 tcptype active"
1617 );
1618 }
1619
1620 #[test]
1621 fn audio_answer_maps_back_to_the_browser_mid_and_codecs() {
1622 let offer =
1623 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1624 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";
1625 let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER)
1626 .unwrap()
1627 .replace("\r\n", "\n");
1628 assert!(
1629 browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"),
1630 "{browser}"
1631 );
1632 assert!(browser.contains("a=rtpmap:97 RED/48000/2\n"));
1633 assert!(
1634 browser.contains("a=fmtp:111 usedtx=1;maxaveragebitrate=40000;maxplaybackrate=48000\n")
1635 );
1636 assert!(browser.contains("a=fmtp:97 111/111\n"));
1637 assert!(browser.contains("a=rtcp-fb:111 transport-cc\n"));
1638 assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n"));
1639 assert!(browser.contains("a=group:BUNDLE 0\n"));
1640 assert!(
1641 !browser.contains("SATINFB")
1642 && !browser.contains("MTURNID")
1643 && !browser.contains("label")
1644 );
1645 }
1646 #[test]
1647 fn a_rejected_answer_line_without_rtpmap_keeps_an_offered_format() {
1648 let offer = to_teams_offer(
1649 ONE_TO_ONE_BROWSER_OFFER,
1650 &OfferPlan::default(),
1651 &mut counter(),
1652 )
1653 .unwrap();
1654 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";
1655 let browser = to_browser_answer(answer, &offer, ONE_TO_ONE_BROWSER_OFFER)
1656 .unwrap()
1657 .replace("\r\n", "\n");
1658 assert!(
1659 browser.contains("m=video 0 UDP/TLS/RTP/SAVPF 102\n"),
1660 "{browser}"
1661 );
1662 assert!(browser.contains("a=group:BUNDLE 0\n"));
1663 }
1664
1665 #[test]
1666 fn an_audio_offer_from_teams_gets_the_browser_shape_back() {
1667 let offer =
1668 to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap();
1669 let remote = from_teams_offer(&offer.sdp).unwrap();
1670 let text = remote.browser_sdp.replace("\r\n", "\n");
1671 assert!(
1672 text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"),
1673 "{text}"
1674 );
1675 assert!(text.contains("c=IN IP4 0.0.0.0\n"));
1676 assert!(text.contains("a=rtcp:9 IN IP4 0.0.0.0\n"));
1677 assert!(text.contains("a=rtpmap:63 red/48000/2\n"));
1678 assert!(
1679 text.contains(
1680 "a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n"
1681 )
1682 );
1683 assert!(
1684 text.contains("a=ice-ufrag:u\n")
1685 && text.contains("a=fingerprint:sha-256 AA\n")
1686 && text.contains("a=setup:actpass\n")
1687 );
1688 assert!(text.contains("a=mid:0\n") && text.contains("a=group:BUNDLE 0\n"));
1689 assert!(
1690 !text.contains("10.10.10.10")
1691 && !text.contains("x-ssrc-range")
1692 && !text.contains("label")
1693 && !text.contains("1234")
1694 );
1695 assert_eq!(remote.lines, offer.lines);
1696 }
1697
1698 #[test]
1699 fn shared_video_feedback_is_spelled_out_per_codec_again() {
1700 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";
1701 let remote = from_teams_offer(teams).unwrap();
1702 let text = remote.browser_sdp.replace("\r\n", "\n");
1703 assert!(text.contains("a=rtcp-fb:102 nack\n") && text.contains("a=rtcp-fb:102 nack pli\n"));
1704 assert!(!text.contains("a=rtcp-fb:103") && !text.contains("a=rtcp-fb:*"));
1705 }
1706
1707 #[test]
1708 fn a_peer_offer_with_only_ssrc_ranges_signals_the_streams_it_sends() {
1709 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";
1710 let remote = from_teams_offer(teams).unwrap();
1711 let parsed = parse(&remote.browser_sdp).unwrap();
1712 let audio: Vec<&str> = parsed.media[0].values("ssrc").collect();
1713 assert!(
1714 audio.iter().any(|value| value.starts_with("40475 cname:")),
1715 "{audio:?}"
1716 );
1717 assert_eq!(
1718 parsed.media[1].values("ssrc-group").collect::<Vec<_>>(),
1719 vec!["FID 40476 40526"]
1720 );
1721 let video: Vec<&str> = parsed.media[1].values("ssrc").collect();
1722 assert!(
1723 video.iter().any(|value| value.starts_with("40476 cname:"))
1724 && video.iter().any(|value| value.starts_with("40526 cname:")),
1725 "{video:?}"
1726 );
1727 }
1728
1729 #[test]
1730 fn a_rejected_video_line_stays_rejected_and_out_of_the_bundle() {
1731 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";
1732 let remote = from_teams_offer(audio_and_video).unwrap();
1733 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";
1734 let signaled = to_teams_answer(answer, &remote, &mut counter()).unwrap();
1735 let text = signaled.sdp.replace("\r\n", "\n");
1736 assert!(text.contains("m=video 0 RTP/SAVP 102\n"), "{text}");
1737 assert!(text.contains("a=group:BUNDLE 0\n"));
1738 let parsed = parse(&signaled.sdp).unwrap();
1739 assert_eq!(parsed.media.len(), 2);
1740 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1741 assert_eq!(parsed.media[1].direction(), Some("inactive"));
1742 }
1743
1744 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";
1745
1746 fn browser_answer(camera_direction: &str, share_port: &str, share_direction: &str) -> String {
1747 format!(
1748 "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"
1749 )
1750 }
1751
1752 #[test]
1753 fn a_folded_line_never_reuses_the_mid_of_another_line() {
1754 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";
1755 let teams = format!(
1756 "{}{folded}",
1757 ONE_TO_ONE_VIDEO_OFFER.replace("BUNDLE 0 1 2", "BUNDLE 0 1 2 3")
1758 );
1759 let remote = from_teams_offer(&teams).unwrap();
1760 let mids: Vec<String> = parse(&remote.browser_sdp)
1761 .unwrap()
1762 .media
1763 .iter()
1764 .filter_map(|line| line.mid().map(str::to_owned))
1765 .collect();
1766 let mut unique = mids.clone();
1767 unique.sort();
1768 unique.dedup();
1769 assert_eq!(unique.len(), mids.len(), "{mids:?}");
1770 assert_eq!(
1771 remote.lines.last().unwrap().browser_mids,
1772 vec!["3-0".to_owned(), "3".to_owned()]
1773 );
1774 }
1775
1776 #[test]
1777 fn a_one_to_one_offer_keeps_a_camera_line_and_a_sharing_line() {
1778 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1779 let roles: Vec<LineRole> = remote.lines.iter().map(|line| line.role).collect();
1780 assert_eq!(
1781 roles,
1782 vec![
1783 LineRole::MainAudio,
1784 LineRole::MainVideo,
1785 LineRole::ScreenShare
1786 ]
1787 );
1788 assert_eq!(remote.plan().screen_share_mids, vec!["2".to_owned()]);
1789 assert!(remote.plan().gallery_mids.is_empty());
1790 assert_eq!(
1791 parse(&remote.browser_sdp)
1792 .unwrap()
1793 .media
1794 .iter()
1795 .filter(|media| media.kind == "video")
1796 .count(),
1797 2
1798 );
1799 }
1800
1801 #[test]
1802 fn accepting_with_audio_answers_the_video_line_receive_only_and_with_video_sending() {
1803 let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap();
1804 for (camera_direction, expected) in [("recvonly", "recvonly"), ("sendrecv", "sendrecv")] {
1805 let answer = to_teams_answer(
1806 &browser_answer(camera_direction, "0", "inactive"),
1807 &remote,
1808 &mut counter(),
1809 )
1810 .unwrap();
1811 let parsed = parse(&answer.sdp).unwrap();
1812 assert_eq!(parsed.media.len(), 3);
1813 assert_eq!(parsed.media[1].port, "1234");
1814 assert_eq!(parsed.media[1].direction(), Some(expected));
1815 assert_eq!(parsed.media[1].value("label"), Some("main-video"));
1816 assert_eq!(parsed.media[2].port, "0");
1817 assert_eq!(
1818 parsed.media[2].value("label"),
1819 Some("applicationsharing-video")
1820 );
1821 }
1822 }
1823
1824 #[test]
1825 fn folded_gallery_lines_expand_below_their_carrier_mid_unless_those_are_taken() {
1826 let taken = ["0".to_owned(), "1".to_owned(), "17".to_owned()];
1827 assert_eq!(
1828 folded_mids("17", 8, &taken),
1829 (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>()
1830 );
1831 assert_eq!(
1832 folded_mids("x", 2, &taken),
1833 vec!["x-0".to_owned(), "x".to_owned()]
1834 );
1835 assert_eq!(
1836 folded_mids("2", 2, &taken),
1837 vec!["2-0".to_owned(), "2".to_owned()]
1838 );
1839 }
1840
1841 /// 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).
1842 fn folded_carrier_neighbor_taken(label: &str) -> String {
1843 format!(
1844 "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"
1845 )
1846 }
1847
1848 #[test]
1849 fn a_folded_answer_keeps_one_teams_line_when_carrier_neighbors_are_taken() {
1850 for label in ["main-video", "applicationsharing-video"] {
1851 let offer = folded_carrier_neighbor_taken(label);
1852 let remote = from_teams_offer(&offer).unwrap();
1853 let folded = remote
1854 .lines
1855 .iter()
1856 .find(|line| line.browser_mids.len() > 1)
1857 .expect("folded line");
1858 assert_eq!(folded.browser_mids, vec!["3-0".to_owned(), "3".to_owned()]);
1859 assert_eq!(
1860 remote.plan().fold_groups,
1861 vec![vec!["3-0".to_owned(), "3".to_owned()]]
1862 );
1863 let offer_lines = parse(&offer).unwrap().media.len();
1864 let browser = parse(&remote.browser_sdp).unwrap();
1865 assert_eq!(browser.media.len(), offer_lines + 1);
1866 for port in ["0", "9"] {
1867 let answer_browser = write(&SessionDescription {
1868 session: browser.session.clone(),
1869 media: browser
1870 .media
1871 .iter()
1872 .map(|line| {
1873 let mut line = line.clone();
1874 line.port = if line.kind == "audio" || line.kind == "application" {
1875 "9".to_owned()
1876 } else {
1877 port.to_owned()
1878 };
1879 line.attributes.retain(|attribute| {
1880 !matches!(
1881 attribute.name.as_str(),
1882 "sendrecv" | "recvonly" | "sendonly" | "inactive"
1883 )
1884 });
1885 if line.kind == "audio" || line.kind == "application" {
1886 line.attributes.push(Attribute::flag("sendrecv"));
1887 } else {
1888 line.attributes.push(Attribute::flag("inactive"));
1889 }
1890 line
1891 })
1892 .collect(),
1893 });
1894 let answer = to_teams_answer(&answer_browser, &remote, &mut counter()).unwrap();
1895 let parsed = parse(&answer.sdp).unwrap();
1896 let mids: Vec<_> = parsed.media.iter().filter_map(|line| line.mid()).collect();
1897 assert_eq!(
1898 parsed.media.len(),
1899 offer_lines,
1900 "{label} port {port}: answer mids {mids:?} must match the offer line count"
1901 );
1902 assert!(
1903 !mids.iter().any(|mid| *mid == "3-0"),
1904 "{label} port {port}: signaled answer must not expose the internal fold mid: {mids:?}"
1905 );
1906 assert!(mids.iter().any(|mid| *mid == "3"), "{label} port {port}");
1907 let carrier = parsed
1908 .media
1909 .iter()
1910 .find(|line| line.mid() == Some("3"))
1911 .unwrap();
1912 assert_eq!(
1913 carrier
1914 .value("x-multi-stream")
1915 .and_then(|value| value.split(' ').next().map(str::to_owned)),
1916 Some("2".to_owned()),
1917 "{label} port {port}: carrier must keep x-multi-stream"
1918 );
1919 assert_eq!(carrier.value("label"), Some(label));
1920 }
1921 }
1922 }
1923
1924 #[test]
1925 fn opus_fmtp_gets_the_send_quality_without_overriding_teams() {
1926 assert_eq!(
1927 with_opus_send_quality("111 minptime=10;useinbandfec=1"),
1928 "111 minptime=10;useinbandfec=1;maxaveragebitrate=40000;maxplaybackrate=48000"
1929 );
1930 assert_eq!(
1931 with_opus_send_quality("111 maxplaybackrate=16000"),
1932 "111 maxplaybackrate=16000;maxaveragebitrate=40000"
1933 );
1934 assert_eq!(
1935 with_opus_send_quality("111"),
1936 "111 maxaveragebitrate=40000;maxplaybackrate=48000"
1937 );
1938 }
1939}