BlueGit

ict rusty-teams

Files

rusty-teams / vendor / webrtc-sys / src / peer_connection_factory.cpp

peer_connection_factory.cpp

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