BlueGit

ict rusty-teams

Files

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

sdp.rs

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