| 1 | // Copyright 2025 LiveKit, Inc. |
| 2 | // |
| 3 | // Licensed under the Apache License, Version 2.0 (the "License"); |
| 4 | // you may not use this file except in compliance with the License. |
| 5 | // You may obtain a copy of the License at |
| 6 | // |
| 7 | // http://www.apache.org/licenses/LICENSE-2.0 |
| 8 | // |
| 9 | // Unless required by applicable law or agreed to in writing, software |
| 10 | // distributed under the License is distributed on an "AS IS" BASIS, |
| 11 | // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. |
| 12 | // See the License for the specific language governing permissions and |
| 13 | // limitations under the License. |
| 14 | |
| 15 | use std::sync::Arc; |
| 16 | |
| 17 | use cxx::SharedPtr; |
| 18 | use parking_lot::Mutex; |
| 19 | use tokio::sync::{mpsc, oneshot}; |
| 20 | use webrtc_sys::{ |
| 21 | data_channel as sys_dc, jsep as sys_jsep, peer_connection as sys_pc, |
| 22 | peer_connection_factory as sys_pcf, rtc_error as sys_err, |
| 23 | }; |
| 24 | |
| 25 | use crate::{ |
| 26 | data_channel::{DataChannel, DataChannelInit}, |
| 27 | ice_candidate::IceCandidate, |
| 28 | imp::{ |
| 29 | data_channel as imp_dc, ice_candidate as imp_ic, media_stream as imp_ms, |
| 30 | media_stream_track as imp_mst, rtp_receiver as imp_rr, rtp_sender as imp_rs, |
| 31 | rtp_transceiver as imp_rt, session_description as imp_sdp, |
| 32 | }, |
| 33 | media_stream::MediaStream, |
| 34 | media_stream_track::MediaStreamTrack, |
| 35 | peer_connection::{ |
| 36 | AnswerOptions, IceCandidateError, IceConnectionState, IceGatheringState, OfferOptions, |
| 37 | OnConnectionChange, OnDataChannel, OnIceCandidate, OnIceCandidateError, |
| 38 | OnIceConnectionChange, OnIceGatheringChange, OnNegotiationNeeded, OnSignalingChange, |
| 39 | OnTrack, PeerConnectionState, SignalingState, TrackEvent, |
| 40 | }, |
| 41 | peer_connection_factory::{ |
| 42 | ContinualGatheringPolicy, IceServer, IceTransportsType, RtcConfiguration, |
| 43 | }, |
| 44 | rtp_receiver::RtpReceiver, |
| 45 | rtp_sender::RtpSender, |
| 46 | rtp_transceiver::{RtpTransceiver, RtpTransceiverInit}, |
| 47 | session_description::SessionDescription, |
| 48 | stats::RtcStats, |
| 49 | MediaType, RtcError, RtcErrorType, |
| 50 | }; |
| 51 | |
| 52 | impl From<OfferOptions> for sys_pc::ffi::RtcOfferAnswerOptions { |
| 53 | fn from(options: OfferOptions) -> Self { |
| 54 | Self { |
| 55 | ice_restart: options.ice_restart, |
| 56 | offer_to_receive_audio: options.offer_to_receive_audio as i32, |
| 57 | offer_to_receive_video: options.offer_to_receive_video as i32, |
| 58 | ..Default::default() |
| 59 | } |
| 60 | } |
| 61 | } |
| 62 | |
| 63 | impl From<AnswerOptions> for sys_pc::ffi::RtcOfferAnswerOptions { |
| 64 | fn from(_options: AnswerOptions) -> Self { |
| 65 | Self::default() |
| 66 | } |
| 67 | } |
| 68 | |
| 69 | impl From<sys_pc::ffi::PeerConnectionState> for PeerConnectionState { |
| 70 | fn from(state: sys_pc::ffi::PeerConnectionState) -> Self { |
| 71 | match state { |
| 72 | sys_pc::ffi::PeerConnectionState::New => PeerConnectionState::New, |
| 73 | sys_pc::ffi::PeerConnectionState::Connecting => PeerConnectionState::Connecting, |
| 74 | sys_pc::ffi::PeerConnectionState::Connected => PeerConnectionState::Connected, |
| 75 | sys_pc::ffi::PeerConnectionState::Disconnected => PeerConnectionState::Disconnected, |
| 76 | sys_pc::ffi::PeerConnectionState::Failed => PeerConnectionState::Failed, |
| 77 | sys_pc::ffi::PeerConnectionState::Closed => PeerConnectionState::Closed, |
| 78 | _ => panic!("unknown PeerConnectionState"), |
| 79 | } |
| 80 | } |
| 81 | } |
| 82 | |
| 83 | impl From<sys_pc::ffi::IceConnectionState> for IceConnectionState { |
| 84 | fn from(state: sys_pc::ffi::IceConnectionState) -> Self { |
| 85 | match state { |
| 86 | sys_pc::ffi::IceConnectionState::IceConnectionNew => IceConnectionState::New, |
| 87 | sys_pc::ffi::IceConnectionState::IceConnectionChecking => IceConnectionState::Checking, |
| 88 | sys_pc::ffi::IceConnectionState::IceConnectionConnected => { |
| 89 | IceConnectionState::Connected |
| 90 | } |
| 91 | sys_pc::ffi::IceConnectionState::IceConnectionCompleted => { |
| 92 | IceConnectionState::Completed |
| 93 | } |
| 94 | sys_pc::ffi::IceConnectionState::IceConnectionFailed => IceConnectionState::Failed, |
| 95 | sys_pc::ffi::IceConnectionState::IceConnectionDisconnected => { |
| 96 | IceConnectionState::Disconnected |
| 97 | } |
| 98 | sys_pc::ffi::IceConnectionState::IceConnectionClosed => IceConnectionState::Closed, |
| 99 | sys_pc::ffi::IceConnectionState::IceConnectionMax => IceConnectionState::Max, |
| 100 | _ => panic!("unknown IceConnectionState"), |
| 101 | } |
| 102 | } |
| 103 | } |
| 104 | |
| 105 | impl From<sys_pc::ffi::IceGatheringState> for IceGatheringState { |
| 106 | fn from(state: sys_pc::ffi::IceGatheringState) -> Self { |
| 107 | match state { |
| 108 | sys_pc::ffi::IceGatheringState::IceGatheringNew => IceGatheringState::New, |
| 109 | sys_pc::ffi::IceGatheringState::IceGatheringGathering => IceGatheringState::Gathering, |
| 110 | sys_pc::ffi::IceGatheringState::IceGatheringComplete => IceGatheringState::Complete, |
| 111 | _ => panic!("unknown IceGatheringState"), |
| 112 | } |
| 113 | } |
| 114 | } |
| 115 | |
| 116 | impl From<sys_pc::ffi::SignalingState> for SignalingState { |
| 117 | fn from(state: sys_pc::ffi::SignalingState) -> Self { |
| 118 | match state { |
| 119 | sys_pc::ffi::SignalingState::Stable => SignalingState::Stable, |
| 120 | sys_pc::ffi::SignalingState::HaveLocalOffer => SignalingState::HaveLocalOffer, |
| 121 | sys_pc::ffi::SignalingState::HaveRemoteOffer => SignalingState::HaveRemoteOffer, |
| 122 | sys_pc::ffi::SignalingState::HaveLocalPrAnswer => SignalingState::HaveLocalPrAnswer, |
| 123 | sys_pc::ffi::SignalingState::HaveRemotePrAnswer => SignalingState::HaveRemotePrAnswer, |
| 124 | sys_pc::ffi::SignalingState::Closed => SignalingState::Closed, |
| 125 | _ => panic!("unknown SignalingState"), |
| 126 | } |
| 127 | } |
| 128 | } |
| 129 | |
| 130 | impl From<IceServer> for sys_pc::ffi::IceServer { |
| 131 | fn from(value: IceServer) -> Self { |
| 132 | sys_pc::ffi::IceServer { |
| 133 | urls: value.urls, |
| 134 | username: value.username, |
| 135 | password: value.password, |
| 136 | } |
| 137 | } |
| 138 | } |
| 139 | |
| 140 | impl From<ContinualGatheringPolicy> for sys_pc::ffi::ContinualGatheringPolicy { |
| 141 | fn from(value: ContinualGatheringPolicy) -> Self { |
| 142 | match value { |
| 143 | ContinualGatheringPolicy::GatherOnce => { |
| 144 | sys_pc::ffi::ContinualGatheringPolicy::GatherOnce |
| 145 | } |
| 146 | ContinualGatheringPolicy::GatherContinually => { |
| 147 | sys_pc::ffi::ContinualGatheringPolicy::GatherContinually |
| 148 | } |
| 149 | } |
| 150 | } |
| 151 | } |
| 152 | |
| 153 | impl From<IceTransportsType> for sys_pc::ffi::IceTransportsType { |
| 154 | fn from(value: IceTransportsType) -> Self { |
| 155 | match value { |
| 156 | IceTransportsType::Relay => sys_pc::ffi::IceTransportsType::Relay, |
| 157 | IceTransportsType::NoHost => sys_pc::ffi::IceTransportsType::NoHost, |
| 158 | IceTransportsType::All => sys_pc::ffi::IceTransportsType::All, |
| 159 | } |
| 160 | } |
| 161 | } |
| 162 | |
| 163 | impl From<RtcConfiguration> for sys_pc::ffi::RtcConfiguration { |
| 164 | fn from(value: RtcConfiguration) -> Self { |
| 165 | Self { |
| 166 | ice_servers: value.ice_servers.into_iter().map(Into::into).collect(), |
| 167 | continual_gathering_policy: value.continual_gathering_policy.into(), |
| 168 | ice_transport_type: value.ice_transport_type.into(), |
| 169 | enable_sctp_snap: value.enable_sctp_snap, |
| 170 | } |
| 171 | } |
| 172 | } |
| 173 | |
| 174 | #[derive(Clone)] |
| 175 | pub struct PeerConnection { |
| 176 | observer: Arc<PeerObserver>, |
| 177 | pub(crate) sys_handle: SharedPtr<sys_pc::ffi::PeerConnection>, |
| 178 | } |
| 179 | |
| 180 | impl PeerConnection { |
| 181 | pub fn configure( |
| 182 | sys_handle: SharedPtr<sys_pc::ffi::PeerConnection>, |
| 183 | observer: Arc<PeerObserver>, |
| 184 | ) -> Self { |
| 185 | Self { sys_handle, observer } |
| 186 | } |
| 187 | |
| 188 | pub fn set_configuration(&self, config: RtcConfiguration) -> Result<(), RtcError> { |
| 189 | let res = self.sys_handle.set_configuration(config.into()); |
| 190 | |
| 191 | match res { |
| 192 | Ok(_) => Ok(()), |
| 193 | Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) }, |
| 194 | } |
| 195 | } |
| 196 | |
| 197 | pub async fn create_offer( |
| 198 | &self, |
| 199 | options: OfferOptions, |
| 200 | ) -> Result<SessionDescription, RtcError> { |
| 201 | let (tx, mut rx) = mpsc::channel::<Result<SessionDescription, RtcError>>(1); |
| 202 | let ctx = Box::new(sys_pc::PeerContext(Box::new(tx))); |
| 203 | type CtxType = mpsc::Sender<Result<SessionDescription, RtcError>>; |
| 204 | |
| 205 | self.sys_handle.create_offer( |
| 206 | options.into(), |
| 207 | ctx, |
| 208 | |ctx, sdp| { |
| 209 | let tx = *ctx.0.downcast::<CtxType>().unwrap(); |
| 210 | let _ = tx.blocking_send(Ok(SessionDescription { |
| 211 | handle: imp_sdp::SessionDescription { sys_handle: sdp }, |
| 212 | })); |
| 213 | }, |
| 214 | |ctx, error| { |
| 215 | let tx = *ctx.0.downcast::<CtxType>().unwrap(); |
| 216 | let _ = tx.blocking_send(Err(error.into())); |
| 217 | }, |
| 218 | ); |
| 219 | |
| 220 | rx.recv().await.unwrap() |
| 221 | } |
| 222 | |
| 223 | pub async fn create_answer( |
| 224 | &self, |
| 225 | options: AnswerOptions, |
| 226 | ) -> Result<SessionDescription, RtcError> { |
| 227 | let (tx, mut rx) = mpsc::channel::<Result<SessionDescription, RtcError>>(1); |
| 228 | let ctx = Box::new(sys_pc::PeerContext(Box::new(tx))); |
| 229 | type CtxType = mpsc::Sender<Result<SessionDescription, RtcError>>; |
| 230 | |
| 231 | self.sys_handle.create_answer( |
| 232 | options.into(), |
| 233 | ctx, |
| 234 | |ctx, sdp| { |
| 235 | let tx = *ctx.0.downcast::<CtxType>().unwrap(); |
| 236 | let _ = tx.blocking_send(Ok(SessionDescription { |
| 237 | handle: imp_sdp::SessionDescription { sys_handle: sdp }, |
| 238 | })); |
| 239 | }, |
| 240 | |ctx, error| { |
| 241 | let tx = *ctx.0.downcast::<CtxType>().unwrap(); |
| 242 | let _ = tx.blocking_send(Err(error.into())); |
| 243 | }, |
| 244 | ); |
| 245 | |
| 246 | rx.recv().await.unwrap() |
| 247 | } |
| 248 | |
| 249 | pub async fn set_local_description(&self, desc: SessionDescription) -> Result<(), RtcError> { |
| 250 | let (tx, rx) = oneshot::channel::<Result<(), RtcError>>(); |
| 251 | let ctx = Box::new(sys_pc::PeerContext(Box::new(tx))); |
| 252 | |
| 253 | self.sys_handle.set_local_description(desc.handle.sys_handle, ctx, |ctx, err| { |
| 254 | let tx = ctx.0.downcast::<oneshot::Sender<Result<(), RtcError>>>().unwrap(); |
| 255 | |
| 256 | if err.ok() { |
| 257 | let _ = tx.send(Ok(())); |
| 258 | } else { |
| 259 | let _ = tx.send(Err(err.into())); |
| 260 | } |
| 261 | }); |
| 262 | |
| 263 | rx.await.unwrap() |
| 264 | } |
| 265 | |
| 266 | pub async fn set_remote_description(&self, desc: SessionDescription) -> Result<(), RtcError> { |
| 267 | let (tx, rx) = oneshot::channel::<Result<(), RtcError>>(); |
| 268 | let ctx = Box::new(sys_pc::PeerContext(Box::new(tx))); |
| 269 | |
| 270 | self.sys_handle.set_remote_description(desc.handle.sys_handle, ctx, |ctx, err| { |
| 271 | let tx = ctx.0.downcast::<oneshot::Sender<Result<(), RtcError>>>().unwrap(); |
| 272 | |
| 273 | if err.ok() { |
| 274 | let _ = tx.send(Ok(())); |
| 275 | } else { |
| 276 | let _ = tx.send(Err(err.into())); |
| 277 | } |
| 278 | }); |
| 279 | |
| 280 | rx.await.map_err(|_| RtcError { |
| 281 | error_type: RtcErrorType::Internal, |
| 282 | message: "set_remote_description cancelled".to_owned(), |
| 283 | })? |
| 284 | } |
| 285 | |
| 286 | pub async fn add_ice_candidate(&self, candidate: IceCandidate) -> Result<(), RtcError> { |
| 287 | let (tx, rx) = oneshot::channel::<Result<(), RtcError>>(); |
| 288 | let ctx = Box::new(sys_pc::PeerContext(Box::new(tx))); |
| 289 | |
| 290 | self.sys_handle.add_ice_candidate(candidate.handle.sys_handle, ctx, |ctx, err| { |
| 291 | let tx = ctx.0.downcast::<oneshot::Sender<Result<(), RtcError>>>().unwrap(); |
| 292 | |
| 293 | if err.ok() { |
| 294 | let _ = tx.send(Ok(())); |
| 295 | } else { |
| 296 | let _ = tx.send(Err(err.into())); |
| 297 | } |
| 298 | }); |
| 299 | |
| 300 | rx.await.map_err(|_| RtcError { |
| 301 | error_type: RtcErrorType::Internal, |
| 302 | message: "add_ice_candidate cancelled".to_owned(), |
| 303 | })? |
| 304 | } |
| 305 | |
| 306 | pub fn create_data_channel( |
| 307 | &self, |
| 308 | label: &str, |
| 309 | init: DataChannelInit, |
| 310 | ) -> Result<DataChannel, RtcError> { |
| 311 | let res = self.sys_handle.create_data_channel(label.to_string(), init.into()); |
| 312 | |
| 313 | match res { |
| 314 | Ok(sys_handle) => { |
| 315 | Ok(DataChannel { handle: imp_dc::DataChannel::configure(sys_handle) }) |
| 316 | } |
| 317 | Err(e) => Err(unsafe { sys_err::ffi::RtcError::from(e.what()).into() }), |
| 318 | } |
| 319 | } |
| 320 | |
| 321 | pub fn add_track<T: AsRef<str>>( |
| 322 | &self, |
| 323 | track: MediaStreamTrack, |
| 324 | stream_ids: &[T], |
| 325 | ) -> Result<RtpSender, RtcError> { |
| 326 | let stream_ids = stream_ids.iter().map(|s| s.as_ref().to_owned()).collect(); |
| 327 | let res = self.sys_handle.add_track(track.sys_handle(), &stream_ids); |
| 328 | |
| 329 | match res { |
| 330 | Ok(sys_handle) => Ok(RtpSender { handle: imp_rs::RtpSender { sys_handle } }), |
| 331 | Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) }, |
| 332 | } |
| 333 | } |
| 334 | |
| 335 | pub fn add_transceiver( |
| 336 | &self, |
| 337 | track: MediaStreamTrack, |
| 338 | init: RtpTransceiverInit, |
| 339 | ) -> Result<RtpTransceiver, RtcError> { |
| 340 | let res = self.sys_handle.add_transceiver(track.sys_handle(), init.into()); |
| 341 | |
| 342 | match res { |
| 343 | Ok(sys_handle) => Ok(RtpTransceiver { handle: imp_rt::RtpTransceiver { sys_handle } }), |
| 344 | Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) }, |
| 345 | } |
| 346 | } |
| 347 | |
| 348 | pub fn add_transceiver_for_media( |
| 349 | &self, |
| 350 | media_type: MediaType, |
| 351 | init: RtpTransceiverInit, |
| 352 | ) -> Result<RtpTransceiver, RtcError> { |
| 353 | let res = self.sys_handle.add_transceiver_for_media(media_type.into(), init.into()); |
| 354 | |
| 355 | match res { |
| 356 | Ok(cxx_handle) => { |
| 357 | Ok(RtpTransceiver { handle: imp_rt::RtpTransceiver { sys_handle: cxx_handle } }) |
| 358 | } |
| 359 | Err(e) => unsafe { Err(sys_err::ffi::RtcError::from(e.what()).into()) }, |
| 360 | } |
| 361 | } |
| 362 | |
| 363 | pub fn restart_ice(&self) { |
| 364 | self.sys_handle.restart_ice(); |
| 365 | } |
| 366 | |
| 367 | pub fn close(&self) { |
| 368 | self.sys_handle.close(); |
| 369 | } |
| 370 | |
| 371 | pub fn connection_state(&self) -> PeerConnectionState { |
| 372 | self.sys_handle.connection_state().into() |
| 373 | } |
| 374 | |
| 375 | pub fn ice_connection_state(&self) -> IceConnectionState { |
| 376 | self.sys_handle.ice_connection_state().into() |
| 377 | } |
| 378 | |
| 379 | pub fn ice_gathering_state(&self) -> IceGatheringState { |
| 380 | self.sys_handle.ice_gathering_state().into() |
| 381 | } |
| 382 | |
| 383 | pub fn signaling_state(&self) -> SignalingState { |
| 384 | self.sys_handle.signaling_state().into() |
| 385 | } |
| 386 | |
| 387 | pub fn current_local_description(&self) -> Option<SessionDescription> { |
| 388 | let sdp = self.sys_handle.current_local_description(); |
| 389 | if sdp.is_null() { |
| 390 | return None; |
| 391 | } |
| 392 | |
| 393 | Some(SessionDescription { handle: imp_sdp::SessionDescription { sys_handle: sdp } }) |
| 394 | } |
| 395 | |
| 396 | pub fn current_remote_description(&self) -> Option<SessionDescription> { |
| 397 | let sdp = self.sys_handle.current_remote_description(); |
| 398 | if sdp.is_null() { |
| 399 | return None; |
| 400 | } |
| 401 | |
| 402 | Some(SessionDescription { handle: imp_sdp::SessionDescription { sys_handle: sdp } }) |
| 403 | } |
| 404 | |
| 405 | pub fn remove_track(&self, sender: RtpSender) -> Result<(), RtcError> { |
| 406 | self.sys_handle |
| 407 | .remove_track(sender.handle.sys_handle) |
| 408 | .map_err(|e| unsafe { sys_err::ffi::RtcError::from(e.what()).into() }) |
| 409 | } |
| 410 | |
| 411 | pub async fn get_stats(&self) -> Result<Vec<RtcStats>, RtcError> { |
| 412 | let (tx, rx) = oneshot::channel::<Result<Vec<RtcStats>, RtcError>>(); |
| 413 | let ctx = Box::new(sys_pc::PeerContext(Box::new(tx))); |
| 414 | |
| 415 | self.sys_handle.get_stats(ctx, |ctx, stats| { |
| 416 | let tx = ctx.0.downcast::<oneshot::Sender<Result<Vec<RtcStats>, RtcError>>>().unwrap(); |
| 417 | |
| 418 | if stats.is_empty() { |
| 419 | let _ = tx.send(Ok(vec![])); |
| 420 | return; |
| 421 | } |
| 422 | |
| 423 | // Unwrap because it should not happens |
| 424 | let vec = serde_json::from_str(&stats).unwrap(); |
| 425 | let _ = tx.send(Ok(vec)); |
| 426 | }); |
| 427 | |
| 428 | rx.await.map_err(|_| RtcError { |
| 429 | error_type: RtcErrorType::Internal, |
| 430 | message: "get_stats cancelled".to_owned(), |
| 431 | })? |
| 432 | } |
| 433 | |
| 434 | pub fn senders(&self) -> Vec<RtpSender> { |
| 435 | self.sys_handle |
| 436 | .get_senders() |
| 437 | .into_iter() |
| 438 | .map(|sender| RtpSender { handle: imp_rs::RtpSender { sys_handle: sender.ptr } }) |
| 439 | .collect() |
| 440 | } |
| 441 | |
| 442 | pub fn receivers(&self) -> Vec<RtpReceiver> { |
| 443 | self.sys_handle |
| 444 | .get_receivers() |
| 445 | .into_iter() |
| 446 | .map(|receiver| RtpReceiver { |
| 447 | handle: imp_rr::RtpReceiver { sys_handle: receiver.ptr }, |
| 448 | }) |
| 449 | .collect() |
| 450 | } |
| 451 | |
| 452 | pub fn transceivers(&self) -> Vec<RtpTransceiver> { |
| 453 | self.sys_handle |
| 454 | .get_transceivers() |
| 455 | .into_iter() |
| 456 | .map(|transceiver| RtpTransceiver { |
| 457 | handle: imp_rt::RtpTransceiver { sys_handle: transceiver.ptr }, |
| 458 | }) |
| 459 | .collect() |
| 460 | } |
| 461 | |
| 462 | pub fn on_connection_state_change(&self, f: Option<OnConnectionChange>) { |
| 463 | *self.observer.connection_change_handler.lock() = f; |
| 464 | } |
| 465 | |
| 466 | pub fn on_data_channel(&self, f: Option<OnDataChannel>) { |
| 467 | *self.observer.data_channel_handler.lock() = f; |
| 468 | } |
| 469 | |
| 470 | pub fn on_ice_candidate(&self, f: Option<OnIceCandidate>) { |
| 471 | *self.observer.ice_candidate_handler.lock() = f; |
| 472 | } |
| 473 | |
| 474 | pub fn on_ice_candidate_error(&self, f: Option<OnIceCandidateError>) { |
| 475 | *self.observer.ice_candidate_error_handler.lock() = f; |
| 476 | } |
| 477 | |
| 478 | pub fn on_ice_connection_state_change(&self, f: Option<OnIceConnectionChange>) { |
| 479 | *self.observer.ice_connection_change_handler.lock() = f; |
| 480 | } |
| 481 | |
| 482 | pub fn on_ice_gathering_state_change(&self, f: Option<OnIceGatheringChange>) { |
| 483 | *self.observer.ice_gathering_change_handler.lock() = f; |
| 484 | } |
| 485 | |
| 486 | pub fn on_negotiation_needed(&self, f: Option<OnNegotiationNeeded>) { |
| 487 | *self.observer.negotiation_needed_handler.lock() = f; |
| 488 | } |
| 489 | |
| 490 | pub fn on_signaling_state_change(&self, f: Option<OnSignalingChange>) { |
| 491 | *self.observer.signaling_change_handler.lock() = f; |
| 492 | } |
| 493 | |
| 494 | pub fn on_track(&self, f: Option<OnTrack>) { |
| 495 | *self.observer.track_handler.lock() = f; |
| 496 | } |
| 497 | } |
| 498 | |
| 499 | #[derive(Default)] |
| 500 | pub struct PeerObserver { |
| 501 | pub connection_change_handler: Mutex<Option<OnConnectionChange>>, |
| 502 | pub data_channel_handler: Mutex<Option<OnDataChannel>>, |
| 503 | pub ice_candidate_handler: Mutex<Option<OnIceCandidate>>, |
| 504 | pub ice_candidate_error_handler: Mutex<Option<OnIceCandidateError>>, |
| 505 | pub ice_connection_change_handler: Mutex<Option<OnIceConnectionChange>>, |
| 506 | pub ice_gathering_change_handler: Mutex<Option<OnIceGatheringChange>>, |
| 507 | pub negotiation_needed_handler: Mutex<Option<OnNegotiationNeeded>>, |
| 508 | pub signaling_change_handler: Mutex<Option<OnSignalingChange>>, |
| 509 | pub track_handler: Mutex<Option<OnTrack>>, |
| 510 | } |
| 511 | |
| 512 | impl sys_pcf::PeerConnectionObserver for PeerObserver { |
| 513 | fn on_signaling_change(&self, new_state: sys_pc::ffi::SignalingState) { |
| 514 | if let Some(f) = self.signaling_change_handler.lock().as_mut() { |
| 515 | f(new_state.into()); |
| 516 | } |
| 517 | } |
| 518 | |
| 519 | fn on_add_stream(&self, _stream: SharedPtr<webrtc_sys::media_stream::ffi::MediaStream>) {} |
| 520 | |
| 521 | fn on_remove_stream(&self, _stream: SharedPtr<webrtc_sys::media_stream::ffi::MediaStream>) {} |
| 522 | |
| 523 | fn on_data_channel(&self, data_channel: SharedPtr<sys_dc::ffi::DataChannel>) { |
| 524 | if let Some(f) = self.data_channel_handler.lock().as_mut() { |
| 525 | f(DataChannel { handle: imp_dc::DataChannel::configure(data_channel) }); |
| 526 | } |
| 527 | } |
| 528 | |
| 529 | fn on_renegotiation_needed(&self) {} |
| 530 | |
| 531 | fn on_negotiation_needed_event(&self, event: u32) { |
| 532 | if let Some(f) = self.negotiation_needed_handler.lock().as_mut() { |
| 533 | f(event); |
| 534 | } |
| 535 | } |
| 536 | |
| 537 | fn on_ice_connection_change(&self, _new_state: sys_pc::ffi::IceConnectionState) {} |
| 538 | |
| 539 | fn on_standardized_ice_connection_change(&self, new_state: sys_pc::ffi::IceConnectionState) { |
| 540 | if let Some(f) = self.ice_connection_change_handler.lock().as_mut() { |
| 541 | f(new_state.into()); |
| 542 | } |
| 543 | } |
| 544 | |
| 545 | fn on_connection_change(&self, new_state: sys_pc::ffi::PeerConnectionState) { |
| 546 | if let Some(f) = self.connection_change_handler.lock().as_mut() { |
| 547 | f(new_state.into()); |
| 548 | } |
| 549 | } |
| 550 | |
| 551 | fn on_ice_gathering_change(&self, new_state: sys_pc::ffi::IceGatheringState) { |
| 552 | if let Some(f) = self.ice_gathering_change_handler.lock().as_mut() { |
| 553 | f(new_state.into()); |
| 554 | } |
| 555 | } |
| 556 | |
| 557 | fn on_ice_candidate(&self, candidate: SharedPtr<sys_jsep::ffi::IceCandidate>) { |
| 558 | if let Some(f) = self.ice_candidate_handler.lock().as_mut() { |
| 559 | f(IceCandidate { handle: imp_ic::IceCandidate { sys_handle: candidate } }); |
| 560 | } |
| 561 | } |
| 562 | |
| 563 | fn on_ice_candidate_error( |
| 564 | &self, |
| 565 | address: String, |
| 566 | port: i32, |
| 567 | url: String, |
| 568 | error_code: i32, |
| 569 | error_text: String, |
| 570 | ) { |
| 571 | if let Some(f) = self.ice_candidate_error_handler.lock().as_mut() { |
| 572 | f(IceCandidateError { address, port, url, error_code, error_text }); |
| 573 | } |
| 574 | } |
| 575 | |
| 576 | fn on_ice_candidates_removed( |
| 577 | &self, |
| 578 | _removed: Vec<SharedPtr<webrtc_sys::candidate::ffi::Candidate>>, |
| 579 | ) { |
| 580 | } |
| 581 | |
| 582 | fn on_ice_connection_receiving_change(&self, _receiving: bool) {} |
| 583 | |
| 584 | fn on_ice_selected_candidate_pair_changed( |
| 585 | &self, |
| 586 | _event: sys_pcf::ffi::CandidatePairChangeEvent, |
| 587 | ) { |
| 588 | } |
| 589 | |
| 590 | fn on_add_track( |
| 591 | &self, |
| 592 | _receiver: SharedPtr<webrtc_sys::rtp_receiver::ffi::RtpReceiver>, |
| 593 | _streams: Vec<SharedPtr<webrtc_sys::media_stream::ffi::MediaStream>>, |
| 594 | ) { |
| 595 | } |
| 596 | |
| 597 | fn on_track(&self, transceiver: SharedPtr<webrtc_sys::rtp_transceiver::ffi::RtpTransceiver>) { |
| 598 | if let Some(f) = self.track_handler.lock().as_mut() { |
| 599 | let receiver = transceiver.receiver(); |
| 600 | let streams = receiver.streams(); |
| 601 | let track = receiver.track(); |
| 602 | |
| 603 | f(TrackEvent { |
| 604 | receiver: RtpReceiver { handle: imp_rr::RtpReceiver { sys_handle: receiver } }, |
| 605 | streams: streams |
| 606 | .into_iter() |
| 607 | .map(|s| MediaStream { handle: imp_ms::MediaStream { sys_handle: s.ptr } }) |
| 608 | .collect(), |
| 609 | track: imp_mst::new_media_stream_track(track), |
| 610 | transceiver: RtpTransceiver { |
| 611 | handle: imp_rt::RtpTransceiver { sys_handle: transceiver }, |
| 612 | }, |
| 613 | }); |
| 614 | } |
| 615 | } |
| 616 | |
| 617 | fn on_remove_track(&self, _receiver: SharedPtr<webrtc_sys::rtp_receiver::ffi::RtpReceiver>) {} |
| 618 | |
| 619 | fn on_interesting_usage(&self, _usage_pattern: i32) {} |
| 620 | } |