| 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_factory.h" |
| 18 | |
| 19 | #include <memory> |
| 20 | #include <utility> |
| 21 | #include <vector> |
| 22 | |
| 23 | #include "api/audio_codecs/builtin_audio_decoder_factory.h" |
| 24 | #include "api/audio_codecs/builtin_audio_encoder_factory.h" |
| 25 | #include "api/audio/builtin_audio_processing_builder.h" |
| 26 | #include "api/create_modular_peer_connection_factory.h" |
| 27 | #include "api/environment/environment_factory.h" |
| 28 | #include "api/field_trials_view.h" |
| 29 | #include "api/peer_connection_interface.h" |
| 30 | #include "api/rtc_error.h" |
| 31 | #include "api/enable_media.h" |
| 32 | #include "api/rtc_event_log/rtc_event_log_factory.h" |
| 33 | #include "api/task_queue/default_task_queue_factory.h" |
| 34 | #include "api/video_codecs/builtin_video_decoder_factory.h" |
| 35 | #include "api/video_codecs/builtin_video_encoder_factory.h" |
| 36 | #include "api/audio/audio_device.h" |
| 37 | #include "api/audio_options.h" |
| 38 | #include "livekit/adm_proxy.h" |
| 39 | #include "livekit/audio_track.h" |
| 40 | #include "livekit/peer_connection.h" |
| 41 | #include "livekit/rtc_error.h" |
| 42 | #include "livekit/rtp_parameters.h" |
| 43 | #include "livekit/video_decoder_factory.h" |
| 44 | #include "livekit/video_encoder_factory.h" |
| 45 | #include "livekit/webrtc.h" |
| 46 | #include "rtc_base/thread.h" |
| 47 | #include "webrtc-sys/src/peer_connection.rs.h" |
| 48 | #include "webrtc-sys/src/peer_connection_factory.rs.h" |
| 49 | |
| 50 | namespace livekit_ffi { |
| 51 | namespace { |
| 52 | |
| 53 | constexpr char kForcePlayoutDelayFieldTrial[] = |
| 54 | "WebRTC-ForcePlayoutDelay/min_ms:0,max_ms:0/"; |
| 55 | constexpr char kForcePlayoutDelayValue[] = "min_ms:0,max_ms:0"; |
| 56 | |
| 57 | class ZeroPlayoutDelayFieldTrials final : public webrtc::FieldTrialsView { |
| 58 | public: |
| 59 | std::string Lookup(absl::string_view key) const override { |
| 60 | return key == "WebRTC-ForcePlayoutDelay" ? kForcePlayoutDelayValue : ""; |
| 61 | } |
| 62 | |
| 63 | std::unique_ptr<webrtc::FieldTrialsView> CreateCopy() const override { |
| 64 | return std::make_unique<ZeroPlayoutDelayFieldTrials>(); |
| 65 | } |
| 66 | }; |
| 67 | |
| 68 | // Enables SPED (DTLS-in-STUN) via the WebRTC-IceHandshakeDtls field trial. |
| 69 | // SNAP (SCTP-INIT-in-SDP) is intentionally NOT set here: it maps to the |
| 70 | // immutable enable_sctp_snap RTCConfiguration field, so it must be carried on |
| 71 | // the RtcConfiguration (see RtcConfiguration.enable_sctp_snap) to stay |
| 72 | // consistent across create + set_configuration. Enabling it via a field trial |
| 73 | // makes set_configuration fail ("Modifying the configuration in an unsupported |
| 74 | // way"). |
| 75 | class EnableWarpFieldTrials final : public webrtc::FieldTrialsView { |
| 76 | public: |
| 77 | std::string Lookup(absl::string_view key) const override { |
| 78 | if (key == "WebRTC-IceHandshakeDtls") { |
| 79 | return "Enabled"; |
| 80 | } |
| 81 | return ""; |
| 82 | } |
| 83 | |
| 84 | std::unique_ptr<webrtc::FieldTrialsView> CreateCopy() const override { |
| 85 | return std::make_unique<EnableWarpFieldTrials>(); |
| 86 | } |
| 87 | }; |
| 88 | |
| 89 | // An Environment accepts a single FieldTrialsView, so to enable several |
| 90 | // independent trial groups (e.g. zero-playout-delay AND WARP) we combine their |
| 91 | // views into one: Lookup delegates to each sub-view and returns the first |
| 92 | // non-empty result. The groups' keys are disjoint, so ordering is irrelevant. |
| 93 | class CompositeFieldTrials final : public webrtc::FieldTrialsView { |
| 94 | public: |
| 95 | explicit CompositeFieldTrials( |
| 96 | std::vector<std::unique_ptr<webrtc::FieldTrialsView>> views) |
| 97 | : views_(std::move(views)) {} |
| 98 | |
| 99 | std::string Lookup(absl::string_view key) const override { |
| 100 | for (const auto& view : views_) { |
| 101 | std::string value = view->Lookup(key); |
| 102 | if (!value.empty()) { |
| 103 | return value; |
| 104 | } |
| 105 | } |
| 106 | return ""; |
| 107 | } |
| 108 | |
| 109 | std::unique_ptr<webrtc::FieldTrialsView> CreateCopy() const override { |
| 110 | std::vector<std::unique_ptr<webrtc::FieldTrialsView>> copies; |
| 111 | copies.reserve(views_.size()); |
| 112 | for (const auto& view : views_) { |
| 113 | copies.push_back(view->CreateCopy()); |
| 114 | } |
| 115 | return std::make_unique<CompositeFieldTrials>(std::move(copies)); |
| 116 | } |
| 117 | |
| 118 | private: |
| 119 | std::vector<std::unique_ptr<webrtc::FieldTrialsView>> views_; |
| 120 | }; |
| 121 | |
| 122 | // zero_playout_delay and enable_warp are independent and may both be enabled; |
| 123 | // their field-trial views are composed into one. |
| 124 | webrtc::Environment CreateEnvironment(bool zero_playout_delay, |
| 125 | bool enable_warp) { |
| 126 | std::vector<std::unique_ptr<webrtc::FieldTrialsView>> views; |
| 127 | if (zero_playout_delay) { |
| 128 | views.push_back(std::make_unique<ZeroPlayoutDelayFieldTrials>()); |
| 129 | } |
| 130 | if (enable_warp) { |
| 131 | views.push_back(std::make_unique<EnableWarpFieldTrials>()); |
| 132 | } |
| 133 | |
| 134 | if (views.empty()) { |
| 135 | return webrtc::CreateEnvironment(); |
| 136 | } |
| 137 | return webrtc::CreateEnvironment( |
| 138 | std::make_unique<CompositeFieldTrials>(std::move(views))); |
| 139 | } |
| 140 | |
| 141 | } // namespace |
| 142 | |
| 143 | class PeerConnectionObserver; |
| 144 | |
| 145 | PeerConnectionFactory::PeerConnectionFactory( |
| 146 | std::shared_ptr<RtcRuntime> rtc_runtime) |
| 147 | : PeerConnectionFactory(std::move(rtc_runtime), false, false) {} |
| 148 | |
| 149 | PeerConnectionFactory::PeerConnectionFactory( |
| 150 | std::shared_ptr<RtcRuntime> rtc_runtime, |
| 151 | bool zero_playout_delay) |
| 152 | : PeerConnectionFactory(std::move(rtc_runtime), zero_playout_delay, false) {} |
| 153 | |
| 154 | PeerConnectionFactory::PeerConnectionFactory( |
| 155 | std::shared_ptr<RtcRuntime> rtc_runtime, |
| 156 | bool zero_playout_delay, |
| 157 | bool enable_warp) |
| 158 | : rtc_runtime_(rtc_runtime), |
| 159 | env_(CreateEnvironment(zero_playout_delay, enable_warp)) { |
| 160 | webrtc::PeerConnectionFactoryDependencies dependencies; |
| 161 | dependencies.network_thread = rtc_runtime_->network_thread(); |
| 162 | dependencies.worker_thread = rtc_runtime_->worker_thread(); |
| 163 | dependencies.signaling_thread = rtc_runtime_->signaling_thread(); |
| 164 | dependencies.socket_factory = rtc_runtime_->network_thread()->socketserver(); |
| 165 | dependencies.event_log_factory = std::make_unique<webrtc::RtcEventLogFactory>(); |
| 166 | dependencies.env = env_; |
| 167 | |
| 168 | if (zero_playout_delay) { |
| 169 | RTC_LOG(LS_INFO) << "WebRTC zero playout delay enabled with field trial: " |
| 170 | << kForcePlayoutDelayFieldTrial; |
| 171 | } |
| 172 | |
| 173 | if (enable_warp) { |
| 174 | RTC_LOG(LS_INFO) << "WebRTC WARP: SPED enabled via field trial " |
| 175 | "WebRTC-IceHandshakeDtls/Enabled/ (SNAP via " |
| 176 | "RtcConfiguration.enable_sctp_snap)"; |
| 177 | } |
| 178 | |
| 179 | // Create AdmProxy - it creates and initializes Platform ADM internally |
| 180 | adm_proxy_ = rtc_runtime_->worker_thread()->BlockingCall([&] { |
| 181 | return webrtc::make_ref_counted<livekit_ffi::AdmProxy>( |
| 182 | env_, rtc_runtime_->worker_thread()); |
| 183 | }); |
| 184 | audio_device_ = |
| 185 | std::make_shared<AudioDeviceController>(rtc_runtime_, adm_proxy_); |
| 186 | |
| 187 | dependencies.adm = adm_proxy_; |
| 188 | |
| 189 | dependencies.video_encoder_factory = |
| 190 | std::move(std::make_unique<livekit_ffi::VideoEncoderFactory>()); |
| 191 | dependencies.video_decoder_factory = |
| 192 | std::move(std::make_unique<livekit_ffi::VideoDecoderFactory>()); |
| 193 | dependencies.audio_encoder_factory = webrtc::CreateBuiltinAudioEncoderFactory(); |
| 194 | dependencies.audio_decoder_factory = webrtc::CreateBuiltinAudioDecoderFactory(); |
| 195 | dependencies.audio_processing_builder = std::make_unique<webrtc::BuiltinAudioProcessingBuilder>(); |
| 196 | |
| 197 | webrtc::EnableMedia(dependencies); |
| 198 | peer_factory_ = |
| 199 | webrtc::CreateModularPeerConnectionFactory(std::move(dependencies)); |
| 200 | |
| 201 | if (peer_factory_.get() == nullptr) { |
| 202 | RTC_LOG_ERR(LS_ERROR) << "Failed to create PeerConnectionFactory"; |
| 203 | return; |
| 204 | } |
| 205 | } |
| 206 | |
| 207 | PeerConnectionFactory::~PeerConnectionFactory() { |
| 208 | RTC_LOG(LS_VERBOSE) << "PeerConnectionFactory::~PeerConnectionFactory()"; |
| 209 | |
| 210 | peer_factory_ = nullptr; |
| 211 | audio_device_ = nullptr; |
| 212 | rtc_runtime_->worker_thread()->BlockingCall( |
| 213 | [this] { adm_proxy_ = nullptr; }); |
| 214 | } |
| 215 | |
| 216 | std::shared_ptr<PeerConnection> PeerConnectionFactory::create_peer_connection( |
| 217 | RtcConfiguration config, |
| 218 | rust::Box<PeerConnectionObserverWrapper> observer) const { |
| 219 | std::shared_ptr<PeerConnection> pc = std::make_shared<PeerConnection>( |
| 220 | rtc_runtime_, peer_factory_, std::move(observer)); |
| 221 | |
| 222 | if (!pc->Initialize(to_native_rtc_configuration(config))) { |
| 223 | throw std::runtime_error(serialize_error(to_error(webrtc::RTCError( |
| 224 | webrtc::RTCErrorType::INTERNAL_ERROR, "failed to initialize pc")))); |
| 225 | } |
| 226 | |
| 227 | return pc; |
| 228 | } |
| 229 | |
| 230 | std::shared_ptr<VideoTrack> PeerConnectionFactory::create_video_track( |
| 231 | rust::String label, |
| 232 | std::shared_ptr<VideoTrackSource> source) const { |
| 233 | return std::static_pointer_cast<VideoTrack>( |
| 234 | rtc_runtime_->get_or_create_media_stream_track( |
| 235 | peer_factory_->CreateVideoTrack(source->get(), label.c_str()))); |
| 236 | } |
| 237 | |
| 238 | std::shared_ptr<AudioTrack> PeerConnectionFactory::create_audio_track( |
| 239 | rust::String label, |
| 240 | std::shared_ptr<AudioTrackSource> source) const { |
| 241 | return std::static_pointer_cast<AudioTrack>( |
| 242 | rtc_runtime_->get_or_create_media_stream_track( |
| 243 | peer_factory_->CreateAudioTrack(label.c_str(), source->get().get()))); |
| 244 | } |
| 245 | |
| 246 | std::shared_ptr<AudioTrack> PeerConnectionFactory::create_device_audio_track( |
| 247 | rust::String label) const { |
| 248 | // Create an audio source that uses the ADM for capture |
| 249 | webrtc::AudioOptions audio_options; |
| 250 | audio_options.echo_cancellation = true; |
| 251 | audio_options.auto_gain_control = true; |
| 252 | audio_options.noise_suppression = true; |
| 253 | |
| 254 | webrtc::scoped_refptr<webrtc::AudioSourceInterface> audio_source = |
| 255 | peer_factory_->CreateAudioSource(audio_options); |
| 256 | |
| 257 | if (!audio_source) { |
| 258 | RTC_LOG(LS_ERROR) << "Failed to create device audio source"; |
| 259 | return nullptr; |
| 260 | } |
| 261 | |
| 262 | return std::static_pointer_cast<AudioTrack>( |
| 263 | rtc_runtime_->get_or_create_media_stream_track( |
| 264 | peer_factory_->CreateAudioTrack(label.c_str(), audio_source.get()))); |
| 265 | } |
| 266 | |
| 267 | RtpCapabilities PeerConnectionFactory::rtp_sender_capabilities( |
| 268 | MediaType type) const { |
| 269 | return to_rust_rtp_capabilities(peer_factory_->GetRtpSenderCapabilities( |
| 270 | static_cast<webrtc::MediaType>(type))); |
| 271 | } |
| 272 | |
| 273 | RtpCapabilities PeerConnectionFactory::rtp_receiver_capabilities( |
| 274 | MediaType type) const { |
| 275 | return to_rust_rtp_capabilities(peer_factory_->GetRtpReceiverCapabilities( |
| 276 | static_cast<webrtc::MediaType>(type))); |
| 277 | } |
| 278 | |
| 279 | std::shared_ptr<AudioDeviceController> PeerConnectionFactory::audio_device() const { |
| 280 | return audio_device_; |
| 281 | } |
| 282 | |
| 283 | bool PeerConnectionFactory::zero_playout_delay_enabled() const { |
| 284 | return env_.field_trials().Lookup("WebRTC-ForcePlayoutDelay") == |
| 285 | kForcePlayoutDelayValue; |
| 286 | } |
| 287 | |
| 288 | std::shared_ptr<PeerConnectionFactory> create_peer_connection_factory() { |
| 289 | return std::make_shared<PeerConnectionFactory>(RtcRuntime::create()); |
| 290 | } |
| 291 | |
| 292 | std::shared_ptr<PeerConnectionFactory> |
| 293 | create_peer_connection_factory_with_zero_playout_delay() { |
| 294 | return std::make_shared<PeerConnectionFactory>(RtcRuntime::create(), true); |
| 295 | } |
| 296 | |
| 297 | std::shared_ptr<PeerConnectionFactory> |
| 298 | create_peer_connection_factory_with_options(bool zero_playout_delay, |
| 299 | bool enable_warp) { |
| 300 | return std::make_shared<PeerConnectionFactory>(RtcRuntime::create(), |
| 301 | zero_playout_delay, |
| 302 | enable_warp); |
| 303 | } |
| 304 | |
| 305 | } // namespace livekit_ffi |