| 1 | use super::*; |
| 2 | |
| 3 | pub(super) enum PeerEvent { |
| 4 | Ice(IceConnectionState), |
| 5 | Connection(PeerConnectionState), |
| 6 | Track(RtcAudioTrack), |
| 7 | VideoTrack { mid: String, track: RtcVideoTrack }, |
| 8 | Data(Vec<u8>), |
| 9 | } |
| 10 | |
| 11 | pub(super) struct PeerSession { |
| 12 | pub(super) peer: PeerConnection, |
| 13 | pub(super) events: mpsc::UnboundedReceiver<PeerEvent>, |
| 14 | pub(super) _data_channel: Option<DataChannel>, |
| 15 | pub(super) gathered: Gathered, |
| 16 | } |
| 17 | |
| 18 | #[derive(Clone, Default)] |
| 19 | pub(super) struct Gathered { |
| 20 | pub(super) candidates: Arc<std::sync::Mutex<Vec<String>>>, |
| 21 | pub(super) complete: Arc<AtomicBool>, |
| 22 | pub(super) relay_seen_at: Arc<std::sync::Mutex<Option<Instant>>>, |
| 23 | pub(super) waited_ms: Arc<AtomicU64>, |
| 24 | } |
| 25 | |
| 26 | /// libwebrtc gathers continually here, and TCP/TLS relays trickle in late, so a UDP relay plus a short settle is enough. |
| 27 | pub(super) fn gathering_settled(complete: bool, since_udp_relay: Option<Duration>) -> bool { |
| 28 | complete || since_udp_relay.is_some_and(|since| since >= RELAY_SETTLE) |
| 29 | } |
| 30 | |
| 31 | impl Gathered { |
| 32 | pub(super) fn settled(&self) -> bool { |
| 33 | let since_udp_relay = self |
| 34 | .relay_seen_at |
| 35 | .lock() |
| 36 | .expect("relay time lock") |
| 37 | .map(|at| at.elapsed()); |
| 38 | gathering_settled(self.complete.load(Ordering::SeqCst), since_udp_relay) |
| 39 | } |
| 40 | |
| 41 | pub(super) async fn candidates(&self) -> Vec<String> { |
| 42 | let waited = Instant::now(); |
| 43 | while !self.settled() && waited.elapsed() < GATHERING_LIMIT { |
| 44 | tokio::time::sleep(GATHERING_POLL).await; |
| 45 | } |
| 46 | self.complete.store(true, Ordering::SeqCst); |
| 47 | self.waited_ms |
| 48 | .store(waited.elapsed().as_millis() as u64, Ordering::SeqCst); |
| 49 | self.candidates.lock().expect("candidates lock").clone() |
| 50 | } |
| 51 | |
| 52 | pub(super) fn summary(&self) -> String { |
| 53 | let count = self.candidates.lock().expect("candidates lock").len(); |
| 54 | format!( |
| 55 | "{count} candidate(s) after {} ms", |
| 56 | self.waited_ms.load(Ordering::SeqCst) |
| 57 | ) |
| 58 | } |
| 59 | } |
| 60 | |
| 61 | pub(super) async fn direct_sdp( |
| 62 | teams_sdp: &str, |
| 63 | gathered: Option<&Gathered>, |
| 64 | kind: SdpKind, |
| 65 | ) -> Result<String> { |
| 66 | match gathered { |
| 67 | Some(gathered) => with_candidates(teams_sdp, &gathered.candidates().await, kind), |
| 68 | None => Ok(teams_sdp.to_owned()), |
| 69 | } |
| 70 | } |
| 71 | |
| 72 | pub(super) struct OfferedMedia { |
| 73 | pub(super) browser_offer: String, |
| 74 | pub(super) signaled: SignaledOffer, |
| 75 | pub(super) video: VideoLines, |
| 76 | pub(super) plan: OfferPlan, |
| 77 | pub(super) modalities: Vec<String>, |
| 78 | } |
| 79 | |
| 80 | #[derive(Clone, Copy)] |
| 81 | pub(super) enum AnswerVideo<'a> { |
| 82 | Reject, |
| 83 | Receive, |
| 84 | Send(&'a RtcVideoTrack), |
| 85 | } |
| 86 | |
| 87 | #[derive(Debug, Clone, Copy, PartialEq, Eq)] |
| 88 | pub(super) enum Change { |
| 89 | Hold(bool), |
| 90 | Camera(bool), |
| 91 | Share(bool), |
| 92 | } |
| 93 | |
| 94 | pub(super) struct SamePeerOffer { |
| 95 | pub(super) browser_offer: String, |
| 96 | pub(super) signaled: SignaledOffer, |
| 97 | pub(super) change: Change, |
| 98 | pub(super) reply_tags: Vec<String>, |
| 99 | } |
| 100 | |
| 101 | pub(super) struct GlareResend { |
| 102 | pub(super) change: Change, |
| 103 | pub(super) reply_tags: Vec<String>, |
| 104 | pub(super) at: Instant, |
| 105 | } |
| 106 | |
| 107 | /// Renegotiation usually carries only `mediaAnswer`/`rejection`; keep the other leg links unless replaced. |
| 108 | pub(super) fn replace_leg_media_links( |
| 109 | media_links: &mut BTreeMap<String, String>, |
| 110 | leg_links: &BTreeMap<String, String>, |
| 111 | ) { |
| 112 | media_links.extend(leg_links.clone()); |
| 113 | } |
| 114 | |
| 115 | pub(super) fn answers_offer(callback_path: &str, reply_tags: &[String]) -> bool { |
| 116 | match callback_tag(callback_path) { |
| 117 | Some(tag) if !reply_tags.is_empty() => reply_tags.contains(&tag), |
| 118 | _ => true, |
| 119 | } |
| 120 | } |
| 121 | |
| 122 | pub(super) fn open_peer( |
| 123 | factory: &PeerConnectionFactory, |
| 124 | grant: &RelayGrant, |
| 125 | relay_host: &str, |
| 126 | with_data_channel: bool, |
| 127 | ) -> Result<PeerSession> { |
| 128 | let mut configuration = RtcConfiguration::default(); |
| 129 | configuration.ice_servers = vec![grant.ice_server(relay_host)]; |
| 130 | let peer = factory |
| 131 | .create_peer_connection(configuration) |
| 132 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 133 | let (sender, events) = mpsc::unbounded_channel(); |
| 134 | let data_channel = with_data_channel |
| 135 | .then(|| open_data_channel(&peer, sender.clone())) |
| 136 | .transpose()?; |
| 137 | let gathered = Gathered::default(); |
| 138 | let candidate_sink = gathered.candidates.clone(); |
| 139 | let relay_seen_at = gathered.relay_seen_at.clone(); |
| 140 | peer.on_ice_candidate(Some(Box::new(move |candidate| { |
| 141 | if candidate.sdp_mline_index() == 0 { |
| 142 | let text = candidate.candidate(); |
| 143 | if is_udp_relay(&text) { |
| 144 | relay_seen_at |
| 145 | .lock() |
| 146 | .expect("relay time lock") |
| 147 | .get_or_insert_with(Instant::now); |
| 148 | } |
| 149 | candidate_sink.lock().expect("candidates lock").push(text); |
| 150 | } |
| 151 | }))); |
| 152 | let gathering_done = gathered.complete.clone(); |
| 153 | peer.on_ice_gathering_state_change(Some(Box::new(move |state| match state { |
| 154 | IceGatheringState::Complete => gathering_done.store(true, Ordering::SeqCst), |
| 155 | IceGatheringState::Gathering => gathering_done.store(false, Ordering::SeqCst), |
| 156 | IceGatheringState::New => {} |
| 157 | }))); |
| 158 | let ice_sender = sender.clone(); |
| 159 | peer.on_ice_connection_state_change(Some(Box::new(move |state| { |
| 160 | let _ = ice_sender.send(PeerEvent::Ice(state)); |
| 161 | }))); |
| 162 | let connection_sender = sender.clone(); |
| 163 | peer.on_connection_state_change(Some(Box::new(move |state| { |
| 164 | let _ = connection_sender.send(PeerEvent::Connection(state)); |
| 165 | }))); |
| 166 | peer.on_track(Some(Box::new(move |event| match event.track { |
| 167 | MediaStreamTrack::Audio(track) => { |
| 168 | let _ = sender.send(PeerEvent::Track(track)); |
| 169 | } |
| 170 | MediaStreamTrack::Video(track) => { |
| 171 | let mid = event.transceiver.mid().unwrap_or_default(); |
| 172 | let _ = sender.send(PeerEvent::VideoTrack { mid, track }); |
| 173 | } |
| 174 | }))); |
| 175 | Ok(PeerSession { |
| 176 | peer, |
| 177 | events, |
| 178 | _data_channel: data_channel, |
| 179 | gathered, |
| 180 | }) |
| 181 | } |
| 182 | |
| 183 | pub(super) fn open_data_channel( |
| 184 | peer: &PeerConnection, |
| 185 | sender: mpsc::UnboundedSender<PeerEvent>, |
| 186 | ) -> Result<DataChannel> { |
| 187 | let channel = peer |
| 188 | .create_data_channel(DATA_CHANNEL_LABEL, DataChannelInit::default()) |
| 189 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 190 | channel.on_message(Some(Box::new(move |buffer| { |
| 191 | let _ = sender.send(PeerEvent::Data(buffer.data.to_vec())); |
| 192 | }))); |
| 193 | Ok(channel) |
| 194 | } |
| 195 | |
| 196 | pub(super) fn one_to_one_directions<'a>( |
| 197 | camera: bool, |
| 198 | share: bool, |
| 199 | camera_mid: &'a str, |
| 200 | share_mid: Option<&'a str>, |
| 201 | remote_shares: bool, |
| 202 | ) -> impl Fn(MediaLine<'_>) -> Option<&'static str> + 'a { |
| 203 | move |line| match line.kind { |
| 204 | "video" if line.mid == camera_mid => Some(if camera { "sendrecv" } else { INACTIVE }), |
| 205 | "video" if Some(line.mid) == share_mid => Some(match (share, remote_shares) { |
| 206 | (true, true) => "sendrecv", |
| 207 | (true, false) => "sendonly", |
| 208 | (false, true) => "recvonly", |
| 209 | (false, false) => INACTIVE, |
| 210 | }), |
| 211 | _ => None, |
| 212 | } |
| 213 | } |
| 214 | |
| 215 | pub(super) fn share_mid_in(offer_text: &str) -> Option<String> { |
| 216 | let mut mid = None; |
| 217 | for line in offer_text.lines().map(|line| line.trim_end_matches('\r')) { |
| 218 | if line.starts_with("m=") { |
| 219 | mid = None; |
| 220 | } else if let Some(value) = line.strip_prefix("a=mid:") { |
| 221 | mid = Some(value.to_owned()); |
| 222 | } else if line.starts_with(&format!("a=msid:{SCREEN_STREAM} ")) && mid.is_some() { |
| 223 | return mid; |
| 224 | } |
| 225 | } |
| 226 | None |
| 227 | } |
| 228 | |
| 229 | #[allow(clippy::too_many_arguments)] |
| 230 | pub(super) fn directions_for( |
| 231 | layout: Layout, |
| 232 | hold: bool, |
| 233 | camera: bool, |
| 234 | share: bool, |
| 235 | camera_mid: &str, |
| 236 | share_mid: Option<&str>, |
| 237 | remote_shares: bool, |
| 238 | text: &str, |
| 239 | ) -> String { |
| 240 | match (hold, layout) { |
| 241 | (true, _) => rewrite_directions(text, |_| Some(INACTIVE)), |
| 242 | (false, Layout::OneToOne) => rewrite_directions( |
| 243 | text, |
| 244 | one_to_one_directions(camera, share, camera_mid, share_mid, remote_shares), |
| 245 | ), |
| 246 | (false, Layout::Conference) => text.to_owned(), |
| 247 | } |
| 248 | } |
| 249 | |
| 250 | pub(super) async fn create_offer( |
| 251 | peer: &PeerConnection, |
| 252 | factory: &PeerConnectionFactory, |
| 253 | track: &RtcAudioTrack, |
| 254 | layout: Layout, |
| 255 | gathered: Option<&Gathered>, |
| 256 | ) -> Result<OfferedMedia> { |
| 257 | let transceiver_init = RtpTransceiverInit { |
| 258 | direction: RtpTransceiverDirection::SendRecv, |
| 259 | stream_ids: vec![MIC_STREAM.into()], |
| 260 | send_encodings: Vec::new(), |
| 261 | }; |
| 262 | peer.add_transceiver(MediaStreamTrack::Audio(track.clone()), transceiver_init) |
| 263 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 264 | let (video, plan) = match layout { |
| 265 | Layout::Conference => (add_video_lines(peer, factory)?, offer_plan()), |
| 266 | Layout::OneToOne => (add_one_to_one_lines(peer, factory)?, one_to_one_plan()), |
| 267 | }; |
| 268 | let offer = peer |
| 269 | .create_offer(OfferOptions { |
| 270 | offer_to_receive_audio: true, |
| 271 | offer_to_receive_video: true, |
| 272 | ..OfferOptions::default() |
| 273 | }) |
| 274 | .await |
| 275 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 276 | let browser_offer = directions_for( |
| 277 | layout, |
| 278 | false, |
| 279 | false, |
| 280 | false, |
| 281 | CAMERA_MID, |
| 282 | Some(ONE_TO_ONE_SHARE_MID), |
| 283 | false, |
| 284 | &offer.to_string(), |
| 285 | ); |
| 286 | let description = parse_sdp(&browser_offer, SdpType::Offer)?; |
| 287 | peer.set_local_description(description) |
| 288 | .await |
| 289 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 290 | let mut numbers = random_u32; |
| 291 | let mut signaled = to_teams_offer(&browser_offer, &plan, &mut numbers)?; |
| 292 | signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?; |
| 293 | Ok(OfferedMedia { |
| 294 | browser_offer, |
| 295 | signaled, |
| 296 | video, |
| 297 | plan, |
| 298 | modalities: accepted_modalities(false), |
| 299 | }) |
| 300 | } |
| 301 | |
| 302 | pub(super) struct AnsweredMedia { |
| 303 | pub(super) remote: RemoteOffer, |
| 304 | pub(super) offer_sdp: String, |
| 305 | pub(super) answer_sdp: String, |
| 306 | pub(super) camera_mid: Option<String>, |
| 307 | pub(super) receiving_share_mid: Option<String>, |
| 308 | } |
| 309 | |
| 310 | pub(super) fn main_video_mid(remote: &RemoteOffer) -> Option<String> { |
| 311 | let main: Vec<_> = remote |
| 312 | .lines |
| 313 | .iter() |
| 314 | .filter(|line| line.role == LineRole::MainVideo) |
| 315 | .filter_map(|line| line.browser_mids.first().cloned()) |
| 316 | .collect(); |
| 317 | main.iter() |
| 318 | .find(|mid| { |
| 319 | matches!( |
| 320 | direction_of(&remote.browser_sdp, mid).as_deref(), |
| 321 | Some("sendrecv" | "recvonly") |
| 322 | ) |
| 323 | }) |
| 324 | .cloned() |
| 325 | .or_else(|| main.into_iter().next()) |
| 326 | } |
| 327 | |
| 328 | pub(super) fn share_mids(remote: &RemoteOffer) -> Vec<String> { |
| 329 | remote |
| 330 | .lines |
| 331 | .iter() |
| 332 | .filter(|line| line.role == LineRole::ScreenShare) |
| 333 | .flat_map(|line| line.browser_mids.iter().cloned()) |
| 334 | .collect() |
| 335 | } |
| 336 | |
| 337 | pub(super) fn share_carrier_mid(remote: &RemoteOffer) -> Option<String> { |
| 338 | remote |
| 339 | .lines |
| 340 | .iter() |
| 341 | .find(|line| line.role == LineRole::ScreenShare) |
| 342 | .and_then(|line| line.browser_mids.last().cloned()) |
| 343 | } |
| 344 | |
| 345 | pub(super) async fn answer_offer( |
| 346 | peer: &PeerConnection, |
| 347 | track: Option<&RtcAudioTrack>, |
| 348 | teams_offer: &str, |
| 349 | video: AnswerVideo<'_>, |
| 350 | sending_share_mid: Option<String>, |
| 351 | camera_on: bool, |
| 352 | gathered: Option<&Gathered>, |
| 353 | ) -> Result<AnsweredMedia> { |
| 354 | answer_offer_with( |
| 355 | peer, |
| 356 | track, |
| 357 | teams_offer, |
| 358 | video, |
| 359 | sending_share_mid, |
| 360 | None, |
| 361 | camera_on, |
| 362 | gathered, |
| 363 | false, |
| 364 | false, |
| 365 | ) |
| 366 | .await |
| 367 | } |
| 368 | |
| 369 | #[allow(clippy::too_many_arguments)] |
| 370 | pub(super) async fn answer_offer_with( |
| 371 | peer: &PeerConnection, |
| 372 | track: Option<&RtcAudioTrack>, |
| 373 | teams_offer: &str, |
| 374 | video: AnswerVideo<'_>, |
| 375 | sending_share_mid: Option<String>, |
| 376 | share_track: Option<&RtcVideoTrack>, |
| 377 | camera_on: bool, |
| 378 | gathered: Option<&Gathered>, |
| 379 | keep_receive_slots: bool, |
| 380 | mixer: bool, |
| 381 | ) -> Result<AnsweredMedia> { |
| 382 | let remote = from_teams_offer(teams_offer)?; |
| 383 | let description = parse_sdp(&remote.browser_sdp, SdpType::Offer)?; |
| 384 | peer.set_remote_description(description) |
| 385 | .await |
| 386 | .map_err(|error| { |
| 387 | let lines: Vec<String> = remote |
| 388 | .lines |
| 389 | .iter() |
| 390 | .map(|line| format!("{:?}{:?}", line.role, line.browser_mids)) |
| 391 | .collect(); |
| 392 | Error::Webrtc(format!("{error} (offer lines: {})", lines.join(" "))) |
| 393 | })?; |
| 394 | let camera_mid = main_video_mid(&remote).filter(|_| !matches!(video, AnswerVideo::Reject)); |
| 395 | let kept_share_mids = if matches!(video, AnswerVideo::Reject) { |
| 396 | Vec::new() |
| 397 | } else { |
| 398 | share_mids(&remote) |
| 399 | }; |
| 400 | if !keep_receive_slots { |
| 401 | for transceiver in peer.transceivers() { |
| 402 | let is_video = matches!( |
| 403 | transceiver.receiver().track(), |
| 404 | Some(MediaStreamTrack::Video(_)) |
| 405 | ); |
| 406 | let unused = transceiver.mid().is_some_and(|mid| { |
| 407 | Some(&mid) != camera_mid.as_ref() |
| 408 | && !kept_share_mids.contains(&mid) |
| 409 | && Some(&mid) != sending_share_mid.as_ref() |
| 410 | }); |
| 411 | if is_video && unused { |
| 412 | let _ = transceiver.stop(); |
| 413 | } |
| 414 | } |
| 415 | } |
| 416 | if let Some(track) = track { |
| 417 | peer.add_track(MediaStreamTrack::Audio(track.clone()), &[MIC_STREAM]) |
| 418 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 419 | } |
| 420 | let sends_camera = camera_on || matches!(video, AnswerVideo::Send(_)); |
| 421 | if mixer { |
| 422 | // Keep camera sendrecv so a later set_track / updateMediaDescriptions |
| 423 | // can start sending without renegotiation. Do NOT force folded |
| 424 | // x-multi-stream share lines to sendrecv: Teams rejects that answer |
| 425 | // with SdpParsingFailure (301000); starting share upgrades the peer. |
| 426 | if let Some(mid) = camera_mid.as_deref() |
| 427 | && let Some(camera) = peer_transceiver(peer, mid) |
| 428 | { |
| 429 | let _ = camera.set_direction(RtpTransceiverDirection::SendRecv); |
| 430 | if let AnswerVideo::Send(track) = video { |
| 431 | let _ = camera |
| 432 | .sender() |
| 433 | .set_track(Some(MediaStreamTrack::Video(track.clone()))); |
| 434 | } |
| 435 | } |
| 436 | if let Some(mid) = sending_share_mid.as_deref() |
| 437 | && let Some(share) = peer_transceiver(peer, mid) |
| 438 | { |
| 439 | let _ = share.set_direction(RtpTransceiverDirection::SendRecv); |
| 440 | if let Some(track) = share_track { |
| 441 | let _ = share |
| 442 | .sender() |
| 443 | .set_track(Some(MediaStreamTrack::Video(track.clone()))); |
| 444 | } |
| 445 | } |
| 446 | } else if let (AnswerVideo::Send(camera), Some(_)) = (video, &camera_mid) { |
| 447 | peer.add_track(MediaStreamTrack::Video(camera.clone()), &[CAMERA_STREAM]) |
| 448 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 449 | } |
| 450 | let answer = peer |
| 451 | .create_answer(AnswerOptions::default()) |
| 452 | .await |
| 453 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 454 | let mut answer_text = answer.to_string(); |
| 455 | for mid in kept_share_mids |
| 456 | .iter() |
| 457 | .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) |
| 458 | { |
| 459 | answer_text = stop_sending_on(&answer_text, mid); |
| 460 | } |
| 461 | if !mixer && let Some(mid) = camera_mid.as_deref().filter(|_| !sends_camera) { |
| 462 | answer_text = stop_sending_on(&answer_text, mid); |
| 463 | } |
| 464 | peer.set_local_description(parse_sdp(&answer_text, SdpType::Answer)?) |
| 465 | .await |
| 466 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 467 | if mixer |
| 468 | && !sends_camera |
| 469 | && let Some(mid) = camera_mid.as_deref() |
| 470 | && let Some(camera) = peer_transceiver(peer, mid) |
| 471 | { |
| 472 | let _ = LocalVideo::set_sender_active(&camera.sender(), false); |
| 473 | } |
| 474 | let receiving_share_mid = share_carrier_mid(&remote) |
| 475 | .into_iter() |
| 476 | .chain(kept_share_mids) |
| 477 | .filter(|mid| sending_share_mid.as_deref() != Some(mid.as_str())) |
| 478 | .find(|mid| { |
| 479 | matches!( |
| 480 | direction_of(&answer_text, mid).as_deref(), |
| 481 | Some("recvonly" | "sendrecv") |
| 482 | ) |
| 483 | }); |
| 484 | let mut numbers = random_u32; |
| 485 | let signaled = to_teams_answer(&answer_text, &remote, &mut numbers)?; |
| 486 | Ok(AnsweredMedia { |
| 487 | remote, |
| 488 | offer_sdp: teams_offer.to_owned(), |
| 489 | answer_sdp: direct_sdp(&signaled.sdp, gathered, SdpKind::Answer).await?, |
| 490 | camera_mid, |
| 491 | receiving_share_mid, |
| 492 | }) |
| 493 | } |
| 494 | |
| 495 | pub(super) fn new_media_leg_id() -> String { |
| 496 | uuid::Uuid::new_v4().simple().to_string().to_uppercase() |
| 497 | } |
| 498 | |
| 499 | pub(super) fn peer_transceiver(peer: &PeerConnection, mid: &str) -> Option<RtpTransceiver> { |
| 500 | peer.transceivers() |
| 501 | .into_iter() |
| 502 | .find(|transceiver| transceiver.mid().as_deref() == Some(mid)) |
| 503 | } |
| 504 | |
| 505 | #[allow(clippy::too_many_arguments)] |
| 506 | pub(super) async fn offer_same_peer( |
| 507 | peer: &PeerConnection, |
| 508 | gathered: &Gathered, |
| 509 | own_share_mid: Option<String>, |
| 510 | plan: &OfferPlan, |
| 511 | layout: Layout, |
| 512 | camera_mid: &str, |
| 513 | hold: bool, |
| 514 | camera: bool, |
| 515 | share: bool, |
| 516 | remote: &RemoteCall, |
| 517 | links: &CallbackLinks, |
| 518 | media_leg_id: &str, |
| 519 | media_links: &BTreeMap<String, String>, |
| 520 | negotiator: &mut MediaNegotiator, |
| 521 | ) -> Result<(String, SignaledOffer, Vec<String>)> { |
| 522 | let direct = layout == Layout::OneToOne && negotiator.path() == MediaPath::Direct; |
| 523 | let url = media_links |
| 524 | .get("mediaRenegotiation") |
| 525 | .cloned() |
| 526 | .ok_or_else(|| Error::Signaling("this call has no mediaRenegotiation link".into()))?; |
| 527 | if !negotiator.begin_same_peer_offer() { |
| 528 | return Err(Error::Signaling( |
| 529 | "another media negotiation is running".into(), |
| 530 | )); |
| 531 | } |
| 532 | let offered = build_same_peer_offer( |
| 533 | peer, |
| 534 | plan, |
| 535 | layout, |
| 536 | hold, |
| 537 | camera, |
| 538 | share, |
| 539 | camera_mid, |
| 540 | own_share_mid, |
| 541 | direct.then_some(gathered), |
| 542 | ) |
| 543 | .await; |
| 544 | let (text, signaled) = match offered { |
| 545 | Ok(offered) => offered, |
| 546 | Err(error) => { |
| 547 | negotiator.same_peer_offer_failed(); |
| 548 | return Err(error); |
| 549 | } |
| 550 | }; |
| 551 | let modalities = offer_modalities( |
| 552 | layout == Layout::OneToOne && camera && !hold, |
| 553 | share && !hold, |
| 554 | ); |
| 555 | let body = renegotiation_body( |
| 556 | &remote.participant, |
| 557 | links, |
| 558 | &signaled.sdp, |
| 559 | media_leg_id, |
| 560 | &modalities, |
| 561 | false, |
| 562 | direct, |
| 563 | ); |
| 564 | let reply_tags = offer_reply_tags(&body); |
| 565 | if let Err(error) = remote |
| 566 | .signaling |
| 567 | .post_json("POST mediaRenegotiation (same peer)", &url, body) |
| 568 | .await |
| 569 | { |
| 570 | negotiator.same_peer_offer_failed(); |
| 571 | rollback_offer(peer).await; |
| 572 | return Err(error); |
| 573 | } |
| 574 | Ok((text, signaled, reply_tags)) |
| 575 | } |
| 576 | |
| 577 | #[allow(clippy::too_many_arguments)] |
| 578 | pub(super) async fn build_same_peer_offer( |
| 579 | peer: &PeerConnection, |
| 580 | plan: &OfferPlan, |
| 581 | layout: Layout, |
| 582 | hold: bool, |
| 583 | camera: bool, |
| 584 | share: bool, |
| 585 | camera_mid: &str, |
| 586 | own_share_mid: Option<String>, |
| 587 | gathered: Option<&Gathered>, |
| 588 | ) -> Result<(String, SignaledOffer)> { |
| 589 | let offer = peer |
| 590 | .create_offer(OfferOptions { |
| 591 | offer_to_receive_audio: true, |
| 592 | offer_to_receive_video: true, |
| 593 | ..OfferOptions::default() |
| 594 | }) |
| 595 | .await |
| 596 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 597 | let offer_text = offer.to_string(); |
| 598 | let share_mid = own_share_mid.or_else(|| share_mid_in(&offer_text)); |
| 599 | let remote_shares = share_mid.as_deref().is_some_and(|mid| { |
| 600 | peer.current_remote_description() |
| 601 | .and_then(|remote| direction_of(&remote.to_string(), mid)) |
| 602 | .is_some_and(|direction| matches!(direction.as_str(), "sendonly" | "sendrecv")) |
| 603 | }); |
| 604 | let text = directions_for( |
| 605 | layout, |
| 606 | false, |
| 607 | camera, |
| 608 | share, |
| 609 | camera_mid, |
| 610 | share_mid.as_deref(), |
| 611 | remote_shares, |
| 612 | &offer_text, |
| 613 | ); |
| 614 | let description = parse_sdp(&text, SdpType::Offer)?; |
| 615 | peer.set_local_description(description) |
| 616 | .await |
| 617 | .map_err(|error| Error::Webrtc(error.to_string()))?; |
| 618 | let mut numbers = random_u32; |
| 619 | let mut plan = plan.clone(); |
| 620 | if let Some(mid) = share_mid |
| 621 | .as_ref() |
| 622 | .filter(|mid| !plan.screen_share_mids.contains(mid)) |
| 623 | { |
| 624 | plan.screen_share_mids.push(mid.clone()); |
| 625 | } |
| 626 | let mut signaled = to_teams_offer( |
| 627 | &directions_for( |
| 628 | layout, |
| 629 | hold, |
| 630 | camera, |
| 631 | share, |
| 632 | camera_mid, |
| 633 | share_mid.as_deref(), |
| 634 | remote_shares, |
| 635 | &text, |
| 636 | ), |
| 637 | &plan, |
| 638 | &mut numbers, |
| 639 | )?; |
| 640 | signaled.sdp = direct_sdp(&signaled.sdp, gathered, SdpKind::Offer).await?; |
| 641 | if gathered.is_some() |
| 642 | && let Some(role) = negotiated_setup( |
| 643 | peer.current_local_description() |
| 644 | .map(|local| local.to_string()) |
| 645 | .as_deref(), |
| 646 | peer.current_remote_description() |
| 647 | .map(|remote| remote.to_string()) |
| 648 | .as_deref(), |
| 649 | ) |
| 650 | { |
| 651 | signaled.sdp = signaled |
| 652 | .sdp |
| 653 | .replace("a=setup:actpass", &format!("a=setup:{role}")); |
| 654 | } |
| 655 | Ok((text, signaled)) |
| 656 | } |
| 657 | |
| 658 | /// libwebrtc panics while decoding some parse errors, which used to kill the call task and leave the call hanging. |
| 659 | pub(super) fn parse_sdp(text: &str, kind: SdpType) -> Result<SessionDescription> { |
| 660 | match std::panic::catch_unwind(|| SessionDescription::parse(text, kind)) { |
| 661 | Ok(Ok(description)) => Ok(description), |
| 662 | Ok(Err(error)) => Err(Error::Sdp(format!( |
| 663 | "{kind:?} rejected: {}", |
| 664 | error.description |
| 665 | ))), |
| 666 | Err(_) => Err(Error::Sdp(format!( |
| 667 | "{kind:?} rejected, libwebrtc gave no readable reason" |
| 668 | ))), |
| 669 | } |
| 670 | } |
| 671 | |
| 672 | pub(super) async fn rollback_offer(peer: &PeerConnection) { |
| 673 | if let Ok(rollback) = parse_sdp("", SdpType::Rollback) { |
| 674 | let _ = peer.set_local_description(rollback).await; |
| 675 | } |
| 676 | } |
| 677 | |
| 678 | pub(super) async fn rollback_remote_offer(peer: &PeerConnection) { |
| 679 | if let Ok(rollback) = parse_sdp("", SdpType::Rollback) { |
| 680 | let _ = peer.set_remote_description(rollback).await; |
| 681 | } |
| 682 | } |
| 683 | |
| 684 | pub(super) fn is_glare_rejection(body: &serde_json::Value) -> bool { |
| 685 | body["mediaNegotiationFailure"]["code"].as_i64() == Some(GLARE_CODE) |
| 686 | } |
| 687 | |
| 688 | pub(super) fn offer_reply_tags(body: &serde_json::Value) -> Vec<String> { |
| 689 | let links = &body["mediaNegotiation"]["links"]; |
| 690 | ["mediaAnswer", "rejection"] |
| 691 | .iter() |
| 692 | .filter_map(|name| links[*name].as_str().and_then(callback_tag)) |
| 693 | .collect() |
| 694 | } |
| 695 | |
| 696 | #[cfg(test)] |
| 697 | mod reply_tag_tests { |
| 698 | use super::*; |
| 699 | |
| 700 | #[test] |
| 701 | fn answers_and_rejections_match_the_offer_by_tag() { |
| 702 | let tags = vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()]; |
| 703 | assert!(answers_offer( |
| 704 | "callAgent/c/aaaa1111/call/mediaAnswer/", |
| 705 | &tags |
| 706 | )); |
| 707 | assert!(answers_offer("callAgent/c/bbbb2222/call/rejection/", &tags)); |
| 708 | assert!(!answers_offer( |
| 709 | "callAgent/c/cccc3333/call/mediaAnswer/", |
| 710 | &tags |
| 711 | )); |
| 712 | assert!(answers_offer("callAgent/c/cccc3333/call/mediaAnswer/", &[])); |
| 713 | } |
| 714 | |
| 715 | #[test] |
| 716 | fn an_offer_names_both_reply_tags() { |
| 717 | let body = serde_json::json!({"mediaNegotiation": {"links": { |
| 718 | "mediaAnswer": "https://t.example/callAgent/c/aaaa1111/call/mediaAnswer/", |
| 719 | "rejection": "https://t.example/callAgent/c/bbbb2222/call/rejection/"}}}); |
| 720 | assert_eq!( |
| 721 | offer_reply_tags(&body), |
| 722 | vec!["aaaa1111".to_owned(), "bbbb2222".to_owned()] |
| 723 | ); |
| 724 | } |
| 725 | } |
| 726 | |
| 727 | pub(super) async fn apply_answer( |
| 728 | peer: &PeerConnection, |
| 729 | teams_answer: &str, |
| 730 | signaled: &SignaledOffer, |
| 731 | browser_offer: &str, |
| 732 | ) -> Result<()> { |
| 733 | let answer = to_browser_answer(teams_answer, signaled, browser_offer)?; |
| 734 | set_browser_answer(peer, &answer).await |
| 735 | } |
| 736 | |
| 737 | /// libwebrtc does not restart a send stream that an inactive answer stopped, so a hold keeps the streams and only mutes. |
| 738 | pub(super) async fn apply_hold_answer( |
| 739 | peer: &PeerConnection, |
| 740 | teams_answer: &str, |
| 741 | signaled: &SignaledOffer, |
| 742 | browser_offer: &str, |
| 743 | ) -> Result<()> { |
| 744 | let answer = to_browser_answer(teams_answer, signaled, browser_offer)?; |
| 745 | set_browser_answer(peer, &keep_media_running(&answer, browser_offer)).await |
| 746 | } |
| 747 | |
| 748 | pub(super) async fn set_browser_answer(peer: &PeerConnection, answer: &str) -> Result<()> { |
| 749 | let description = parse_sdp(answer, SdpType::Answer)?; |
| 750 | peer.set_remote_description(description) |
| 751 | .await |
| 752 | .map_err(|error| Error::Webrtc(error.to_string())) |
| 753 | } |
| 754 | |
| 755 | /// Writes an SDP with ICE credentials, fingerprints and addresses masked, for debugging the dialect. |
| 756 | pub(super) fn dump_sdp(options: &CallOptions, name: &str, sdp: &str) { |
| 757 | let Some(directory) = &options.sdp_dump_dir else { |
| 758 | return; |
| 759 | }; |
| 760 | let masked: Vec<String> = sdp |
| 761 | .lines() |
| 762 | .map(|line| { |
| 763 | for prefix in ["a=ice-ufrag:", "a=ice-pwd:", "a=fingerprint:", "a=crypto:"] { |
| 764 | if line.starts_with(prefix) { |
| 765 | return format!("{prefix}<masked>"); |
| 766 | } |
| 767 | } |
| 768 | line.split(' ') |
| 769 | .map(mask_address) |
| 770 | .collect::<Vec<_>>() |
| 771 | .join(" ") |
| 772 | }) |
| 773 | .collect(); |
| 774 | let _ = std::fs::create_dir_all(directory); |
| 775 | let _ = std::fs::write(directory.join(name), masked.join("\n")); |
| 776 | } |
| 777 | |
| 778 | pub(super) fn dump_timeline(options: &CallOptions, timeline: &Timeline, failure: Option<&Error>) { |
| 779 | let Some(directory) = &options.sdp_dump_dir else { |
| 780 | return; |
| 781 | }; |
| 782 | let mut lines: Vec<String> = timeline |
| 783 | .entries() |
| 784 | .iter() |
| 785 | .map(|entry| { |
| 786 | format!( |
| 787 | "{:>6} ms {} {}", |
| 788 | entry.elapsed_ms, entry.label, entry.detail |
| 789 | ) |
| 790 | }) |
| 791 | .collect(); |
| 792 | lines.push(match failure { |
| 793 | Some(error) => format!("failed: {error}"), |
| 794 | None => "ended without error".to_owned(), |
| 795 | }); |
| 796 | let _ = std::fs::create_dir_all(directory); |
| 797 | let _ = std::fs::write(directory.join("timeline.txt"), lines.join("\n")); |
| 798 | } |
| 799 | |
| 800 | pub(super) fn mask_address(token: &str) -> String { |
| 801 | let dotted_quad = |
| 802 | token.split('.').count() == 4 && token.split('.').all(|part| part.parse::<u8>().is_ok()); |
| 803 | let colon_address = |
| 804 | token.matches(':').count() >= 2 && !token.starts_with("a=") && !token.starts_with("urn:"); |
| 805 | if (dotted_quad && token != "10.10.10.10" && token != "0.0.0.0" && token != "127.0.0.1") |
| 806 | || colon_address |
| 807 | { |
| 808 | "<addr>".to_owned() |
| 809 | } else { |
| 810 | token.to_owned() |
| 811 | } |
| 812 | } |