| 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 | fn new(name: &str, value: impl Into<String>) -> Self { |
| 28 | Attribute { |
| 29 | name: name.to_owned(), |
| 30 | value: Some(value.into()), |
| 31 | } |
| 32 | } |
| 33 | |
| 34 | fn flag(name: &str) -> Self { |
| 35 | Attribute { |
| 36 | name: name.to_owned(), |
| 37 | value: None, |
| 38 | } |
| 39 | } |
| 40 | |
| 41 | fn render(&self) -> String { |
| 42 | match &self.value { |
| 43 | Some(value) => format!("a={}:{value}", self.name), |
| 44 | None => format!("a={}", self.name), |
| 45 | } |
| 46 | } |
| 47 | } |
| 48 | |
| 49 | #[derive(Debug, Clone, Default)] |
| 50 | pub struct Session { |
| 51 | pub version: String, |
| 52 | pub origin: String, |
| 53 | pub name: String, |
| 54 | pub connection: Option<String>, |
| 55 | pub bandwidths: Vec<String>, |
| 56 | pub timing: String, |
| 57 | pub attributes: Vec<Attribute>, |
| 58 | } |
| 59 | |
| 60 | #[derive(Debug, Clone)] |
| 61 | pub struct Media { |
| 62 | pub kind: String, |
| 63 | pub port: String, |
| 64 | pub proto: String, |
| 65 | pub formats: Vec<String>, |
| 66 | pub connection: Option<String>, |
| 67 | pub bandwidths: Vec<String>, |
| 68 | pub attributes: Vec<Attribute>, |
| 69 | } |
| 70 | |
| 71 | #[derive(Debug, Clone)] |
| 72 | pub struct SessionDescription { |
| 73 | pub session: Session, |
| 74 | pub media: Vec<Media>, |
| 75 | } |
| 76 | |
| 77 | impl Media { |
| 78 | pub fn values<'a>(&'a self, name: &str) -> impl Iterator<Item = &'a str> + 'a { |
| 79 | let name = name.to_owned(); |
| 80 | self.attributes |
| 81 | .iter() |
| 82 | .filter(move |attribute| attribute.name == name) |
| 83 | .filter_map(|attribute| attribute.value.as_deref()) |
| 84 | } |
| 85 | |
| 86 | pub fn value(&self, name: &str) -> Option<&str> { |
| 87 | self.values(name).next() |
| 88 | } |
| 89 | |
| 90 | pub fn has(&self, name: &str) -> bool { |
| 91 | self.attributes.iter().any(|attribute| attribute.name == name) |
| 92 | } |
| 93 | |
| 94 | pub fn mid(&self) -> Option<&str> { |
| 95 | self.value("mid") |
| 96 | } |
| 97 | |
| 98 | pub fn direction(&self) -> Option<&str> { |
| 99 | self.attributes |
| 100 | .iter() |
| 101 | .find(|attribute| DIRECTIONS.contains(&attribute.name.as_str())) |
| 102 | .map(|attribute| attribute.name.as_str()) |
| 103 | } |
| 104 | |
| 105 | fn rtpmap(&self) -> HashMap<String, String> { |
| 106 | self.values("rtpmap") |
| 107 | .filter_map(|value| value.split_once(' ')) |
| 108 | .map(|(payload, encoding)| (payload.to_owned(), encoding.to_owned())) |
| 109 | .collect() |
| 110 | } |
| 111 | } |
| 112 | |
| 113 | pub fn parse(text: &str) -> Result<SessionDescription> { |
| 114 | let mut session = Session::default(); |
| 115 | let mut media: Vec<Media> = Vec::new(); |
| 116 | for raw in text.split('\n') { |
| 117 | let line = raw.trim_end_matches('\r'); |
| 118 | if line.is_empty() { |
| 119 | continue; |
| 120 | } |
| 121 | let (kind, value) = line |
| 122 | .split_once('=') |
| 123 | .ok_or_else(|| Error::Sdp(format!("line without '=': {line}")))?; |
| 124 | if kind == "m" { |
| 125 | let mut parts = value.split(' '); |
| 126 | let (Some(media_kind), Some(port), Some(proto)) = (parts.next(), parts.next(), parts.next()) else { |
| 127 | return Err(Error::Sdp(format!("short m-line: {line}"))); |
| 128 | }; |
| 129 | media.push(Media { |
| 130 | kind: media_kind.to_owned(), |
| 131 | port: port.to_owned(), |
| 132 | proto: proto.to_owned(), |
| 133 | formats: parts.map(str::to_owned).collect(), |
| 134 | connection: None, |
| 135 | bandwidths: Vec::new(), |
| 136 | attributes: Vec::new(), |
| 137 | }); |
| 138 | continue; |
| 139 | } |
| 140 | let attribute = || { |
| 141 | let (name, value) = match value.split_once(':') { |
| 142 | Some((name, value)) => (name, Some(value.to_owned())), |
| 143 | None => (value, None), |
| 144 | }; |
| 145 | Attribute { |
| 146 | name: name.to_owned(), |
| 147 | value, |
| 148 | } |
| 149 | }; |
| 150 | match (media.last_mut(), kind) { |
| 151 | (None, "v") => session.version = value.to_owned(), |
| 152 | (None, "o") => session.origin = value.to_owned(), |
| 153 | (None, "s") => session.name = value.to_owned(), |
| 154 | (None, "c") => session.connection = Some(value.to_owned()), |
| 155 | (None, "b") => session.bandwidths.push(value.to_owned()), |
| 156 | (None, "t") => session.timing = value.to_owned(), |
| 157 | (None, "a") => session.attributes.push(attribute()), |
| 158 | (Some(current), "c") => current.connection = Some(value.to_owned()), |
| 159 | (Some(current), "b") => current.bandwidths.push(value.to_owned()), |
| 160 | (Some(current), "a") => current.attributes.push(attribute()), |
| 161 | _ => {} |
| 162 | } |
| 163 | } |
| 164 | Ok(SessionDescription { session, media }) |
| 165 | } |
| 166 | |
| 167 | fn session_rank(name: &str) -> usize { |
| 168 | match name { |
| 169 | "x-mediabw" => 0, |
| 170 | "extmap-allow-mixed" => 1, |
| 171 | "msid-semantic" => 2, |
| 172 | "group" => 3, |
| 173 | _ => 99, |
| 174 | } |
| 175 | } |
| 176 | |
| 177 | fn media_rank(name: &str) -> usize { |
| 178 | match name { |
| 179 | "x-multi-stream" => 0, |
| 180 | "x-data-protocol" => 1, |
| 181 | "x-signaling-fb" => 2, |
| 182 | "x-ssrc-range" => 3, |
| 183 | "x-source-streamid" => 4, |
| 184 | "rtpmap" => 10, |
| 185 | "fmtp" => 11, |
| 186 | "rtcp" => 12, |
| 187 | "rtcp-fb" => 13, |
| 188 | "extmap" => 14, |
| 189 | "extmap-allow-mixed" => 15, |
| 190 | "setup" => 16, |
| 191 | "mid" => 17, |
| 192 | "msid" => 18, |
| 193 | "ptime" => 19, |
| 194 | "maxptime" => 20, |
| 195 | "sendrecv" | "sendonly" | "recvonly" | "inactive" => 21, |
| 196 | "ice-ufrag" => 22, |
| 197 | "ice-pwd" => 23, |
| 198 | "fingerprint" => 24, |
| 199 | "candidate" => 25, |
| 200 | "end-of-candidates" => 26, |
| 201 | "ice-options" => 27, |
| 202 | "ssrc" => 28, |
| 203 | "ssrc-group" => 29, |
| 204 | "rtcp-mux" => 30, |
| 205 | "rtcp-rsize" => 31, |
| 206 | "rid" => 32, |
| 207 | "simulcast" => 33, |
| 208 | "label" => 34, |
| 209 | "sctp-port" => 35, |
| 210 | "max-message-size" => 36, |
| 211 | _ => 99, |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | pub fn write(description: &SessionDescription) -> String { |
| 216 | let session = &description.session; |
| 217 | let mut lines = vec![ |
| 218 | format!("v={}", session.version), |
| 219 | format!("o={}", session.origin), |
| 220 | format!("s={}", session.name), |
| 221 | ]; |
| 222 | lines.extend(session.connection.iter().map(|connection| format!("c={connection}"))); |
| 223 | lines.extend(session.bandwidths.iter().map(|bandwidth| format!("b={bandwidth}"))); |
| 224 | lines.push(format!("t={}", session.timing)); |
| 225 | let mut session_attributes: Vec<&Attribute> = session.attributes.iter().collect(); |
| 226 | session_attributes.sort_by_key(|attribute| session_rank(&attribute.name)); |
| 227 | lines.extend(session_attributes.into_iter().map(Attribute::render)); |
| 228 | for media in &description.media { |
| 229 | let mut header = vec![media.kind.clone(), media.port.clone(), media.proto.clone()]; |
| 230 | header.extend(media.formats.iter().cloned()); |
| 231 | lines.push(format!("m={}", header.join(" "))); |
| 232 | lines.extend(media.connection.iter().map(|connection| format!("c={connection}"))); |
| 233 | lines.extend(media.bandwidths.iter().map(|bandwidth| format!("b={bandwidth}"))); |
| 234 | let mut attributes: Vec<&Attribute> = media.attributes.iter().collect(); |
| 235 | attributes.sort_by_key(|attribute| media_rank(&attribute.name)); |
| 236 | lines.extend(attributes.into_iter().map(Attribute::render)); |
| 237 | } |
| 238 | let mut text = lines.join("\r\n"); |
| 239 | text.push_str("\r\n"); |
| 240 | text |
| 241 | } |
| 242 | |
| 243 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 244 | pub enum LineRole { |
| 245 | MainAudio, |
| 246 | MainVideo, |
| 247 | ScreenShare, |
| 248 | Data, |
| 249 | } |
| 250 | |
| 251 | impl LineRole { |
| 252 | fn label(self) -> &'static str { |
| 253 | match self { |
| 254 | LineRole::MainAudio => "main-audio", |
| 255 | LineRole::MainVideo => "main-video", |
| 256 | LineRole::ScreenShare => "applicationsharing-video", |
| 257 | LineRole::Data => "data", |
| 258 | } |
| 259 | } |
| 260 | |
| 261 | fn stream_prefix(self) -> &'static str { |
| 262 | match self { |
| 263 | LineRole::MainAudio => "mainAudio", |
| 264 | LineRole::MainVideo => "mainVideo", |
| 265 | LineRole::ScreenShare => "applicationsharingVideo", |
| 266 | LineRole::Data => "data", |
| 267 | } |
| 268 | } |
| 269 | } |
| 270 | |
| 271 | /// Which browser m-lines play which Teams role; `gallery_mids` are folded into one `x-multi-stream` line. |
| 272 | #[derive(Debug, Clone, Default)] |
| 273 | pub struct OfferPlan { |
| 274 | pub screen_share_mids: Vec<String>, |
| 275 | pub gallery_mids: Vec<String>, |
| 276 | } |
| 277 | |
| 278 | #[derive(Debug, Clone, PartialEq, Eq)] |
| 279 | pub struct SignaledLine { |
| 280 | pub browser_mids: Vec<String>, |
| 281 | pub role: LineRole, |
| 282 | } |
| 283 | |
| 284 | #[derive(Debug, Clone)] |
| 285 | pub struct SignaledOffer { |
| 286 | pub sdp: String, |
| 287 | pub lines: Vec<SignaledLine>, |
| 288 | } |
| 289 | |
| 290 | /// Random numbers for SSRCs; injected so tests stay deterministic. |
| 291 | pub trait NumberSource { |
| 292 | fn next_u32(&mut self) -> u32; |
| 293 | } |
| 294 | |
| 295 | impl<F: FnMut() -> u32> NumberSource for F { |
| 296 | fn next_u32(&mut self) -> u32 { |
| 297 | self() |
| 298 | } |
| 299 | } |
| 300 | |
| 301 | pub fn to_teams_offer(browser_sdp: &str, plan: &OfferPlan, numbers: &mut impl NumberSource) -> Result<SignaledOffer> { |
| 302 | let browser = parse(browser_sdp)?; |
| 303 | let cname = browser |
| 304 | .media |
| 305 | .iter() |
| 306 | .flat_map(|media| media.values("ssrc")) |
| 307 | .find_map(|value| value.split_once(" cname:").map(|(_, cname)| cname.to_owned())) |
| 308 | .unwrap_or_else(|| format!("{:08x}{:08x}", numbers.next_u32(), numbers.next_u32())); |
| 309 | let gallery_carrier = plan.gallery_mids.last().cloned(); |
| 310 | let mut lines = Vec::new(); |
| 311 | let mut media = Vec::new(); |
| 312 | for source in &browser.media { |
| 313 | let mid = source.mid().unwrap_or_default().to_owned(); |
| 314 | if plan.gallery_mids.contains(&mid) && Some(&mid) != gallery_carrier.as_ref() { |
| 315 | continue; |
| 316 | } |
| 317 | let role = match source.kind.as_str() { |
| 318 | "audio" => LineRole::MainAudio, |
| 319 | "application" => LineRole::Data, |
| 320 | _ if plan.screen_share_mids.contains(&mid) => LineRole::ScreenShare, |
| 321 | _ => LineRole::MainVideo, |
| 322 | }; |
| 323 | let multi_stream = (Some(&mid) == gallery_carrier.as_ref()).then_some(plan.gallery_mids.len()); |
| 324 | let is_first = media.is_empty(); |
| 325 | let signaled = if role == LineRole::Data { |
| 326 | signal_data_line(source, numbers) |
| 327 | } else { |
| 328 | signal_rtp_line(source, role, multi_stream, &cname, is_first, numbers) |
| 329 | }; |
| 330 | media.push(signaled); |
| 331 | lines.push(SignaledLine { |
| 332 | browser_mids: match multi_stream { |
| 333 | Some(_) => plan.gallery_mids.clone(), |
| 334 | None => vec![mid], |
| 335 | }, |
| 336 | role, |
| 337 | }); |
| 338 | } |
| 339 | let mut session = browser.session.clone(); |
| 340 | session.bandwidths = vec![SESSION_BANDWIDTH.to_owned()]; |
| 341 | for attribute in &mut session.attributes { |
| 342 | match attribute.name.as_str() { |
| 343 | "msid-semantic" => attribute.value = Some(" WMS *".to_owned()), |
| 344 | "group" if attribute.value.as_deref().is_some_and(|value| value.starts_with("BUNDLE")) => { |
| 345 | let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect(); |
| 346 | attribute.value = Some(format!("BUNDLE {}", mids.join(" "))); |
| 347 | } |
| 348 | _ => {} |
| 349 | } |
| 350 | } |
| 351 | let description = SessionDescription { session, media }; |
| 352 | Ok(SignaledOffer { |
| 353 | sdp: write(&description), |
| 354 | lines, |
| 355 | }) |
| 356 | } |
| 357 | |
| 358 | fn signal_rtp_line( |
| 359 | source: &Media, |
| 360 | role: LineRole, |
| 361 | multi_stream: Option<usize>, |
| 362 | cname: &str, |
| 363 | carries_candidate: bool, |
| 364 | numbers: &mut impl NumberSource, |
| 365 | ) -> Media { |
| 366 | let mut media = source.clone(); |
| 367 | media.port = SIGNALED_PORT.to_owned(); |
| 368 | media.proto = SIGNALED_PROTO.to_owned(); |
| 369 | media.connection = Some(PLACEHOLDER_CONNECTION.to_owned()); |
| 370 | let rtpmap = source.rtpmap(); |
| 371 | let is_rtx = |payload: &str| rtpmap.get(payload).is_some_and(|encoding| encoding.starts_with("rtx/")); |
| 372 | let mid = source.mid().unwrap_or_default().to_owned(); |
| 373 | |
| 374 | let mut attributes = Vec::new(); |
| 375 | if let Some(count) = multi_stream { |
| 376 | attributes.push(Attribute::new("x-multi-stream", format!("{count} 1 1 1"))); |
| 377 | } |
| 378 | attributes.push(Attribute::new( |
| 379 | "x-signaling-fb", |
| 380 | match role { |
| 381 | LineRole::MainAudio => "* x-message app recv:dsh", |
| 382 | _ => "* x-message app send:src recv:src,vc", |
| 383 | }, |
| 384 | )); |
| 385 | let browser_ssrcs: Vec<u32> = source |
| 386 | .values("ssrc") |
| 387 | .filter_map(|value| value.split(' ').next()?.parse().ok()) |
| 388 | .collect(); |
| 389 | let simulcast = source.has("simulcast"); |
| 390 | let receive_only = source.direction() == Some("recvonly"); |
| 391 | let (range, ssrc_lines) = if multi_stream.is_some() { |
| 392 | (None, vec![Attribute::new("ssrc", format!("1 cname:{cname}"))]) |
| 393 | } else if let Some(&first) = browser_ssrcs.first() { |
| 394 | let lines = source |
| 395 | .values("ssrc") |
| 396 | .map(|value| Attribute::new("ssrc", rewrite_ssrc_msid(value, &mid))) |
| 397 | .collect(); |
| 398 | (Some((first, first)), lines) |
| 399 | } else if simulcast { |
| 400 | let base = numbers.next_u32(); |
| 401 | let lines = vec![Attribute::new("ssrc", format!("{base} fake_attribute:fake_value"))]; |
| 402 | (Some((base, base + SSRC_RANGE_SIZE - 1)), lines) |
| 403 | } else if receive_only && role != LineRole::MainAudio { |
| 404 | (Some((1, 1)), vec![Attribute::new("ssrc", format!("1 cname:{cname}"))]) |
| 405 | } else { |
| 406 | let base = numbers.next_u32(); |
| 407 | (Some((base, base)), vec![Attribute::new("ssrc", format!("{base} cname:{cname}"))]) |
| 408 | }; |
| 409 | if let Some((first, last)) = range { |
| 410 | attributes.push(Attribute::new("x-ssrc-range", format!("{first}-{last}"))); |
| 411 | } |
| 412 | |
| 413 | let video = source.kind == "video"; |
| 414 | let feedback_by_payload = feedback_by_payload(source); |
| 415 | let shared_feedback = shared_feedback(&feedback_by_payload, source, &is_rtx); |
| 416 | let mut fmtp: Vec<(usize, Attribute)> = Vec::new(); |
| 417 | for attribute in &source.attributes { |
| 418 | let value = attribute.value.as_deref().unwrap_or_default(); |
| 419 | match attribute.name.as_str() { |
| 420 | "ssrc" | "ssrc-group" | "rid" | "simulcast" | "rtcp-xr" | "rtcp-fb" => {} |
| 421 | "rtpmap" => attributes.push(Attribute::new("rtpmap", signal_rtpmap(value))), |
| 422 | "fmtp" => { |
| 423 | let payload = value.split(' ').next().unwrap_or_default(); |
| 424 | let position = source.formats.iter().position(|format| format == payload).unwrap_or(usize::MAX); |
| 425 | let cleaned = if video { |
| 426 | value.replace(";sps-pps-idr-in-keyframe=1", "") |
| 427 | } else { |
| 428 | value.to_owned() |
| 429 | }; |
| 430 | fmtp.push((position, Attribute::new("fmtp", cleaned))); |
| 431 | } |
| 432 | "rtcp" => attributes.push(Attribute::new("rtcp", SIGNALED_PORT)), |
| 433 | "extmap" => { |
| 434 | if let Some(signaled) = signal_extmap(value) { |
| 435 | attributes.push(Attribute::new("extmap", signaled)); |
| 436 | } |
| 437 | } |
| 438 | _ => attributes.push(attribute.clone()), |
| 439 | } |
| 440 | } |
| 441 | fmtp.sort_by_key(|(position, _)| *position); |
| 442 | attributes.extend(fmtp.into_iter().map(|(_, attribute)| attribute)); |
| 443 | match shared_feedback { |
| 444 | Some(feedback) => attributes.extend(feedback.iter().map(|kind| Attribute::new("rtcp-fb", format!("* {kind}")))), |
| 445 | None => attributes.extend(source.attributes.iter().filter(|attribute| attribute.name == "rtcp-fb").cloned()), |
| 446 | } |
| 447 | if carries_candidate { |
| 448 | attributes.push(Attribute::new("candidate", PLACEHOLDER_CANDIDATE)); |
| 449 | } |
| 450 | attributes.extend(ssrc_lines); |
| 451 | attributes.extend(source.attributes.iter().filter(|attribute| attribute.name == "ssrc-group").cloned()); |
| 452 | attributes.push(Attribute::new("label", role.label())); |
| 453 | if !source.has("rtcp-mux") { |
| 454 | attributes.push(Attribute::flag("rtcp-mux")); |
| 455 | } |
| 456 | media.attributes = attributes; |
| 457 | media |
| 458 | } |
| 459 | |
| 460 | fn rewrite_ssrc_msid(value: &str, mid: &str) -> String { |
| 461 | match value.split_once(" msid:") { |
| 462 | Some((ssrc, msid)) => { |
| 463 | let stream = msid.split(' ').next().unwrap_or("-"); |
| 464 | format!("{ssrc} msid:{stream} {mid}") |
| 465 | } |
| 466 | None => value.to_owned(), |
| 467 | } |
| 468 | } |
| 469 | |
| 470 | fn signal_rtpmap(value: &str) -> String { |
| 471 | match value.split_once(' ') { |
| 472 | Some((payload, encoding)) if encoding.eq_ignore_ascii_case("red/48000/2") => format!("{payload} RED/8000"), |
| 473 | _ => value.to_owned(), |
| 474 | } |
| 475 | } |
| 476 | |
| 477 | fn signal_extmap(value: &str) -> Option<String> { |
| 478 | let (identifier, uri) = value.split_once(' ')?; |
| 479 | if DROPPED_EXTENSIONS.contains(&uri) { |
| 480 | return None; |
| 481 | } |
| 482 | if BACKSLASHED_EXTENSIONS.contains(&uri) { |
| 483 | return Some(format!("{identifier} {}", uri.replace('/', "\\"))); |
| 484 | } |
| 485 | if uri == LAYERS_ALLOCATION { |
| 486 | return Some(format!("{identifier} {uri}{NOT_ADVERTISED_SUFFIX}")); |
| 487 | } |
| 488 | Some(value.to_owned()) |
| 489 | } |
| 490 | |
| 491 | fn feedback_by_payload(source: &Media) -> HashMap<String, Vec<String>> { |
| 492 | let mut map: HashMap<String, Vec<String>> = HashMap::new(); |
| 493 | for value in source.values("rtcp-fb") { |
| 494 | if let Some((payload, kind)) = value.split_once(' ') { |
| 495 | map.entry(payload.to_owned()).or_default().push(kind.to_owned()); |
| 496 | } |
| 497 | } |
| 498 | map |
| 499 | } |
| 500 | |
| 501 | fn shared_feedback( |
| 502 | by_payload: &HashMap<String, Vec<String>>, |
| 503 | source: &Media, |
| 504 | is_rtx: &impl Fn(&str) -> bool, |
| 505 | ) -> Option<Vec<String>> { |
| 506 | let mut codecs = source.formats.iter().filter(|payload| !is_rtx(payload)); |
| 507 | let first = by_payload.get(codecs.next()?)?; |
| 508 | codecs.all(|payload| by_payload.get(payload) == Some(first)).then(|| first.clone()) |
| 509 | } |
| 510 | |
| 511 | fn signal_data_line(source: &Media, numbers: &mut impl NumberSource) -> Media { |
| 512 | let ssrc = numbers.next_u32(); |
| 513 | let mut attributes = vec![ |
| 514 | Attribute::new("x-data-protocol", "sctp"), |
| 515 | Attribute::new("x-ssrc-range", format!("{ssrc}-{ssrc}")), |
| 516 | Attribute::new("rtpmap", "127 x-data/90000"), |
| 517 | Attribute::new("rtpmap", "126 rtx/90000"), |
| 518 | Attribute::new("fmtp", "126 apt=127"), |
| 519 | Attribute::flag("sendrecv"), |
| 520 | Attribute::flag("rtcp-mux"), |
| 521 | Attribute::new("label", LineRole::Data.label()), |
| 522 | ]; |
| 523 | attributes.extend(source.attributes.iter().cloned()); |
| 524 | Media { |
| 525 | kind: "x-data".to_owned(), |
| 526 | port: SIGNALED_PORT.to_owned(), |
| 527 | proto: SIGNALED_PROTO.to_owned(), |
| 528 | formats: vec!["127".to_owned(), "126".to_owned()], |
| 529 | connection: Some(PLACEHOLDER_CONNECTION.to_owned()), |
| 530 | bandwidths: Vec::new(), |
| 531 | attributes, |
| 532 | } |
| 533 | } |
| 534 | |
| 535 | pub fn to_browser_answer(teams_sdp: &str, offer: &SignaledOffer, browser_offer_sdp: &str) -> Result<String> { |
| 536 | let answer = parse(teams_sdp)?; |
| 537 | let browser_offer = parse(browser_offer_sdp)?; |
| 538 | if answer.media.len() != offer.lines.len() { |
| 539 | return Err(Error::Sdp(format!( |
| 540 | "answer has {} m-lines, offer signaled {}", |
| 541 | answer.media.len(), |
| 542 | offer.lines.len() |
| 543 | ))); |
| 544 | } |
| 545 | let offered: HashMap<&str, &Media> = browser_offer |
| 546 | .media |
| 547 | .iter() |
| 548 | .filter_map(|media| Some((media.mid()?, media))) |
| 549 | .collect(); |
| 550 | let mut media = Vec::new(); |
| 551 | for (index, (teams_line, signaled)) in answer.media.iter().zip(&offer.lines).enumerate() { |
| 552 | for (stream_index, browser_mid) in signaled.browser_mids.iter().enumerate() { |
| 553 | let offered_line = offered |
| 554 | .get(browser_mid.as_str()) |
| 555 | .ok_or_else(|| Error::Sdp(format!("offer has no mid {browser_mid}")))?; |
| 556 | let section = if signaled.role == LineRole::Data { |
| 557 | browser_data_line(teams_line, offered_line, &answer.session) |
| 558 | } else { |
| 559 | browser_rtp_line(teams_line, offered_line, signaled.role, stream_index as u32, index == 0, &answer.session) |
| 560 | }; |
| 561 | media.push(section); |
| 562 | } |
| 563 | } |
| 564 | let mut session = answer.session.clone(); |
| 565 | session.attributes.retain(|attribute| attribute.name.starts_with("x-")); |
| 566 | session.attributes.push(Attribute::flag("extmap-allow-mixed")); |
| 567 | session.attributes.push(Attribute::new("msid-semantic", " WMS *")); |
| 568 | let mids: Vec<&str> = media.iter().filter_map(Media::mid).collect(); |
| 569 | session.attributes.push(Attribute::new("group", format!("BUNDLE {}", mids.join(" ")))); |
| 570 | Ok(write(&SessionDescription { session, media })) |
| 571 | } |
| 572 | |
| 573 | fn transport_attributes(teams_line: &Media, session: &Session) -> Vec<Attribute> { |
| 574 | ["setup", "ice-ufrag", "ice-pwd", "fingerprint"] |
| 575 | .into_iter() |
| 576 | .filter_map(|name| { |
| 577 | teams_line |
| 578 | .attributes |
| 579 | .iter() |
| 580 | .chain(&session.attributes) |
| 581 | .find(|attribute| attribute.name == name) |
| 582 | .cloned() |
| 583 | }) |
| 584 | .collect() |
| 585 | } |
| 586 | |
| 587 | fn browser_rtp_line( |
| 588 | teams_line: &Media, |
| 589 | offered: &Media, |
| 590 | role: LineRole, |
| 591 | stream_index: u32, |
| 592 | carries_candidates: bool, |
| 593 | session: &Session, |
| 594 | ) -> Media { |
| 595 | let offered_rtpmap = offered.rtpmap(); |
| 596 | let offered_codecs: HashMap<String, String> = offered_rtpmap |
| 597 | .values() |
| 598 | .filter_map(|encoding| { |
| 599 | let (name, rest) = encoding.split_once('/')?; |
| 600 | Some((name.to_ascii_lowercase(), rest.to_owned())) |
| 601 | }) |
| 602 | .collect(); |
| 603 | let answer_rtpmap = teams_line.rtpmap(); |
| 604 | let kept: Vec<String> = teams_line |
| 605 | .formats |
| 606 | .iter() |
| 607 | .filter(|payload| { |
| 608 | answer_rtpmap |
| 609 | .get(*payload) |
| 610 | .and_then(|encoding| encoding.split('/').next()) |
| 611 | .is_some_and(|name| offered_codecs.contains_key(&name.to_ascii_lowercase())) |
| 612 | }) |
| 613 | .cloned() |
| 614 | .collect(); |
| 615 | let kept_set: HashSet<&str> = kept.iter().map(String::as_str).collect(); |
| 616 | let payload_of = |value: &str| value.split(' ').next().unwrap_or_default().to_owned(); |
| 617 | let codec_payload = |codec: &str| { |
| 618 | kept.iter().find(|payload| { |
| 619 | answer_rtpmap |
| 620 | .get(*payload) |
| 621 | .is_some_and(|encoding| encoding.to_ascii_lowercase().starts_with(&format!("{codec}/"))) |
| 622 | }) |
| 623 | }; |
| 624 | |
| 625 | let mut attributes = Vec::new(); |
| 626 | attributes.extend(teams_line.values("x-source-streamid").map(|value| Attribute::new("x-source-streamid", value))); |
| 627 | for value in teams_line.values("rtpmap") { |
| 628 | let payload = payload_of(value); |
| 629 | if !kept_set.contains(payload.as_str()) { |
| 630 | continue; |
| 631 | } |
| 632 | let encoding = answer_rtpmap.get(&payload).cloned().unwrap_or_default(); |
| 633 | let name = encoding.split('/').next().unwrap_or_default(); |
| 634 | let offered_rest = offered_codecs.get(&name.to_ascii_lowercase()); |
| 635 | let rewritten = match offered_rest { |
| 636 | Some(rest) if name.eq_ignore_ascii_case("red") => format!("{payload} {name}/{rest}"), |
| 637 | _ => value.to_owned(), |
| 638 | }; |
| 639 | attributes.push(Attribute::new("rtpmap", rewritten)); |
| 640 | } |
| 641 | let mut fmtp_payloads = HashSet::new(); |
| 642 | for value in teams_line.values("fmtp") { |
| 643 | let payload = payload_of(value); |
| 644 | if !kept_set.contains(payload.as_str()) { |
| 645 | continue; |
| 646 | } |
| 647 | fmtp_payloads.insert(payload); |
| 648 | let cleaned = value |
| 649 | .split(';') |
| 650 | .filter(|parameter| !parameter.starts_with("rtx-time=")) |
| 651 | .collect::<Vec<_>>() |
| 652 | .join(";"); |
| 653 | attributes.push(Attribute::new("fmtp", cleaned)); |
| 654 | } |
| 655 | if let Some(opus) = codec_payload("opus").filter(|payload| !fmtp_payloads.contains(*payload)) { |
| 656 | attributes.push(Attribute::new("fmtp", format!("{opus} usedtx=1"))); |
| 657 | } |
| 658 | if let (Some(red), Some(opus)) = (codec_payload("red"), codec_payload("opus")) |
| 659 | && !fmtp_payloads.contains(red) |
| 660 | { |
| 661 | attributes.push(Attribute::new("fmtp", format!("{red} {opus}/{opus}"))); |
| 662 | } |
| 663 | attributes.extend(teams_line.values("rtcp").map(|value| Attribute::new("rtcp", value))); |
| 664 | let answer_feedback: Vec<&str> = teams_line |
| 665 | .values("rtcp-fb") |
| 666 | .filter(|value| !value.contains("x-message")) |
| 667 | .collect(); |
| 668 | if answer_feedback.is_empty() && !teams_line.has("rtcp-fb") { |
| 669 | attributes.extend( |
| 670 | offered |
| 671 | .values("rtcp-fb") |
| 672 | .filter(|value| kept_set.contains(payload_of(value).as_str())) |
| 673 | .map(|value| Attribute::new("rtcp-fb", value)), |
| 674 | ); |
| 675 | } else { |
| 676 | attributes.extend(answer_feedback.into_iter().map(|value| Attribute::new("rtcp-fb", value))); |
| 677 | } |
| 678 | for value in teams_line.values("extmap") { |
| 679 | let restored = value.replace('\\', "/").replace(NOT_ADVERTISED_SUFFIX, ""); |
| 680 | attributes.push(Attribute::new("extmap", restored)); |
| 681 | } |
| 682 | attributes.extend(transport_attributes(teams_line, session)); |
| 683 | attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default())); |
| 684 | attributes.extend(teams_line.values("ptime").map(|value| Attribute::new("ptime", value))); |
| 685 | if let Some(direction) = teams_line.direction() { |
| 686 | attributes.push(Attribute::flag(direction)); |
| 687 | } |
| 688 | if carries_candidates { |
| 689 | attributes.extend(teams_line.values("candidate").map(|value| Attribute::new("candidate", browser_candidate(value)))); |
| 690 | } |
| 691 | let (primary, retransmission) = stream_ssrcs(teams_line, stream_index); |
| 692 | if let Some(primary) = primary { |
| 693 | let stream = format!("{}-{primary}", role.stream_prefix()); |
| 694 | for ssrc in [Some(primary), retransmission].into_iter().flatten() { |
| 695 | attributes.push(Attribute::new("ssrc", format!("{ssrc} cname:{}", stream_cname(primary)))); |
| 696 | attributes.push(Attribute::new("ssrc", format!("{ssrc} msid:{stream} {stream}"))); |
| 697 | } |
| 698 | if let Some(retransmission) = retransmission { |
| 699 | attributes.push(Attribute::new("ssrc-group", format!("FID {primary} {retransmission}"))); |
| 700 | } |
| 701 | } |
| 702 | attributes.push(Attribute::flag("rtcp-mux")); |
| 703 | if teams_line.has("rtcp-rsize") { |
| 704 | attributes.push(Attribute::flag("rtcp-rsize")); |
| 705 | } |
| 706 | if let Some(simulcast) = offered.value("simulcast").and_then(|value| value.strip_prefix("send ")) { |
| 707 | let rids: Vec<String> = simulcast.split(';').map(|rid| rid.trim_start_matches('~').to_owned()).collect(); |
| 708 | attributes.extend(rids.iter().map(|rid| Attribute::new("rid", format!("{rid} recv")))); |
| 709 | attributes.push(Attribute::new("simulcast", format!("recv {}", rids.join(";")))); |
| 710 | } |
| 711 | Media { |
| 712 | kind: offered.kind.clone(), |
| 713 | port: teams_line.port.clone(), |
| 714 | proto: offered.proto.clone(), |
| 715 | formats: kept, |
| 716 | connection: teams_line.connection.clone().or_else(|| session.connection.clone()), |
| 717 | bandwidths: teams_line.bandwidths.clone(), |
| 718 | attributes, |
| 719 | } |
| 720 | } |
| 721 | |
| 722 | fn stream_cname(primary: u32) -> String { |
| 723 | format!("teams{primary}") |
| 724 | } |
| 725 | |
| 726 | fn stream_ssrcs(teams_line: &Media, stream_index: u32) -> (Option<u32>, Option<u32>) { |
| 727 | let offset = stream_index * SSRC_RANGE_SIZE; |
| 728 | if let Some(group) = teams_line.value("ssrc-group").and_then(|value| value.strip_prefix("FID ")) { |
| 729 | let mut ssrcs = group.split(' ').filter_map(|value| value.parse::<u32>().ok()); |
| 730 | let primary = ssrcs.next().map(|ssrc| ssrc + offset); |
| 731 | return (primary, ssrcs.next().map(|ssrc| ssrc + offset)); |
| 732 | } |
| 733 | let first = teams_line |
| 734 | .value("x-ssrc-range") |
| 735 | .and_then(|range| range.split('-').next()?.parse::<u32>().ok()) |
| 736 | .map(|ssrc| ssrc + offset); |
| 737 | (first, None) |
| 738 | } |
| 739 | |
| 740 | fn browser_candidate(value: &str) -> String { |
| 741 | let mut parts: Vec<&str> = value.split(' ').collect(); |
| 742 | if let Some(position) = parts.iter().position(|part| *part == "MTURNID") { |
| 743 | parts.truncate(position); |
| 744 | } |
| 745 | let passive = parts.get(2) == Some(&"tcp-pass"); |
| 746 | if passive { |
| 747 | parts[2] = "tcp"; |
| 748 | } |
| 749 | let mut candidate = parts.join(" "); |
| 750 | if passive { |
| 751 | candidate.push_str(" tcptype passive"); |
| 752 | } |
| 753 | candidate |
| 754 | } |
| 755 | |
| 756 | fn browser_data_line(teams_line: &Media, offered: &Media, session: &Session) -> Media { |
| 757 | let mut attributes = Vec::new(); |
| 758 | attributes.extend(teams_line.values("x-source-streamid").map(|value| Attribute::new("x-source-streamid", value))); |
| 759 | attributes.extend(transport_attributes(teams_line, session)); |
| 760 | attributes.push(Attribute::new("mid", offered.mid().unwrap_or_default())); |
| 761 | attributes.extend(offered.values("sctp-port").map(|value| Attribute::new("sctp-port", value))); |
| 762 | Media { |
| 763 | kind: offered.kind.clone(), |
| 764 | port: teams_line.port.clone(), |
| 765 | proto: offered.proto.clone(), |
| 766 | formats: offered.formats.clone(), |
| 767 | connection: teams_line.connection.clone().or_else(|| session.connection.clone()), |
| 768 | bandwidths: Vec::new(), |
| 769 | attributes, |
| 770 | } |
| 771 | } |
| 772 | |
| 773 | #[cfg(test)] |
| 774 | mod tests { |
| 775 | use super::*; |
| 776 | |
| 777 | fn counter() -> impl FnMut() -> u32 { |
| 778 | let mut next = 1000u32; |
| 779 | move || { |
| 780 | next += 1; |
| 781 | next |
| 782 | } |
| 783 | } |
| 784 | |
| 785 | 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"; |
| 786 | |
| 787 | #[test] |
| 788 | fn audio_only_offer_gets_the_teams_shape() { |
| 789 | let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap(); |
| 790 | let text = offer.sdp.replace("\r\n", "\n"); |
| 791 | assert!(text.contains("\nb=CT:4000\n")); |
| 792 | assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\n")); |
| 793 | assert!(text.contains("a=x-signaling-fb:* x-message app recv:dsh\n")); |
| 794 | assert!(text.contains("a=x-ssrc-range:42-42\n")); |
| 795 | assert!(text.contains("a=rtpmap:63 RED/8000\n")); |
| 796 | assert!(text.contains("a=rtcp:1234\n")); |
| 797 | assert!(text.contains("a=extmap:2 http:\\\\www.webrtc.org\\experiments\\rtp-hdrext\\abs-send-time\n")); |
| 798 | assert!(text.contains("a=ssrc:42 msid:stream 0\n")); |
| 799 | assert!(text.contains("a=candidate:1755259772 1 UDP 2122197247 10.10.10.10 1234 typ host\n")); |
| 800 | assert!(text.contains("m=audio 1234 RTP/SAVP 111 63 9 0 8 13 110 126\nc=IN IP4 10.10.10.10\n")); |
| 801 | assert!(text.ends_with("a=label:main-audio\n")); |
| 802 | assert_eq!(offer.lines, vec![SignaledLine { browser_mids: vec!["0".into()], role: LineRole::MainAudio }]); |
| 803 | } |
| 804 | |
| 805 | #[test] |
| 806 | fn answer_candidates_lose_teams_extensions() { |
| 807 | assert_eq!( |
| 808 | browser_candidate("1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480 MTURNID 158"), |
| 809 | "1 1 UDP 54001663 52.112.0.1 3480 typ relay raddr 10.0.0.1 rport 3480" |
| 810 | ); |
| 811 | assert_eq!( |
| 812 | browser_candidate("3 1 tcp-pass 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478"), |
| 813 | "3 1 tcp 18087935 52.112.0.1 3478 typ relay raddr 10.0.0.1 rport 3478 tcptype passive" |
| 814 | ); |
| 815 | } |
| 816 | |
| 817 | #[test] |
| 818 | fn audio_answer_maps_back_to_the_browser_mid_and_codecs() { |
| 819 | let offer = to_teams_offer(AUDIO_ONLY_OFFER, &OfferPlan::default(), &mut counter()).unwrap(); |
| 820 | 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"; |
| 821 | let browser = to_browser_answer(answer, &offer, AUDIO_ONLY_OFFER).unwrap().replace("\r\n", "\n"); |
| 822 | assert!(browser.contains("m=audio 3480 UDP/TLS/RTP/SAVPF 111 97 13 101\n"), "{browser}"); |
| 823 | assert!(browser.contains("a=rtpmap:97 RED/48000/2\n")); |
| 824 | assert!(browser.contains("a=fmtp:111 usedtx=1\n")); |
| 825 | assert!(browser.contains("a=fmtp:97 111/111\n")); |
| 826 | assert!(browser.contains("a=rtcp-fb:111 transport-cc\n")); |
| 827 | assert!(browser.contains("a=ssrc:1000 msid:mainAudio-1000 mainAudio-1000\n")); |
| 828 | assert!(browser.contains("a=group:BUNDLE 0\n")); |
| 829 | assert!(!browser.contains("SATINFB") && !browser.contains("MTURNID") && !browser.contains("label")); |
| 830 | } |
| 831 | } |