fork/rust-sdks
git clone https://git.julia.blue/fork/rust-sdks
e33c5a9
main
1/* 2* Copyright 2023 LiveKit 3* 4* Licensed under the Apache License, Version 2.0 (the “License”); 5* you may not use this file except in compliance with the License. 6* You may obtain a copy of the License at 7* 8* http://www.apache.org/licenses/LICENSE-2.0 9* 10* Unless required by applicable law or agreed to in writing, software 11* distributed under the License is distributed on an “AS IS” BASIS, 12* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. 13* See the License for the specific language governing permissions and 14* limitations under the License. 15*/ 16 17#include "livekit/peer_connection.h" 18#include "livekit/peer_connection_factory.h" 19 20#include <memory> 21 22#include "api/data_channel_interface.h" 23#include "api/peer_connection_interface.h" 24#include "api/scoped_refptr.h" 25#include "livekit/data_channel.h" 26#include "livekit/jsep.h" 27#include "livekit/media_stream.h" 28#include "livekit/rtc_error.h" 29#include "livekit/rtp_transceiver.h" 30#include "rtc_base/logging.h" 31 32namespace livekit { 33 34webrtc::PeerConnectionInterface ::RTCConfiguration to_native_rtc_configuration ( 35RtcConfiguration config ) { 36 webrtc::PeerConnectionInterface ::RTCConfiguration rtc_config {}; 37 38for (auto item :config .ice_servers ) { 39 webrtc::PeerConnectionInterface ::IceServer ice_server ; 40ice_server .username = item .username .c_str (); 41ice_server .password = item .password .c_str (); 42 43for (auto url :item .urls ) 44ice_server .urls .emplace_back (url .c_str ()); 45 46rtc_config .servers .push_back (ice_server ); 47 } 48 49rtc_config .continual_gathering_policy = 50static_cast < webrtc::PeerConnectionInterface ::ContinualGatheringPolicy > ( 51config .continual_gathering_policy ); 52 53rtc_config .type = 54static_cast < webrtc::PeerConnectionInterface ::IceTransportsType > ( 55config .ice_transport_type ); 56 57return rtc_config ; 58} 59 60inline webrtc::PeerConnectionInterface ::RTCOfferAnswerOptions 61to_native_offer_answer_options (const RtcOfferAnswerOptions & options ) { 62 webrtc::PeerConnectionInterface ::RTCOfferAnswerOptions rtc_options ; 63rtc_options .offer_to_receive_video = options .offer_to_receive_video ; 64rtc_options .offer_to_receive_audio = options .offer_to_receive_audio ; 65rtc_options .voice_activity_detection = options .voice_activity_detection ; 66rtc_options .ice_restart = options .ice_restart ; 67rtc_options .use_rtp_mux = options .use_rtp_mux ; 68rtc_options .raw_packetization_for_video = options .raw_packetization_for_video ; 69rtc_options .num_simulcast_layers = options .num_simulcast_layers ; 70rtc_options .use_obsolete_sctp_sdp = options .use_obsolete_sctp_sdp ; 71return rtc_options ; 72} 73 74PeerConnection ::PeerConnection ( 75 std::shared_ptr < RtcRuntime > rtc_runtime , 76 rtc::scoped_refptr < webrtc::PeerConnectionFactoryInterface > pc_factory , 77 rust::Box < PeerConnectionObserverWrapper > observer ) 78 :rtc_runtime_ (std::move (rtc_runtime )), 79pc_factory_ (std::move (pc_factory )), 80observer_ (std::move (observer )) { 81RTC_LOG (LS_VERBOSE ) <<"PeerConnection::PeerConnection()" ; 82} 83 84PeerConnection ::~PeerConnection () { 85RTC_LOG (LS_VERBOSE ) <<"PeerConnection::~PeerConnection()" ; 86} 87 88bool PeerConnection ::Initialize ( 89 webrtc::PeerConnectionInterface ::RTCConfiguration config ) { 90 webrtc::PeerConnectionDependencies deps {this }; 91auto result = 92pc_factory_ -> CreatePeerConnectionOrError (config , std::move (deps )); 93 94if (!result .ok ()) { 95RTC_LOG (LS_ERROR ) <<"Failed to create peer connection: " 96 <<result .error ().message (); 97return false; 98 } 99peer_connection_ = std::move (result .value ()); 100return true; 101} 102 103void PeerConnection ::set_configuration (RtcConfiguration config )const { 104auto result = 105peer_connection_ -> SetConfiguration (to_native_rtc_configuration (config )); 106 107if (!result .ok ()) { 108throw std::runtime_error (serialize_error (to_error (result ))); 109 } 110} 111 112void PeerConnection ::create_offer ( 113RtcOfferAnswerOptions options , 114 rust::Box < PeerContext > ctx , 115 rust::Fn < void (rust::Box < PeerContext > , std::unique_ptr < SessionDescription > )> 116on_success , 117 rust::Fn < void (rust::Box < PeerContext > ,RtcError )> on_error )const { 118 rtc::scoped_refptr < NativeCreateSdpObserver > observer = 119 rtc::make_ref_counted < NativeCreateSdpObserver > (std::move (ctx ),on_success , 120on_error ); 121 122peer_connection_ -> CreateOffer (observer .get (), 123to_native_offer_answer_options (options )); 124} 125 126void PeerConnection ::create_answer ( 127RtcOfferAnswerOptions options , 128 rust::Box < PeerContext > ctx , 129 rust::Fn < void (rust::Box < PeerContext > , std::unique_ptr < SessionDescription > )> 130on_success , 131 rust::Fn < void (rust::Box < PeerContext > ,RtcError )> on_error )const { 132 rtc::scoped_refptr < NativeCreateSdpObserver > observer = 133 rtc::make_ref_counted < NativeCreateSdpObserver > (std::move (ctx ),on_success , 134on_error ); 135 136peer_connection_ -> CreateAnswer (observer .get (), 137to_native_offer_answer_options (options )); 138} 139 140void PeerConnection ::set_local_description ( 141 std::unique_ptr < SessionDescription > desc , 142 rust::Box < PeerContext > ctx , 143 rust::Fn < void (rust::Box < PeerContext > ,RtcError )> on_complete )const { 144 rtc::scoped_refptr < NativeSetLocalSdpObserver > observer = 145 rtc::make_ref_counted < NativeSetLocalSdpObserver > (std::move (ctx ), 146on_complete ); 147 148peer_connection_ -> SetLocalDescription (desc -> clone ()-> release (),observer ); 149} 150 151void PeerConnection ::set_remote_description ( 152 std::unique_ptr < SessionDescription > desc , 153 rust::Box < PeerContext > ctx , 154 rust::Fn < void (rust::Box < PeerContext > ,RtcError )> on_complete )const { 155 rtc::scoped_refptr < NativeSetRemoteSdpObserver > observer = 156 rtc::make_ref_counted < NativeSetRemoteSdpObserver > (std::move (ctx ), 157on_complete ); 158 159peer_connection_ -> SetRemoteDescription (desc -> clone ()-> release (),observer ); 160} 161 162void PeerConnection ::restart_ice ()const { 163peer_connection_ -> RestartIce (); 164} 165 166void PeerConnection ::add_ice_candidate ( 167 std::shared_ptr < IceCandidate > candidate , 168 rust::Box < PeerContext > ctx , 169 rust::Fn < void (rust::Box < PeerContext > ,RtcError )> on_complete )const { 170peer_connection_ -> AddIceCandidate ( 171candidate -> release (), [& ](const webrtc::RTCError & err ) { 172on_complete (std::move (ctx ),to_error (err )); 173 }); 174} 175 176std::shared_ptr < DataChannel > PeerConnection ::create_data_channel ( 177 rust::String label , 178DataChannelInit init )const { 179 webrtc::DataChannelInit rtc_init = to_native_data_channel_init (init ); 180auto result = 181peer_connection_ -> CreateDataChannelOrError (label .c_str (),& rtc_init ); 182 183if (!result .ok ()) { 184throw std::runtime_error (serialize_error (to_error (result .error ()))); 185 } 186 187return std::make_shared < DataChannel > (rtc_runtime_ ,result .value ()); 188} 189 190std::shared_ptr < RtpSender > PeerConnection ::add_track ( 191 std::shared_ptr < MediaStreamTrack > track , 192const rust::Vec < rust::String >& stream_ids )const { 193 std::vector < std::string > std_stream_ids (stream_ids .begin (),stream_ids .end ()); 194auto result = peer_connection_ -> AddTrack (track -> rtc_track (),std_stream_ids ); 195if (!result .ok ()) { 196throw std::runtime_error (serialize_error (to_error (result .error ()))); 197 } 198 199return std::make_shared < RtpSender > (rtc_runtime_ ,result .value (), 200peer_connection_ ); 201} 202 203void PeerConnection ::remove_track (std::shared_ptr < RtpSender > sender )const { 204auto error = peer_connection_ -> RemoveTrackOrError (sender -> rtc_sender ()); 205if (!error .ok ()) 206throw std::runtime_error (serialize_error (to_error (error ))); 207} 208 209void PeerConnection ::get_stats ( 210 rust::Box < PeerContext > ctx , 211 rust::Fn < void (rust::Box < PeerContext > , rust::String )> on_stats )const { 212auto observer = rtc::make_ref_counted < NativeRtcStatsCollector < PeerContext >> ( 213 std::move (ctx ),on_stats ); 214peer_connection_ -> GetStats (observer .get ()); 215} 216 217std::shared_ptr < RtpTransceiver > PeerConnection ::add_transceiver ( 218 std::shared_ptr < MediaStreamTrack > track , 219RtpTransceiverInit init )const { 220auto result = peer_connection_ -> AddTransceiver ( 221track -> rtc_track (),to_native_rtp_transceiver_init (init )); 222if (!result .ok ()) 223throw std::runtime_error (serialize_error (to_error (result .error ()))); 224 225return std::make_shared < RtpTransceiver > (rtc_runtime_ ,result .value (), 226peer_connection_ ); 227} 228 229std::shared_ptr < RtpTransceiver > PeerConnection ::add_transceiver_for_media ( 230MediaType media_type , 231RtpTransceiverInit init )const { 232auto result = peer_connection_ -> AddTransceiver ( 233static_cast < cricket::MediaType > (media_type ), 234to_native_rtp_transceiver_init (init )); 235 236if (!result .ok ()) 237throw std::runtime_error (serialize_error (to_error (result .error ()))); 238 239return std::make_shared < RtpTransceiver > (rtc_runtime_ ,result .value (), 240peer_connection_ ); 241} 242 243rust::Vec < RtpSenderPtr > PeerConnection ::get_senders ()const { 244 rust::Vec < RtpSenderPtr > vec ; 245for (auto sender :peer_connection_ -> GetSenders ()) 246vec .push_back (RtpSenderPtr { 247 std::make_shared < RtpSender > (rtc_runtime_ ,sender ,peer_connection_ )}); 248 249return vec ; 250} 251 252rust::Vec < RtpReceiverPtr > PeerConnection ::get_receivers ()const { 253 rust::Vec < RtpReceiverPtr > vec ; 254for (auto receiver :peer_connection_ -> GetReceivers ()) 255vec .push_back (RtpReceiverPtr {std::make_shared < RtpReceiver > ( 256rtc_runtime_ ,receiver ,peer_connection_ )}); 257 258return vec ; 259} 260 261rust::Vec < RtpTransceiverPtr > PeerConnection ::get_transceivers ()const { 262 rust::Vec < RtpTransceiverPtr > vec ; 263for (auto transceiver :peer_connection_ -> GetTransceivers ()) 264vec .push_back (RtpTransceiverPtr {std::make_shared < RtpTransceiver > ( 265rtc_runtime_ ,transceiver ,peer_connection_ )}); 266 267return vec ; 268} 269 270std::unique_ptr < SessionDescription > PeerConnection ::current_local_description () 271const { 272auto local_description = peer_connection_ -> current_local_description (); 273if (local_description ) 274return std::make_unique < SessionDescription > (local_description -> Clone ()); 275 276return nullptr ; 277} 278 279std::unique_ptr < SessionDescription > PeerConnection ::current_remote_description () 280const { 281auto remote_description = peer_connection_ -> current_remote_description (); 282if (remote_description ) 283return std::make_unique < SessionDescription > (remote_description -> Clone ()); 284 285return nullptr ; 286} 287 288std::unique_ptr < SessionDescription > PeerConnection ::pending_local_description () 289const { 290auto local_description = peer_connection_ -> pending_local_description (); 291if (local_description ) 292return std::make_unique < SessionDescription > (local_description -> Clone ()); 293 294return nullptr ; 295} 296 297std::unique_ptr < SessionDescription > PeerConnection ::pending_remote_description () 298const { 299auto remote_description = peer_connection_ -> pending_remote_description (); 300if (remote_description ) 301return std::make_unique < SessionDescription > (remote_description -> Clone ()); 302 303return nullptr ; 304} 305 306std::unique_ptr < SessionDescription > PeerConnection ::local_description ()const { 307auto local_description = peer_connection_ -> local_description (); 308if (local_description ) 309return std::make_unique < SessionDescription > (local_description -> Clone ()); 310 311return nullptr ; 312} 313 314std::unique_ptr < SessionDescription > PeerConnection ::remote_description ()const { 315auto remote_description = peer_connection_ -> remote_description (); 316if (remote_description ) 317return std::make_unique < SessionDescription > (remote_description -> Clone ()); 318 319return nullptr ; 320} 321 322PeerConnectionState PeerConnection ::connection_state ()const { 323return static_cast < PeerConnectionState > ( 324peer_connection_ -> peer_connection_state ()); 325} 326 327SignalingState PeerConnection ::signaling_state ()const { 328return static_cast < SignalingState > (peer_connection_ -> signaling_state ()); 329} 330 331IceGatheringState PeerConnection ::ice_gathering_state ()const { 332return static_cast < IceGatheringState > ( 333peer_connection_ -> ice_gathering_state ()); 334} 335 336IceConnectionState PeerConnection ::ice_connection_state ()const { 337return static_cast < IceConnectionState > ( 338peer_connection_ -> ice_connection_state ()); 339} 340 341void PeerConnection ::close ()const { 342peer_connection_ -> Close (); 343} 344 345// PeerConnectionObserver 346 347void PeerConnection ::OnSignalingChange ( 348 webrtc::PeerConnectionInterface ::SignalingState new_state ) { 349observer_ -> on_signaling_change (static_cast < SignalingState > (new_state )); 350} 351 352void PeerConnection ::OnAddStream ( 353 rtc::scoped_refptr < webrtc::MediaStreamInterface > stream ) { 354observer_ -> on_add_stream (std::make_unique < MediaStream > (rtc_runtime_ ,stream )); 355} 356 357void PeerConnection ::OnRemoveStream ( 358 rtc::scoped_refptr < webrtc::MediaStreamInterface > stream ) { 359// Find current MediaStream 360// observer_->on_remove_stream(std::make_unique<MediaStream>(rtc_runtime_, 361// stream)); 362} 363 364void PeerConnection ::OnDataChannel ( 365 rtc::scoped_refptr < webrtc::DataChannelInterface > data_channel ) { 366observer_ -> on_data_channel ( 367 std::make_shared < DataChannel > (rtc_runtime_ ,data_channel )); 368} 369 370void PeerConnection ::OnRenegotiationNeeded () { 371observer_ -> on_renegotiation_needed (); 372} 373 374void PeerConnection ::OnNegotiationNeededEvent (uint32_t event_id ) { 375observer_ -> on_negotiation_needed_event (event_id ); 376} 377 378void PeerConnection ::OnIceConnectionChange ( 379 webrtc::PeerConnectionInterface ::IceConnectionState new_state ) { 380observer_ -> on_ice_connection_change ( 381static_cast < IceConnectionState > (new_state )); 382} 383 384void PeerConnection ::OnStandardizedIceConnectionChange ( 385 webrtc::PeerConnectionInterface ::IceConnectionState new_state ) { 386observer_ -> on_standardized_ice_connection_change ( 387static_cast < IceConnectionState > (new_state )); 388} 389 390void PeerConnection ::OnConnectionChange ( 391 webrtc::PeerConnectionInterface ::PeerConnectionState new_state ) { 392observer_ -> on_connection_change (static_cast < PeerConnectionState > (new_state )); 393} 394 395void PeerConnection ::OnIceGatheringChange ( 396 webrtc::PeerConnectionInterface ::IceGatheringState new_state ) { 397observer_ -> on_ice_gathering_change (static_cast < IceGatheringState > (new_state )); 398} 399 400void PeerConnection ::OnIceCandidate ( 401const webrtc::IceCandidateInterface * candidate ) { 402auto new_candidate = webrtc::CreateIceCandidate (candidate -> sdp_mid (), 403candidate -> sdp_mline_index (), 404candidate -> candidate ()); 405observer_ -> on_ice_candidate ( 406 std::make_unique < IceCandidate > (std::move (new_candidate ))); 407} 408 409void PeerConnection ::OnIceCandidateError (const std::string & address , 410int port , 411const std::string & url , 412int error_code , 413const std::string & error_text ) { 414observer_ -> on_ice_candidate_error (address ,port ,url ,error_code ,error_text ); 415} 416 417void PeerConnection ::OnIceCandidatesRemoved ( 418const std::vector < cricket::Candidate >& candidates ) { 419 rust::Vec < CandidatePtr > vec ; 420 421for (const auto & item :candidates ) { 422vec .push_back (CandidatePtr {std::make_unique < Candidate > (item )}); 423 } 424 425observer_ -> on_ice_candidates_removed (std::move (vec )); 426} 427 428void PeerConnection ::OnIceConnectionReceivingChange (bool receiving ) { 429observer_ -> on_ice_connection_receiving_change (receiving ); 430} 431 432void PeerConnection ::OnIceSelectedCandidatePairChanged ( 433const cricket::CandidatePairChangeEvent & event ) { 434CandidatePairChangeEvent e {}; 435e .selected_candidate_pair .local = 436 std::make_unique < Candidate > (event .selected_candidate_pair .local ); 437e .selected_candidate_pair .remote = 438 std::make_unique < Candidate > (event .selected_candidate_pair .remote ); 439e .last_data_received_ms = event .last_data_received_ms ; 440e .reason = event .reason ; 441e .estimated_disconnected_time_ms = event .estimated_disconnected_time_ms ; 442 443observer_ -> on_ice_selected_candidate_pair_changed (std::move (e )); 444} 445 446void PeerConnection ::OnAddTrack ( 447 rtc::scoped_refptr < webrtc::RtpReceiverInterface > receiver , 448const std::vector < rtc::scoped_refptr < webrtc::MediaStreamInterface >>& 449streams ) { 450 rust::Vec < MediaStreamPtr > vec ; 451 452for (const auto & item :streams ) { 453vec .push_back ( 454MediaStreamPtr {std::make_unique < MediaStream > (rtc_runtime_ ,item )}); 455 } 456 457observer_ -> on_add_track ( 458 std::make_unique < RtpReceiver > (rtc_runtime_ ,receiver ,peer_connection_ ), 459 std::move (vec )); 460} 461 462void PeerConnection ::OnTrack ( 463 rtc::scoped_refptr < webrtc::RtpTransceiverInterface > transceiver ) { 464observer_ -> on_track (std::make_unique < RtpTransceiver > ( 465rtc_runtime_ ,transceiver ,peer_connection_ )); 466} 467 468void PeerConnection ::OnRemoveTrack ( 469 rtc::scoped_refptr < webrtc::RtpReceiverInterface > receiver ) { 470observer_ -> on_remove_track ( 471 std::make_unique < RtpReceiver > (rtc_runtime_ ,receiver ,peer_connection_ )); 472} 473 474void PeerConnection ::OnInterestingUsage (int usage_pattern ) { 475observer_ -> on_interesting_usage (usage_pattern ); 476} 477 478}// namespace livekit