| 1 | use std::collections::{HashMap, HashSet}; |
| 2 | |
| 3 | use crate::error::{Error, Result}; |
| 4 | |
| 5 | const SIGNALED_PORT: &str = "1234"; |
| 6 | const SIGNALED_PROTO: &str = "RTP/SAVP"; |
| 7 | const SESSION_BANDWIDTH: &str = "CT:4000"; |
| 8 | const PLACEHOLDER_CANDIDATE: &str = "1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"; |
| 9 | const PLACEHOLDER_CONNECTION: &str = "IN IP4 10.10.10.10"; |
| 10 | const SSRC_RANGE_SIZE: u32 = 100; |
| 11 | const 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 | ]; |
| 15 | const DROPPED_EXTENSIONS: [&str; 1] = ["http://www.webrtc.org/experiments/rtp-hdrext/playout-delay"]; |
| 16 | const LAYERS_ALLOCATION: &str = "http://www.webrtc.org/experiments/rtp-hdrext/video-layers-allocation00"; |
| 17 | const NOT_ADVERTISED_SUFFIX: &str = "-non-advertised"; |
| 18 | const DIRECTIONS: [&str; 4] = ["sendrecv", "sendonly", "recvonly", "inactive"]; |
| 19 | |
| 20 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 21 | pub struct Attribute { |
| 22 | pub name: String, |
| 23 | pub value: Option<String>, |
| 24 | } |
| 25 | |
| 26 | impl 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)] |
| 54 | pub 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)] |
| 65 | pub 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)] |
| 76 | pub struct SessionDescription { |
| 77 | pub session: Session, |
| 78 | pub media: Vec<Media>, |
| 79 | } |
| 80 | |
| 81 | impl 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 | |
| 117 | pub 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 | |
| 171 | fn 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 | |
| 181 | fn 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 | |
| 219 | pub 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)] |
| 248 | pub enum LineRole { |
| 249 | MainAudio, |
| 250 | MainVideo, |
| 251 | ScreenShare, |
| 252 | Data, |
| 253 | } |
| 254 | |
| 255 | impl 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)] |
| 277 | pub struct OfferPlan { |
| 278 | pub screen_share_mids: Vec<String>, |
| 279 | pub gallery_mids: Vec<String>, |
| 280 | } |
| 281 | |
| 282 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 283 | pub struct SignaledLine { |
| 284 | pub browser_mids: Vec<String>, |
| 285 | pub role: LineRole, |
| 286 | } |
| 287 | |
| 288 | #[derive(Debug, Clone)] |
| 289 | pub struct SignaledOffer { |
| 290 | pub sdp: String, |
| 291 | pub lines: Vec<SignaledLine>, |
| 292 | } |
| 293 | |
| 294 | /// Random numbers for SSRCs; injected so tests stay deterministic. |
| 295 | pub trait NumberSource { |
| 296 | fn next_u32(&mut self) -> u32; |
| 297 | } |
| 298 | |
| 299 | impl<F: FnMut() -> u32> NumberSource for F { |
| 300 | fn next_u32(&mut self) -> u32 { |
| 301 | self() |
| 302 | } |
| 303 | } |
| 304 | |
| 305 | pub 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 | |
| 364 | fn 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 | |
| 381 | fn 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 is_opus = rtpmap.get(payload).is_some_and(|encoding| encoding.to_ascii_lowercase().starts_with("opus/")); |
| 449 | let cleaned = if video { |
| 450 | value.replace(";sps-pps-idr-in-keyframe=1", "") |
| 451 | } else if is_opus { |
| 452 | with_fmtp_parameters(value, &OPUS_RECEIVE_FULLBAND) |
| 453 | } else { |
| 454 | value.to_owned() |
| 455 | }; |
| 456 | fmtp.push((position, Attribute::new("fmtp", cleaned))); |
| 457 | } |
| 458 | "rtcp" => attributes.push(Attribute::new("rtcp", SIGNALED_PORT)), |
| 459 | "extmap" => { |
| 460 | if let Some(signaled) = signal_extmap(value) { |
| 461 | attributes.push(Attribute::new("extmap", signaled)); |
| 462 | } |
| 463 | } |
| 464 | _ => attributes.push(attribute.clone()), |
| 465 | } |
| 466 | } |
| 467 | fmtp.sort_by_key(|(position, _)| *position); |
| 468 | attributes.extend(fmtp.into_iter().map(|(_, attribute)| attribute)); |
| 469 | match shared_feedback { |
| 470 | Some(feedback) => attributes.extend(feedback.iter().map(|kind| Attribute::new("rtcp-fb", format!("* {kind}")))), |
| 471 | None => attributes.extend(source.attributes.iter().filter(|attribute| attribute.name == "rtcp-fb").cloned()), |
| 472 | } |
| 473 | if carries_candidate { |
| 474 | attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE)); |
| 475 | } |
| 476 | attributes.extend(ssrc_lines); |
| 477 | attributes.extend(source.attributes.iter().filter(|attribute| attribute.name == "ssrc-group").cloned()); |
| 478 | attributes.push(Attribute::new("label", role.label())); |
| 479 | if !source.has("rtcp-mux") { |
| 480 | attributes.push(Attribute::flag("rtcp-mux")); |
| 481 | } |
| 482 | media.attributes = attributes; |
| 483 | media |
| 484 | } |
| 485 | |
| 486 | fn rewrite_ssrc_msid(value: &str, mid: &str) -> String { |
| 487 | match value.split_once(" msid:") { |
| 488 | Some((ssrc, msid)) => { |
| 489 | let stream = msid.split(' ').next().unwrap_or("-"); |
| 490 | format!("{ssrc} msid:{stream} {mid}") |
| 491 | } |
| 492 | None => value.to_owned(), |
| 493 | } |
| 494 | } |
| 495 | |
| 496 | fn signal_rtpmap(value: &str) -> String { |
| 497 | match value.split_once(' ') { |
| 498 | Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/48000/2") => format!("{payload} RED/8000"), |
| 499 | _ => value.to_owned(), |
| 500 | } |
| 501 | } |
| 502 | |
| 503 | fn signal_extmap(value: &str) -> Option<String> { |
| 504 | let (identifier, uri) = value.split_once(' ')?; |
| 505 | if DROPPED_EXTENSIONS.contains(&uri) { |
| 506 | return None; |
| 507 | } |
| 508 | if BACKSLASHED_EXTENSIONS.contains(&uri) { |
| 509 | return Some(format!("{identifier} {}", uri.replace('/', "\\"))); |
| 510 | } |
| 511 | if uri == LAYERS_ALLOCATION { |
| 512 | return Some(format!("{identifier} {uri}{NOT_ADVERTISED_SUFFIX}")); |
| 513 | } |
| 514 | Some(value.to_owned()) |
| 515 | } |
| 516 | |
| 517 | fn feedback_by_payload(source: &Media) -> HashMap<String, Vec<String>> { |
| 518 | let mut map: HashMap<String, Vec<String>> = HashMap::new(); |
| 519 | for value in source.values("rtcp-fb") { |
| 520 | if let Some((payload, kind)) = value.split_once(' ') { |
| 521 | map.entry(payload.to_owned()).or_default().push(kind.to_owned()); |
| 522 | } |
| 523 | } |
| 524 | map |
| 525 | } |
| 526 | |
| 527 | fn shared_feedback( |
| 528 | by_payload: &HashMap<String, Vec<String>>, |
| 529 | source: &Media, |
| 530 | is_rtx: &impl Fn(&str) -> bool, |
| 531 | ) -> Option<Vec<String>> { |
| 532 | let mut codecs = source.formats.iter().filter(|payload| !is_rtx(payload)); |
| 533 | let first = by_payload.get(codecs.next()?)?; |
| 534 | codecs.all(|payload| by_payload.get(payload) == Some(first)).then(|| first.clone()) |
| 535 | } |
| 536 | |
| 537 | fn signal_data_line(source: &Media, numbers: &mut impl NumberSource) -> Media { |
| 538 | let ssrc = numbers.next_u32(); |
| 539 | let mut attributes = vec![ |
| 540 | Attribute::new("x-data-protocol", "sctp"), |
| 541 | Attribute::new("x-ssrc-range", format!("{ssrc}-{ssrc}")), |
| 542 | Attribute::new("rtpmap", "127 x-data/90000"), |
| 543 | Attribute::new("rtpmap", "126 rtx/90000"), |
| 544 | Attribute::new("fmtp", "126 apt=127"), |
| 545 | Attribute::flag("sendrecv"), |
| 546 | Attribute::flag("rtcp-mux"), |
| 547 | Attribute::new("label", LineRole::Data.label()), |
| 548 | ]; |
| 549 | attributes.extend(source.attributes.iter().cloned()); |
| 550 | Media { |
| 551 | kind: "x-data".to_owned(), |
| 552 | port: SIGNALED_PORT.to_owned(), |
| 553 | proto: SIGNALED_PROTO.to_owned(), |
| 554 | formats: vec!["127".to_owned(), "126".to_owned()], |
| 555 | connection: Some(PLACEHOLDER_CONNECTION.to_owned()), |
| 556 | bandwidths: Vec::new(), |
| 557 | attributes, |
| 558 | } |
| 559 | } |
| 560 | |
| 561 | pub fn to_browser_answer(teams_sdp: &str, offer: &SignaledOffer, browser_offer_sdp: &str) -> Result<String> { |
| 562 | let answer = parse(teams_sdp)?; |
| 563 | let browser_offer = parse(browser_offer_sdp)?; |
| 564 | if answer.media.len() != offer.lines.len() { |
| 565 | return Err(Error::Sdp(format!( |
| 566 | "answer has {} m-lines, offer signaled {}", |
| 567 | answer.media.len(), |
| 568 | offer.lines.len() |
| 569 | ))); |
| 570 | } |
| 571 | let offered: HashMap<&str, &Media> = browser_offer |
| 572 | .media |
| 573 | .iter() |
| 574 | .filter_map(|media| Some((media.mid()?, media))) |
| 575 | .collect(); |
| 576 | let mut media = Vec::new(); |
| 577 | for (index, (teams_line, signaled)) in answer.media.iter().zip(&offer.lines).enumerate() { |
| 578 | for (stream_index, browser_mid) in signaled.browser_mids.iter().enumerate() { |
| 579 | let offered_line = offered |
| 580 | .get(browser_mid.as_str()) |
| 581 | .ok_or_else(|| Error::Sdp(format!("offer has no mid {browser_mid}")))?; |
| 582 | let section = if signaled.role == LineRole::Data { |
| 583 | browser_data_line(teams_line, offered_line, &answer.session) |
| 584 | } else { |
| 585 | browser_rtp_line(teams_line, offered_line, signaled.role, stream_index as u32, index == 0, &answer.session) |
| 586 | }; |
| 587 | media.push(section); |
| 588 | } |
| 589 | } |
| 590 | let mut session = answer.session.clone(); |
| 591 | session.attributes.retain(|attribute| attribute.name.starts_with("x-")); |
| 592 | session.attributes.push(Attribute::flag("extmap-allow-mixed")); |
| 593 | session.attributes.push(Attribute::new("msid-semantic", " WMS *")); |
| 594 | session.attributes.push(Attribute::new("group", bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))))); |
| 595 | Ok(write(&SessionDescription { session, media })) |
| 596 | } |
| 597 | |
| 598 | fn bundle_group<'a>(lines: impl Iterator<Item = (&'a str, Option<&'a str>)>) -> String { |
| 599 | let mids: Vec<&str> = lines.filter(|(port, _)| *port != "0").filter_map(|(_, mid)| mid).collect(); |
| 600 | format!("BUNDLE {}", mids.join(" ")) |
| 601 | } |
| 602 | |
| 603 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 604 | pub struct StreamLine { |
| 605 | pub mid: String, |
| 606 | pub browser_mid: String, |
| 607 | pub role: LineRole, |
| 608 | pub source_stream_id: Option<u32>, |
| 609 | } |
| 610 | |
| 611 | pub fn stream_lines(teams_sdp: &str, lines: &[SignaledLine]) -> Result<Vec<StreamLine>> { |
| 612 | let teams = parse(teams_sdp)?; |
| 613 | if teams.media.len() != lines.len() { |
| 614 | return Err(Error::Sdp(format!("sdp has {} m-lines, {} were signaled", teams.media.len(), lines.len()))); |
| 615 | } |
| 616 | let mut streams = Vec::new(); |
| 617 | for (media, line) in teams.media.iter().zip(lines) { |
| 618 | let source_stream_id = media.value("x-source-streamid").and_then(|value| value.trim().parse().ok()); |
| 619 | let mid = media.mid().unwrap_or_default().to_owned(); |
| 620 | match line.browser_mids.as_slice() { |
| 621 | [browser_mid] => streams.push(StreamLine { |
| 622 | mid, |
| 623 | browser_mid: browser_mid.clone(), |
| 624 | role: line.role, |
| 625 | source_stream_id, |
| 626 | }), |
| 627 | folded => streams.extend(folded.iter().map(|browser_mid| StreamLine { |
| 628 | mid: mid.clone(), |
| 629 | browser_mid: browser_mid.clone(), |
| 630 | role: line.role, |
| 631 | source_stream_id: None, |
| 632 | })), |
| 633 | } |
| 634 | } |
| 635 | Ok(streams) |
| 636 | } |
| 637 | |
| 638 | fn transport_attributes(teams_line: &Media, session: &Session) -> Vec<Attribute> { |
| 639 | ["setup", "ice-ufrag", "ice-pwd", "fingerprint"] |
| 640 | .into_iter() |
| 641 | .filter_map(|name| { |
| 642 | teams_line |
| 643 | .attributes |
| 644 | .iter() |
| 645 | .chain(&session.attributes) |
| 646 | .find(|attribute| attribute.name == name) |
| 647 | .cloned() |
| 648 | }) |
| 649 | .collect() |
| 650 | } |
| 651 | |
| 652 | const OPUS_SEND_QUALITY: [(&str, &str); 2] = [("maxaveragebitrate", "40000"), ("maxplaybackrate", "48000")]; |
| 653 | |
| 654 | const OPUS_RECEIVE_FULLBAND: [(&str, &str); 2] = [("maxplaybackrate", "48000"), ("sprop-maxcapturerate", "48000")]; |
| 655 | |
| 656 | /// libwebrtc sizes its Opus encoder from these remote fmtp parameters; without them it picks its own bitrate. |
| 657 | fn with_opus_send_quality(fmtp: &str) -> String { |
| 658 | with_fmtp_parameters(fmtp, &OPUS_SEND_QUALITY) |
| 659 | } |
| 660 | |
| 661 | fn with_fmtp_parameters(fmtp: &str, parameters: &[(&str, &str)]) -> String { |
| 662 | let mut value = fmtp.to_owned(); |
| 663 | for &(name, setting) in parameters { |
| 664 | if value.split([' ', ';']).any(|parameter| parameter.split('=').next() == Some(name)) { |
| 665 | continue; |
| 666 | } |
| 667 | if !value.ends_with(' ') { |
| 668 | value.push(if value.contains(' ') { ';' } else { ' ' }); |
| 669 | } |
| 670 | value.push_str(&format!("{name}={setting}")); |
| 671 | } |
| 672 | value |
| 673 | } |
| 674 | |
| 675 | fn browser_rtp_line( |
| 676 | teams_line: &Media, |
| 677 | offered: &Media, |
| 678 | role: LineRole, |
| 679 | stream_index: u32, |
| 680 | carries_candidates: bool, |
| 681 | session: &Session, |
| 682 | ) -> Media { |
| 683 | let offered_rtpmap = offered.rtpmap(); |
| 684 | let offered_codecs: HashMap<String, String> = offered_rtpmap |
| 685 | .values() |
| 686 | .filter_map(|encoding| { |
| 687 | let (name, rest) = encoding.split_once('/')?; |
| 688 | Some((name.to_ascii_lowercase(), rest.to_owned())) |
| 689 | }) |
| 690 | .collect(); |
| 691 | let answer_rtpmap = teams_line.rtpmap(); |
| 692 | let kept: Vec<String> = teams_line |
| 693 | .formats |
| 694 | .iter() |
| 695 | .filter(|payload| { |
| 696 | answer_rtpmap |
| 697 | .get(*payload) |
| 698 | .and_then(|encoding| encoding.split('/').next()) |
| 699 | .is_some_and(|name| offered_codecs.contains_key(&name.to_ascii_lowercase())) |
| 700 | }) |
| 701 | .cloned() |
| 702 | .collect(); |
| 703 | let kept_set: HashSet<&str> = kept.iter().map(String::as_str).collect(); |
| 704 | let payload_of = |value: &str| value.split(' ').next().unwrap_or_default().to_owned(); |
| 705 | let codec_payload = |codec: &str| { |
| 706 | kept.iter().find(|payload| { |
| 707 | answer_rtpmap |
| 708 | .get(*payload) |
| 709 | .is_some_and(|encoding| encoding.to_ascii_lowercase().starts_with(&format!("{codec}/"))) |
| 710 | }) |
| 711 | }; |
| 712 | |
| 713 | let mut attributes = Vec::new(); |
| 714 | attributes.extend(teams_line.values("x-source-streamid").map(|value| Attribute::new("x-source-streamid", value))); |
| 715 | for value in teams_line.values("rtpmap") { |
| 716 | let payload = payload_of(value); |
| 717 | if !kept_set.contains(payload.as_str()) { |
| 718 | continue; |
| 719 | } |
| 720 | let encoding = answer_rtpmap.get(&payload).cloned().unwrap_or_default(); |
| 721 | let name = encoding.split('/').next().unwrap_or_default(); |
| 722 | let offered_rest = offered_codecs.get(&name.to_ascii_lowercase()); |
| 723 | let rewritten = match offered_rest { |
| 724 | Some(rest) if name.eq_ignore_ascii_case("red") => format!("{payload} {name}/{rest}"), |
| 725 | _ => value.to_owned(), |
| 726 | }; |
| 727 | attributes.push(Attribute::new("rtpmap", rewritten)); |
| 728 | } |
| 729 | let mut fmtp_payloads = HashSet::new(); |
| 730 | for value in teams_line.values("fmtp") { |
| 731 | let payload = payload_of(value); |
| 732 | if !kept_set.contains(payload.as_str()) { |
| 733 | continue; |
| 734 | } |
| 735 | let cleaned = value |
| 736 | .split(';') |
| 737 | .filter(|parameter| !parameter.starts_with("rtx-time=")) |
| 738 | .collect::<Vec<_>>() |
| 739 | .join(";"); |
| 740 | let is_opus = codec_payload("opus").is_some_and(|opus| *opus == payload); |
| 741 | fmtp_payloads.insert(payload); |
| 742 | attributes.push(Attribute::new("fmtp", if is_opus { with_opus_send_quality(&cleaned) } else { cleaned })); |
| 743 | } |
| 744 | if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) { |
| 745 | attributes.push(Attribute::new("fmtp", with_opus_send_quality(&format!("{opus} usedtx=1")))); |
| 746 | } |
| 747 | if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus")) |
| 748 | && !fmtp_payloads.contains(red) |
| 749 | { |
| 750 | attributes.push(Attribute::new("fmtp", format!("{red} {opus}/{opus}"))); |
| 751 | } |
| 752 | attributes.extend(teams_line.values("rtcp").map(|value| Attribute::new("rtcp", value))); |
| 753 | let answer_feedback: Vec<&str> = teams_line |
| 754 | .values("rtcp-fb") |
| 755 | .filter(|value| !value.contains("x-message")) |
| 756 | .collect(); |
| 757 | if answer_feedback.is_empty() && !teams_line.has("rtcp-fb") { |
| 758 | attributes.extend( |
| 759 | offered |
| 760 | .values("rtcp-fb") |
| 761 | .filter(|value| kept_set.contains(payload_of(value).as_str())) |
| 762 | .map(|value| Attribute::new("rtcp-fb", value)), |
| 763 | ); |
| 764 | } else { |
| 765 | attributes.extend(answer_feedback.into_iter().map(|value| Attribute::new("rtcp-fb", value))); |
| 766 | } |
| 767 | for value in teams_line.values("extmap") { |
| 768 | let restored = value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, ""); |
| 769 | attributes.push(Attribute::new("extmap", restored)); |
| 770 | } |
| 771 | attributes.extend(transport_attributes(teams_line, session)); |
| 772 | attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default())); |
| 773 | attributes.extend(teams_line.values("ptime").map(|value| Attribute::new("ptime", value))); |
| 774 | if let Some(direction) = teams_line.direction() { |
| 775 | attributes.push(Attribute::flag(direction)); |
| 776 | } |
| 777 | if carries_candidates { |
| 778 | attributes.extend(teams_line.values("candidate").chain(teams_line.values("x-candidate-ipv6")).map(|value| Attribute::new("candidate", browser_candidate(value)))); |
| 779 | } |
| 780 | attributes.extend(stream_ssrc_attributes(teams_line, stream_index, role)); |
| 781 | attributes.push(Attribute::flag("rtcp-mux")); |
| 782 | if teams_line.has("rtcp-rsize") { |
| 783 | attributes.push(Attribute::flag("rtcp-rsize")); |
| 784 | } |
| 785 | if let Some(simulcast) = offered.value("simulcast").and_then(|value| value.strip_prefix("send ")) { |
| 786 | let rids: Vec<String> = simulcast.split(';').map(|rid| rid.trim_start_matches('~').to_owned()).collect(); |
| 787 | attributes.extend(rids.iter().map(|rid| Attribute::new("rid", format!("{rid} recv")))); |
| 788 | attributes.push(Attribute::new("simulcast", format!("recv {}", rids.join(";")))); |
| 789 | } |
| 790 | Media { |
| 791 | kind: offered.kind.clone(), |
| 792 | port: teams_line.port.clone(), |
| 793 | proto: offered.proto.clone(), |
| 794 | formats: kept, |
| 795 | connection: teams_line.connection.clone().or_else(|| session.connection.clone()), |
| 796 | bandwidths: teams_line.bandwidths.clone(), |
| 797 | attributes, |
| 798 | } |
| 799 | } |
| 800 | |
| 801 | fn stream_ssrc_attributes(teams_line: &Media, stream_index: u32, role: LineRole) -> Vec<Attribute> { |
| 802 | let (Some(primary), retransmission) = stream_ssrcs(teams_line, stream_index) else { |
| 803 | return Vec::new(); |
| 804 | }; |
| 805 | let stream = format!("{}-{primary}", role.stream_prefix()); |
| 806 | let mut attributes = Vec::new(); |
| 807 | for ssrc in [Some(primary), retransmission].into_iter().flatten() { |
| 808 | attributes.push(Attribute::new("ssrc", format!("{ssrc} cname:{}", stream_cname(primary)))); |
| 809 | attributes.push(Attribute::new("ssrc", format!("{ssrc} msid:{stream} {stream}"))); |
| 810 | } |
| 811 | if let Some(retransmission) = retransmission { |
| 812 | attributes.push(Attribute::new("ssrc-group", format!("FID {primary} {retransmission}"))); |
| 813 | } |
| 814 | attributes |
| 815 | } |
| 816 | |
| 817 | fn stream_cname(primary: u32) -> String { |
| 818 | format!("teams{primary}") |
| 819 | } |
| 820 | |
| 821 | fn stream_ssrcs(teams_line: &Media, stream_index: u32) -> (Option<u32>, Option<u32>) { |
| 822 | let offset = stream_index * SSRC_RANGE_SIZE; |
| 823 | if let Some(group) = teams_line.value("ssrc-group").and_then(|value| value.strip_prefix("FID ")) { |
| 824 | let mut ssrcs = group.split(' ').filter_map(|value| value.parse::<u32>().ok()); |
| 825 | let primary = ssrcs.next().map(|ssrc| ssrc + offset); |
| 826 | return (primary, ssrcs.next().map(|ssrc| ssrc + offset)); |
| 827 | } |
| 828 | let first = teams_line |
| 829 | .value("x-ssrc-range") |
| 830 | .and_then(|range| range.split('-').next()?.parse::<u32>().ok()) |
| 831 | .map(|ssrc| ssrc + offset); |
| 832 | (first, None) |
| 833 | } |
| 834 | |
| 835 | fn browser_candidate(value: &str) -> String { |
| 836 | let mut parts: Vec<&str> = value.split(' ').collect(); |
| 837 | if let Some(position) = parts.iter().position(|part| *part == "MTURNID") { |
| 838 | parts.truncate(position); |
| 839 | } |
| 840 | let tcp_type = match parts.get(2).map(|transport| transport.to_ascii_lowercase()).as_deref() { |
| 841 | Some("tcp-pass") => Some("passive"), |
| 842 | Some("tcp-act") => Some("active"), |
| 843 | Some("tcp-so") => Some("so"), |
| 844 | _ => None, |
| 845 | }; |
| 846 | if tcp_type.is_some() { |
| 847 | parts[2] = "tcp"; |
| 848 | } |
| 849 | let mut candidate = parts.join(" "); |
| 850 | if let Some(tcp_type) = tcp_type { |
| 851 | candidate.push_str(" tcptype "); |
| 852 | candidate.push_str(tcp_type); |
| 853 | } |
| 854 | candidate |
| 855 | } |
| 856 | |
| 857 | fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) -> Media { |
| 858 | let mut attributes = Vec::new(); |
| 859 | attributes.extend(teams_line.values("x-source-streamid").map(|value| Attribute::new("x-source-streamid", value))); |
| 860 | attributes.extend(transport_attributes(teams_line, session)); |
| 861 | attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default())); |
| 862 | attributes.extend(offered.values("sctp-port").map(|value| Attribute::new("sctp-port", value))); |
| 863 | Media { |
| 864 | kind: offered.kind.clone(), |
| 865 | port: teams_line.port.clone(), |
| 866 | proto: offered.proto.clone(), |
| 867 | formats: offered.formats.clone(), |
| 868 | connection: teams_line.connection.clone().or_else(|| session.connection.clone()), |
| 869 | bandwidths: Vec::new(), |
| 870 | attributes, |
| 871 | } |
| 872 | } |
| 873 | |
| 874 | const BROWSER_PORT: &str = "9"; |
| 875 | const BROWSER_PROTO: &str = "UDP/TLS/RTP/SAVPF"; |
| 876 | const BROWSER_CONNECTION: &str = "IN IP4 0.0.0.0"; |
| 877 | const BROWSER_RTCP: &str = "9 IN IP4 0.0.0.0"; |
| 878 | const BROWSER_DATA_PROTO: &str = "UDP/DTLS/SCTP"; |
| 879 | const BROWSER_DATA_FORMAT: &str = "webrtc-datachannel"; |
| 880 | const SCTP_PORT: &str = "5000"; |
| 881 | const SCTP_MAX_MESSAGE_SIZE: &str = "262144"; |
| 882 | const PLACEHOLDER_CANDIDATE_TAIL: &str = " 1234 typ host"; |
| 883 | const TEAMS_ONLY_ATTRIBUTES: [&str; 6] = [ |
| 884 | "x-multi-stream", |
| 885 | "x-signaling-fb", |
| 886 | "x-ssrc-range", |
| 887 | "x-source-streamid", |
| 888 | "x-data-protocol", |
| 889 | "label", |
| 890 | ]; |
| 891 | const TRANSPORT_ATTRIBUTES: [&str; 5] = ["setup", "ice-ufrag", "ice-pwd", "fingerprint", "ice-options"]; |
| 892 | |
| 893 | /// A Teams offer translated for libwebrtc; `lines` remembers which browser mids each signaled line stands for. |
| 894 | #[derive(Debug, Clone)] |
| 895 | pub struct RemoteOffer { |
| 896 | pub browser_sdp: String, |
| 897 | pub lines: Vec<SignaledLine>, |
| 898 | } |
| 899 | |
| 900 | impl RemoteOffer { |
| 901 | pub fn plan(&self) -> OfferPlan { |
| 902 | let mut plan = OfferPlan::default(); |
| 903 | for line in &self.lines { |
| 904 | match line.role { |
| 905 | LineRole::ScreenShare => plan.screen_share_mids.extend(line.browser_mids.iter().cloned()), |
| 906 | _ if line.browser_mids.len() > 1 => plan.gallery_mids.extend(line.browser_mids.iter().cloned()), |
| 907 | _ => {} |
| 908 | } |
| 909 | } |
| 910 | plan |
| 911 | } |
| 912 | } |
| 913 | |
| 914 | fn role_of_teams_line(line: &Media) -> LineRole { |
| 915 | match line.value("label") { |
| 916 | Some("main-audio") => LineRole::MainAudio, |
| 917 | Some("main-video") => LineRole::MainVideo, |
| 918 | Some("applicationsharing-video") => LineRole::ScreenShare, |
| 919 | Some("data") => LineRole::Data, |
| 920 | _ => match line.kind.as_str() { |
| 921 | "audio" => LineRole::MainAudio, |
| 922 | "x-data" | "application" => LineRole::Data, |
| 923 | _ => LineRole::MainVideo, |
| 924 | }, |
| 925 | } |
| 926 | } |
| 927 | |
| 928 | /// Folded gallery lines get the mids just below the carrier line's own mid, unless another line already uses one of them. |
| 929 | fn folded_mids(carrier: &str, count: usize, taken: &[String]) -> Vec<String> { |
| 930 | let below = match carrier.parse::<usize>() { |
| 931 | Ok(last) if last + 1 >= count => Some((last + 1 - count..=last).map(|mid| mid.to_string()).collect::<Vec<_>>()), |
| 932 | _ => None, |
| 933 | }; |
| 934 | match below.filter(|mids| mids.iter().all(|mid| mid == carrier || !taken.contains(mid))) { |
| 935 | Some(mids) => mids, |
| 936 | None => (0..count) |
| 937 | .map(|index| if index + 1 == count { carrier.to_owned() } else { format!("{carrier}-{index}") }) |
| 938 | .collect(), |
| 939 | } |
| 940 | } |
| 941 | |
| 942 | pub fn from_teams_offer(teams_sdp: &str) -> Result<RemoteOffer> { |
| 943 | let teams = parse(teams_sdp)?; |
| 944 | let mut media = Vec::new(); |
| 945 | let mut lines = Vec::new(); |
| 946 | let mut taken: Vec<String> = teams.media.iter().filter_map(|line| line.mid().map(str::to_owned)).collect(); |
| 947 | for source in &teams.media { |
| 948 | let role = role_of_teams_line(source); |
| 949 | let carrier = source.mid().unwrap_or_default().to_owned(); |
| 950 | let folded = source |
| 951 | .value("x-multi-stream") |
| 952 | .and_then(|value| value.split(' ').next()?.parse::<usize>().ok()) |
| 953 | .filter(|count| *count > 1); |
| 954 | let mids = match folded { |
| 955 | Some(count) => folded_mids(&carrier, count, &taken), |
| 956 | None => vec![carrier.clone()], |
| 957 | }; |
| 958 | taken.extend(mids.iter().cloned()); |
| 959 | for (index, mid) in mids.iter().enumerate() { |
| 960 | let converted = if role == LineRole::Data { |
| 961 | browser_data_from_teams(source, mid, &teams.session) |
| 962 | } else { |
| 963 | browser_rtp_from_teams(source, mid, role, folded.is_some(), index == 0 && lines.is_empty(), &teams.session) |
| 964 | }; |
| 965 | media.push(converted); |
| 966 | } |
| 967 | lines.push(SignaledLine { |
| 968 | browser_mids: mids, |
| 969 | role, |
| 970 | }); |
| 971 | } |
| 972 | let mut session = teams.session.clone(); |
| 973 | session.bandwidths.clear(); |
| 974 | session.connection = None; |
| 975 | session.attributes.retain(|attribute| matches!(attribute.name.as_str(), "extmap-allow-mixed" | "msid-semantic")); |
| 976 | session.attributes.push(Attribute::new("group", bundle_group(media.iter().map(|line| (line.port.as_str(), line.mid()))))); |
| 977 | Ok(RemoteOffer { |
| 978 | browser_sdp: write(&SessionDescription { session, media }), |
| 979 | lines, |
| 980 | }) |
| 981 | } |
| 982 | |
| 983 | fn transport_from_teams(source: &Media, session: &Session) -> Vec<Attribute> { |
| 984 | TRANSPORT_ATTRIBUTES |
| 985 | .iter() |
| 986 | .filter_map(|name| { |
| 987 | source |
| 988 | .attributes |
| 989 | .iter() |
| 990 | .chain(&session.attributes) |
| 991 | .find(|attribute| attribute.name == *name) |
| 992 | .cloned() |
| 993 | }) |
| 994 | .collect() |
| 995 | } |
| 996 | |
| 997 | fn browser_data_from_teams(source: &Media, mid: &str, session: &Session) -> Media { |
| 998 | let mut attributes = transport_from_teams(source, session); |
| 999 | attributes.push(Attribute::new("mid", mid)); |
| 1000 | attributes.push(Attribute::new("sctp-port", SCTP_PORT)); |
| 1001 | attributes.push(Attribute::new("max-message-size", SCTP_MAX_MESSAGE_SIZE)); |
| 1002 | Media { |
| 1003 | kind: "application".to_owned(), |
| 1004 | port: BROWSER_PORT.to_owned(), |
| 1005 | proto: BROWSER_DATA_PROTO.to_owned(), |
| 1006 | formats: vec![BROWSER_DATA_FORMAT.to_owned()], |
| 1007 | connection: Some(BROWSER_CONNECTION.to_owned()), |
| 1008 | bandwidths: Vec::new(), |
| 1009 | attributes, |
| 1010 | } |
| 1011 | } |
| 1012 | |
| 1013 | fn browser_rtp_from_teams(source: &Media, mid: &str, role: LineRole, folded: bool, carries_candidate: bool, session: &Session) -> Media { |
| 1014 | let rtpmap = source.rtpmap(); |
| 1015 | let is_rtx = |payload: &str| rtpmap.get(payload).is_some_and(|encoding| encoding.starts_with("rtx/")); |
| 1016 | let mut attributes = Vec::new(); |
| 1017 | let mut expanded_feedback: Vec<Attribute> = Vec::new(); |
| 1018 | let mut signals_ssrc = false; |
| 1019 | let mut ssrc_groups = Vec::new(); |
| 1020 | for attribute in &source.attributes { |
| 1021 | let value = attribute.value.as_deref().unwrap_or_default(); |
| 1022 | match attribute.name.as_str() { |
| 1023 | name if TEAMS_ONLY_ATTRIBUTES.contains(&name) => {} |
| 1024 | "x-candidate-ipv6" => { |
| 1025 | if carries_candidate { |
| 1026 | attributes.push(Attribute::new("candidate", browser_candidate(value))); |
| 1027 | } |
| 1028 | } |
| 1029 | name if name.starts_with("x-") => {} |
| 1030 | "mid" | "rtcp-mux" => {} |
| 1031 | name if TRANSPORT_ATTRIBUTES.contains(&name) => {} |
| 1032 | "candidate" => { |
| 1033 | if carries_candidate && !value.contains(PLACEHOLDER_CANDIDATE_TAIL) { |
| 1034 | attributes.push(Attribute::new("candidate", browser_candidate(value))); |
| 1035 | } |
| 1036 | } |
| 1037 | "ssrc" => { |
| 1038 | let placeholder = value.contains("fake_attribute") || value.starts_with("1 "); |
| 1039 | if !folded && !placeholder { |
| 1040 | signals_ssrc = true; |
| 1041 | attributes.push(attribute.clone()); |
| 1042 | } |
| 1043 | } |
| 1044 | "ssrc-group" => { |
| 1045 | if !folded { |
| 1046 | ssrc_groups.push(attribute.clone()); |
| 1047 | } |
| 1048 | } |
| 1049 | "rtcp" => attributes.push(Attribute::new("rtcp", BROWSER_RTCP)), |
| 1050 | "rtpmap" => attributes.push(Attribute::new("rtpmap", browser_rtpmap(value))), |
| 1051 | "extmap" => attributes.push(Attribute::new("extmap", browser_extmap(value))), |
| 1052 | "rtcp-fb" => match value.strip_prefix("* ") { |
| 1053 | Some(kind) => expanded_feedback.extend( |
| 1054 | source |
| 1055 | .formats |
| 1056 | .iter() |
| 1057 | .filter(|payload| !is_rtx(payload)) |
| 1058 | .map(|payload| Attribute::new("rtcp-fb", format!("{payload} {kind}"))), |
| 1059 | ), |
| 1060 | None => attributes.push(attribute.clone()), |
| 1061 | }, |
| 1062 | _ => attributes.push(attribute.clone()), |
| 1063 | } |
| 1064 | } |
| 1065 | attributes.extend(expanded_feedback); |
| 1066 | attributes.extend(transport_from_teams(source, session)); |
| 1067 | attributes.push(Attribute::new("mid", mid)); |
| 1068 | if signals_ssrc { |
| 1069 | attributes.extend(ssrc_groups); |
| 1070 | } else if !folded { |
| 1071 | attributes.extend(stream_ssrc_attributes(source, 0, role)); |
| 1072 | } |
| 1073 | attributes.push(Attribute::flag("rtcp-mux")); |
| 1074 | Media { |
| 1075 | kind: source.kind.clone(), |
| 1076 | port: BROWSER_PORT.to_owned(), |
| 1077 | proto: BROWSER_PROTO.to_owned(), |
| 1078 | formats: source.formats.clone(), |
| 1079 | connection: Some(BROWSER_CONNECTION.to_owned()), |
| 1080 | bandwidths: Vec::new(), |
| 1081 | attributes, |
| 1082 | } |
| 1083 | } |
| 1084 | |
| 1085 | fn browser_rtpmap(value: &str) -> String { |
| 1086 | match value.split_once(' ') { |
| 1087 | Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/8000") => format!("{payload} red/48000/2"), |
| 1088 | _ => value.to_owned(), |
| 1089 | } |
| 1090 | } |
| 1091 | |
| 1092 | fn browser_extmap(value: &str) -> String { |
| 1093 | value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, "") |
| 1094 | } |
| 1095 | |
| 1096 | /// libwebrtc answers every offered line in the offer's order and with its mids, so the offer's plan applies unchanged. |
| 1097 | pub fn to_teams_answer(browser_answer_sdp: &str, remote: &RemoteOffer, numbers: &mut impl NumberSource) -> Result<SignaledOffer> { |
| 1098 | to_teams_offer(browser_answer_sdp, &remote.plan(), numbers) |
| 1099 | } |
| 1100 | |
| 1101 | #[cfg(test)] |
| 1102 | mod tests { |
| 1103 | use super::*; |
| 1104 | |
| 1105 | fn counter() -> impl FnMut() -> u32 { |
| 1106 | let mut next = 1000u32; |
| 1107 | move || { |
| 1108 | next += 1; |
| 1109 | next |
| 1110 | } |
| 1111 | } |
| 1112 | |
| 1113 | #[test] |
| 1114 | fn rejected_lines_stay_out_of_the_bundle() { |
| 1115 | let lines = [("9", Some("0")), ("0", Some("1")), ("9", Some("2"))]; |
| 1116 | assert_eq!(bundle_group(lines.into_iter()), "BUNDLE 0 2"); |
| 1117 | } |
| 1118 | |
| 1119 | 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"; |
| 1120 | |
| 1121 | #[test] |
| 1122 | fn audio_only_offer_gets_the_teams_shape() { |
| 1123 | let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap(); |
| 1124 | let text = offer.sdp.replace("\r\n", "\n"); |
| 1125 | assert!(text.contains("\nb=CT:4000\n")); |
| 1126 | assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\n")); |
| 1127 | assert!(text.contains("a=x-signaling-fb:* x-message app recv:dsh\n")); |
| 1128 | assert!(text.contains("a=x-ssrc-range:42-42\n")); |
| 1129 | assert!(text.contains("a=rtpmap:63 RED/8000\n")); |
| 1130 | assert!(text.contains("a=fmtp:111 minptime=10;useinbandfec=1;maxplaybackrate=48000;sprop-maxcapturerate=48000\n")); |
| 1131 | assert!(text.contains("a=rtcp:1234\n")); |
| 1132 | assert!(text.contains("a=extmap:2 http:\\\\www.webrtc.org\\experiments\\rtp-hdrext\\abs-send-time\n")); |
| 1133 | assert!(text.contains("a=ssrc:42 msid:stream 0\n")); |
| 1134 | assert!(text.contains("a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\n")); |
| 1135 | assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\nc=IN IP4 10.10.10.10\n")); |
| 1136 | assert!(text.ends_with("a=label:main-audio\n")); |
| 1137 | assert_eq!(offer.lines, vec![SignaledLine { browser_mids: vec!["0".into()], role: LineRole::MainAudio }]); |
| 1138 | } |
| 1139 | |
| 1140 | #[test] |
| 1141 | fn a_renegotiation_signals_only_the_placeholder_candidate() { |
| 1142 | let gathered = AUDIO_ONLY_OFFER.replace( |
| 1143 | "a=mid:0\r\n", |
| 1144 | "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", |
| 1145 | ); |
| 1146 | let text = to_teams_offer(&gathered, &OfferPlan::default(), &mut counter()).unwrap().sdp; |
| 1147 | let candidates: Vec<&str> = text.lines().filter(|line| line.starts_with("a=candidate:") || line.starts_with("a=end-of-candidates")).collect(); |
| 1148 | assert_eq!(candidates, vec!["a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host"]); |
| 1149 | } |
| 1150 | |
| 1151 | #[test] |
| 1152 | fn answer_candidates_lose_teams_extensions() { |
| 1153 | assert_eq!( |
| 1154 | browser_candidate("1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 158"), |
| 1155 | "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480" |
| 1156 | ); |
| 1157 | assert_eq!( |
| 1158 | browser_candidate("3 1 tcp-pass 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478"), |
| 1159 | "3 1 tcp 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478 tcptype passive" |
| 1160 | ); |
| 1161 | assert_eq!( |
| 1162 | browser_candidate("10 1 TCP-ACT 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009"), |
| 1163 | "10 1 tcp 1684794366 192.0.2.1 59611 typ srflx raddr 192.0.2.1 rport 50009 tcptype active" |
| 1164 | ); |
| 1165 | } |
| 1166 | |
| 1167 | #[test] |
| 1168 | fn audio_answer_maps_back_to_the_browser_mid_and_codecs() { |
| 1169 | let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap(); |
| 1170 | 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"; |
| 1171 | let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER).unwrap().replace("\r\n", "\n"); |
| 1172 | assert!(browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"), "{browser}"); |
| 1173 | assert!(browser.contains("a=rtpmap:97 RED/48000/2\n")); |
| 1174 | assert!(browser.contains("a=fmtp:111 usedtx=1;maxaveragebitrate=40000;maxplaybackrate=48000\n")); |
| 1175 | assert!(browser.contains("a=fmtp:97 111/111\n")); |
| 1176 | assert!(browser.contains("a=rtcp-fb:111 transport-cc\n")); |
| 1177 | assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n")); |
| 1178 | assert!(browser.contains("a=group:BUNDLE 0\n")); |
| 1179 | assert!(!browser.contains("SATINFB") && !browser.contains("MTURNID") && !browser.contains("label")); |
| 1180 | } |
| 1181 | #[test] |
| 1182 | fn an_audio_offer_from_teams_gets_the_browser_shape_back() { |
| 1183 | let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap(); |
| 1184 | let remote = from_teams_offer(&offer.sdp).unwrap(); |
| 1185 | let text = remote.browser_sdp.replace("\r\n", "\n"); |
| 1186 | assert!(text.contains("m=audio 9 UDP/TLS/RTP/SAVPF 111 63 9 0 8 13 110 126\n"), "{text}"); |
| 1187 | assert!(text.contains("c=IN IP4 0.0.0.0\n")); |
| 1188 | assert!(text.contains("a=rtcp:9 IN IP4 0.0.0.0\n")); |
| 1189 | assert!(text.contains("a=rtpmap:63 red/48000/2\n")); |
| 1190 | assert!(text.contains("a=extmap:2 http://www.webrtc.org/experiments/rtp-hdrext/abs-send-time\n")); |
| 1191 | assert!(text.contains("a=ice-ufrag:u\n") && text.contains("a=fingerprint:sha-256 AA\n") && text.contains("a=setup:actpass\n")); |
| 1192 | assert!(text.contains("a=mid:0\n") && text.contains("a=group:BUNDLE 0\n")); |
| 1193 | assert!(!text.contains("10.10.10.10") && !text.contains("x-ssrc-range") && !text.contains("label") && !text.contains("1234")); |
| 1194 | assert_eq!(remote.lines, offer.lines); |
| 1195 | } |
| 1196 | |
| 1197 | #[test] |
| 1198 | fn shared_video_feedback_is_spelled_out_per_codec_again() { |
| 1199 | 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"; |
| 1200 | let remote = from_teams_offer(teams).unwrap(); |
| 1201 | let text = remote.browser_sdp.replace("\r\n", "\n"); |
| 1202 | assert!(text.contains("a=rtcp-fb:102 nack\n") && text.contains("a=rtcp-fb:102 nack pli\n")); |
| 1203 | assert!(!text.contains("a=rtcp-fb:103") && !text.contains("a=rtcp-fb:*")); |
| 1204 | } |
| 1205 | |
| 1206 | #[test] |
| 1207 | fn a_peer_offer_with_only_ssrc_ranges_signals_the_streams_it_sends() { |
| 1208 | 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"; |
| 1209 | let remote = from_teams_offer(teams).unwrap(); |
| 1210 | let parsed = parse(&remote.browser_sdp).unwrap(); |
| 1211 | let audio: Vec<&str> = parsed.media[0].values("ssrc").collect(); |
| 1212 | assert!(audio.iter().any(|value| value.starts_with("40475 cname:")), "{audio:?}"); |
| 1213 | assert_eq!(parsed.media[1].values("ssrc-group").collect::<Vec<_>>(), vec!["FID 40476 40526"]); |
| 1214 | let video: Vec<&str> = parsed.media[1].values("ssrc").collect(); |
| 1215 | assert!(video.iter().any(|value| value.starts_with("40476 cname:")) && video.iter().any(|value| value.starts_with("40526 cname:")), "{video:?}"); |
| 1216 | } |
| 1217 | |
| 1218 | #[test] |
| 1219 | fn a_rejected_video_line_stays_rejected_and_out_of_the_bundle() { |
| 1220 | 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"; |
| 1221 | let remote = from_teams_offer(audio_and_video).unwrap(); |
| 1222 | 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"; |
| 1223 | let signaled = to_teams_answer(answer, &remote, &mut counter()).unwrap(); |
| 1224 | let text = signaled.sdp.replace("\r\n", "\n"); |
| 1225 | assert!(text.contains("m=video 0 RTP/SAVP 102\n"), "{text}"); |
| 1226 | assert!(text.contains("a=group:BUNDLE 0\n")); |
| 1227 | let parsed = parse(&signaled.sdp).unwrap(); |
| 1228 | assert_eq!(parsed.media.len(), 2); |
| 1229 | assert_eq!(parsed.media[1].value("label"), Some("main-video")); |
| 1230 | assert_eq!(parsed.media[1].direction(), Some("inactive")); |
| 1231 | } |
| 1232 | |
| 1233 | 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"; |
| 1234 | |
| 1235 | fn browser_answer(camera_direction: &str, share_port: &str, share_direction: &str) -> String { |
| 1236 | 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") |
| 1237 | } |
| 1238 | |
| 1239 | #[test] |
| 1240 | fn a_folded_line_never_reuses_the_mid_of_another_line() { |
| 1241 | 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"; |
| 1242 | let teams = format!("{}{folded}", ONE_TO_ONE_VIDEO_OFFER.replace("BUNDLE 0 1 2", "BUNDLE 0 1 2 3")); |
| 1243 | let remote = from_teams_offer(&teams).unwrap(); |
| 1244 | let mids: Vec<String> = parse(&remote.browser_sdp).unwrap().media.iter().filter_map(|line| line.mid().map(str::to_owned)).collect(); |
| 1245 | let mut unique = mids.clone(); |
| 1246 | unique.sort(); |
| 1247 | unique.dedup(); |
| 1248 | assert_eq!(unique.len(), mids.len(), "{mids:?}"); |
| 1249 | assert_eq!(remote.lines.last().unwrap().browser_mids, vec!["3-0".to_owned(), "3".to_owned()]); |
| 1250 | } |
| 1251 | |
| 1252 | #[test] |
| 1253 | fn a_one_to_one_offer_keeps_a_camera_line_and_a_sharing_line() { |
| 1254 | let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap(); |
| 1255 | let roles: Vec<LineRole> = remote.lines.iter().map(|line| line.role).collect(); |
| 1256 | assert_eq!(roles, vec![LineRole::MainAudio, LineRole::MainVideo, LineRole::ScreenShare]); |
| 1257 | assert_eq!(remote.plan().screen_share_mids, vec!["2".to_owned()]); |
| 1258 | assert!(remote.plan().gallery_mids.is_empty()); |
| 1259 | assert_eq!(parse(&remote.browser_sdp).unwrap().media.iter().filter(|media| media.kind == "video").count(), 2); |
| 1260 | } |
| 1261 | |
| 1262 | #[test] |
| 1263 | fn accepting_with_audio_answers_the_video_line_receive_only_and_with_video_sending() { |
| 1264 | let remote = from_teams_offer(ONE_TO_ONE_VIDEO_OFFER).unwrap(); |
| 1265 | for (camera_direction, expected) in [("recvonly", "recvonly"), ("sendrecv", "sendrecv")] { |
| 1266 | let answer = to_teams_answer(&browser_answer(camera_direction, "0", "inactive"), &remote, &mut counter()).unwrap(); |
| 1267 | let parsed = parse(&answer.sdp).unwrap(); |
| 1268 | assert_eq!(parsed.media.len(), 3); |
| 1269 | assert_eq!(parsed.media[1].port, "1234"); |
| 1270 | assert_eq!(parsed.media[1].direction(), Some(expected)); |
| 1271 | assert_eq!(parsed.media[1].value("label"), Some("main-video")); |
| 1272 | assert_eq!(parsed.media[2].port, "0"); |
| 1273 | assert_eq!(parsed.media[2].value("label"), Some("applicationsharing-video")); |
| 1274 | } |
| 1275 | } |
| 1276 | |
| 1277 | #[test] |
| 1278 | fn folded_gallery_lines_expand_below_their_carrier_mid_unless_those_are_taken() { |
| 1279 | let taken = ["0".to_owned(), "1".to_owned(), "17".to_owned()]; |
| 1280 | assert_eq!(folded_mids("17", 8, &taken), (10..=17).map(|mid| mid.to_string()).collect::<Vec<_>>()); |
| 1281 | assert_eq!(folded_mids("x", 2, &taken), vec!["x-0".to_owned(), "x".to_owned()]); |
| 1282 | assert_eq!(folded_mids("2", 2, &taken), vec!["2-0".to_owned(), "2".to_owned()]); |
| 1283 | } |
| 1284 | |
| 1285 | #[test] |
| 1286 | fn opus_fmtp_gets_the_send_quality_without_overriding_teams() { |
| 1287 | assert_eq!( |
| 1288 | with_opus_send_quality("111 minptime=10;useinbandfec=1"), |
| 1289 | "111 minptime=10;useinbandfec=1;maxaveragebitrate=40000;maxplaybackrate=48000" |
| 1290 | ); |
| 1291 | assert_eq!(with_opus_send_quality("111 maxplaybackrate=16000"), "111 maxplaybackrate=16000;maxaveragebitrate=40000"); |
| 1292 | assert_eq!(with_opus_send_quality("111"), "111 maxaveragebitrate=40000;maxplaybackrate=48000"); |
| 1293 | } |
| 1294 | } |