blob: b232a26b818d6afe5f8fb02d051cf0ffc20b7dcb [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
kwiberg0eb15ed2015-12-17 03:04:15 -080014#include <utility>
15#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000016
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020017#include "api/jsepicecandidate.h"
18#include "api/jsepsessiondescription.h"
19#include "api/mediaconstraintsinterface.h"
20#include "api/mediastreamproxy.h"
21#include "api/mediastreamtrackproxy.h"
22#include "call/call.h"
23#include "logging/rtc_event_log/rtc_event_log.h"
24#include "media/sctp/sctptransport.h"
25#include "pc/audiotrack.h"
26#include "pc/channelmanager.h"
27#include "pc/dtmfsender.h"
28#include "pc/mediastream.h"
29#include "pc/mediastreamobserver.h"
30#include "pc/remoteaudiosource.h"
31#include "pc/rtpreceiver.h"
32#include "pc/rtpsender.h"
33#include "pc/streamcollection.h"
34#include "pc/videocapturertracksource.h"
35#include "pc/videotrack.h"
36#include "rtc_base/bind.h"
37#include "rtc_base/checks.h"
38#include "rtc_base/logging.h"
39#include "rtc_base/stringencode.h"
40#include "rtc_base/stringutils.h"
41#include "rtc_base/trace_event.h"
42#include "system_wrappers/include/clock.h"
43#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000044
45namespace {
46
deadbeefab9b2d12015-10-14 11:33:11 -070047using webrtc::DataChannel;
48using webrtc::MediaConstraintsInterface;
49using webrtc::MediaStreamInterface;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050using webrtc::PeerConnectionInterface;
deadbeef293e9262017-01-11 12:28:30 -080051using webrtc::RTCError;
52using webrtc::RTCErrorType;
deadbeefa601f5c2016-06-06 14:27:39 -070053using webrtc::RtpSenderInternal;
deadbeeffac06552015-11-25 11:26:01 -080054using webrtc::RtpSenderInterface;
deadbeefa601f5c2016-06-06 14:27:39 -070055using webrtc::RtpSenderProxy;
56using webrtc::RtpSenderProxyWithInternal;
deadbeefab9b2d12015-10-14 11:33:11 -070057using webrtc::StreamCollection;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000058
deadbeefab9b2d12015-10-14 11:33:11 -070059static const char kDefaultStreamLabel[] = "default";
60static const char kDefaultAudioTrackLabel[] = "defaulta0";
61static const char kDefaultVideoTrackLabel[] = "defaultv0";
62
zhihuang8f65cdf2016-05-06 18:40:30 -070063// The length of RTCP CNAMEs.
64static const int kRtcpCnameLength = 16;
65
henrike@webrtc.org28e20752013-07-10 00:45:36 +000066enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +000067 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000068 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -070069 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000070 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -080071 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +000072};
73
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000074struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000075 explicit SetSessionDescriptionMsg(
76 webrtc::SetSessionDescriptionObserver* observer)
77 : observer(observer) {
78 }
79
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000080 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +000081 std::string error;
82};
83
deadbeefab9b2d12015-10-14 11:33:11 -070084struct CreateSessionDescriptionMsg : public rtc::MessageData {
85 explicit CreateSessionDescriptionMsg(
86 webrtc::CreateSessionDescriptionObserver* observer)
87 : observer(observer) {}
88
89 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
90 std::string error;
91};
92
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000093struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +000094 GetStatsMsg(webrtc::StatsObserver* observer,
95 webrtc::MediaStreamTrackInterface* track)
96 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000097 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +000098 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +000099 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100};
101
deadbeefab9b2d12015-10-14 11:33:11 -0700102// Check if we can send |new_stream| on a PeerConnection.
103bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
104 webrtc::MediaStreamInterface* new_stream) {
105 if (!new_stream || !current_streams) {
106 return false;
107 }
108 if (current_streams->find(new_stream->label()) != nullptr) {
109 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
110 << " is already added.";
111 return false;
112 }
113 return true;
114}
115
116bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
117 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
118}
119
deadbeef5e97fb52015-10-15 12:49:08 -0700120// If the direction is "recvonly" or "inactive", treat the description
121// as containing no streams.
122// See: https://code.google.com/p/webrtc/issues/detail?id=5054
123std::vector<cricket::StreamParams> GetActiveStreams(
124 const cricket::MediaContentDescription* desc) {
125 return MediaContentDirectionHasSend(desc->direction())
126 ? desc->streams()
127 : std::vector<cricket::StreamParams>();
128}
129
deadbeefab9b2d12015-10-14 11:33:11 -0700130bool IsValidOfferToReceiveMedia(int value) {
131 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
132 return (value >= Options::kUndefined) &&
133 (value <= Options::kMaxOfferToReceiveMedia);
134}
135
zhihuang1c378ed2017-08-17 14:10:50 -0700136// Add options to |[audio/video]_media_description_options| from |senders|.
137void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700138 const std::vector<rtc::scoped_refptr<
139 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700140 cricket::MediaDescriptionOptions* audio_media_description_options,
141 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700142 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700143 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
144 if (audio_media_description_options) {
145 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700146 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700147 }
148 } else {
149 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
150 if (video_media_description_options) {
151 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700152 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700153 }
154 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700155 }
zhihuang1c378ed2017-08-17 14:10:50 -0700156}
olka3c747662017-08-17 06:50:32 -0700157
zhihuang1c378ed2017-08-17 14:10:50 -0700158// Add options to |session_options| from |rtp_data_channels|.
159void AddRtpDataChannelOptions(
160 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
161 rtp_data_channels,
162 cricket::MediaDescriptionOptions* data_media_description_options) {
163 if (!data_media_description_options) {
164 return;
165 }
deadbeefab9b2d12015-10-14 11:33:11 -0700166 // Check for data channels.
167 for (const auto& kv : rtp_data_channels) {
168 const DataChannel* channel = kv.second;
169 if (channel->state() == DataChannel::kConnecting ||
170 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700171 // Legacy RTP data channels are signaled with the track/stream ID set to
172 // the data channel's label.
173 data_media_description_options->AddRtpDataChannel(channel->label(),
174 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700175 }
176 }
177}
178
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700179uint32_t ConvertIceTransportTypeToCandidateFilter(
180 PeerConnectionInterface::IceTransportsType type) {
181 switch (type) {
182 case PeerConnectionInterface::kNone:
183 return cricket::CF_NONE;
184 case PeerConnectionInterface::kRelay:
185 return cricket::CF_RELAY;
186 case PeerConnectionInterface::kNoHost:
187 return (cricket::CF_ALL & ~cricket::CF_HOST);
188 case PeerConnectionInterface::kAll:
189 return cricket::CF_ALL;
190 default:
nissec80e7412017-01-11 05:56:46 -0800191 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700192 }
193 return cricket::CF_NONE;
194}
195
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700196// Helper method to set a voice/video channel on all applicable senders
197// and receivers when one is created/destroyed by WebRtcSession.
198//
199// Used by On(Voice|Video)Channel(Created|Destroyed)
200template <class SENDER,
201 class RECEIVER,
202 class CHANNEL,
203 class SENDERS,
204 class RECEIVERS>
205void SetChannelOnSendersAndReceivers(CHANNEL* channel,
206 SENDERS& senders,
207 RECEIVERS& receivers,
208 cricket::MediaType media_type) {
209 for (auto& sender : senders) {
210 if (sender->media_type() == media_type) {
211 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
212 }
213 }
214 for (auto& receiver : receivers) {
215 if (receiver->media_type() == media_type) {
216 if (!channel) {
217 receiver->internal()->Stop();
218 }
219 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
220 }
221 }
222}
223
deadbeef293e9262017-01-11 12:28:30 -0800224// Helper to set an error and return from a method.
225bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
226 if (error) {
227 error->set_type(type);
228 }
229 return type == webrtc::RTCErrorType::NONE;
230}
231
Steve Anton038834f2017-07-14 15:59:59 -0700232bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
233 if (error_out) {
234 *error_out = std::move(error);
235 }
236 return error.ok();
237}
238
deadbeef0a6c4ca2015-10-06 11:38:28 -0700239} // namespace
240
241namespace webrtc {
242
deadbeef293e9262017-01-11 12:28:30 -0800243bool PeerConnectionInterface::RTCConfiguration::operator==(
244 const PeerConnectionInterface::RTCConfiguration& o) const {
245 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700246 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800247 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000248 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700249 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800250 BundlePolicy bundle_policy;
251 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700252 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
253 int ice_candidate_pool_size;
254 bool disable_ipv6;
255 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700256 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700257 bool enable_rtp_data_channel;
258 rtc::Optional<int> screencast_min_bitrate;
259 rtc::Optional<bool> combined_audio_video_bwe;
260 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800261 TcpCandidatePolicy tcp_candidate_policy;
262 CandidateNetworkPolicy candidate_network_policy;
263 int audio_jitter_buffer_max_packets;
264 bool audio_jitter_buffer_fast_accelerate;
265 int ice_connection_receiving_timeout;
266 int ice_backup_candidate_pair_ping_interval;
267 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800268 bool prioritize_most_likely_ice_candidate_pairs;
269 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800270 bool enable_quic;
deadbeef293e9262017-01-11 12:28:30 -0800271 bool prune_turn_ports;
272 bool presume_writable_when_fully_relayed;
273 bool enable_ice_renomination;
274 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800275 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700276 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800277 };
278 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
279 "Did you add something to RTCConfiguration and forget to "
280 "update operator==?");
281 return type == o.type && servers == o.servers &&
282 bundle_policy == o.bundle_policy &&
283 rtcp_mux_policy == o.rtcp_mux_policy &&
284 tcp_candidate_policy == o.tcp_candidate_policy &&
285 candidate_network_policy == o.candidate_network_policy &&
286 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
287 audio_jitter_buffer_fast_accelerate ==
288 o.audio_jitter_buffer_fast_accelerate &&
289 ice_connection_receiving_timeout ==
290 o.ice_connection_receiving_timeout &&
291 ice_backup_candidate_pair_ping_interval ==
292 o.ice_backup_candidate_pair_ping_interval &&
293 continual_gathering_policy == o.continual_gathering_policy &&
294 certificates == o.certificates &&
295 prioritize_most_likely_ice_candidate_pairs ==
296 o.prioritize_most_likely_ice_candidate_pairs &&
297 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800298 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700299 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800300 enable_rtp_data_channel == o.enable_rtp_data_channel &&
301 enable_quic == o.enable_quic &&
302 screencast_min_bitrate == o.screencast_min_bitrate &&
303 combined_audio_video_bwe == o.combined_audio_video_bwe &&
304 enable_dtls_srtp == o.enable_dtls_srtp &&
305 ice_candidate_pool_size == o.ice_candidate_pool_size &&
306 prune_turn_ports == o.prune_turn_ports &&
307 presume_writable_when_fully_relayed ==
308 o.presume_writable_when_fully_relayed &&
309 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800310 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700311 ice_check_min_interval == o.ice_check_min_interval &&
312 ice_regather_interval_range == o.ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800313}
314
315bool PeerConnectionInterface::RTCConfiguration::operator!=(
316 const PeerConnectionInterface::RTCConfiguration& o) const {
317 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800318}
319
zhihuang8f65cdf2016-05-06 18:40:30 -0700320// Generate a RTCP CNAME when a PeerConnection is created.
321std::string GenerateRtcpCname() {
322 std::string cname;
323 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
324 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800325 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700326 }
327 return cname;
328}
329
zhihuang1c378ed2017-08-17 14:10:50 -0700330bool ValidateOfferAnswerOptions(
331 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
332 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
333 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700334}
335
zhihuang1c378ed2017-08-17 14:10:50 -0700336// From |rtc_options|, fill parts of |session_options| shared by all generated
337// m= sections (in other words, nothing that involves a map/array).
338void ExtractSharedMediaSessionOptions(
339 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
340 cricket::MediaSessionOptions* session_options) {
341 session_options->vad_enabled = rtc_options.voice_activity_detection;
342 session_options->bundle_enabled = rtc_options.use_rtp_mux;
343}
zhihuanga77e6bb2017-08-14 18:17:48 -0700344
zhihuang1c378ed2017-08-17 14:10:50 -0700345bool ConvertConstraintsToOfferAnswerOptions(
346 const MediaConstraintsInterface* constraints,
347 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700348 if (!constraints) {
349 return true;
350 }
zhihuang1c378ed2017-08-17 14:10:50 -0700351
352 bool value = false;
353 size_t mandatory_constraints_satisfied = 0;
354
355 if (FindConstraint(constraints,
356 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
357 &mandatory_constraints_satisfied)) {
358 offer_answer_options->offer_to_receive_audio =
359 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
360 kOfferToReceiveMediaTrue
361 : 0;
362 }
363
364 if (FindConstraint(constraints,
365 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
366 &mandatory_constraints_satisfied)) {
367 offer_answer_options->offer_to_receive_video =
368 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
369 kOfferToReceiveMediaTrue
370 : 0;
371 }
372 if (FindConstraint(constraints,
373 MediaConstraintsInterface::kVoiceActivityDetection, &value,
374 &mandatory_constraints_satisfied)) {
375 offer_answer_options->voice_activity_detection = value;
376 }
377 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
378 &mandatory_constraints_satisfied)) {
379 offer_answer_options->use_rtp_mux = value;
380 }
381 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
382 &value, &mandatory_constraints_satisfied)) {
383 offer_answer_options->ice_restart = value;
384 }
385
deadbeefab9b2d12015-10-14 11:33:11 -0700386 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
387}
388
zhihuang38ede132017-06-15 12:52:32 -0700389PeerConnection::PeerConnection(PeerConnectionFactory* factory,
390 std::unique_ptr<RtcEventLog> event_log,
391 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000392 : factory_(factory),
393 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000394 uma_observer_(NULL),
zhihuang38ede132017-06-15 12:52:32 -0700395 event_log_(std::move(event_log)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000396 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000397 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700398 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700399 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700400 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700401 remote_streams_(StreamCollection::Create()),
402 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000403
404PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100405 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700406 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700407 // Need to detach RTP senders/receivers from WebRtcSession,
408 // since it's about to be destroyed.
409 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700410 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700411 }
412 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700413 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700414 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700415 // Destroy stats_ because it depends on session_.
416 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800417 if (stats_collector_) {
418 stats_collector_->WaitForPendingRequest();
419 stats_collector_ = nullptr;
420 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700421 // Now destroy session_ before destroying other members,
422 // because its destruction fires signals (such as VoiceChannelDestroyed)
423 // which will trigger some final actions in PeerConnection...
Steve Anton978b8762017-09-29 12:15:02 -0700424 owned_session_.reset(nullptr);
425 session_ = nullptr;
deadbeef91dd5672016-05-18 16:55:30 -0700426 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700427 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700428 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700429 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700430 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700431 call_.reset();
432 event_log_.reset();
433 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000434}
435
436bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000437 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700438 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200439 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800440 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100441 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700442
443 RTCError config_error = ValidateConfiguration(configuration);
444 if (!config_error.ok()) {
445 LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
446 return false;
447 }
448
deadbeef293e9262017-01-11 12:28:30 -0800449 if (!allocator) {
450 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
451 << "This shouldn't happen if using PeerConnectionFactory.";
452 return false;
453 }
deadbeef653b8e02015-11-11 12:55:10 -0800454 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800455 // TODO(deadbeef): Why do we do this?
456 LOG(LS_ERROR) << "PeerConnection initialized without a "
457 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800458 return false;
459 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000460 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800461 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800462
deadbeef91dd5672016-05-18 16:55:30 -0700463 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700464 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700465 if (!network_thread()->Invoke<bool>(
466 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
467 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000468 return false;
469 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000470
Steve Anton978b8762017-09-29 12:15:02 -0700471 owned_session_.reset(new WebRtcSession(
nisseeaabdf62017-05-05 02:23:02 -0700472 call_.get(), factory_->channel_manager(), configuration.media_config,
Steve Anton978b8762017-09-29 12:15:02 -0700473 event_log_.get(), network_thread(), worker_thread(), signaling_thread(),
zhihuang29ff8442016-07-27 11:07:25 -0700474 port_allocator_.get(),
475 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700476 factory_->CreateTransportController(
477 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800478 configuration.redetermine_role_on_ice_restart)),
479#ifdef HAVE_SCTP
480 std::unique_ptr<cricket::SctpTransportInternalFactory>(
Steve Anton978b8762017-09-29 12:15:02 -0700481 new cricket::SctpTransportFactory(network_thread()))
deadbeef953c2ce2017-01-09 14:53:41 -0800482#else
483 nullptr
484#endif
485 ));
Steve Anton978b8762017-09-29 12:15:02 -0700486 session_ = owned_session_.get();
zhihuang29ff8442016-07-27 11:07:25 -0700487
deadbeefab9b2d12015-10-14 11:33:11 -0700488 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700489 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000490
491 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200492 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800493 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000494 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700495 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000496
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000497 // Register PeerConnection as receiver of local ice candidates.
498 // All the callbacks will be posted to the application from PeerConnection.
499 session_->RegisterIceObserver(this);
500 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700501 session_->SignalVoiceChannelCreated.connect(
502 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700503 session_->SignalVoiceChannelDestroyed.connect(
504 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700505 session_->SignalVideoChannelCreated.connect(
506 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700507 session_->SignalVideoChannelDestroyed.connect(
508 this, &PeerConnection::OnVideoChannelDestroyed);
509 session_->SignalDataChannelCreated.connect(
510 this, &PeerConnection::OnDataChannelCreated);
511 session_->SignalDataChannelDestroyed.connect(
512 this, &PeerConnection::OnDataChannelDestroyed);
513 session_->SignalDataChannelOpenMessage.connect(
514 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800515
516 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000517 return true;
518}
519
Steve Anton038834f2017-07-14 15:59:59 -0700520RTCError PeerConnection::ValidateConfiguration(
521 const RTCConfiguration& config) const {
522 if (config.ice_regather_interval_range &&
523 config.continual_gathering_policy == GATHER_ONCE) {
524 return RTCError(RTCErrorType::INVALID_PARAMETER,
525 "ice_regather_interval_range specified but continual "
526 "gathering policy is GATHER_ONCE");
527 }
528 return RTCError::OK();
529}
530
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000531rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000532PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700533 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000534}
535
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000536rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000537PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700538 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000539}
540
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000541bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100542 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000543 if (IsClosed()) {
544 return false;
545 }
deadbeefab9b2d12015-10-14 11:33:11 -0700546 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000547 return false;
548 }
deadbeefab9b2d12015-10-14 11:33:11 -0700549
550 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800551 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
552 observer->SignalAudioTrackAdded.connect(this,
553 &PeerConnection::OnAudioTrackAdded);
554 observer->SignalAudioTrackRemoved.connect(
555 this, &PeerConnection::OnAudioTrackRemoved);
556 observer->SignalVideoTrackAdded.connect(this,
557 &PeerConnection::OnVideoTrackAdded);
558 observer->SignalVideoTrackRemoved.connect(
559 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700560 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700561
deadbeefab9b2d12015-10-14 11:33:11 -0700562 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700563 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700564 }
565 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700566 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700567 }
568
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000569 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000570 observer_->OnRenegotiationNeeded();
571 return true;
572}
573
574void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100575 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700576 if (!IsClosed()) {
577 for (const auto& track : local_stream->GetAudioTracks()) {
578 RemoveAudioTrack(track.get(), local_stream);
579 }
580 for (const auto& track : local_stream->GetVideoTracks()) {
581 RemoveVideoTrack(track.get(), local_stream);
582 }
deadbeefab9b2d12015-10-14 11:33:11 -0700583 }
deadbeefab9b2d12015-10-14 11:33:11 -0700584 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800585 stream_observers_.erase(
586 std::remove_if(
587 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700588 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800589 return observer->stream()->label().compare(local_stream->label()) ==
590 0;
591 }),
592 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700593
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000594 if (IsClosed()) {
595 return;
596 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000597 observer_->OnRenegotiationNeeded();
598}
599
deadbeefe1f9d832016-01-14 15:35:42 -0800600rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
601 MediaStreamTrackInterface* track,
602 std::vector<MediaStreamInterface*> streams) {
603 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
604 if (IsClosed()) {
605 return nullptr;
606 }
607 if (streams.size() >= 2) {
608 LOG(LS_ERROR)
609 << "Adding a track with two streams is not currently supported.";
610 return nullptr;
611 }
612 // TODO(deadbeef): Support adding a track to two different senders.
613 if (FindSenderForTrack(track) != senders_.end()) {
614 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
615 return nullptr;
616 }
617
618 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700619 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800620 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700621 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800622 signaling_thread(),
623 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700624 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800625 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700626 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800627 }
628 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700629 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800630 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700631 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800632 }
633 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700634 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800635 signaling_thread(),
636 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700637 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800638 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700639 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800640 }
641 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700642 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800643 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700644 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800645 }
646 } else {
647 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
648 return rtc::scoped_refptr<RtpSenderInterface>();
649 }
650
651 senders_.push_back(new_sender);
652 observer_->OnRenegotiationNeeded();
653 return new_sender;
654}
655
656bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
657 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
658 if (IsClosed()) {
659 return false;
660 }
661
662 auto it = std::find(senders_.begin(), senders_.end(), sender);
663 if (it == senders_.end()) {
664 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
665 return false;
666 }
deadbeefa601f5c2016-06-06 14:27:39 -0700667 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800668 senders_.erase(it);
669
670 observer_->OnRenegotiationNeeded();
671 return true;
672}
673
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000674rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000675 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100676 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700677 if (IsClosed()) {
678 return nullptr;
679 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000680 if (!track) {
681 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800682 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000683 }
deadbeef20cb0c12017-02-01 20:27:00 -0800684 auto it = FindSenderForTrack(track);
685 if (it == senders_.end()) {
686 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
687 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000688 }
689
deadbeef20cb0c12017-02-01 20:27:00 -0800690 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000691}
692
deadbeeffac06552015-11-25 11:26:01 -0800693rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800694 const std::string& kind,
695 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100696 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700697 if (IsClosed()) {
698 return nullptr;
699 }
deadbeefa601f5c2016-06-06 14:27:39 -0700700 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800701 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700702 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700703 signaling_thread(),
704 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800705 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700706 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700707 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800708 } else {
709 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800710 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800711 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800712 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700713 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800714 }
deadbeeffac06552015-11-25 11:26:01 -0800715 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800716 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800717}
718
deadbeef70ab1a12015-09-28 16:53:55 -0700719std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
720 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700721 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
722 for (const auto& sender : senders_) {
723 ret.push_back(sender.get());
724 }
725 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700726}
727
728std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
729PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700730 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
731 for (const auto& receiver : receivers_) {
732 ret.push_back(receiver.get());
733 }
734 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700735}
736
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000737bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000738 MediaStreamTrackInterface* track,
739 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100740 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700741 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800742 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000743 LOG(LS_ERROR) << "GetStats - observer is NULL.";
744 return false;
745 }
746
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000747 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700748 // The StatsCollector is used to tell if a track is valid because it may
749 // remember tracks that the PeerConnection previously removed.
750 if (track && !stats_->IsValidTrack(track->id())) {
751 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
752 << track->id();
753 return false;
754 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700755 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000756 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000757 return true;
758}
759
hbos74e1a4f2016-09-15 23:33:01 -0700760void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
761 RTC_DCHECK(stats_collector_);
762 stats_collector_->GetStatsReport(callback);
763}
764
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000765PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
766 return signaling_state_;
767}
768
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000769PeerConnectionInterface::IceConnectionState
770PeerConnection::ice_connection_state() {
771 return ice_connection_state_;
772}
773
774PeerConnectionInterface::IceGatheringState
775PeerConnection::ice_gathering_state() {
776 return ice_gathering_state_;
777}
778
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000779rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000780PeerConnection::CreateDataChannel(
781 const std::string& label,
782 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100783 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700784#ifdef HAVE_QUIC
785 if (session_->data_channel_type() == cricket::DCT_QUIC) {
786 // TODO(zhihuang): Handle case when config is NULL.
787 if (!config) {
788 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
789 return nullptr;
790 }
791 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
792 if (!config->reliable || config->ordered) {
793 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
794 "ordered delivery.";
795 return nullptr;
796 }
797 return session_->quic_data_transport()->CreateDataChannel(label, config);
798 }
799#endif // HAVE_QUIC
800
deadbeefab9b2d12015-10-14 11:33:11 -0700801 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000802
kwibergd1fe2812016-04-27 06:47:29 -0700803 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000804 if (config) {
805 internal_config.reset(new InternalDataChannelInit(*config));
806 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000807 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700808 InternalCreateDataChannel(label, internal_config.get()));
809 if (!channel.get()) {
810 return nullptr;
811 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000812
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000813 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
814 // the first SCTP DataChannel.
815 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
816 observer_->OnRenegotiationNeeded();
817 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000818
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000819 return DataChannelProxy::Create(signaling_thread(), channel.get());
820}
821
822void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
823 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100824 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800825 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
827 return;
828 }
zhihuang1c378ed2017-08-17 14:10:50 -0700829 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
830 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
831 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
832 // compares the mandatory fields parsed with the mandatory fields added in the
833 // |constraints| and some downstream applications might create offers with
834 // mandatory fields which would not be parsed in the helper method. For
835 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
836 // |constraints| as a mandatory field but it is not parsed.
837 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000838
zhihuang1c378ed2017-08-17 14:10:50 -0700839 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000840}
841
842void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
843 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100844 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800845 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000846 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
847 return;
848 }
deadbeefab9b2d12015-10-14 11:33:11 -0700849
zhihuang1c378ed2017-08-17 14:10:50 -0700850 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700851 std::string error = "CreateOffer called with invalid options.";
852 LOG(LS_ERROR) << error;
853 PostCreateSessionDescriptionFailure(observer, error);
854 return;
855 }
856
zhihuang1c378ed2017-08-17 14:10:50 -0700857 cricket::MediaSessionOptions session_options;
858 GetOptionsForOffer(options, &session_options);
deadbeefab9b2d12015-10-14 11:33:11 -0700859 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000860}
861
862void PeerConnection::CreateAnswer(
863 CreateSessionDescriptionObserver* observer,
864 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100865 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800866 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000867 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
868 return;
869 }
deadbeefab9b2d12015-10-14 11:33:11 -0700870
zhihuang1c378ed2017-08-17 14:10:50 -0700871 if (!session_->remote_description() ||
872 session_->remote_description()->type() !=
873 SessionDescriptionInterface::kOffer) {
874 std::string error = "CreateAnswer called without remote offer.";
875 LOG(LS_ERROR) << error;
876 PostCreateSessionDescriptionFailure(observer, error);
877 return;
878 }
879
880 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
881 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
882 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700883 std::string error = "CreateAnswer called with invalid constraints.";
884 LOG(LS_ERROR) << error;
885 PostCreateSessionDescriptionFailure(observer, error);
886 return;
887 }
888
zhihuang1c378ed2017-08-17 14:10:50 -0700889 cricket::MediaSessionOptions session_options;
890 GetOptionsForAnswer(offer_answer_options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800891 session_->CreateAnswer(observer, session_options);
892}
893
894void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
895 const RTCOfferAnswerOptions& options) {
896 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800897 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800898 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
899 return;
900 }
901
902 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -0700903 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800904
905 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000906}
907
908void PeerConnection::SetLocalDescription(
909 SetSessionDescriptionObserver* observer,
910 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100911 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -0700912 if (IsClosed()) {
913 return;
914 }
nisse7ce109a2017-01-31 00:57:56 -0800915 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000916 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
917 return;
918 }
919 if (!desc) {
920 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
921 return;
922 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000923 // Update stats here so that we have the most recent stats for tracks and
924 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000925 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000926 std::string error;
927 if (!session_->SetLocalDescription(desc, &error)) {
928 PostSetSessionDescriptionFailure(observer, error);
929 return;
930 }
deadbeefab9b2d12015-10-14 11:33:11 -0700931
932 // If setting the description decided our SSL role, allocate any necessary
933 // SCTP sids.
934 rtc::SSLRole role;
935 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800936 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700937 AllocateSctpSids(role);
938 }
939
940 // Update state and SSRC of local MediaStreams and DataChannels based on the
941 // local session description.
942 const cricket::ContentInfo* audio_content =
943 GetFirstAudioContent(desc->description());
944 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800945 if (audio_content->rejected) {
946 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
947 } else {
948 const cricket::AudioContentDescription* audio_desc =
949 static_cast<const cricket::AudioContentDescription*>(
950 audio_content->description);
951 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
952 }
deadbeefab9b2d12015-10-14 11:33:11 -0700953 }
954
955 const cricket::ContentInfo* video_content =
956 GetFirstVideoContent(desc->description());
957 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800958 if (video_content->rejected) {
959 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
960 } else {
961 const cricket::VideoContentDescription* video_desc =
962 static_cast<const cricket::VideoContentDescription*>(
963 video_content->description);
964 UpdateLocalTracks(video_desc->streams(), video_desc->type());
965 }
deadbeefab9b2d12015-10-14 11:33:11 -0700966 }
967
968 const cricket::ContentInfo* data_content =
969 GetFirstDataContent(desc->description());
970 if (data_content) {
971 const cricket::DataContentDescription* data_desc =
972 static_cast<const cricket::DataContentDescription*>(
973 data_content->description);
974 if (rtc::starts_with(data_desc->protocol().data(),
975 cricket::kMediaProtocolRtpPrefix)) {
976 UpdateLocalRtpDataChannels(data_desc->streams());
977 }
978 }
979
980 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700981 signaling_thread()->Post(RTC_FROM_HERE, this,
982 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700983
deadbeef42a42632017-03-10 15:18:00 -0800984 // According to JSEP, after setLocalDescription, changing the candidate pool
985 // size is not allowed, and changing the set of ICE servers will not result
986 // in new candidates being gathered.
987 port_allocator_->FreezeCandidatePool();
988
deadbeefcbecd352015-09-23 11:50:27 -0700989 // MaybeStartGathering needs to be called after posting
990 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
991 // before signaling that SetLocalDescription completed.
992 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -0800993
994 if (desc->type() == SessionDescriptionInterface::kAnswer) {
995 // TODO(deadbeef): We already had to hop to the network thread for
996 // MaybeStartGathering...
997 network_thread()->Invoke<void>(
998 RTC_FROM_HERE,
999 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1000 port_allocator_.get()));
1001 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001002}
1003
1004void PeerConnection::SetRemoteDescription(
1005 SetSessionDescriptionObserver* observer,
1006 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001007 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001008 if (IsClosed()) {
1009 return;
1010 }
nisse7ce109a2017-01-31 00:57:56 -08001011 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1013 return;
1014 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015 if (!desc) {
1016 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1017 return;
1018 }
1019 // Update stats here so that we have the most recent stats for tracks and
1020 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001021 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022 std::string error;
1023 if (!session_->SetRemoteDescription(desc, &error)) {
1024 PostSetSessionDescriptionFailure(observer, error);
1025 return;
1026 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001027
deadbeefab9b2d12015-10-14 11:33:11 -07001028 // If setting the description decided our SSL role, allocate any necessary
1029 // SCTP sids.
1030 rtc::SSLRole role;
1031 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001032 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001033 AllocateSctpSids(role);
1034 }
1035
1036 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001037 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1038 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1039 const cricket::AudioContentDescription* audio_desc =
1040 GetFirstAudioContentDescription(remote_desc);
1041 const cricket::VideoContentDescription* video_desc =
1042 GetFirstVideoContentDescription(remote_desc);
1043 const cricket::DataContentDescription* data_desc =
1044 GetFirstDataContentDescription(remote_desc);
1045
1046 // Check if the descriptions include streams, just in case the peer supports
1047 // MSID, but doesn't indicate so with "a=msid-semantic".
1048 if (remote_desc->msid_supported() ||
1049 (audio_desc && !audio_desc->streams().empty()) ||
1050 (video_desc && !video_desc->streams().empty())) {
1051 remote_peer_supports_msid_ = true;
1052 }
deadbeefab9b2d12015-10-14 11:33:11 -07001053
1054 // We wait to signal new streams until we finish processing the description,
1055 // since only at that point will new streams have all their tracks.
1056 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1057
1058 // Find all audio rtp streams and create corresponding remote AudioTracks
1059 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001060 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001061 if (audio_content->rejected) {
1062 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1063 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001064 bool default_audio_track_needed =
1065 !remote_peer_supports_msid_ &&
1066 MediaContentDirectionHasSend(audio_desc->direction());
1067 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1068 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001069 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001070 }
deadbeefab9b2d12015-10-14 11:33:11 -07001071 }
1072
1073 // Find all video rtp streams and create corresponding remote VideoTracks
1074 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001075 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001076 if (video_content->rejected) {
1077 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1078 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001079 bool default_video_track_needed =
1080 !remote_peer_supports_msid_ &&
1081 MediaContentDirectionHasSend(video_desc->direction());
1082 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1083 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001084 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001085 }
deadbeefab9b2d12015-10-14 11:33:11 -07001086 }
1087
1088 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001089 if (data_desc) {
1090 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001091 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001092 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001093 }
1094 }
1095
1096 // Iterate new_streams and notify the observer about new MediaStreams.
1097 for (size_t i = 0; i < new_streams->count(); ++i) {
1098 MediaStreamInterface* new_stream = new_streams->at(i);
1099 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001100 observer_->OnAddStream(
1101 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001102 }
1103
deadbeefbda7e0b2015-12-08 17:13:40 -08001104 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001105
1106 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001107 signaling_thread()->Post(RTC_FROM_HERE, this,
1108 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001109
1110 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1111 // TODO(deadbeef): We already had to hop to the network thread for
1112 // MaybeStartGathering...
1113 network_thread()->Invoke<void>(
1114 RTC_FROM_HERE,
1115 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1116 port_allocator_.get()));
1117 }
deadbeeffc648b62015-10-13 16:42:33 -07001118}
1119
deadbeef46c73892016-11-16 19:42:04 -08001120PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1121 return configuration_;
1122}
1123
deadbeef293e9262017-01-11 12:28:30 -08001124bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1125 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001126 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001127
1128 if (session_->local_description() &&
1129 configuration.ice_candidate_pool_size !=
1130 configuration_.ice_candidate_pool_size) {
1131 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1132 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001133 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001134 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001135
deadbeef293e9262017-01-11 12:28:30 -08001136 // The simplest (and most future-compatible) way to tell if the config was
1137 // modified in an invalid way is to copy each property we do support
1138 // modifying, then use operator==. There are far more properties we don't
1139 // support modifying than those we do, and more could be added.
1140 RTCConfiguration modified_config = configuration_;
1141 modified_config.servers = configuration.servers;
1142 modified_config.type = configuration.type;
1143 modified_config.ice_candidate_pool_size =
1144 configuration.ice_candidate_pool_size;
1145 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001146 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001147 if (configuration != modified_config) {
1148 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1149 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1150 }
1151
Steve Anton038834f2017-07-14 15:59:59 -07001152 // Validate the modified configuration.
1153 RTCError validate_error = ValidateConfiguration(modified_config);
1154 if (!validate_error.ok()) {
1155 return SafeSetError(std::move(validate_error), error);
1156 }
1157
deadbeef293e9262017-01-11 12:28:30 -08001158 // Note that this isn't possible through chromium, since it's an unsigned
1159 // short in WebIDL.
1160 if (configuration.ice_candidate_pool_size < 0 ||
1161 configuration.ice_candidate_pool_size > UINT16_MAX) {
1162 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1163 }
1164
1165 // Parse ICE servers before hopping to network thread.
1166 cricket::ServerAddresses stun_servers;
1167 std::vector<cricket::RelayServerConfig> turn_servers;
1168 RTCErrorType parse_error =
1169 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1170 if (parse_error != RTCErrorType::NONE) {
1171 return SafeSetError(parse_error, error);
1172 }
1173
1174 // In theory this shouldn't fail.
1175 if (!network_thread()->Invoke<bool>(
1176 RTC_FROM_HERE,
1177 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1178 stun_servers, turn_servers, modified_config.type,
1179 modified_config.ice_candidate_pool_size,
1180 modified_config.prune_turn_ports))) {
1181 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1182 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1183 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001184
deadbeefd1a38b52016-12-10 13:15:33 -08001185 // As described in JSEP, calling setConfiguration with new ICE servers or
1186 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1187 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001188 if (modified_config.servers != configuration_.servers ||
1189 modified_config.type != configuration_.type ||
1190 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001191 session_->SetNeedsIceRestartFlag();
1192 }
skvladd1f5fda2017-02-03 16:54:05 -08001193
1194 if (modified_config.ice_check_min_interval !=
1195 configuration_.ice_check_min_interval) {
1196 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1197 }
1198
deadbeef293e9262017-01-11 12:28:30 -08001199 configuration_ = modified_config;
1200 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001201}
1202
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203bool PeerConnection::AddIceCandidate(
1204 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001205 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001206 if (IsClosed()) {
1207 return false;
1208 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001209 return session_->ProcessIceMessage(ice_candidate);
1210}
1211
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001212bool PeerConnection::RemoveIceCandidates(
1213 const std::vector<cricket::Candidate>& candidates) {
1214 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1215 return session_->RemoveRemoteIceCandidates(candidates);
1216}
1217
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001218void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001219 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001220 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001221
1222 if (session_) {
1223 session_->set_metrics_observer(uma_observer_);
1224 }
1225
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001226 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001227 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001228 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001229 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001230 uma_observer_->IncrementEnumCounter(
1231 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1232 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001233 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001234 uma_observer_->IncrementEnumCounter(
1235 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1236 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001237 }
1238 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001239}
1240
zstein4b979802017-06-02 14:37:37 -07001241RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001242 if (!worker_thread()->IsCurrent()) {
1243 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001244 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1245 }
1246
1247 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1248 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1249 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1250 if (has_min && *bitrate.min_bitrate_bps < 0) {
1251 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1252 "min_bitrate_bps <= 0");
1253 }
1254 if (has_current) {
1255 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1256 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1257 "current_bitrate_bps < min_bitrate_bps");
1258 } else if (*bitrate.current_bitrate_bps < 0) {
1259 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1260 "curent_bitrate_bps < 0");
1261 }
1262 }
1263 if (has_max) {
1264 if (has_current &&
1265 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1266 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1267 "max_bitrate_bps < current_bitrate_bps");
1268 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1269 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1270 "max_bitrate_bps < min_bitrate_bps");
1271 } else if (*bitrate.max_bitrate_bps < 0) {
1272 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1273 "max_bitrate_bps < 0");
1274 }
1275 }
1276
1277 Call::Config::BitrateConfigMask mask;
1278 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1279 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1280 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1281
1282 RTC_DCHECK(call_.get());
1283 call_->SetBitrateConfigMask(mask);
1284
1285 return RTCError::OK();
1286}
1287
ivoc14d5dbe2016-07-04 07:06:55 -07001288bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1289 int64_t max_size_bytes) {
Steve Anton978b8762017-09-29 12:15:02 -07001290 return worker_thread()->Invoke<bool>(
ivoc14d5dbe2016-07-04 07:06:55 -07001291 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1292 max_size_bytes));
1293}
1294
1295void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001296 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001297 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1298}
1299
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300const SessionDescriptionInterface* PeerConnection::local_description() const {
1301 return session_->local_description();
1302}
1303
1304const SessionDescriptionInterface* PeerConnection::remote_description() const {
1305 return session_->remote_description();
1306}
1307
deadbeeffe4a8a42016-12-20 17:56:17 -08001308const SessionDescriptionInterface* PeerConnection::current_local_description()
1309 const {
1310 return session_->current_local_description();
1311}
1312
1313const SessionDescriptionInterface* PeerConnection::current_remote_description()
1314 const {
1315 return session_->current_remote_description();
1316}
1317
1318const SessionDescriptionInterface* PeerConnection::pending_local_description()
1319 const {
1320 return session_->pending_local_description();
1321}
1322
1323const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1324 const {
1325 return session_->pending_remote_description();
1326}
1327
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001329 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001330 // Update stats here so that we have the most recent stats for tracks and
1331 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001332 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001333
deadbeefd59daf82015-10-14 15:02:44 -07001334 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001335 network_thread()->Invoke<void>(
1336 RTC_FROM_HERE,
1337 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1338 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001339
Steve Anton978b8762017-09-29 12:15:02 -07001340 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07001341 call_.reset();
1342 // The event log must outlive call (and any other object that uses it).
1343 event_log_.reset();
1344 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345}
1346
deadbeefd59daf82015-10-14 15:02:44 -07001347void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1348 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001350 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001352 break;
deadbeefd59daf82015-10-14 15:02:44 -07001353 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001354 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1355 break;
deadbeefd59daf82015-10-14 15:02:44 -07001356 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1358 break;
deadbeefd59daf82015-10-14 15:02:44 -07001359 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1361 break;
deadbeefd59daf82015-10-14 15:02:44 -07001362 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1364 break;
deadbeefd59daf82015-10-14 15:02:44 -07001365 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 ChangeSignalingState(PeerConnectionInterface::kStable);
1367 break;
deadbeefd59daf82015-10-14 15:02:44 -07001368 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 ChangeSignalingState(PeerConnectionInterface::kClosed);
1370 break;
1371 default:
1372 break;
1373 }
1374}
1375
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001376void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001377 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1379 SetSessionDescriptionMsg* param =
1380 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1381 param->observer->OnSuccess();
1382 delete param;
1383 break;
1384 }
1385 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1386 SetSessionDescriptionMsg* param =
1387 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1388 param->observer->OnFailure(param->error);
1389 delete param;
1390 break;
1391 }
deadbeefab9b2d12015-10-14 11:33:11 -07001392 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1393 CreateSessionDescriptionMsg* param =
1394 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1395 param->observer->OnFailure(param->error);
1396 delete param;
1397 break;
1398 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001399 case MSG_GETSTATS: {
1400 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001401 StatsReports reports;
1402 stats_->GetStats(param->track, &reports);
1403 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 delete param;
1405 break;
1406 }
deadbeefbd292462015-12-14 18:15:29 -08001407 case MSG_FREE_DATACHANNELS: {
1408 sctp_data_channels_to_free_.clear();
1409 break;
1410 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001412 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 break;
1414 }
1415}
1416
deadbeefab9b2d12015-10-14 11:33:11 -07001417void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001418 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001419 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001420 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1421 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001422 signaling_thread(),
1423 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1424 stream->AddTrack(
1425 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001426 receivers_.push_back(receiver);
1427 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1428 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1429 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430}
1431
deadbeefab9b2d12015-10-14 11:33:11 -07001432void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001433 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001434 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001435 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1436 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001437 signaling_thread(),
Steve Anton978b8762017-09-29 12:15:02 -07001438 new VideoRtpReceiver(track_id, worker_thread(), ssrc,
deadbeefe814a0d2017-02-25 18:15:09 -08001439 session_->video_channel()));
1440 stream->AddTrack(
1441 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001442 receivers_.push_back(receiver);
1443 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1444 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1445 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446}
1447
deadbeef70ab1a12015-09-28 16:53:55 -07001448// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1449// description.
perkjd61bf802016-03-24 03:16:19 -07001450void PeerConnection::DestroyReceiver(const std::string& track_id) {
1451 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001452 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001453 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001454 << " doesn't exist.";
1455 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001456 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001457 receivers_.erase(it);
1458 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459}
1460
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001461void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
1462 MediaStreamInterface* stream) {
1463 RTC_DCHECK(!IsClosed());
1464 auto sender = FindSenderForTrack(track);
1465 if (sender != senders_.end()) {
1466 // We already have a sender for this track, so just change the stream_id
1467 // so that it's correct in the next call to CreateOffer.
1468 (*sender)->internal()->set_stream_id(stream->label());
1469 return;
1470 }
1471
1472 // Normal case; we've never seen this track before.
1473 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1474 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1475 signaling_thread(),
Steve Anton8ffb9c32017-08-31 15:45:38 -07001476 new AudioRtpSender(track, {stream->label()},
1477 session_->voice_channel(), stats_.get()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001478 senders_.push_back(new_sender);
1479 // If the sender has already been configured in SDP, we call SetSsrc,
1480 // which will connect the sender to the underlying transport. This can
1481 // occur if a local session description that contains the ID of the sender
1482 // is set before AddStream is called. It can also occur if the local
1483 // session description is not changed and RemoveStream is called, and
1484 // later AddStream is called again with the same stream.
1485 const TrackInfo* track_info =
1486 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1487 if (track_info) {
1488 new_sender->internal()->SetSsrc(track_info->ssrc);
1489 }
1490}
1491
1492// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1493// indefinitely, when we have unified plan SDP.
1494void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
1495 MediaStreamInterface* stream) {
1496 RTC_DCHECK(!IsClosed());
1497 auto sender = FindSenderForTrack(track);
1498 if (sender == senders_.end()) {
1499 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1500 << " doesn't exist.";
1501 return;
1502 }
1503 (*sender)->internal()->Stop();
1504 senders_.erase(sender);
1505}
1506
1507void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
1508 MediaStreamInterface* stream) {
1509 RTC_DCHECK(!IsClosed());
1510 auto sender = FindSenderForTrack(track);
1511 if (sender != senders_.end()) {
1512 // We already have a sender for this track, so just change the stream_id
1513 // so that it's correct in the next call to CreateOffer.
1514 (*sender)->internal()->set_stream_id(stream->label());
1515 return;
1516 }
1517
1518 // Normal case; we've never seen this track before.
1519 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1520 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton8ffb9c32017-08-31 15:45:38 -07001521 signaling_thread(), new VideoRtpSender(track, {stream->label()},
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001522 session_->video_channel()));
1523 senders_.push_back(new_sender);
1524 const TrackInfo* track_info =
1525 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1526 if (track_info) {
1527 new_sender->internal()->SetSsrc(track_info->ssrc);
1528 }
1529}
1530
1531void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
1532 MediaStreamInterface* stream) {
1533 RTC_DCHECK(!IsClosed());
1534 auto sender = FindSenderForTrack(track);
1535 if (sender == senders_.end()) {
1536 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1537 << " doesn't exist.";
1538 return;
1539 }
1540 (*sender)->internal()->Stop();
1541 senders_.erase(sender);
1542}
1543
zstein6dfd53a2017-03-06 13:49:03 -08001544void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001546 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001547 // After transitioning to "closed", ignore any additional states from
1548 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001549 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001550 return;
1551 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001552 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001553 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001554}
1555
1556void PeerConnection::OnIceGatheringChange(
1557 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001558 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559 if (IsClosed()) {
1560 return;
1561 }
1562 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001563 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001564}
1565
jbauch81bf7b02017-03-25 08:31:12 -07001566void PeerConnection::OnIceCandidate(
1567 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001568 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001569 if (IsClosed()) {
1570 return;
1571 }
jbauch81bf7b02017-03-25 08:31:12 -07001572 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001573}
1574
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001575void PeerConnection::OnIceCandidatesRemoved(
1576 const std::vector<cricket::Candidate>& candidates) {
1577 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001578 if (IsClosed()) {
1579 return;
1580 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001581 observer_->OnIceCandidatesRemoved(candidates);
1582}
1583
Peter Thatcher54360512015-07-08 11:08:35 -07001584void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001585 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001586 if (IsClosed()) {
1587 return;
1588 }
Peter Thatcher54360512015-07-08 11:08:35 -07001589 observer_->OnIceConnectionReceivingChange(receiving);
1590}
1591
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001592void PeerConnection::ChangeSignalingState(
1593 PeerConnectionInterface::SignalingState signaling_state) {
1594 signaling_state_ = signaling_state;
1595 if (signaling_state == kClosed) {
1596 ice_connection_state_ = kIceConnectionClosed;
1597 observer_->OnIceConnectionChange(ice_connection_state_);
1598 if (ice_gathering_state_ != kIceGatheringComplete) {
1599 ice_gathering_state_ = kIceGatheringComplete;
1600 observer_->OnIceGatheringChange(ice_gathering_state_);
1601 }
1602 }
1603 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001604}
1605
deadbeefeb459812015-12-15 19:24:43 -08001606void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1607 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001608 if (IsClosed()) {
1609 return;
1610 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001611 AddAudioTrack(track, stream);
1612 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001613}
1614
deadbeefeb459812015-12-15 19:24:43 -08001615void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1616 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001617 if (IsClosed()) {
1618 return;
1619 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001620 RemoveAudioTrack(track, stream);
1621 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001622}
1623
1624void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1625 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001626 if (IsClosed()) {
1627 return;
1628 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001629 AddVideoTrack(track, stream);
1630 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001631}
1632
1633void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1634 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001635 if (IsClosed()) {
1636 return;
1637 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001638 RemoveVideoTrack(track, stream);
1639 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001640}
1641
deadbeefab9b2d12015-10-14 11:33:11 -07001642void PeerConnection::PostSetSessionDescriptionFailure(
1643 SetSessionDescriptionObserver* observer,
1644 const std::string& error) {
1645 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1646 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001647 signaling_thread()->Post(RTC_FROM_HERE, this,
1648 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001649}
1650
1651void PeerConnection::PostCreateSessionDescriptionFailure(
1652 CreateSessionDescriptionObserver* observer,
1653 const std::string& error) {
1654 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1655 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001656 signaling_thread()->Post(RTC_FROM_HERE, this,
1657 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001658}
1659
zhihuang1c378ed2017-08-17 14:10:50 -07001660void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07001661 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1662 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001663 ExtractSharedMediaSessionOptions(rtc_options, session_options);
1664
1665 // Figure out transceiver directional preferences.
1666 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1667 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1668
1669 // By default, generate sendrecv/recvonly m= sections.
1670 bool recv_audio = true;
1671 bool recv_video = true;
1672
1673 // By default, only offer a new m= section if we have media to send with it.
1674 bool offer_new_audio_description = send_audio;
1675 bool offer_new_video_description = send_video;
1676 bool offer_new_data_description = HasDataChannels();
1677
1678 // The "offer_to_receive_X" options allow those defaults to be overridden.
1679 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1680 recv_audio = (rtc_options.offer_to_receive_audio > 0);
1681 offer_new_audio_description =
1682 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
1683 }
1684 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1685 recv_video = (rtc_options.offer_to_receive_video > 0);
1686 offer_new_video_description =
1687 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
1688 }
1689
1690 rtc::Optional<size_t> audio_index;
1691 rtc::Optional<size_t> video_index;
1692 rtc::Optional<size_t> data_index;
1693 // If a current description exists, generate m= sections in the same order,
1694 // using the first audio/video/data section that appears and rejecting
1695 // extraneous ones.
deadbeef0ed85b22016-02-23 17:24:52 -08001696 if (session_->local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07001697 GenerateMediaDescriptionOptions(
1698 session_->local_description(),
1699 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1700 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1701 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001702 }
1703
zhihuang1c378ed2017-08-17 14:10:50 -07001704 // Add audio/video/data m= sections to the end if needed.
1705 if (!audio_index && offer_new_audio_description) {
1706 session_options->media_description_options.push_back(
1707 cricket::MediaDescriptionOptions(
1708 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
1709 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
1710 audio_index = rtc::Optional<size_t>(
1711 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001712 }
zhihuang1c378ed2017-08-17 14:10:50 -07001713 if (!video_index && offer_new_video_description) {
1714 session_options->media_description_options.push_back(
1715 cricket::MediaDescriptionOptions(
1716 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
1717 cricket::RtpTransceiverDirection(send_video, recv_video), false));
1718 video_index = rtc::Optional<size_t>(
1719 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001720 }
zhihuang1c378ed2017-08-17 14:10:50 -07001721 if (!data_index && offer_new_data_description) {
1722 session_options->media_description_options.push_back(
1723 cricket::MediaDescriptionOptions(
1724 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
1725 cricket::RtpTransceiverDirection(true, true), false));
1726 data_index = rtc::Optional<size_t>(
1727 session_options->media_description_options.size() - 1);
1728 }
1729
1730 cricket::MediaDescriptionOptions* audio_media_description_options =
1731 !audio_index ? nullptr
1732 : &session_options->media_description_options[*audio_index];
1733 cricket::MediaDescriptionOptions* video_media_description_options =
1734 !video_index ? nullptr
1735 : &session_options->media_description_options[*video_index];
1736 cricket::MediaDescriptionOptions* data_media_description_options =
1737 !data_index ? nullptr
1738 : &session_options->media_description_options[*data_index];
1739
1740 // Apply ICE restart flag and renomination flag.
1741 for (auto& options : session_options->media_description_options) {
1742 options.transport_options.ice_restart = rtc_options.ice_restart;
1743 options.transport_options.enable_ice_renomination =
1744 configuration_.enable_ice_renomination;
1745 }
1746
1747 AddRtpSenderOptions(senders_, audio_media_description_options,
1748 video_media_description_options);
1749 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07001750
zhihuang9763d562016-08-05 11:14:50 -07001751 // Intentionally unset the data channel type for RTP data channel with the
1752 // second condition. Otherwise the RTP data channels would be successfully
1753 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1754 // when building with chromium. We want to leave RTP data channels broken, so
1755 // people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001756 if (!rtp_data_channels_.empty() ||
1757 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001758 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001759 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001760
1761 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001762 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001763}
1764
zhihuang1c378ed2017-08-17 14:10:50 -07001765void PeerConnection::GetOptionsForAnswer(
1766 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001767 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001768 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001769
zhihuang1c378ed2017-08-17 14:10:50 -07001770 // Figure out transceiver directional preferences.
1771 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1772 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1773
1774 // By default, generate sendrecv/recvonly m= sections. The direction is also
1775 // restricted by the direction in the offer.
1776 bool recv_audio = true;
1777 bool recv_video = true;
1778
1779 // The "offer_to_receive_X" options allow those defaults to be overridden.
1780 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1781 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08001782 }
zhihuang1c378ed2017-08-17 14:10:50 -07001783 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1784 recv_video = (rtc_options.offer_to_receive_video > 0);
1785 }
1786
1787 rtc::Optional<size_t> audio_index;
1788 rtc::Optional<size_t> video_index;
1789 rtc::Optional<size_t> data_index;
zhihuang141aacb2017-08-29 13:23:53 -07001790 if (session_->remote_description()) {
1791 // The pending remote description should be an offer.
1792 RTC_DCHECK(session_->remote_description()->type() ==
1793 SessionDescriptionInterface::kOffer);
1794 // Generate m= sections that match those in the offer.
1795 // Note that mediasession.cc will handle intersection our preferred
1796 // direction with the offered direction.
1797 GenerateMediaDescriptionOptions(
1798 session_->remote_description(),
1799 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1800 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1801 &video_index, &data_index, session_options);
1802 }
zhihuang1c378ed2017-08-17 14:10:50 -07001803
1804 cricket::MediaDescriptionOptions* audio_media_description_options =
1805 !audio_index ? nullptr
1806 : &session_options->media_description_options[*audio_index];
1807 cricket::MediaDescriptionOptions* video_media_description_options =
1808 !video_index ? nullptr
1809 : &session_options->media_description_options[*video_index];
1810 cricket::MediaDescriptionOptions* data_media_description_options =
1811 !data_index ? nullptr
1812 : &session_options->media_description_options[*data_index];
1813
1814 // Apply ICE renomination flag.
1815 for (auto& options : session_options->media_description_options) {
1816 options.transport_options.enable_ice_renomination =
1817 configuration_.enable_ice_renomination;
1818 }
1819
1820 AddRtpSenderOptions(senders_, audio_media_description_options,
1821 video_media_description_options);
1822 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
1823
zhihuang9763d562016-08-05 11:14:50 -07001824 // Intentionally unset the data channel type for RTP data channel. Otherwise
1825 // the RTP data channels would be successfully negotiated by default and the
1826 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1827 // We want to leave RTP data channels broken, so people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001828 if (!rtp_data_channels_.empty() ||
1829 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001830 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001831 }
zhihuangaf388472016-11-02 16:49:48 -07001832
zhihuang1c378ed2017-08-17 14:10:50 -07001833 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001834 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001835}
1836
zhihuang1c378ed2017-08-17 14:10:50 -07001837void PeerConnection::GenerateMediaDescriptionOptions(
1838 const SessionDescriptionInterface* session_desc,
1839 cricket::RtpTransceiverDirection audio_direction,
1840 cricket::RtpTransceiverDirection video_direction,
1841 rtc::Optional<size_t>* audio_index,
1842 rtc::Optional<size_t>* video_index,
1843 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08001844 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001845 for (const cricket::ContentInfo& content :
1846 session_desc->description()->contents()) {
1847 if (IsAudioContent(&content)) {
1848 // If we already have an audio m= section, reject this extra one.
1849 if (*audio_index) {
1850 session_options->media_description_options.push_back(
1851 cricket::MediaDescriptionOptions(
1852 cricket::MEDIA_TYPE_AUDIO, content.name,
1853 cricket::RtpTransceiverDirection(false, false), true));
1854 } else {
1855 session_options->media_description_options.push_back(
1856 cricket::MediaDescriptionOptions(
1857 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
1858 !audio_direction.send && !audio_direction.recv));
1859 *audio_index = rtc::Optional<size_t>(
1860 session_options->media_description_options.size() - 1);
1861 }
1862 } else if (IsVideoContent(&content)) {
1863 // If we already have an video m= section, reject this extra one.
1864 if (*video_index) {
1865 session_options->media_description_options.push_back(
1866 cricket::MediaDescriptionOptions(
1867 cricket::MEDIA_TYPE_VIDEO, content.name,
1868 cricket::RtpTransceiverDirection(false, false), true));
1869 } else {
1870 session_options->media_description_options.push_back(
1871 cricket::MediaDescriptionOptions(
1872 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
1873 !video_direction.send && !video_direction.recv));
1874 *video_index = rtc::Optional<size_t>(
1875 session_options->media_description_options.size() - 1);
1876 }
1877 } else {
1878 RTC_DCHECK(IsDataContent(&content));
1879 // If we already have an data m= section, reject this extra one.
1880 if (*data_index) {
1881 session_options->media_description_options.push_back(
1882 cricket::MediaDescriptionOptions(
1883 cricket::MEDIA_TYPE_DATA, content.name,
1884 cricket::RtpTransceiverDirection(false, false), true));
1885 } else {
1886 session_options->media_description_options.push_back(
1887 cricket::MediaDescriptionOptions(
1888 cricket::MEDIA_TYPE_DATA, content.name,
1889 // Direction for data sections is meaningless, but legacy
1890 // endpoints might expect sendrecv.
1891 cricket::RtpTransceiverDirection(true, true), false));
1892 *data_index = rtc::Optional<size_t>(
1893 session_options->media_description_options.size() - 1);
1894 }
1895 }
htaa2a49d92016-03-04 02:51:39 -08001896 }
deadbeefab9b2d12015-10-14 11:33:11 -07001897}
1898
deadbeeffaac4972015-11-12 15:33:07 -08001899void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1900 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001901 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1902 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001903}
1904
deadbeefab9b2d12015-10-14 11:33:11 -07001905void PeerConnection::UpdateRemoteStreamsList(
1906 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001907 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001908 cricket::MediaType media_type,
1909 StreamCollection* new_streams) {
1910 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1911
1912 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001913 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001914 auto track_it = current_tracks->begin();
1915 while (track_it != current_tracks->end()) {
1916 const TrackInfo& info = *track_it;
1917 const cricket::StreamParams* params =
1918 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001919 bool track_exists = params && params->id == info.track_id;
1920 // If this is a default track, and we still need it, don't remove it.
1921 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1922 track_exists) {
1923 ++track_it;
1924 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001925 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1926 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001927 }
1928 }
1929
1930 // Find new and active tracks.
1931 for (const cricket::StreamParams& params : streams) {
1932 // The sync_label is the MediaStream label and the |stream.id| is the
1933 // track id.
1934 const std::string& stream_label = params.sync_label;
1935 const std::string& track_id = params.id;
1936 uint32_t ssrc = params.first_ssrc();
1937
1938 rtc::scoped_refptr<MediaStreamInterface> stream =
1939 remote_streams_->find(stream_label);
1940 if (!stream) {
1941 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001942 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1943 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001944 remote_streams_->AddStream(stream);
1945 new_streams->AddStream(stream);
1946 }
1947
1948 const TrackInfo* track_info =
1949 FindTrackInfo(*current_tracks, stream_label, track_id);
1950 if (!track_info) {
1951 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1952 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1953 }
1954 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001955
1956 // Add default track if necessary.
1957 if (default_track_needed) {
1958 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1959 remote_streams_->find(kDefaultStreamLabel);
1960 if (!default_stream) {
1961 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001962 default_stream = MediaStreamProxy::Create(
1963 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001964 remote_streams_->AddStream(default_stream);
1965 new_streams->AddStream(default_stream);
1966 }
1967 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1968 ? kDefaultAudioTrackLabel
1969 : kDefaultVideoTrackLabel;
1970 const TrackInfo* default_track_info =
1971 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1972 if (!default_track_info) {
1973 current_tracks->push_back(
1974 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1975 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1976 }
1977 }
deadbeefab9b2d12015-10-14 11:33:11 -07001978}
1979
1980void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1981 const std::string& track_id,
1982 uint32_t ssrc,
1983 cricket::MediaType media_type) {
1984 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1985
1986 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001987 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001988 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001989 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001990 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08001991 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001992 }
1993}
1994
1995void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1996 const std::string& track_id,
1997 cricket::MediaType media_type) {
1998 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1999
2000 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002001 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2002 // will be notified which will end the AudioRtpReceiver::track().
2003 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002004 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2005 stream->FindAudioTrack(track_id);
2006 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002007 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002008 }
2009 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002010 // Stopping or destroying a VideoRtpReceiver will end the
2011 // VideoRtpReceiver::track().
2012 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002013 rtc::scoped_refptr<VideoTrackInterface> video_track =
2014 stream->FindVideoTrack(track_id);
2015 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002016 // There's no guarantee the track is still available, e.g. the track may
2017 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002018 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002019 }
2020 } else {
nisseede5da42017-01-12 05:15:36 -08002021 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002022 }
2023}
2024
2025void PeerConnection::UpdateEndedRemoteMediaStreams() {
2026 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2027 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2028 MediaStreamInterface* stream = remote_streams_->at(i);
2029 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2030 streams_to_remove.push_back(stream);
2031 }
2032 }
2033
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002034 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002035 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002036 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002037 }
2038}
2039
deadbeefab9b2d12015-10-14 11:33:11 -07002040void PeerConnection::UpdateLocalTracks(
2041 const std::vector<cricket::StreamParams>& streams,
2042 cricket::MediaType media_type) {
2043 TrackInfos* current_tracks = GetLocalTracks(media_type);
2044
2045 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2046 // don't match the new StreamParam.
2047 TrackInfos::iterator track_it = current_tracks->begin();
2048 while (track_it != current_tracks->end()) {
2049 const TrackInfo& info = *track_it;
2050 const cricket::StreamParams* params =
2051 cricket::GetStreamBySsrc(streams, info.ssrc);
2052 if (!params || params->id != info.track_id ||
2053 params->sync_label != info.stream_label) {
2054 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2055 media_type);
2056 track_it = current_tracks->erase(track_it);
2057 } else {
2058 ++track_it;
2059 }
2060 }
2061
2062 // Find new and active tracks.
2063 for (const cricket::StreamParams& params : streams) {
2064 // The sync_label is the MediaStream label and the |stream.id| is the
2065 // track id.
2066 const std::string& stream_label = params.sync_label;
2067 const std::string& track_id = params.id;
2068 uint32_t ssrc = params.first_ssrc();
2069 const TrackInfo* track_info =
2070 FindTrackInfo(*current_tracks, stream_label, track_id);
2071 if (!track_info) {
2072 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2073 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2074 }
2075 }
2076}
2077
2078void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2079 const std::string& track_id,
2080 uint32_t ssrc,
2081 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002082 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002083 if (!sender) {
2084 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2085 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002086 return;
2087 }
2088
deadbeeffac06552015-11-25 11:26:01 -08002089 if (sender->media_type() != media_type) {
2090 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2091 << " description with an unexpected media type.";
2092 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002093 }
deadbeeffac06552015-11-25 11:26:01 -08002094
2095 sender->set_stream_id(stream_label);
2096 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002097}
2098
2099void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2100 const std::string& track_id,
2101 uint32_t ssrc,
2102 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002103 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002104 if (!sender) {
2105 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002106 // SessionDescriptions has been renegotiated.
2107 return;
2108 }
deadbeeffac06552015-11-25 11:26:01 -08002109
2110 // A sender has been removed from the SessionDescription but it's still
2111 // associated with the PeerConnection. This only occurs if the SDP doesn't
2112 // match with the calls to CreateSender, AddStream and RemoveStream.
2113 if (sender->media_type() != media_type) {
2114 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2115 << " description with an unexpected media type.";
2116 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002117 }
deadbeeffac06552015-11-25 11:26:01 -08002118
2119 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002120}
2121
2122void PeerConnection::UpdateLocalRtpDataChannels(
2123 const cricket::StreamParamsVec& streams) {
2124 std::vector<std::string> existing_channels;
2125
2126 // Find new and active data channels.
2127 for (const cricket::StreamParams& params : streams) {
2128 // |it->sync_label| is actually the data channel label. The reason is that
2129 // we use the same naming of data channels as we do for
2130 // MediaStreams and Tracks.
2131 // For MediaStreams, the sync_label is the MediaStream label and the
2132 // track label is the same as |streamid|.
2133 const std::string& channel_label = params.sync_label;
2134 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002135 if (data_channel_it == rtp_data_channels_.end()) {
2136 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002137 continue;
2138 }
2139 // Set the SSRC the data channel should use for sending.
2140 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2141 existing_channels.push_back(data_channel_it->first);
2142 }
2143
2144 UpdateClosingRtpDataChannels(existing_channels, true);
2145}
2146
2147void PeerConnection::UpdateRemoteRtpDataChannels(
2148 const cricket::StreamParamsVec& streams) {
2149 std::vector<std::string> existing_channels;
2150
2151 // Find new and active data channels.
2152 for (const cricket::StreamParams& params : streams) {
2153 // The data channel label is either the mslabel or the SSRC if the mslabel
2154 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2155 std::string label = params.sync_label.empty()
2156 ? rtc::ToString(params.first_ssrc())
2157 : params.sync_label;
2158 auto data_channel_it = rtp_data_channels_.find(label);
2159 if (data_channel_it == rtp_data_channels_.end()) {
2160 // This is a new data channel.
2161 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2162 } else {
2163 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2164 }
2165 existing_channels.push_back(label);
2166 }
2167
2168 UpdateClosingRtpDataChannels(existing_channels, false);
2169}
2170
2171void PeerConnection::UpdateClosingRtpDataChannels(
2172 const std::vector<std::string>& active_channels,
2173 bool is_local_update) {
2174 auto it = rtp_data_channels_.begin();
2175 while (it != rtp_data_channels_.end()) {
2176 DataChannel* data_channel = it->second;
2177 if (std::find(active_channels.begin(), active_channels.end(),
2178 data_channel->label()) != active_channels.end()) {
2179 ++it;
2180 continue;
2181 }
2182
2183 if (is_local_update) {
2184 data_channel->SetSendSsrc(0);
2185 } else {
2186 data_channel->RemotePeerRequestClose();
2187 }
2188
2189 if (data_channel->state() == DataChannel::kClosed) {
2190 rtp_data_channels_.erase(it);
2191 it = rtp_data_channels_.begin();
2192 } else {
2193 ++it;
2194 }
2195 }
2196}
2197
2198void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2199 uint32_t remote_ssrc) {
2200 rtc::scoped_refptr<DataChannel> channel(
2201 InternalCreateDataChannel(label, nullptr));
2202 if (!channel.get()) {
2203 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2204 << "CreateDataChannel failed.";
2205 return;
2206 }
2207 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002208 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2209 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002210 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002211}
2212
2213rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2214 const std::string& label,
2215 const InternalDataChannelInit* config) {
2216 if (IsClosed()) {
2217 return nullptr;
2218 }
2219 if (session_->data_channel_type() == cricket::DCT_NONE) {
2220 LOG(LS_ERROR)
2221 << "InternalCreateDataChannel: Data is not supported in this call.";
2222 return nullptr;
2223 }
2224 InternalDataChannelInit new_config =
2225 config ? (*config) : InternalDataChannelInit();
2226 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2227 if (new_config.id < 0) {
2228 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002229 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002230 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2231 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2232 return nullptr;
2233 }
2234 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2235 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2236 << "because the id is already in use or out of range.";
2237 return nullptr;
2238 }
2239 }
2240
2241 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
Steve Anton978b8762017-09-29 12:15:02 -07002242 session_, session_->data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002243 if (!channel) {
2244 sid_allocator_.ReleaseSid(new_config.id);
2245 return nullptr;
2246 }
2247
2248 if (channel->data_channel_type() == cricket::DCT_RTP) {
2249 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2250 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2251 << " already exists.";
2252 return nullptr;
2253 }
2254 rtp_data_channels_[channel->label()] = channel;
2255 } else {
2256 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2257 sctp_data_channels_.push_back(channel);
2258 channel->SignalClosed.connect(this,
2259 &PeerConnection::OnSctpDataChannelClosed);
2260 }
2261
hbos82ebe022016-11-14 01:41:09 -08002262 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002263 return channel;
2264}
2265
2266bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002267#ifdef HAVE_QUIC
2268 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2269 (session_->quic_data_transport() &&
2270 session_->quic_data_transport()->HasDataChannels());
2271#else
deadbeefab9b2d12015-10-14 11:33:11 -07002272 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002273#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002274}
2275
2276void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2277 for (const auto& channel : sctp_data_channels_) {
2278 if (channel->id() < 0) {
2279 int sid;
2280 if (!sid_allocator_.AllocateSid(role, &sid)) {
2281 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2282 continue;
2283 }
2284 channel->SetSctpSid(sid);
2285 }
2286 }
2287}
2288
2289void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002290 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002291 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2292 ++it) {
2293 if (it->get() == channel) {
2294 if (channel->id() >= 0) {
2295 sid_allocator_.ReleaseSid(channel->id());
2296 }
deadbeefbd292462015-12-14 18:15:29 -08002297 // Since this method is triggered by a signal from the DataChannel,
2298 // we can't free it directly here; we need to free it asynchronously.
2299 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002300 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002301 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2302 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002303 return;
2304 }
2305 }
2306}
2307
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002308void PeerConnection::OnVoiceChannelCreated() {
2309 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2310 session_->voice_channel(), senders_, receivers_,
2311 cricket::MEDIA_TYPE_AUDIO);
2312}
2313
deadbeefab9b2d12015-10-14 11:33:11 -07002314void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002315 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2316 cricket::VoiceChannel>(
2317 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2318}
2319
2320void PeerConnection::OnVideoChannelCreated() {
2321 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2322 session_->video_channel(), senders_, receivers_,
2323 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002324}
2325
2326void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002327 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2328 cricket::VideoChannel>(
2329 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002330}
2331
2332void PeerConnection::OnDataChannelCreated() {
2333 for (const auto& channel : sctp_data_channels_) {
2334 channel->OnTransportChannelCreated();
2335 }
2336}
2337
2338void PeerConnection::OnDataChannelDestroyed() {
2339 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2340 // DataChannel may callback to us and try to modify the list.
2341 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2342 temp_rtp_dcs.swap(rtp_data_channels_);
2343 for (const auto& kv : temp_rtp_dcs) {
2344 kv.second->OnTransportChannelDestroyed();
2345 }
2346
2347 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2348 temp_sctp_dcs.swap(sctp_data_channels_);
2349 for (const auto& channel : temp_sctp_dcs) {
2350 channel->OnTransportChannelDestroyed();
2351 }
2352}
2353
2354void PeerConnection::OnDataChannelOpenMessage(
2355 const std::string& label,
2356 const InternalDataChannelInit& config) {
2357 rtc::scoped_refptr<DataChannel> channel(
2358 InternalCreateDataChannel(label, &config));
2359 if (!channel.get()) {
2360 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2361 return;
2362 }
2363
deadbeefa601f5c2016-06-06 14:27:39 -07002364 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2365 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002366 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002367}
2368
zhihuang1c378ed2017-08-17 14:10:50 -07002369bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2370 return std::find_if(
2371 senders_.begin(), senders_.end(),
2372 [type](const rtc::scoped_refptr<
2373 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2374 return sender->media_type() == type;
2375 }) != senders_.end();
2376}
2377
deadbeefa601f5c2016-06-06 14:27:39 -07002378RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2379 auto it = std::find_if(
2380 senders_.begin(), senders_.end(),
2381 [id](const rtc::scoped_refptr<
2382 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2383 return sender->id() == id;
2384 });
2385 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002386}
2387
deadbeefa601f5c2016-06-06 14:27:39 -07002388std::vector<
2389 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002390PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2391 return std::find_if(
2392 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002393 [track](const rtc::scoped_refptr<
2394 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002395 return sender->track() == track;
2396 });
2397}
2398
deadbeefa601f5c2016-06-06 14:27:39 -07002399std::vector<rtc::scoped_refptr<
2400 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002401PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002402 return std::find_if(
2403 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002404 [track_id](const rtc::scoped_refptr<
2405 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002406 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002407 });
2408}
2409
deadbeefab9b2d12015-10-14 11:33:11 -07002410PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2411 cricket::MediaType media_type) {
2412 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2413 media_type == cricket::MEDIA_TYPE_VIDEO);
2414 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2415 : &remote_video_tracks_;
2416}
2417
2418PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2419 cricket::MediaType media_type) {
2420 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2421 media_type == cricket::MEDIA_TYPE_VIDEO);
2422 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2423 : &local_video_tracks_;
2424}
2425
2426const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2427 const PeerConnection::TrackInfos& infos,
2428 const std::string& stream_label,
2429 const std::string track_id) const {
2430 for (const TrackInfo& track_info : infos) {
2431 if (track_info.stream_label == stream_label &&
2432 track_info.track_id == track_id) {
2433 return &track_info;
2434 }
2435 }
2436 return nullptr;
2437}
2438
2439DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2440 for (const auto& channel : sctp_data_channels_) {
2441 if (channel->id() == sid) {
2442 return channel;
2443 }
2444 }
2445 return nullptr;
2446}
2447
deadbeef91dd5672016-05-18 16:55:30 -07002448bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002449 const RTCConfiguration& configuration) {
2450 cricket::ServerAddresses stun_servers;
2451 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002452 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2453 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002454 return false;
2455 }
2456
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002457 port_allocator_->Initialize();
2458
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002459 // To handle both internal and externally created port allocator, we will
2460 // enable BUNDLE here.
2461 int portallocator_flags = port_allocator_->flags();
2462 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002463 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2464 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002465 // If the disable-IPv6 flag was specified, we'll not override it
2466 // by experiment.
2467 if (configuration.disable_ipv6) {
2468 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002469 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2470 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002471 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2472 }
2473
zhihuangb09b3f92017-03-07 14:40:51 -08002474 if (configuration.disable_ipv6_on_wifi) {
2475 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2476 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2477 }
2478
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002479 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2480 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2481 LOG(LS_INFO) << "TCP candidates are disabled.";
2482 }
2483
honghaiz60347052016-05-31 18:29:12 -07002484 if (configuration.candidate_network_policy ==
2485 kCandidateNetworkPolicyLowCost) {
2486 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2487 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2488 }
2489
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002490 port_allocator_->set_flags(portallocator_flags);
2491 // No step delay is used while allocating ports.
2492 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2493 port_allocator_->set_candidate_filter(
2494 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07002495 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002496
2497 // Call this last since it may create pooled allocator sessions using the
2498 // properties set above.
2499 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002500 configuration.ice_candidate_pool_size,
2501 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002502 return true;
2503}
2504
deadbeef91dd5672016-05-18 16:55:30 -07002505bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002506 const cricket::ServerAddresses& stun_servers,
2507 const std::vector<cricket::RelayServerConfig>& turn_servers,
2508 IceTransportsType type,
2509 int candidate_pool_size,
2510 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002511 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002512 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002513 // Call this last since it may create pooled allocator sessions using the
2514 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002515 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002516 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002517}
2518
ivoc14d5dbe2016-07-04 07:06:55 -07002519bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2520 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002521 if (!event_log_) {
2522 return false;
2523 }
skvlad11a9cbf2016-10-07 11:53:05 -07002524 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002525}
2526
2527void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002528 if (event_log_) {
2529 event_log_->StopLogging();
2530 }
ivoc14d5dbe2016-07-04 07:06:55 -07002531}
nisseeaabdf62017-05-05 02:23:02 -07002532
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002533} // namespace webrtc