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