fork/rust-sdks

git clone https://git.julia.blue/fork/rust-sdks

Théo Monnomfeat: stats request (#229)e33c5a9

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