blob: 77e8e024f1073dde206a696649613969e74ba95d [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
Steve Anton8c0f7a72017-10-03 10:03:10 -07001288std::unique_ptr<rtc::SSLCertificate>
1289PeerConnection::GetRemoteAudioSSLCertificate() {
1290 if (!session_) {
1291 return nullptr;
1292 }
1293 auto* voice_channel = session_->voice_channel();
1294 if (!voice_channel) {
1295 return nullptr;
1296 }
1297 return GetRemoteSSLCertificate(voice_channel->transport_name());
1298}
1299
ivoc14d5dbe2016-07-04 07:06:55 -07001300bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1301 int64_t max_size_bytes) {
Steve Anton978b8762017-09-29 12:15:02 -07001302 return worker_thread()->Invoke<bool>(
ivoc14d5dbe2016-07-04 07:06:55 -07001303 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1304 max_size_bytes));
1305}
1306
1307void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001308 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001309 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1310}
1311
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001312const SessionDescriptionInterface* PeerConnection::local_description() const {
1313 return session_->local_description();
1314}
1315
1316const SessionDescriptionInterface* PeerConnection::remote_description() const {
1317 return session_->remote_description();
1318}
1319
deadbeeffe4a8a42016-12-20 17:56:17 -08001320const SessionDescriptionInterface* PeerConnection::current_local_description()
1321 const {
1322 return session_->current_local_description();
1323}
1324
1325const SessionDescriptionInterface* PeerConnection::current_remote_description()
1326 const {
1327 return session_->current_remote_description();
1328}
1329
1330const SessionDescriptionInterface* PeerConnection::pending_local_description()
1331 const {
1332 return session_->pending_local_description();
1333}
1334
1335const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1336 const {
1337 return session_->pending_remote_description();
1338}
1339
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001340void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001341 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001342 // Update stats here so that we have the most recent stats for tracks and
1343 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001344 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345
deadbeefd59daf82015-10-14 15:02:44 -07001346 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001347 network_thread()->Invoke<void>(
1348 RTC_FROM_HERE,
1349 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1350 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001351
Steve Anton978b8762017-09-29 12:15:02 -07001352 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07001353 call_.reset();
1354 // The event log must outlive call (and any other object that uses it).
1355 event_log_.reset();
1356 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357}
1358
deadbeefd59daf82015-10-14 15:02:44 -07001359void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1360 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001361 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001362 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001364 break;
deadbeefd59daf82015-10-14 15:02:44 -07001365 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1367 break;
deadbeefd59daf82015-10-14 15:02:44 -07001368 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1370 break;
deadbeefd59daf82015-10-14 15:02:44 -07001371 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001372 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1373 break;
deadbeefd59daf82015-10-14 15:02:44 -07001374 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1376 break;
deadbeefd59daf82015-10-14 15:02:44 -07001377 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378 ChangeSignalingState(PeerConnectionInterface::kStable);
1379 break;
deadbeefd59daf82015-10-14 15:02:44 -07001380 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001381 ChangeSignalingState(PeerConnectionInterface::kClosed);
1382 break;
1383 default:
1384 break;
1385 }
1386}
1387
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001388void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001389 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001390 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1391 SetSessionDescriptionMsg* param =
1392 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1393 param->observer->OnSuccess();
1394 delete param;
1395 break;
1396 }
1397 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1398 SetSessionDescriptionMsg* param =
1399 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1400 param->observer->OnFailure(param->error);
1401 delete param;
1402 break;
1403 }
deadbeefab9b2d12015-10-14 11:33:11 -07001404 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1405 CreateSessionDescriptionMsg* param =
1406 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1407 param->observer->OnFailure(param->error);
1408 delete param;
1409 break;
1410 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411 case MSG_GETSTATS: {
1412 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001413 StatsReports reports;
1414 stats_->GetStats(param->track, &reports);
1415 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416 delete param;
1417 break;
1418 }
deadbeefbd292462015-12-14 18:15:29 -08001419 case MSG_FREE_DATACHANNELS: {
1420 sctp_data_channels_to_free_.clear();
1421 break;
1422 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001423 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001424 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001425 break;
1426 }
1427}
1428
deadbeefab9b2d12015-10-14 11:33:11 -07001429void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001430 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001431 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001432 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1433 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001434 signaling_thread(),
1435 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1436 stream->AddTrack(
1437 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001438 receivers_.push_back(receiver);
1439 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1440 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1441 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001442}
1443
deadbeefab9b2d12015-10-14 11:33:11 -07001444void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001445 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001446 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001447 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1448 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001449 signaling_thread(),
Steve Anton978b8762017-09-29 12:15:02 -07001450 new VideoRtpReceiver(track_id, worker_thread(), ssrc,
deadbeefe814a0d2017-02-25 18:15:09 -08001451 session_->video_channel()));
1452 stream->AddTrack(
1453 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001454 receivers_.push_back(receiver);
1455 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1456 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1457 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001458}
1459
deadbeef70ab1a12015-09-28 16:53:55 -07001460// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1461// description.
perkjd61bf802016-03-24 03:16:19 -07001462void PeerConnection::DestroyReceiver(const std::string& track_id) {
1463 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001464 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001465 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001466 << " doesn't exist.";
1467 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001468 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001469 receivers_.erase(it);
1470 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001471}
1472
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001473void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
1474 MediaStreamInterface* stream) {
1475 RTC_DCHECK(!IsClosed());
1476 auto sender = FindSenderForTrack(track);
1477 if (sender != senders_.end()) {
1478 // We already have a sender for this track, so just change the stream_id
1479 // so that it's correct in the next call to CreateOffer.
1480 (*sender)->internal()->set_stream_id(stream->label());
1481 return;
1482 }
1483
1484 // Normal case; we've never seen this track before.
1485 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1486 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1487 signaling_thread(),
Steve Anton8ffb9c32017-08-31 15:45:38 -07001488 new AudioRtpSender(track, {stream->label()},
1489 session_->voice_channel(), stats_.get()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001490 senders_.push_back(new_sender);
1491 // If the sender has already been configured in SDP, we call SetSsrc,
1492 // which will connect the sender to the underlying transport. This can
1493 // occur if a local session description that contains the ID of the sender
1494 // is set before AddStream is called. It can also occur if the local
1495 // session description is not changed and RemoveStream is called, and
1496 // later AddStream is called again with the same stream.
1497 const TrackInfo* track_info =
1498 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1499 if (track_info) {
1500 new_sender->internal()->SetSsrc(track_info->ssrc);
1501 }
1502}
1503
1504// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1505// indefinitely, when we have unified plan SDP.
1506void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
1507 MediaStreamInterface* stream) {
1508 RTC_DCHECK(!IsClosed());
1509 auto sender = FindSenderForTrack(track);
1510 if (sender == senders_.end()) {
1511 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1512 << " doesn't exist.";
1513 return;
1514 }
1515 (*sender)->internal()->Stop();
1516 senders_.erase(sender);
1517}
1518
1519void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
1520 MediaStreamInterface* stream) {
1521 RTC_DCHECK(!IsClosed());
1522 auto sender = FindSenderForTrack(track);
1523 if (sender != senders_.end()) {
1524 // We already have a sender for this track, so just change the stream_id
1525 // so that it's correct in the next call to CreateOffer.
1526 (*sender)->internal()->set_stream_id(stream->label());
1527 return;
1528 }
1529
1530 // Normal case; we've never seen this track before.
1531 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1532 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton8ffb9c32017-08-31 15:45:38 -07001533 signaling_thread(), new VideoRtpSender(track, {stream->label()},
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001534 session_->video_channel()));
1535 senders_.push_back(new_sender);
1536 const TrackInfo* track_info =
1537 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1538 if (track_info) {
1539 new_sender->internal()->SetSsrc(track_info->ssrc);
1540 }
1541}
1542
1543void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
1544 MediaStreamInterface* stream) {
1545 RTC_DCHECK(!IsClosed());
1546 auto sender = FindSenderForTrack(track);
1547 if (sender == senders_.end()) {
1548 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1549 << " doesn't exist.";
1550 return;
1551 }
1552 (*sender)->internal()->Stop();
1553 senders_.erase(sender);
1554}
1555
zstein6dfd53a2017-03-06 13:49:03 -08001556void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001557 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001558 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001559 // After transitioning to "closed", ignore any additional states from
1560 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001561 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001562 return;
1563 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001564 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001565 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566}
1567
1568void PeerConnection::OnIceGatheringChange(
1569 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001570 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001571 if (IsClosed()) {
1572 return;
1573 }
1574 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001575 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001576}
1577
jbauch81bf7b02017-03-25 08:31:12 -07001578void PeerConnection::OnIceCandidate(
1579 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001580 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001581 if (IsClosed()) {
1582 return;
1583 }
jbauch81bf7b02017-03-25 08:31:12 -07001584 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001585}
1586
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001587void PeerConnection::OnIceCandidatesRemoved(
1588 const std::vector<cricket::Candidate>& candidates) {
1589 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001590 if (IsClosed()) {
1591 return;
1592 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001593 observer_->OnIceCandidatesRemoved(candidates);
1594}
1595
Peter Thatcher54360512015-07-08 11:08:35 -07001596void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001597 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001598 if (IsClosed()) {
1599 return;
1600 }
Peter Thatcher54360512015-07-08 11:08:35 -07001601 observer_->OnIceConnectionReceivingChange(receiving);
1602}
1603
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001604void PeerConnection::ChangeSignalingState(
1605 PeerConnectionInterface::SignalingState signaling_state) {
1606 signaling_state_ = signaling_state;
1607 if (signaling_state == kClosed) {
1608 ice_connection_state_ = kIceConnectionClosed;
1609 observer_->OnIceConnectionChange(ice_connection_state_);
1610 if (ice_gathering_state_ != kIceGatheringComplete) {
1611 ice_gathering_state_ = kIceGatheringComplete;
1612 observer_->OnIceGatheringChange(ice_gathering_state_);
1613 }
1614 }
1615 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001616}
1617
deadbeefeb459812015-12-15 19:24:43 -08001618void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1619 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001620 if (IsClosed()) {
1621 return;
1622 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001623 AddAudioTrack(track, stream);
1624 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001625}
1626
deadbeefeb459812015-12-15 19:24:43 -08001627void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1628 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001629 if (IsClosed()) {
1630 return;
1631 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001632 RemoveAudioTrack(track, stream);
1633 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001634}
1635
1636void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1637 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001638 if (IsClosed()) {
1639 return;
1640 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001641 AddVideoTrack(track, stream);
1642 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001643}
1644
1645void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1646 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001647 if (IsClosed()) {
1648 return;
1649 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001650 RemoveVideoTrack(track, stream);
1651 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001652}
1653
deadbeefab9b2d12015-10-14 11:33:11 -07001654void PeerConnection::PostSetSessionDescriptionFailure(
1655 SetSessionDescriptionObserver* observer,
1656 const std::string& error) {
1657 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1658 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001659 signaling_thread()->Post(RTC_FROM_HERE, this,
1660 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001661}
1662
1663void PeerConnection::PostCreateSessionDescriptionFailure(
1664 CreateSessionDescriptionObserver* observer,
1665 const std::string& error) {
1666 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1667 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001668 signaling_thread()->Post(RTC_FROM_HERE, this,
1669 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001670}
1671
zhihuang1c378ed2017-08-17 14:10:50 -07001672void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07001673 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1674 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001675 ExtractSharedMediaSessionOptions(rtc_options, session_options);
1676
1677 // Figure out transceiver directional preferences.
1678 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1679 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1680
1681 // By default, generate sendrecv/recvonly m= sections.
1682 bool recv_audio = true;
1683 bool recv_video = true;
1684
1685 // By default, only offer a new m= section if we have media to send with it.
1686 bool offer_new_audio_description = send_audio;
1687 bool offer_new_video_description = send_video;
1688 bool offer_new_data_description = HasDataChannels();
1689
1690 // The "offer_to_receive_X" options allow those defaults to be overridden.
1691 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1692 recv_audio = (rtc_options.offer_to_receive_audio > 0);
1693 offer_new_audio_description =
1694 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
1695 }
1696 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1697 recv_video = (rtc_options.offer_to_receive_video > 0);
1698 offer_new_video_description =
1699 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
1700 }
1701
1702 rtc::Optional<size_t> audio_index;
1703 rtc::Optional<size_t> video_index;
1704 rtc::Optional<size_t> data_index;
1705 // If a current description exists, generate m= sections in the same order,
1706 // using the first audio/video/data section that appears and rejecting
1707 // extraneous ones.
deadbeef0ed85b22016-02-23 17:24:52 -08001708 if (session_->local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07001709 GenerateMediaDescriptionOptions(
1710 session_->local_description(),
1711 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1712 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1713 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001714 }
1715
zhihuang1c378ed2017-08-17 14:10:50 -07001716 // Add audio/video/data m= sections to the end if needed.
1717 if (!audio_index && offer_new_audio_description) {
1718 session_options->media_description_options.push_back(
1719 cricket::MediaDescriptionOptions(
1720 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
1721 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
1722 audio_index = rtc::Optional<size_t>(
1723 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001724 }
zhihuang1c378ed2017-08-17 14:10:50 -07001725 if (!video_index && offer_new_video_description) {
1726 session_options->media_description_options.push_back(
1727 cricket::MediaDescriptionOptions(
1728 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
1729 cricket::RtpTransceiverDirection(send_video, recv_video), false));
1730 video_index = rtc::Optional<size_t>(
1731 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001732 }
zhihuang1c378ed2017-08-17 14:10:50 -07001733 if (!data_index && offer_new_data_description) {
1734 session_options->media_description_options.push_back(
1735 cricket::MediaDescriptionOptions(
1736 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
1737 cricket::RtpTransceiverDirection(true, true), false));
1738 data_index = rtc::Optional<size_t>(
1739 session_options->media_description_options.size() - 1);
1740 }
1741
1742 cricket::MediaDescriptionOptions* audio_media_description_options =
1743 !audio_index ? nullptr
1744 : &session_options->media_description_options[*audio_index];
1745 cricket::MediaDescriptionOptions* video_media_description_options =
1746 !video_index ? nullptr
1747 : &session_options->media_description_options[*video_index];
1748 cricket::MediaDescriptionOptions* data_media_description_options =
1749 !data_index ? nullptr
1750 : &session_options->media_description_options[*data_index];
1751
1752 // Apply ICE restart flag and renomination flag.
1753 for (auto& options : session_options->media_description_options) {
1754 options.transport_options.ice_restart = rtc_options.ice_restart;
1755 options.transport_options.enable_ice_renomination =
1756 configuration_.enable_ice_renomination;
1757 }
1758
1759 AddRtpSenderOptions(senders_, audio_media_description_options,
1760 video_media_description_options);
1761 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07001762
zhihuang9763d562016-08-05 11:14:50 -07001763 // Intentionally unset the data channel type for RTP data channel with the
1764 // second condition. Otherwise the RTP data channels would be successfully
1765 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1766 // when building with chromium. We want to leave RTP data channels broken, so
1767 // people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001768 if (!rtp_data_channels_.empty() ||
1769 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001770 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001771 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001772
1773 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001774 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001775}
1776
zhihuang1c378ed2017-08-17 14:10:50 -07001777void PeerConnection::GetOptionsForAnswer(
1778 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001779 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001780 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001781
zhihuang1c378ed2017-08-17 14:10:50 -07001782 // Figure out transceiver directional preferences.
1783 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1784 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1785
1786 // By default, generate sendrecv/recvonly m= sections. The direction is also
1787 // restricted by the direction in the offer.
1788 bool recv_audio = true;
1789 bool recv_video = true;
1790
1791 // The "offer_to_receive_X" options allow those defaults to be overridden.
1792 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1793 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08001794 }
zhihuang1c378ed2017-08-17 14:10:50 -07001795 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1796 recv_video = (rtc_options.offer_to_receive_video > 0);
1797 }
1798
1799 rtc::Optional<size_t> audio_index;
1800 rtc::Optional<size_t> video_index;
1801 rtc::Optional<size_t> data_index;
zhihuang141aacb2017-08-29 13:23:53 -07001802 if (session_->remote_description()) {
1803 // The pending remote description should be an offer.
1804 RTC_DCHECK(session_->remote_description()->type() ==
1805 SessionDescriptionInterface::kOffer);
1806 // Generate m= sections that match those in the offer.
1807 // Note that mediasession.cc will handle intersection our preferred
1808 // direction with the offered direction.
1809 GenerateMediaDescriptionOptions(
1810 session_->remote_description(),
1811 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1812 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1813 &video_index, &data_index, session_options);
1814 }
zhihuang1c378ed2017-08-17 14:10:50 -07001815
1816 cricket::MediaDescriptionOptions* audio_media_description_options =
1817 !audio_index ? nullptr
1818 : &session_options->media_description_options[*audio_index];
1819 cricket::MediaDescriptionOptions* video_media_description_options =
1820 !video_index ? nullptr
1821 : &session_options->media_description_options[*video_index];
1822 cricket::MediaDescriptionOptions* data_media_description_options =
1823 !data_index ? nullptr
1824 : &session_options->media_description_options[*data_index];
1825
1826 // Apply ICE renomination flag.
1827 for (auto& options : session_options->media_description_options) {
1828 options.transport_options.enable_ice_renomination =
1829 configuration_.enable_ice_renomination;
1830 }
1831
1832 AddRtpSenderOptions(senders_, audio_media_description_options,
1833 video_media_description_options);
1834 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
1835
zhihuang9763d562016-08-05 11:14:50 -07001836 // Intentionally unset the data channel type for RTP data channel. Otherwise
1837 // the RTP data channels would be successfully negotiated by default and the
1838 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1839 // We want to leave RTP data channels broken, so people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001840 if (!rtp_data_channels_.empty() ||
1841 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001842 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001843 }
zhihuangaf388472016-11-02 16:49:48 -07001844
zhihuang1c378ed2017-08-17 14:10:50 -07001845 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001846 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001847}
1848
zhihuang1c378ed2017-08-17 14:10:50 -07001849void PeerConnection::GenerateMediaDescriptionOptions(
1850 const SessionDescriptionInterface* session_desc,
1851 cricket::RtpTransceiverDirection audio_direction,
1852 cricket::RtpTransceiverDirection video_direction,
1853 rtc::Optional<size_t>* audio_index,
1854 rtc::Optional<size_t>* video_index,
1855 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08001856 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001857 for (const cricket::ContentInfo& content :
1858 session_desc->description()->contents()) {
1859 if (IsAudioContent(&content)) {
1860 // If we already have an audio m= section, reject this extra one.
1861 if (*audio_index) {
1862 session_options->media_description_options.push_back(
1863 cricket::MediaDescriptionOptions(
1864 cricket::MEDIA_TYPE_AUDIO, content.name,
1865 cricket::RtpTransceiverDirection(false, false), true));
1866 } else {
1867 session_options->media_description_options.push_back(
1868 cricket::MediaDescriptionOptions(
1869 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
1870 !audio_direction.send && !audio_direction.recv));
1871 *audio_index = rtc::Optional<size_t>(
1872 session_options->media_description_options.size() - 1);
1873 }
1874 } else if (IsVideoContent(&content)) {
1875 // If we already have an video m= section, reject this extra one.
1876 if (*video_index) {
1877 session_options->media_description_options.push_back(
1878 cricket::MediaDescriptionOptions(
1879 cricket::MEDIA_TYPE_VIDEO, content.name,
1880 cricket::RtpTransceiverDirection(false, false), true));
1881 } else {
1882 session_options->media_description_options.push_back(
1883 cricket::MediaDescriptionOptions(
1884 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
1885 !video_direction.send && !video_direction.recv));
1886 *video_index = rtc::Optional<size_t>(
1887 session_options->media_description_options.size() - 1);
1888 }
1889 } else {
1890 RTC_DCHECK(IsDataContent(&content));
1891 // If we already have an data m= section, reject this extra one.
1892 if (*data_index) {
1893 session_options->media_description_options.push_back(
1894 cricket::MediaDescriptionOptions(
1895 cricket::MEDIA_TYPE_DATA, content.name,
1896 cricket::RtpTransceiverDirection(false, false), true));
1897 } else {
1898 session_options->media_description_options.push_back(
1899 cricket::MediaDescriptionOptions(
1900 cricket::MEDIA_TYPE_DATA, content.name,
1901 // Direction for data sections is meaningless, but legacy
1902 // endpoints might expect sendrecv.
1903 cricket::RtpTransceiverDirection(true, true), false));
1904 *data_index = rtc::Optional<size_t>(
1905 session_options->media_description_options.size() - 1);
1906 }
1907 }
htaa2a49d92016-03-04 02:51:39 -08001908 }
deadbeefab9b2d12015-10-14 11:33:11 -07001909}
1910
deadbeeffaac4972015-11-12 15:33:07 -08001911void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1912 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001913 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1914 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001915}
1916
deadbeefab9b2d12015-10-14 11:33:11 -07001917void PeerConnection::UpdateRemoteStreamsList(
1918 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001919 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001920 cricket::MediaType media_type,
1921 StreamCollection* new_streams) {
1922 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1923
1924 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001925 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001926 auto track_it = current_tracks->begin();
1927 while (track_it != current_tracks->end()) {
1928 const TrackInfo& info = *track_it;
1929 const cricket::StreamParams* params =
1930 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001931 bool track_exists = params && params->id == info.track_id;
1932 // If this is a default track, and we still need it, don't remove it.
1933 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1934 track_exists) {
1935 ++track_it;
1936 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001937 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1938 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001939 }
1940 }
1941
1942 // Find new and active tracks.
1943 for (const cricket::StreamParams& params : streams) {
1944 // The sync_label is the MediaStream label and the |stream.id| is the
1945 // track id.
1946 const std::string& stream_label = params.sync_label;
1947 const std::string& track_id = params.id;
1948 uint32_t ssrc = params.first_ssrc();
1949
1950 rtc::scoped_refptr<MediaStreamInterface> stream =
1951 remote_streams_->find(stream_label);
1952 if (!stream) {
1953 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001954 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1955 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001956 remote_streams_->AddStream(stream);
1957 new_streams->AddStream(stream);
1958 }
1959
1960 const TrackInfo* track_info =
1961 FindTrackInfo(*current_tracks, stream_label, track_id);
1962 if (!track_info) {
1963 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1964 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1965 }
1966 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001967
1968 // Add default track if necessary.
1969 if (default_track_needed) {
1970 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1971 remote_streams_->find(kDefaultStreamLabel);
1972 if (!default_stream) {
1973 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001974 default_stream = MediaStreamProxy::Create(
1975 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001976 remote_streams_->AddStream(default_stream);
1977 new_streams->AddStream(default_stream);
1978 }
1979 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1980 ? kDefaultAudioTrackLabel
1981 : kDefaultVideoTrackLabel;
1982 const TrackInfo* default_track_info =
1983 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1984 if (!default_track_info) {
1985 current_tracks->push_back(
1986 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1987 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1988 }
1989 }
deadbeefab9b2d12015-10-14 11:33:11 -07001990}
1991
1992void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1993 const std::string& track_id,
1994 uint32_t ssrc,
1995 cricket::MediaType media_type) {
1996 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1997
1998 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001999 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002000 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002001 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002002 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002003 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002004 }
2005}
2006
2007void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2008 const std::string& track_id,
2009 cricket::MediaType media_type) {
2010 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2011
2012 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002013 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2014 // will be notified which will end the AudioRtpReceiver::track().
2015 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002016 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2017 stream->FindAudioTrack(track_id);
2018 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002019 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002020 }
2021 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002022 // Stopping or destroying a VideoRtpReceiver will end the
2023 // VideoRtpReceiver::track().
2024 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002025 rtc::scoped_refptr<VideoTrackInterface> video_track =
2026 stream->FindVideoTrack(track_id);
2027 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002028 // There's no guarantee the track is still available, e.g. the track may
2029 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002030 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002031 }
2032 } else {
nisseede5da42017-01-12 05:15:36 -08002033 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002034 }
2035}
2036
2037void PeerConnection::UpdateEndedRemoteMediaStreams() {
2038 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2039 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2040 MediaStreamInterface* stream = remote_streams_->at(i);
2041 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2042 streams_to_remove.push_back(stream);
2043 }
2044 }
2045
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002046 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002047 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002048 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002049 }
2050}
2051
deadbeefab9b2d12015-10-14 11:33:11 -07002052void PeerConnection::UpdateLocalTracks(
2053 const std::vector<cricket::StreamParams>& streams,
2054 cricket::MediaType media_type) {
2055 TrackInfos* current_tracks = GetLocalTracks(media_type);
2056
2057 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2058 // don't match the new StreamParam.
2059 TrackInfos::iterator track_it = current_tracks->begin();
2060 while (track_it != current_tracks->end()) {
2061 const TrackInfo& info = *track_it;
2062 const cricket::StreamParams* params =
2063 cricket::GetStreamBySsrc(streams, info.ssrc);
2064 if (!params || params->id != info.track_id ||
2065 params->sync_label != info.stream_label) {
2066 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2067 media_type);
2068 track_it = current_tracks->erase(track_it);
2069 } else {
2070 ++track_it;
2071 }
2072 }
2073
2074 // Find new and active tracks.
2075 for (const cricket::StreamParams& params : streams) {
2076 // The sync_label is the MediaStream label and the |stream.id| is the
2077 // track id.
2078 const std::string& stream_label = params.sync_label;
2079 const std::string& track_id = params.id;
2080 uint32_t ssrc = params.first_ssrc();
2081 const TrackInfo* track_info =
2082 FindTrackInfo(*current_tracks, stream_label, track_id);
2083 if (!track_info) {
2084 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2085 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2086 }
2087 }
2088}
2089
2090void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2091 const std::string& track_id,
2092 uint32_t ssrc,
2093 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002094 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002095 if (!sender) {
2096 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2097 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002098 return;
2099 }
2100
deadbeeffac06552015-11-25 11:26:01 -08002101 if (sender->media_type() != media_type) {
2102 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2103 << " description with an unexpected media type.";
2104 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002105 }
deadbeeffac06552015-11-25 11:26:01 -08002106
2107 sender->set_stream_id(stream_label);
2108 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002109}
2110
2111void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2112 const std::string& track_id,
2113 uint32_t ssrc,
2114 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002115 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002116 if (!sender) {
2117 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002118 // SessionDescriptions has been renegotiated.
2119 return;
2120 }
deadbeeffac06552015-11-25 11:26:01 -08002121
2122 // A sender has been removed from the SessionDescription but it's still
2123 // associated with the PeerConnection. This only occurs if the SDP doesn't
2124 // match with the calls to CreateSender, AddStream and RemoveStream.
2125 if (sender->media_type() != media_type) {
2126 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2127 << " description with an unexpected media type.";
2128 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002129 }
deadbeeffac06552015-11-25 11:26:01 -08002130
2131 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002132}
2133
2134void PeerConnection::UpdateLocalRtpDataChannels(
2135 const cricket::StreamParamsVec& streams) {
2136 std::vector<std::string> existing_channels;
2137
2138 // Find new and active data channels.
2139 for (const cricket::StreamParams& params : streams) {
2140 // |it->sync_label| is actually the data channel label. The reason is that
2141 // we use the same naming of data channels as we do for
2142 // MediaStreams and Tracks.
2143 // For MediaStreams, the sync_label is the MediaStream label and the
2144 // track label is the same as |streamid|.
2145 const std::string& channel_label = params.sync_label;
2146 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002147 if (data_channel_it == rtp_data_channels_.end()) {
2148 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002149 continue;
2150 }
2151 // Set the SSRC the data channel should use for sending.
2152 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2153 existing_channels.push_back(data_channel_it->first);
2154 }
2155
2156 UpdateClosingRtpDataChannels(existing_channels, true);
2157}
2158
2159void PeerConnection::UpdateRemoteRtpDataChannels(
2160 const cricket::StreamParamsVec& streams) {
2161 std::vector<std::string> existing_channels;
2162
2163 // Find new and active data channels.
2164 for (const cricket::StreamParams& params : streams) {
2165 // The data channel label is either the mslabel or the SSRC if the mslabel
2166 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2167 std::string label = params.sync_label.empty()
2168 ? rtc::ToString(params.first_ssrc())
2169 : params.sync_label;
2170 auto data_channel_it = rtp_data_channels_.find(label);
2171 if (data_channel_it == rtp_data_channels_.end()) {
2172 // This is a new data channel.
2173 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2174 } else {
2175 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2176 }
2177 existing_channels.push_back(label);
2178 }
2179
2180 UpdateClosingRtpDataChannels(existing_channels, false);
2181}
2182
2183void PeerConnection::UpdateClosingRtpDataChannels(
2184 const std::vector<std::string>& active_channels,
2185 bool is_local_update) {
2186 auto it = rtp_data_channels_.begin();
2187 while (it != rtp_data_channels_.end()) {
2188 DataChannel* data_channel = it->second;
2189 if (std::find(active_channels.begin(), active_channels.end(),
2190 data_channel->label()) != active_channels.end()) {
2191 ++it;
2192 continue;
2193 }
2194
2195 if (is_local_update) {
2196 data_channel->SetSendSsrc(0);
2197 } else {
2198 data_channel->RemotePeerRequestClose();
2199 }
2200
2201 if (data_channel->state() == DataChannel::kClosed) {
2202 rtp_data_channels_.erase(it);
2203 it = rtp_data_channels_.begin();
2204 } else {
2205 ++it;
2206 }
2207 }
2208}
2209
2210void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2211 uint32_t remote_ssrc) {
2212 rtc::scoped_refptr<DataChannel> channel(
2213 InternalCreateDataChannel(label, nullptr));
2214 if (!channel.get()) {
2215 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2216 << "CreateDataChannel failed.";
2217 return;
2218 }
2219 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002220 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2221 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002222 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002223}
2224
2225rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2226 const std::string& label,
2227 const InternalDataChannelInit* config) {
2228 if (IsClosed()) {
2229 return nullptr;
2230 }
2231 if (session_->data_channel_type() == cricket::DCT_NONE) {
2232 LOG(LS_ERROR)
2233 << "InternalCreateDataChannel: Data is not supported in this call.";
2234 return nullptr;
2235 }
2236 InternalDataChannelInit new_config =
2237 config ? (*config) : InternalDataChannelInit();
2238 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2239 if (new_config.id < 0) {
2240 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002241 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002242 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2243 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2244 return nullptr;
2245 }
2246 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2247 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2248 << "because the id is already in use or out of range.";
2249 return nullptr;
2250 }
2251 }
2252
2253 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
Steve Anton978b8762017-09-29 12:15:02 -07002254 session_, session_->data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002255 if (!channel) {
2256 sid_allocator_.ReleaseSid(new_config.id);
2257 return nullptr;
2258 }
2259
2260 if (channel->data_channel_type() == cricket::DCT_RTP) {
2261 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2262 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2263 << " already exists.";
2264 return nullptr;
2265 }
2266 rtp_data_channels_[channel->label()] = channel;
2267 } else {
2268 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2269 sctp_data_channels_.push_back(channel);
2270 channel->SignalClosed.connect(this,
2271 &PeerConnection::OnSctpDataChannelClosed);
2272 }
2273
hbos82ebe022016-11-14 01:41:09 -08002274 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002275 return channel;
2276}
2277
2278bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002279#ifdef HAVE_QUIC
2280 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2281 (session_->quic_data_transport() &&
2282 session_->quic_data_transport()->HasDataChannels());
2283#else
deadbeefab9b2d12015-10-14 11:33:11 -07002284 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002285#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002286}
2287
2288void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2289 for (const auto& channel : sctp_data_channels_) {
2290 if (channel->id() < 0) {
2291 int sid;
2292 if (!sid_allocator_.AllocateSid(role, &sid)) {
2293 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2294 continue;
2295 }
2296 channel->SetSctpSid(sid);
2297 }
2298 }
2299}
2300
2301void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002302 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002303 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2304 ++it) {
2305 if (it->get() == channel) {
2306 if (channel->id() >= 0) {
2307 sid_allocator_.ReleaseSid(channel->id());
2308 }
deadbeefbd292462015-12-14 18:15:29 -08002309 // Since this method is triggered by a signal from the DataChannel,
2310 // we can't free it directly here; we need to free it asynchronously.
2311 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002312 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002313 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2314 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002315 return;
2316 }
2317 }
2318}
2319
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002320void PeerConnection::OnVoiceChannelCreated() {
2321 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2322 session_->voice_channel(), senders_, receivers_,
2323 cricket::MEDIA_TYPE_AUDIO);
2324}
2325
deadbeefab9b2d12015-10-14 11:33:11 -07002326void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002327 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2328 cricket::VoiceChannel>(
2329 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2330}
2331
2332void PeerConnection::OnVideoChannelCreated() {
2333 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2334 session_->video_channel(), senders_, receivers_,
2335 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002336}
2337
2338void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002339 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2340 cricket::VideoChannel>(
2341 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002342}
2343
2344void PeerConnection::OnDataChannelCreated() {
2345 for (const auto& channel : sctp_data_channels_) {
2346 channel->OnTransportChannelCreated();
2347 }
2348}
2349
2350void PeerConnection::OnDataChannelDestroyed() {
2351 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2352 // DataChannel may callback to us and try to modify the list.
2353 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2354 temp_rtp_dcs.swap(rtp_data_channels_);
2355 for (const auto& kv : temp_rtp_dcs) {
2356 kv.second->OnTransportChannelDestroyed();
2357 }
2358
2359 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2360 temp_sctp_dcs.swap(sctp_data_channels_);
2361 for (const auto& channel : temp_sctp_dcs) {
2362 channel->OnTransportChannelDestroyed();
2363 }
2364}
2365
2366void PeerConnection::OnDataChannelOpenMessage(
2367 const std::string& label,
2368 const InternalDataChannelInit& config) {
2369 rtc::scoped_refptr<DataChannel> channel(
2370 InternalCreateDataChannel(label, &config));
2371 if (!channel.get()) {
2372 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2373 return;
2374 }
2375
deadbeefa601f5c2016-06-06 14:27:39 -07002376 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2377 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002378 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002379}
2380
zhihuang1c378ed2017-08-17 14:10:50 -07002381bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2382 return std::find_if(
2383 senders_.begin(), senders_.end(),
2384 [type](const rtc::scoped_refptr<
2385 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2386 return sender->media_type() == type;
2387 }) != senders_.end();
2388}
2389
deadbeefa601f5c2016-06-06 14:27:39 -07002390RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2391 auto it = std::find_if(
2392 senders_.begin(), senders_.end(),
2393 [id](const rtc::scoped_refptr<
2394 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2395 return sender->id() == id;
2396 });
2397 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002398}
2399
deadbeefa601f5c2016-06-06 14:27:39 -07002400std::vector<
2401 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002402PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2403 return std::find_if(
2404 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002405 [track](const rtc::scoped_refptr<
2406 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002407 return sender->track() == track;
2408 });
2409}
2410
deadbeefa601f5c2016-06-06 14:27:39 -07002411std::vector<rtc::scoped_refptr<
2412 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002413PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002414 return std::find_if(
2415 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002416 [track_id](const rtc::scoped_refptr<
2417 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002418 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002419 });
2420}
2421
deadbeefab9b2d12015-10-14 11:33:11 -07002422PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2423 cricket::MediaType media_type) {
2424 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2425 media_type == cricket::MEDIA_TYPE_VIDEO);
2426 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2427 : &remote_video_tracks_;
2428}
2429
2430PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2431 cricket::MediaType media_type) {
2432 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2433 media_type == cricket::MEDIA_TYPE_VIDEO);
2434 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2435 : &local_video_tracks_;
2436}
2437
2438const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2439 const PeerConnection::TrackInfos& infos,
2440 const std::string& stream_label,
2441 const std::string track_id) const {
2442 for (const TrackInfo& track_info : infos) {
2443 if (track_info.stream_label == stream_label &&
2444 track_info.track_id == track_id) {
2445 return &track_info;
2446 }
2447 }
2448 return nullptr;
2449}
2450
2451DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2452 for (const auto& channel : sctp_data_channels_) {
2453 if (channel->id() == sid) {
2454 return channel;
2455 }
2456 }
2457 return nullptr;
2458}
2459
deadbeef91dd5672016-05-18 16:55:30 -07002460bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002461 const RTCConfiguration& configuration) {
2462 cricket::ServerAddresses stun_servers;
2463 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002464 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2465 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002466 return false;
2467 }
2468
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002469 port_allocator_->Initialize();
2470
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002471 // To handle both internal and externally created port allocator, we will
2472 // enable BUNDLE here.
2473 int portallocator_flags = port_allocator_->flags();
2474 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002475 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2476 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002477 // If the disable-IPv6 flag was specified, we'll not override it
2478 // by experiment.
2479 if (configuration.disable_ipv6) {
2480 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002481 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2482 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002483 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2484 }
2485
zhihuangb09b3f92017-03-07 14:40:51 -08002486 if (configuration.disable_ipv6_on_wifi) {
2487 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2488 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2489 }
2490
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002491 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2492 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2493 LOG(LS_INFO) << "TCP candidates are disabled.";
2494 }
2495
honghaiz60347052016-05-31 18:29:12 -07002496 if (configuration.candidate_network_policy ==
2497 kCandidateNetworkPolicyLowCost) {
2498 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2499 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2500 }
2501
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002502 port_allocator_->set_flags(portallocator_flags);
2503 // No step delay is used while allocating ports.
2504 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2505 port_allocator_->set_candidate_filter(
2506 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07002507 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002508
2509 // Call this last since it may create pooled allocator sessions using the
2510 // properties set above.
2511 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002512 configuration.ice_candidate_pool_size,
2513 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002514 return true;
2515}
2516
deadbeef91dd5672016-05-18 16:55:30 -07002517bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002518 const cricket::ServerAddresses& stun_servers,
2519 const std::vector<cricket::RelayServerConfig>& turn_servers,
2520 IceTransportsType type,
2521 int candidate_pool_size,
2522 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002523 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002524 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002525 // Call this last since it may create pooled allocator sessions using the
2526 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002527 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002528 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002529}
2530
ivoc14d5dbe2016-07-04 07:06:55 -07002531bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2532 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002533 if (!event_log_) {
2534 return false;
2535 }
skvlad11a9cbf2016-10-07 11:53:05 -07002536 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002537}
2538
2539void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002540 if (event_log_) {
2541 event_log_->StopLogging();
2542 }
ivoc14d5dbe2016-07-04 07:06:55 -07002543}
nisseeaabdf62017-05-05 02:23:02 -07002544
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002545} // namespace webrtc