blob: d975ed9ad40170d5a61236a19f57358ef9372db6 [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
ossu7bb87ee2017-01-23 04:56:25 -080011#include "webrtc/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
Henrik Kjellander15583c12016-02-10 10:53:12 +010017#include "webrtc/api/jsepicecandidate.h"
18#include "webrtc/api/jsepsessiondescription.h"
19#include "webrtc/api/mediaconstraintsinterface.h"
Henrik Kjellander15583c12016-02-10 10:53:12 +010020#include "webrtc/api/mediastreamproxy.h"
21#include "webrtc/api/mediastreamtrackproxy.h"
ossuf515ab82016-12-07 04:52:58 -080022#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070023#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
deadbeef953c2ce2017-01-09 14:53:41 -080024#include "webrtc/media/sctp/sctptransport.h"
ossu7bb87ee2017-01-23 04:56:25 -080025#include "webrtc/pc/audiotrack.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010026#include "webrtc/pc/channelmanager.h"
ossu7bb87ee2017-01-23 04:56:25 -080027#include "webrtc/pc/dtmfsender.h"
28#include "webrtc/pc/mediastream.h"
29#include "webrtc/pc/mediastreamobserver.h"
30#include "webrtc/pc/remoteaudiosource.h"
31#include "webrtc/pc/rtpreceiver.h"
32#include "webrtc/pc/rtpsender.h"
33#include "webrtc/pc/streamcollection.h"
34#include "webrtc/pc/videocapturertracksource.h"
35#include "webrtc/pc/videotrack.h"
Edward Lemurc20978e2017-07-06 19:44:34 +020036#include "webrtc/rtc_base/bind.h"
37#include "webrtc/rtc_base/checks.h"
38#include "webrtc/rtc_base/logging.h"
39#include "webrtc/rtc_base/stringencode.h"
40#include "webrtc/rtc_base/stringutils.h"
41#include "webrtc/rtc_base/trace_event.h"
ossu7bb87ee2017-01-23 04:56:25 -080042#include "webrtc/system_wrappers/include/clock.h"
Henrik Kjellander98f53512015-10-28 18:17:40 +010043#include "webrtc/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
zhihuanga77e6bb2017-08-14 18:17:48 -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,
zhihuanga77e6bb2017-08-14 18:17:48 -0700140 cricket::MediaDescriptionOptions* audio_media_description_options,
141 cricket::MediaDescriptionOptions* video_media_description_options) {
deadbeeffac06552015-11-25 11:26:01 -0800142 for (const auto& sender : senders) {
zhihuanga77e6bb2017-08-14 18:17:48 -0700143 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
144 if (audio_media_description_options) {
145 audio_media_description_options->AddAudioSender(
146 sender->id(), sender->internal()->stream_id());
147 }
148 } else {
149 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
150 if (video_media_description_options) {
151 video_media_description_options->AddVideoSender(
152 sender->id(), sender->internal()->stream_id(), 1);
153 }
154 }
deadbeefab9b2d12015-10-14 11:33:11 -0700155 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700156}
deadbeefab9b2d12015-10-14 11:33:11 -0700157
zhihuanga77e6bb2017-08-14 18:17:48 -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) {
zhihuanga77e6bb2017-08-14 18:17:48 -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
zhihuanga77e6bb2017-08-14 18:17:48 -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);
deadbeefab9b2d12015-10-14 11:33:11 -0700334}
335
zhihuanga77e6bb2017-08-14 18:17:48 -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}
deadbeefab9b2d12015-10-14 11:33:11 -0700344
zhihuanga77e6bb2017-08-14 18:17:48 -0700345bool ConvertConstraintsToOfferAnswerOptions(
346 const MediaConstraintsInterface* constraints,
347 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
deadbeefab9b2d12015-10-14 11:33:11 -0700348 if (!constraints) {
349 return true;
350 }
zhihuanga77e6bb2017-08-14 18:17:48 -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...
424 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700425 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700426 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700427 [this] { port_allocator_.reset(); });
428 // call_ must be destroyed on the worker thread.
429 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
430 [this] { call_.reset(); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000431}
432
433bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000434 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700435 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200436 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800437 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100438 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700439
440 RTCError config_error = ValidateConfiguration(configuration);
441 if (!config_error.ok()) {
442 LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
443 return false;
444 }
445
deadbeef293e9262017-01-11 12:28:30 -0800446 if (!allocator) {
447 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
448 << "This shouldn't happen if using PeerConnectionFactory.";
449 return false;
450 }
deadbeef653b8e02015-11-11 12:55:10 -0800451 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800452 // TODO(deadbeef): Why do we do this?
453 LOG(LS_ERROR) << "PeerConnection initialized without a "
454 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800455 return false;
456 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000457 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800458 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800459
deadbeef91dd5672016-05-18 16:55:30 -0700460 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700461 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700462 if (!network_thread()->Invoke<bool>(
463 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
464 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000465 return false;
466 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000467
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000468
zhihuang29ff8442016-07-27 11:07:25 -0700469 session_.reset(new WebRtcSession(
nisseeaabdf62017-05-05 02:23:02 -0700470 call_.get(), factory_->channel_manager(), configuration.media_config,
471 event_log_.get(),
472 factory_->network_thread(),
zhihuang29ff8442016-07-27 11:07:25 -0700473 factory_->worker_thread(), factory_->signaling_thread(),
474 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>(
481 new cricket::SctpTransportFactory(factory_->network_thread()))
482#else
483 nullptr
484#endif
485 ));
zhihuang29ff8442016-07-27 11:07:25 -0700486
deadbeefab9b2d12015-10-14 11:33:11 -0700487 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700488 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000489
490 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200491 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800492 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000493 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700494 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000495
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000496 // Register PeerConnection as receiver of local ice candidates.
497 // All the callbacks will be posted to the application from PeerConnection.
498 session_->RegisterIceObserver(this);
499 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700500 session_->SignalVoiceChannelCreated.connect(
501 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700502 session_->SignalVoiceChannelDestroyed.connect(
503 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700504 session_->SignalVideoChannelCreated.connect(
505 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700506 session_->SignalVideoChannelDestroyed.connect(
507 this, &PeerConnection::OnVideoChannelDestroyed);
508 session_->SignalDataChannelCreated.connect(
509 this, &PeerConnection::OnDataChannelCreated);
510 session_->SignalDataChannelDestroyed.connect(
511 this, &PeerConnection::OnDataChannelDestroyed);
512 session_->SignalDataChannelOpenMessage.connect(
513 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800514
515 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000516 return true;
517}
518
Steve Anton038834f2017-07-14 15:59:59 -0700519RTCError PeerConnection::ValidateConfiguration(
520 const RTCConfiguration& config) const {
521 if (config.ice_regather_interval_range &&
522 config.continual_gathering_policy == GATHER_ONCE) {
523 return RTCError(RTCErrorType::INVALID_PARAMETER,
524 "ice_regather_interval_range specified but continual "
525 "gathering policy is GATHER_ONCE");
526 }
527 return RTCError::OK();
528}
529
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000530rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000531PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700532 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000533}
534
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000535rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000536PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700537 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000538}
539
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000540bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100541 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000542 if (IsClosed()) {
543 return false;
544 }
deadbeefab9b2d12015-10-14 11:33:11 -0700545 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000546 return false;
547 }
deadbeefab9b2d12015-10-14 11:33:11 -0700548
549 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800550 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
551 observer->SignalAudioTrackAdded.connect(this,
552 &PeerConnection::OnAudioTrackAdded);
553 observer->SignalAudioTrackRemoved.connect(
554 this, &PeerConnection::OnAudioTrackRemoved);
555 observer->SignalVideoTrackAdded.connect(this,
556 &PeerConnection::OnVideoTrackAdded);
557 observer->SignalVideoTrackRemoved.connect(
558 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700559 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700560
deadbeefab9b2d12015-10-14 11:33:11 -0700561 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700562 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700563 }
564 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700565 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700566 }
567
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000568 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000569 observer_->OnRenegotiationNeeded();
570 return true;
571}
572
573void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100574 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700575 if (!IsClosed()) {
576 for (const auto& track : local_stream->GetAudioTracks()) {
577 RemoveAudioTrack(track.get(), local_stream);
578 }
579 for (const auto& track : local_stream->GetVideoTracks()) {
580 RemoveVideoTrack(track.get(), local_stream);
581 }
deadbeefab9b2d12015-10-14 11:33:11 -0700582 }
deadbeefab9b2d12015-10-14 11:33:11 -0700583 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800584 stream_observers_.erase(
585 std::remove_if(
586 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700587 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800588 return observer->stream()->label().compare(local_stream->label()) ==
589 0;
590 }),
591 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700592
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000593 if (IsClosed()) {
594 return;
595 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000596 observer_->OnRenegotiationNeeded();
597}
598
deadbeefe1f9d832016-01-14 15:35:42 -0800599rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
600 MediaStreamTrackInterface* track,
601 std::vector<MediaStreamInterface*> streams) {
602 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
603 if (IsClosed()) {
604 return nullptr;
605 }
606 if (streams.size() >= 2) {
607 LOG(LS_ERROR)
608 << "Adding a track with two streams is not currently supported.";
609 return nullptr;
610 }
611 // TODO(deadbeef): Support adding a track to two different senders.
612 if (FindSenderForTrack(track) != senders_.end()) {
613 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
614 return nullptr;
615 }
616
617 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700618 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800619 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700620 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800621 signaling_thread(),
622 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700623 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800624 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700625 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800626 }
627 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700628 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800629 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700630 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800631 }
632 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700633 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800634 signaling_thread(),
635 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700636 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800637 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700638 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800639 }
640 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700641 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800642 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700643 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800644 }
645 } else {
646 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
647 return rtc::scoped_refptr<RtpSenderInterface>();
648 }
649
650 senders_.push_back(new_sender);
651 observer_->OnRenegotiationNeeded();
652 return new_sender;
653}
654
655bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
656 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
657 if (IsClosed()) {
658 return false;
659 }
660
661 auto it = std::find(senders_.begin(), senders_.end(), sender);
662 if (it == senders_.end()) {
663 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
664 return false;
665 }
deadbeefa601f5c2016-06-06 14:27:39 -0700666 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800667 senders_.erase(it);
668
669 observer_->OnRenegotiationNeeded();
670 return true;
671}
672
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000673rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000674 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100675 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700676 if (IsClosed()) {
677 return nullptr;
678 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000679 if (!track) {
680 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800681 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000682 }
deadbeef20cb0c12017-02-01 20:27:00 -0800683 auto it = FindSenderForTrack(track);
684 if (it == senders_.end()) {
685 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
686 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000687 }
688
deadbeef20cb0c12017-02-01 20:27:00 -0800689 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000690}
691
deadbeeffac06552015-11-25 11:26:01 -0800692rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800693 const std::string& kind,
694 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100695 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700696 if (IsClosed()) {
697 return nullptr;
698 }
deadbeefa601f5c2016-06-06 14:27:39 -0700699 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800700 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700701 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700702 signaling_thread(),
703 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800704 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700705 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700706 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800707 } else {
708 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800709 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800710 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800711 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700712 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800713 }
deadbeeffac06552015-11-25 11:26:01 -0800714 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800715 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800716}
717
deadbeef70ab1a12015-09-28 16:53:55 -0700718std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
719 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700720 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
721 for (const auto& sender : senders_) {
722 ret.push_back(sender.get());
723 }
724 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700725}
726
727std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
728PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700729 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
730 for (const auto& receiver : receivers_) {
731 ret.push_back(receiver.get());
732 }
733 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700734}
735
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000737 MediaStreamTrackInterface* track,
738 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100739 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700740 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800741 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000742 LOG(LS_ERROR) << "GetStats - observer is NULL.";
743 return false;
744 }
745
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000746 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700747 // The StatsCollector is used to tell if a track is valid because it may
748 // remember tracks that the PeerConnection previously removed.
749 if (track && !stats_->IsValidTrack(track->id())) {
750 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
751 << track->id();
752 return false;
753 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700754 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000755 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000756 return true;
757}
758
hbos74e1a4f2016-09-15 23:33:01 -0700759void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
760 RTC_DCHECK(stats_collector_);
761 stats_collector_->GetStatsReport(callback);
762}
763
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000764PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
765 return signaling_state_;
766}
767
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000768PeerConnectionInterface::IceConnectionState
769PeerConnection::ice_connection_state() {
770 return ice_connection_state_;
771}
772
773PeerConnectionInterface::IceGatheringState
774PeerConnection::ice_gathering_state() {
775 return ice_gathering_state_;
776}
777
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000778rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000779PeerConnection::CreateDataChannel(
780 const std::string& label,
781 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100782 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700783#ifdef HAVE_QUIC
784 if (session_->data_channel_type() == cricket::DCT_QUIC) {
785 // TODO(zhihuang): Handle case when config is NULL.
786 if (!config) {
787 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
788 return nullptr;
789 }
790 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
791 if (!config->reliable || config->ordered) {
792 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
793 "ordered delivery.";
794 return nullptr;
795 }
796 return session_->quic_data_transport()->CreateDataChannel(label, config);
797 }
798#endif // HAVE_QUIC
799
deadbeefab9b2d12015-10-14 11:33:11 -0700800 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000801
kwibergd1fe2812016-04-27 06:47:29 -0700802 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000803 if (config) {
804 internal_config.reset(new InternalDataChannelInit(*config));
805 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000806 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700807 InternalCreateDataChannel(label, internal_config.get()));
808 if (!channel.get()) {
809 return nullptr;
810 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000811
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000812 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
813 // the first SCTP DataChannel.
814 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
815 observer_->OnRenegotiationNeeded();
816 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000817
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000818 return DataChannelProxy::Create(signaling_thread(), channel.get());
819}
820
821void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
822 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100823 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800824 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000825 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
826 return;
827 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700828 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
829 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
830 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
831 // compares the mandatory fields parsed with the mandatory fields added in the
832 // |constraints| and some downstream applications might create offers with
833 // mandatory fields which would not be parsed in the helper method. For
834 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
835 // |constraints| as a mandatory field but it is not parsed.
836 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000837
zhihuanga77e6bb2017-08-14 18:17:48 -0700838 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000839}
840
841void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
842 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100843 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800844 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000845 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
846 return;
847 }
deadbeefab9b2d12015-10-14 11:33:11 -0700848
zhihuanga77e6bb2017-08-14 18:17:48 -0700849 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700850 std::string error = "CreateOffer called with invalid options.";
851 LOG(LS_ERROR) << error;
852 PostCreateSessionDescriptionFailure(observer, error);
853 return;
854 }
855
zhihuanga77e6bb2017-08-14 18:17:48 -0700856 cricket::MediaSessionOptions session_options;
857 GetOptionsForOffer(options, &session_options);
deadbeefab9b2d12015-10-14 11:33:11 -0700858 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000859}
860
861void PeerConnection::CreateAnswer(
862 CreateSessionDescriptionObserver* observer,
863 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100864 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800865 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000866 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
867 return;
868 }
deadbeefab9b2d12015-10-14 11:33:11 -0700869
zhihuanga77e6bb2017-08-14 18:17:48 -0700870 if (!session_->remote_description() ||
871 session_->remote_description()->type() !=
872 SessionDescriptionInterface::kOffer) {
873 std::string error = "CreateAnswer called without remote offer.";
874 LOG(LS_ERROR) << error;
875 PostCreateSessionDescriptionFailure(observer, error);
876 return;
877 }
878
879 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
880 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
881 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700882 std::string error = "CreateAnswer called with invalid constraints.";
883 LOG(LS_ERROR) << error;
884 PostCreateSessionDescriptionFailure(observer, error);
885 return;
886 }
887
zhihuanga77e6bb2017-08-14 18:17:48 -0700888 cricket::MediaSessionOptions session_options;
889 GetOptionsForAnswer(offer_answer_options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800890 session_->CreateAnswer(observer, session_options);
891}
892
893void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
894 const RTCOfferAnswerOptions& options) {
895 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800896 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800897 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
898 return;
899 }
900
901 cricket::MediaSessionOptions session_options;
zhihuanga77e6bb2017-08-14 18:17:48 -0700902 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800903
904 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000905}
906
907void PeerConnection::SetLocalDescription(
908 SetSessionDescriptionObserver* observer,
909 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100910 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -0700911 if (IsClosed()) {
912 return;
913 }
nisse7ce109a2017-01-31 00:57:56 -0800914 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000915 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
916 return;
917 }
918 if (!desc) {
919 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
920 return;
921 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000922 // Update stats here so that we have the most recent stats for tracks and
923 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000924 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000925 std::string error;
926 if (!session_->SetLocalDescription(desc, &error)) {
927 PostSetSessionDescriptionFailure(observer, error);
928 return;
929 }
deadbeefab9b2d12015-10-14 11:33:11 -0700930
931 // If setting the description decided our SSL role, allocate any necessary
932 // SCTP sids.
933 rtc::SSLRole role;
934 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800935 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700936 AllocateSctpSids(role);
937 }
938
939 // Update state and SSRC of local MediaStreams and DataChannels based on the
940 // local session description.
941 const cricket::ContentInfo* audio_content =
942 GetFirstAudioContent(desc->description());
943 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800944 if (audio_content->rejected) {
945 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
946 } else {
947 const cricket::AudioContentDescription* audio_desc =
948 static_cast<const cricket::AudioContentDescription*>(
949 audio_content->description);
950 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
951 }
deadbeefab9b2d12015-10-14 11:33:11 -0700952 }
953
954 const cricket::ContentInfo* video_content =
955 GetFirstVideoContent(desc->description());
956 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800957 if (video_content->rejected) {
958 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
959 } else {
960 const cricket::VideoContentDescription* video_desc =
961 static_cast<const cricket::VideoContentDescription*>(
962 video_content->description);
963 UpdateLocalTracks(video_desc->streams(), video_desc->type());
964 }
deadbeefab9b2d12015-10-14 11:33:11 -0700965 }
966
967 const cricket::ContentInfo* data_content =
968 GetFirstDataContent(desc->description());
969 if (data_content) {
970 const cricket::DataContentDescription* data_desc =
971 static_cast<const cricket::DataContentDescription*>(
972 data_content->description);
973 if (rtc::starts_with(data_desc->protocol().data(),
974 cricket::kMediaProtocolRtpPrefix)) {
975 UpdateLocalRtpDataChannels(data_desc->streams());
976 }
977 }
978
979 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700980 signaling_thread()->Post(RTC_FROM_HERE, this,
981 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700982
deadbeef42a42632017-03-10 15:18:00 -0800983 // According to JSEP, after setLocalDescription, changing the candidate pool
984 // size is not allowed, and changing the set of ICE servers will not result
985 // in new candidates being gathered.
986 port_allocator_->FreezeCandidatePool();
987
deadbeefcbecd352015-09-23 11:50:27 -0700988 // MaybeStartGathering needs to be called after posting
989 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
990 // before signaling that SetLocalDescription completed.
991 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -0800992
993 if (desc->type() == SessionDescriptionInterface::kAnswer) {
994 // TODO(deadbeef): We already had to hop to the network thread for
995 // MaybeStartGathering...
996 network_thread()->Invoke<void>(
997 RTC_FROM_HERE,
998 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
999 port_allocator_.get()));
1000 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001001}
1002
1003void PeerConnection::SetRemoteDescription(
1004 SetSessionDescriptionObserver* observer,
1005 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001006 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001007 if (IsClosed()) {
1008 return;
1009 }
nisse7ce109a2017-01-31 00:57:56 -08001010 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001011 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1012 return;
1013 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001014 if (!desc) {
1015 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1016 return;
1017 }
1018 // Update stats here so that we have the most recent stats for tracks and
1019 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001020 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001021 std::string error;
1022 if (!session_->SetRemoteDescription(desc, &error)) {
1023 PostSetSessionDescriptionFailure(observer, error);
1024 return;
1025 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001026
deadbeefab9b2d12015-10-14 11:33:11 -07001027 // If setting the description decided our SSL role, allocate any necessary
1028 // SCTP sids.
1029 rtc::SSLRole role;
1030 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001031 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001032 AllocateSctpSids(role);
1033 }
1034
1035 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001036 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1037 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1038 const cricket::AudioContentDescription* audio_desc =
1039 GetFirstAudioContentDescription(remote_desc);
1040 const cricket::VideoContentDescription* video_desc =
1041 GetFirstVideoContentDescription(remote_desc);
1042 const cricket::DataContentDescription* data_desc =
1043 GetFirstDataContentDescription(remote_desc);
1044
1045 // Check if the descriptions include streams, just in case the peer supports
1046 // MSID, but doesn't indicate so with "a=msid-semantic".
1047 if (remote_desc->msid_supported() ||
1048 (audio_desc && !audio_desc->streams().empty()) ||
1049 (video_desc && !video_desc->streams().empty())) {
1050 remote_peer_supports_msid_ = true;
1051 }
deadbeefab9b2d12015-10-14 11:33:11 -07001052
1053 // We wait to signal new streams until we finish processing the description,
1054 // since only at that point will new streams have all their tracks.
1055 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1056
1057 // Find all audio rtp streams and create corresponding remote AudioTracks
1058 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001059 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001060 if (audio_content->rejected) {
1061 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1062 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001063 bool default_audio_track_needed =
1064 !remote_peer_supports_msid_ &&
1065 MediaContentDirectionHasSend(audio_desc->direction());
1066 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1067 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001068 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001069 }
deadbeefab9b2d12015-10-14 11:33:11 -07001070 }
1071
1072 // Find all video rtp streams and create corresponding remote VideoTracks
1073 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001074 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001075 if (video_content->rejected) {
1076 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1077 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001078 bool default_video_track_needed =
1079 !remote_peer_supports_msid_ &&
1080 MediaContentDirectionHasSend(video_desc->direction());
1081 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1082 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001083 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001084 }
deadbeefab9b2d12015-10-14 11:33:11 -07001085 }
1086
1087 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001088 if (data_desc) {
1089 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001090 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001091 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001092 }
1093 }
1094
1095 // Iterate new_streams and notify the observer about new MediaStreams.
1096 for (size_t i = 0; i < new_streams->count(); ++i) {
1097 MediaStreamInterface* new_stream = new_streams->at(i);
1098 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001099 observer_->OnAddStream(
1100 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001101 }
1102
deadbeefbda7e0b2015-12-08 17:13:40 -08001103 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001104
1105 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001106 signaling_thread()->Post(RTC_FROM_HERE, this,
1107 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001108
1109 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1110 // TODO(deadbeef): We already had to hop to the network thread for
1111 // MaybeStartGathering...
1112 network_thread()->Invoke<void>(
1113 RTC_FROM_HERE,
1114 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1115 port_allocator_.get()));
1116 }
deadbeeffc648b62015-10-13 16:42:33 -07001117}
1118
deadbeef46c73892016-11-16 19:42:04 -08001119PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1120 return configuration_;
1121}
1122
deadbeef293e9262017-01-11 12:28:30 -08001123bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1124 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001125 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001126
1127 if (session_->local_description() &&
1128 configuration.ice_candidate_pool_size !=
1129 configuration_.ice_candidate_pool_size) {
1130 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1131 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001132 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001133 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001134
deadbeef293e9262017-01-11 12:28:30 -08001135 // The simplest (and most future-compatible) way to tell if the config was
1136 // modified in an invalid way is to copy each property we do support
1137 // modifying, then use operator==. There are far more properties we don't
1138 // support modifying than those we do, and more could be added.
1139 RTCConfiguration modified_config = configuration_;
1140 modified_config.servers = configuration.servers;
1141 modified_config.type = configuration.type;
1142 modified_config.ice_candidate_pool_size =
1143 configuration.ice_candidate_pool_size;
1144 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001145 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001146 if (configuration != modified_config) {
1147 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1148 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1149 }
1150
Steve Anton038834f2017-07-14 15:59:59 -07001151 // Validate the modified configuration.
1152 RTCError validate_error = ValidateConfiguration(modified_config);
1153 if (!validate_error.ok()) {
1154 return SafeSetError(std::move(validate_error), error);
1155 }
1156
deadbeef293e9262017-01-11 12:28:30 -08001157 // Note that this isn't possible through chromium, since it's an unsigned
1158 // short in WebIDL.
1159 if (configuration.ice_candidate_pool_size < 0 ||
1160 configuration.ice_candidate_pool_size > UINT16_MAX) {
1161 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1162 }
1163
1164 // Parse ICE servers before hopping to network thread.
1165 cricket::ServerAddresses stun_servers;
1166 std::vector<cricket::RelayServerConfig> turn_servers;
1167 RTCErrorType parse_error =
1168 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1169 if (parse_error != RTCErrorType::NONE) {
1170 return SafeSetError(parse_error, error);
1171 }
1172
1173 // In theory this shouldn't fail.
1174 if (!network_thread()->Invoke<bool>(
1175 RTC_FROM_HERE,
1176 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1177 stun_servers, turn_servers, modified_config.type,
1178 modified_config.ice_candidate_pool_size,
1179 modified_config.prune_turn_ports))) {
1180 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1181 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1182 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001183
deadbeefd1a38b52016-12-10 13:15:33 -08001184 // As described in JSEP, calling setConfiguration with new ICE servers or
1185 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1186 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001187 if (modified_config.servers != configuration_.servers ||
1188 modified_config.type != configuration_.type ||
1189 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001190 session_->SetNeedsIceRestartFlag();
1191 }
skvladd1f5fda2017-02-03 16:54:05 -08001192
1193 if (modified_config.ice_check_min_interval !=
1194 configuration_.ice_check_min_interval) {
1195 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1196 }
1197
deadbeef293e9262017-01-11 12:28:30 -08001198 configuration_ = modified_config;
1199 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001200}
1201
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001202bool PeerConnection::AddIceCandidate(
1203 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001204 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001205 if (IsClosed()) {
1206 return false;
1207 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001208 return session_->ProcessIceMessage(ice_candidate);
1209}
1210
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001211bool PeerConnection::RemoveIceCandidates(
1212 const std::vector<cricket::Candidate>& candidates) {
1213 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1214 return session_->RemoveRemoteIceCandidates(candidates);
1215}
1216
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001217void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001218 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001219 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001220
1221 if (session_) {
1222 session_->set_metrics_observer(uma_observer_);
1223 }
1224
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001225 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001226 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001227 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001228 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001229 uma_observer_->IncrementEnumCounter(
1230 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1231 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001232 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001233 uma_observer_->IncrementEnumCounter(
1234 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1235 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001236 }
1237 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001238}
1239
zstein4b979802017-06-02 14:37:37 -07001240RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
1241 rtc::Thread* worker_thread = factory_->worker_thread();
1242 if (!worker_thread->IsCurrent()) {
1243 return worker_thread->Invoke<RTCError>(
1244 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1245 }
1246
1247 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1248 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1249 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1250 if (has_min && *bitrate.min_bitrate_bps < 0) {
1251 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1252 "min_bitrate_bps <= 0");
1253 }
1254 if (has_current) {
1255 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1256 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1257 "current_bitrate_bps < min_bitrate_bps");
1258 } else if (*bitrate.current_bitrate_bps < 0) {
1259 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1260 "curent_bitrate_bps < 0");
1261 }
1262 }
1263 if (has_max) {
1264 if (has_current &&
1265 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1266 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1267 "max_bitrate_bps < current_bitrate_bps");
1268 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1269 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1270 "max_bitrate_bps < min_bitrate_bps");
1271 } else if (*bitrate.max_bitrate_bps < 0) {
1272 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1273 "max_bitrate_bps < 0");
1274 }
1275 }
1276
1277 Call::Config::BitrateConfigMask mask;
1278 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1279 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1280 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1281
1282 RTC_DCHECK(call_.get());
1283 call_->SetBitrateConfigMask(mask);
1284
1285 return RTCError::OK();
1286}
1287
ivoc14d5dbe2016-07-04 07:06:55 -07001288bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1289 int64_t max_size_bytes) {
1290 return factory_->worker_thread()->Invoke<bool>(
1291 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1292 max_size_bytes));
1293}
1294
1295void PeerConnection::StopRtcEventLog() {
1296 factory_->worker_thread()->Invoke<void>(
1297 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1298}
1299
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001300const SessionDescriptionInterface* PeerConnection::local_description() const {
1301 return session_->local_description();
1302}
1303
1304const SessionDescriptionInterface* PeerConnection::remote_description() const {
1305 return session_->remote_description();
1306}
1307
deadbeeffe4a8a42016-12-20 17:56:17 -08001308const SessionDescriptionInterface* PeerConnection::current_local_description()
1309 const {
1310 return session_->current_local_description();
1311}
1312
1313const SessionDescriptionInterface* PeerConnection::current_remote_description()
1314 const {
1315 return session_->current_remote_description();
1316}
1317
1318const SessionDescriptionInterface* PeerConnection::pending_local_description()
1319 const {
1320 return session_->pending_local_description();
1321}
1322
1323const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1324 const {
1325 return session_->pending_remote_description();
1326}
1327
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001328void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001329 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001330 // Update stats here so that we have the most recent stats for tracks and
1331 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001332 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001333
deadbeefd59daf82015-10-14 15:02:44 -07001334 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001335 network_thread()->Invoke<void>(
1336 RTC_FROM_HERE,
1337 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1338 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001339
1340 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE,
1341 [this] { call_.reset(); });
terelius33860252017-05-12 23:37:18 -07001342
1343 // The event log must outlive call (and any other object that uses it).
1344 event_log_.reset();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001345}
1346
deadbeefd59daf82015-10-14 15:02:44 -07001347void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1348 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001350 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001352 break;
deadbeefd59daf82015-10-14 15:02:44 -07001353 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001354 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1355 break;
deadbeefd59daf82015-10-14 15:02:44 -07001356 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001357 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1358 break;
deadbeefd59daf82015-10-14 15:02:44 -07001359 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001360 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1361 break;
deadbeefd59daf82015-10-14 15:02:44 -07001362 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1364 break;
deadbeefd59daf82015-10-14 15:02:44 -07001365 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001366 ChangeSignalingState(PeerConnectionInterface::kStable);
1367 break;
deadbeefd59daf82015-10-14 15:02:44 -07001368 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001369 ChangeSignalingState(PeerConnectionInterface::kClosed);
1370 break;
1371 default:
1372 break;
1373 }
1374}
1375
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001376void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001377 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001378 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1379 SetSessionDescriptionMsg* param =
1380 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1381 param->observer->OnSuccess();
1382 delete param;
1383 break;
1384 }
1385 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1386 SetSessionDescriptionMsg* param =
1387 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1388 param->observer->OnFailure(param->error);
1389 delete param;
1390 break;
1391 }
deadbeefab9b2d12015-10-14 11:33:11 -07001392 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1393 CreateSessionDescriptionMsg* param =
1394 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1395 param->observer->OnFailure(param->error);
1396 delete param;
1397 break;
1398 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001399 case MSG_GETSTATS: {
1400 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001401 StatsReports reports;
1402 stats_->GetStats(param->track, &reports);
1403 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404 delete param;
1405 break;
1406 }
deadbeefbd292462015-12-14 18:15:29 -08001407 case MSG_FREE_DATACHANNELS: {
1408 sctp_data_channels_to_free_.clear();
1409 break;
1410 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001412 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 break;
1414 }
1415}
1416
deadbeefab9b2d12015-10-14 11:33:11 -07001417void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001418 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001419 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001420 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1421 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001422 signaling_thread(),
1423 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1424 stream->AddTrack(
1425 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001426 receivers_.push_back(receiver);
1427 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1428 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1429 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001430}
1431
deadbeefab9b2d12015-10-14 11:33:11 -07001432void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001433 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001434 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001435 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1436 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001437 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001438 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1439 session_->video_channel()));
1440 stream->AddTrack(
1441 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001442 receivers_.push_back(receiver);
1443 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1444 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1445 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001446}
1447
deadbeef70ab1a12015-09-28 16:53:55 -07001448// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1449// description.
perkjd61bf802016-03-24 03:16:19 -07001450void PeerConnection::DestroyReceiver(const std::string& track_id) {
1451 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001452 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001453 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001454 << " doesn't exist.";
1455 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001456 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001457 receivers_.erase(it);
1458 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001459}
1460
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001461void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
1462 MediaStreamInterface* stream) {
1463 RTC_DCHECK(!IsClosed());
1464 auto sender = FindSenderForTrack(track);
1465 if (sender != senders_.end()) {
1466 // We already have a sender for this track, so just change the stream_id
1467 // so that it's correct in the next call to CreateOffer.
1468 (*sender)->internal()->set_stream_id(stream->label());
1469 return;
1470 }
1471
1472 // Normal case; we've never seen this track before.
1473 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1474 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1475 signaling_thread(),
1476 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1477 stats_.get()));
1478 senders_.push_back(new_sender);
1479 // If the sender has already been configured in SDP, we call SetSsrc,
1480 // which will connect the sender to the underlying transport. This can
1481 // occur if a local session description that contains the ID of the sender
1482 // is set before AddStream is called. It can also occur if the local
1483 // session description is not changed and RemoveStream is called, and
1484 // later AddStream is called again with the same stream.
1485 const TrackInfo* track_info =
1486 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1487 if (track_info) {
1488 new_sender->internal()->SetSsrc(track_info->ssrc);
1489 }
1490}
1491
1492// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1493// indefinitely, when we have unified plan SDP.
1494void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
1495 MediaStreamInterface* stream) {
1496 RTC_DCHECK(!IsClosed());
1497 auto sender = FindSenderForTrack(track);
1498 if (sender == senders_.end()) {
1499 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1500 << " doesn't exist.";
1501 return;
1502 }
1503 (*sender)->internal()->Stop();
1504 senders_.erase(sender);
1505}
1506
1507void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
1508 MediaStreamInterface* stream) {
1509 RTC_DCHECK(!IsClosed());
1510 auto sender = FindSenderForTrack(track);
1511 if (sender != senders_.end()) {
1512 // We already have a sender for this track, so just change the stream_id
1513 // so that it's correct in the next call to CreateOffer.
1514 (*sender)->internal()->set_stream_id(stream->label());
1515 return;
1516 }
1517
1518 // Normal case; we've never seen this track before.
1519 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1520 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1521 signaling_thread(), new VideoRtpSender(track, stream->label(),
1522 session_->video_channel()));
1523 senders_.push_back(new_sender);
1524 const TrackInfo* track_info =
1525 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1526 if (track_info) {
1527 new_sender->internal()->SetSsrc(track_info->ssrc);
1528 }
1529}
1530
1531void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
1532 MediaStreamInterface* stream) {
1533 RTC_DCHECK(!IsClosed());
1534 auto sender = FindSenderForTrack(track);
1535 if (sender == senders_.end()) {
1536 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1537 << " doesn't exist.";
1538 return;
1539 }
1540 (*sender)->internal()->Stop();
1541 senders_.erase(sender);
1542}
1543
zstein6dfd53a2017-03-06 13:49:03 -08001544void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001546 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001547 // After transitioning to "closed", ignore any additional states from
1548 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001549 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001550 return;
1551 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001552 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001553 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001554}
1555
1556void PeerConnection::OnIceGatheringChange(
1557 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001558 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001559 if (IsClosed()) {
1560 return;
1561 }
1562 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001563 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001564}
1565
jbauch81bf7b02017-03-25 08:31:12 -07001566void PeerConnection::OnIceCandidate(
1567 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001568 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001569 if (IsClosed()) {
1570 return;
1571 }
jbauch81bf7b02017-03-25 08:31:12 -07001572 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001573}
1574
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001575void PeerConnection::OnIceCandidatesRemoved(
1576 const std::vector<cricket::Candidate>& candidates) {
1577 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001578 if (IsClosed()) {
1579 return;
1580 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001581 observer_->OnIceCandidatesRemoved(candidates);
1582}
1583
Peter Thatcher54360512015-07-08 11:08:35 -07001584void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001585 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001586 if (IsClosed()) {
1587 return;
1588 }
Peter Thatcher54360512015-07-08 11:08:35 -07001589 observer_->OnIceConnectionReceivingChange(receiving);
1590}
1591
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001592void PeerConnection::ChangeSignalingState(
1593 PeerConnectionInterface::SignalingState signaling_state) {
1594 signaling_state_ = signaling_state;
1595 if (signaling_state == kClosed) {
1596 ice_connection_state_ = kIceConnectionClosed;
1597 observer_->OnIceConnectionChange(ice_connection_state_);
1598 if (ice_gathering_state_ != kIceGatheringComplete) {
1599 ice_gathering_state_ = kIceGatheringComplete;
1600 observer_->OnIceGatheringChange(ice_gathering_state_);
1601 }
1602 }
1603 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001604}
1605
deadbeefeb459812015-12-15 19:24:43 -08001606void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1607 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001608 if (IsClosed()) {
1609 return;
1610 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001611 AddAudioTrack(track, stream);
1612 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001613}
1614
deadbeefeb459812015-12-15 19:24:43 -08001615void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1616 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001617 if (IsClosed()) {
1618 return;
1619 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001620 RemoveAudioTrack(track, stream);
1621 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001622}
1623
1624void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1625 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001626 if (IsClosed()) {
1627 return;
1628 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001629 AddVideoTrack(track, stream);
1630 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001631}
1632
1633void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1634 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001635 if (IsClosed()) {
1636 return;
1637 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001638 RemoveVideoTrack(track, stream);
1639 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001640}
1641
deadbeefab9b2d12015-10-14 11:33:11 -07001642void PeerConnection::PostSetSessionDescriptionFailure(
1643 SetSessionDescriptionObserver* observer,
1644 const std::string& error) {
1645 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1646 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001647 signaling_thread()->Post(RTC_FROM_HERE, this,
1648 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001649}
1650
1651void PeerConnection::PostCreateSessionDescriptionFailure(
1652 CreateSessionDescriptionObserver* observer,
1653 const std::string& error) {
1654 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1655 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001656 signaling_thread()->Post(RTC_FROM_HERE, this,
1657 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001658}
1659
zhihuanga77e6bb2017-08-14 18:17:48 -07001660void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07001661 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1662 cricket::MediaSessionOptions* session_options) {
zhihuanga77e6bb2017-08-14 18:17:48 -07001663 ExtractSharedMediaSessionOptions(rtc_options, session_options);
1664
1665 // Figure out transceiver directional preferences.
1666 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1667 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1668
1669 // By default, generate sendrecv/recvonly m= sections.
1670 bool recv_audio = true;
1671 bool recv_video = true;
1672
1673 // By default, only offer a new m= section if we have media to send with it.
1674 bool offer_new_audio_description = send_audio;
1675 bool offer_new_video_description = send_video;
1676 bool offer_new_data_description = HasDataChannels();
1677
1678 // The "offer_to_receive_X" options allow those defaults to be overridden.
1679 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1680 recv_audio = (rtc_options.offer_to_receive_audio > 0);
1681 offer_new_audio_description =
1682 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
1683 }
1684 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1685 recv_video = (rtc_options.offer_to_receive_video > 0);
1686 offer_new_video_description =
1687 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
1688 }
1689
1690 int audio_index = -1;
1691 int video_index = -1;
1692 int data_index = -1;
1693 // If a current description exists, generate m= sections in the same order,
1694 // using the first audio/video/data section that appears and rejecting
1695 // extraneous ones.
deadbeef0ed85b22016-02-23 17:24:52 -08001696 if (session_->local_description()) {
zhihuanga77e6bb2017-08-14 18:17:48 -07001697 GenerateMediaDescriptionOptions(
1698 session_->local_description(),
1699 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1700 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1701 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001702 }
1703
zhihuanga77e6bb2017-08-14 18:17:48 -07001704 // Add audio/video/data m= sections to the end if needed.
1705 if (audio_index == -1 && offer_new_audio_description) {
1706 session_options->media_description_options.push_back(
1707 cricket::MediaDescriptionOptions(
1708 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
1709 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
1710 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07001711 }
zhihuanga77e6bb2017-08-14 18:17:48 -07001712 if (video_index == -1 && offer_new_video_description) {
1713 session_options->media_description_options.push_back(
1714 cricket::MediaDescriptionOptions(
1715 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
1716 cricket::RtpTransceiverDirection(send_video, recv_video), false));
1717 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07001718 }
zhihuanga77e6bb2017-08-14 18:17:48 -07001719 if (data_index == -1 && offer_new_data_description) {
1720 session_options->media_description_options.push_back(
1721 cricket::MediaDescriptionOptions(
1722 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
1723 cricket::RtpTransceiverDirection(true, true), false));
1724 data_index = session_options->media_description_options.size() - 1;
1725 }
1726
1727 cricket::MediaDescriptionOptions* audio_media_description_options =
1728 audio_index == -1
1729 ? nullptr
1730 : &session_options->media_description_options[audio_index];
1731 cricket::MediaDescriptionOptions* video_media_description_options =
1732 video_index == -1
1733 ? nullptr
1734 : &session_options->media_description_options[video_index];
1735 cricket::MediaDescriptionOptions* data_media_description_options =
1736 data_index == -1
1737 ? nullptr
1738 : &session_options->media_description_options[data_index];
1739
1740 // Apply ICE restart flag and renomination flag.
1741 for (auto& options : session_options->media_description_options) {
1742 options.transport_options.ice_restart = rtc_options.ice_restart;
1743 options.transport_options.enable_ice_renomination =
1744 configuration_.enable_ice_renomination;
1745 }
1746
1747 AddRtpSenderOptions(senders_, audio_media_description_options,
1748 video_media_description_options);
1749 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07001750
zhihuang9763d562016-08-05 11:14:50 -07001751 // Intentionally unset the data channel type for RTP data channel with the
1752 // second condition. Otherwise the RTP data channels would be successfully
1753 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1754 // when building with chromium. We want to leave RTP data channels broken, so
1755 // people won't try to use them.
zhihuanga77e6bb2017-08-14 18:17:48 -07001756 if (!rtp_data_channels_.empty() ||
1757 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001758 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001759 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001760
1761 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001762 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001763}
1764
zhihuanga77e6bb2017-08-14 18:17:48 -07001765void PeerConnection::GetOptionsForAnswer(
1766 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001767 cricket::MediaSessionOptions* session_options) {
zhihuanga77e6bb2017-08-14 18:17:48 -07001768 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001769
zhihuanga77e6bb2017-08-14 18:17:48 -07001770 // Figure out transceiver directional preferences.
1771 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1772 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1773
1774 // By default, generate sendrecv/recvonly m= sections. The direction is also
1775 // restricted by the direction in the offer.
1776 bool recv_audio = true;
1777 bool recv_video = true;
1778
1779 // The "offer_to_receive_X" options allow those defaults to be overridden.
1780 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1781 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08001782 }
zhihuanga77e6bb2017-08-14 18:17:48 -07001783 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1784 recv_video = (rtc_options.offer_to_receive_video > 0);
1785 }
1786
1787 int audio_index = -1;
1788 int video_index = -1;
1789 int data_index = -1;
1790 // There should be a pending remote description that's an offer...
1791 RTC_DCHECK(session_->remote_description());
1792 RTC_DCHECK(session_->remote_description()->type() ==
1793 SessionDescriptionInterface::kOffer);
1794 // Generate m= sections that match those in the offer.
1795 // Note that mediasession.cc will handle intersection our preferred direction
1796 // with the offered direction.
1797 GenerateMediaDescriptionOptions(
1798 session_->remote_description(),
1799 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1800 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1801 &video_index, &data_index, session_options);
1802
1803 cricket::MediaDescriptionOptions* audio_media_description_options =
1804 audio_index == -1
1805 ? nullptr
1806 : &session_options->media_description_options[audio_index];
1807 cricket::MediaDescriptionOptions* video_media_description_options =
1808 video_index == -1
1809 ? nullptr
1810 : &session_options->media_description_options[video_index];
1811 cricket::MediaDescriptionOptions* data_media_description_options =
1812 data_index == -1
1813 ? nullptr
1814 : &session_options->media_description_options[data_index];
1815
1816 // Apply ICE renomination flag.
1817 for (auto& options : session_options->media_description_options) {
1818 options.transport_options.enable_ice_renomination =
1819 configuration_.enable_ice_renomination;
1820 }
1821
1822 AddRtpSenderOptions(senders_, audio_media_description_options,
1823 video_media_description_options);
1824 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
1825
zhihuang9763d562016-08-05 11:14:50 -07001826 // Intentionally unset the data channel type for RTP data channel. Otherwise
1827 // the RTP data channels would be successfully negotiated by default and the
1828 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1829 // We want to leave RTP data channels broken, so people won't try to use them.
zhihuanga77e6bb2017-08-14 18:17:48 -07001830 if (!rtp_data_channels_.empty() ||
1831 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001832 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001833 }
zhihuangaf388472016-11-02 16:49:48 -07001834
zhihuanga77e6bb2017-08-14 18:17:48 -07001835 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001836 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001837}
1838
zhihuanga77e6bb2017-08-14 18:17:48 -07001839void PeerConnection::GenerateMediaDescriptionOptions(
1840 const SessionDescriptionInterface* session_desc,
1841 cricket::RtpTransceiverDirection audio_direction,
1842 cricket::RtpTransceiverDirection video_direction,
1843 int* audio_index,
1844 int* video_index,
1845 int* data_index,
htaa2a49d92016-03-04 02:51:39 -08001846 cricket::MediaSessionOptions* session_options) {
zhihuanga77e6bb2017-08-14 18:17:48 -07001847 for (const cricket::ContentInfo& content :
1848 session_desc->description()->contents()) {
1849 if (IsAudioContent(&content)) {
1850 // If we already have an audio m= section, reject this extra one.
1851 if (*audio_index != -1) {
1852 session_options->media_description_options.push_back(
1853 cricket::MediaDescriptionOptions(
1854 cricket::MEDIA_TYPE_AUDIO, content.name,
1855 cricket::RtpTransceiverDirection(false, false), true));
1856 } else {
1857 session_options->media_description_options.push_back(
1858 cricket::MediaDescriptionOptions(
1859 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
1860 !audio_direction.send && !audio_direction.recv));
1861 *audio_index = session_options->media_description_options.size() - 1;
1862 }
1863 } else if (IsVideoContent(&content)) {
1864 // If we already have an video m= section, reject this extra one.
1865 if (*video_index != -1) {
1866 session_options->media_description_options.push_back(
1867 cricket::MediaDescriptionOptions(
1868 cricket::MEDIA_TYPE_VIDEO, content.name,
1869 cricket::RtpTransceiverDirection(false, false), true));
1870 } else {
1871 session_options->media_description_options.push_back(
1872 cricket::MediaDescriptionOptions(
1873 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
1874 !video_direction.send && !video_direction.recv));
1875 *video_index = session_options->media_description_options.size() - 1;
1876 }
1877 } else {
1878 RTC_DCHECK(IsDataContent(&content));
1879 // If we already have an data m= section, reject this extra one.
1880 if (*data_index != -1) {
1881 session_options->media_description_options.push_back(
1882 cricket::MediaDescriptionOptions(
1883 cricket::MEDIA_TYPE_DATA, content.name,
1884 cricket::RtpTransceiverDirection(false, false), true));
1885 } else {
1886 session_options->media_description_options.push_back(
1887 cricket::MediaDescriptionOptions(
1888 cricket::MEDIA_TYPE_DATA, content.name,
1889 // Direction for data sections is meaningless, but legacy
1890 // endpoints might expect sendrecv.
1891 cricket::RtpTransceiverDirection(true, true), false));
1892 *data_index = session_options->media_description_options.size() - 1;
1893 }
1894 }
htaa2a49d92016-03-04 02:51:39 -08001895 }
deadbeefab9b2d12015-10-14 11:33:11 -07001896}
1897
deadbeeffaac4972015-11-12 15:33:07 -08001898void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1899 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001900 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1901 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001902}
1903
deadbeefab9b2d12015-10-14 11:33:11 -07001904void PeerConnection::UpdateRemoteStreamsList(
1905 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001906 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001907 cricket::MediaType media_type,
1908 StreamCollection* new_streams) {
1909 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1910
1911 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001912 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001913 auto track_it = current_tracks->begin();
1914 while (track_it != current_tracks->end()) {
1915 const TrackInfo& info = *track_it;
1916 const cricket::StreamParams* params =
1917 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001918 bool track_exists = params && params->id == info.track_id;
1919 // If this is a default track, and we still need it, don't remove it.
1920 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1921 track_exists) {
1922 ++track_it;
1923 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001924 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1925 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001926 }
1927 }
1928
1929 // Find new and active tracks.
1930 for (const cricket::StreamParams& params : streams) {
1931 // The sync_label is the MediaStream label and the |stream.id| is the
1932 // track id.
1933 const std::string& stream_label = params.sync_label;
1934 const std::string& track_id = params.id;
1935 uint32_t ssrc = params.first_ssrc();
1936
1937 rtc::scoped_refptr<MediaStreamInterface> stream =
1938 remote_streams_->find(stream_label);
1939 if (!stream) {
1940 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001941 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1942 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001943 remote_streams_->AddStream(stream);
1944 new_streams->AddStream(stream);
1945 }
1946
1947 const TrackInfo* track_info =
1948 FindTrackInfo(*current_tracks, stream_label, track_id);
1949 if (!track_info) {
1950 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1951 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1952 }
1953 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001954
1955 // Add default track if necessary.
1956 if (default_track_needed) {
1957 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1958 remote_streams_->find(kDefaultStreamLabel);
1959 if (!default_stream) {
1960 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001961 default_stream = MediaStreamProxy::Create(
1962 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001963 remote_streams_->AddStream(default_stream);
1964 new_streams->AddStream(default_stream);
1965 }
1966 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1967 ? kDefaultAudioTrackLabel
1968 : kDefaultVideoTrackLabel;
1969 const TrackInfo* default_track_info =
1970 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1971 if (!default_track_info) {
1972 current_tracks->push_back(
1973 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1974 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1975 }
1976 }
deadbeefab9b2d12015-10-14 11:33:11 -07001977}
1978
1979void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1980 const std::string& track_id,
1981 uint32_t ssrc,
1982 cricket::MediaType media_type) {
1983 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1984
1985 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001986 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001987 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001988 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001989 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08001990 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001991 }
1992}
1993
1994void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1995 const std::string& track_id,
1996 cricket::MediaType media_type) {
1997 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1998
1999 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002000 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2001 // will be notified which will end the AudioRtpReceiver::track().
2002 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002003 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2004 stream->FindAudioTrack(track_id);
2005 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002006 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002007 }
2008 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002009 // Stopping or destroying a VideoRtpReceiver will end the
2010 // VideoRtpReceiver::track().
2011 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002012 rtc::scoped_refptr<VideoTrackInterface> video_track =
2013 stream->FindVideoTrack(track_id);
2014 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002015 // There's no guarantee the track is still available, e.g. the track may
2016 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002017 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002018 }
2019 } else {
nisseede5da42017-01-12 05:15:36 -08002020 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002021 }
2022}
2023
2024void PeerConnection::UpdateEndedRemoteMediaStreams() {
2025 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2026 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2027 MediaStreamInterface* stream = remote_streams_->at(i);
2028 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2029 streams_to_remove.push_back(stream);
2030 }
2031 }
2032
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002033 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002034 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002035 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002036 }
2037}
2038
deadbeefab9b2d12015-10-14 11:33:11 -07002039void PeerConnection::UpdateLocalTracks(
2040 const std::vector<cricket::StreamParams>& streams,
2041 cricket::MediaType media_type) {
2042 TrackInfos* current_tracks = GetLocalTracks(media_type);
2043
2044 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2045 // don't match the new StreamParam.
2046 TrackInfos::iterator track_it = current_tracks->begin();
2047 while (track_it != current_tracks->end()) {
2048 const TrackInfo& info = *track_it;
2049 const cricket::StreamParams* params =
2050 cricket::GetStreamBySsrc(streams, info.ssrc);
2051 if (!params || params->id != info.track_id ||
2052 params->sync_label != info.stream_label) {
2053 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2054 media_type);
2055 track_it = current_tracks->erase(track_it);
2056 } else {
2057 ++track_it;
2058 }
2059 }
2060
2061 // Find new and active tracks.
2062 for (const cricket::StreamParams& params : streams) {
2063 // The sync_label is the MediaStream label and the |stream.id| is the
2064 // track id.
2065 const std::string& stream_label = params.sync_label;
2066 const std::string& track_id = params.id;
2067 uint32_t ssrc = params.first_ssrc();
2068 const TrackInfo* track_info =
2069 FindTrackInfo(*current_tracks, stream_label, track_id);
2070 if (!track_info) {
2071 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2072 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2073 }
2074 }
2075}
2076
2077void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2078 const std::string& track_id,
2079 uint32_t ssrc,
2080 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002081 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002082 if (!sender) {
2083 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2084 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002085 return;
2086 }
2087
deadbeeffac06552015-11-25 11:26:01 -08002088 if (sender->media_type() != media_type) {
2089 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2090 << " description with an unexpected media type.";
2091 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002092 }
deadbeeffac06552015-11-25 11:26:01 -08002093
2094 sender->set_stream_id(stream_label);
2095 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002096}
2097
2098void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2099 const std::string& track_id,
2100 uint32_t ssrc,
2101 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002102 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002103 if (!sender) {
2104 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002105 // SessionDescriptions has been renegotiated.
2106 return;
2107 }
deadbeeffac06552015-11-25 11:26:01 -08002108
2109 // A sender has been removed from the SessionDescription but it's still
2110 // associated with the PeerConnection. This only occurs if the SDP doesn't
2111 // match with the calls to CreateSender, AddStream and RemoveStream.
2112 if (sender->media_type() != media_type) {
2113 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2114 << " description with an unexpected media type.";
2115 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002116 }
deadbeeffac06552015-11-25 11:26:01 -08002117
2118 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002119}
2120
2121void PeerConnection::UpdateLocalRtpDataChannels(
2122 const cricket::StreamParamsVec& streams) {
2123 std::vector<std::string> existing_channels;
2124
2125 // Find new and active data channels.
2126 for (const cricket::StreamParams& params : streams) {
2127 // |it->sync_label| is actually the data channel label. The reason is that
2128 // we use the same naming of data channels as we do for
2129 // MediaStreams and Tracks.
2130 // For MediaStreams, the sync_label is the MediaStream label and the
2131 // track label is the same as |streamid|.
2132 const std::string& channel_label = params.sync_label;
2133 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002134 if (data_channel_it == rtp_data_channels_.end()) {
2135 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002136 continue;
2137 }
2138 // Set the SSRC the data channel should use for sending.
2139 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2140 existing_channels.push_back(data_channel_it->first);
2141 }
2142
2143 UpdateClosingRtpDataChannels(existing_channels, true);
2144}
2145
2146void PeerConnection::UpdateRemoteRtpDataChannels(
2147 const cricket::StreamParamsVec& streams) {
2148 std::vector<std::string> existing_channels;
2149
2150 // Find new and active data channels.
2151 for (const cricket::StreamParams& params : streams) {
2152 // The data channel label is either the mslabel or the SSRC if the mslabel
2153 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2154 std::string label = params.sync_label.empty()
2155 ? rtc::ToString(params.first_ssrc())
2156 : params.sync_label;
2157 auto data_channel_it = rtp_data_channels_.find(label);
2158 if (data_channel_it == rtp_data_channels_.end()) {
2159 // This is a new data channel.
2160 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2161 } else {
2162 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2163 }
2164 existing_channels.push_back(label);
2165 }
2166
2167 UpdateClosingRtpDataChannels(existing_channels, false);
2168}
2169
2170void PeerConnection::UpdateClosingRtpDataChannels(
2171 const std::vector<std::string>& active_channels,
2172 bool is_local_update) {
2173 auto it = rtp_data_channels_.begin();
2174 while (it != rtp_data_channels_.end()) {
2175 DataChannel* data_channel = it->second;
2176 if (std::find(active_channels.begin(), active_channels.end(),
2177 data_channel->label()) != active_channels.end()) {
2178 ++it;
2179 continue;
2180 }
2181
2182 if (is_local_update) {
2183 data_channel->SetSendSsrc(0);
2184 } else {
2185 data_channel->RemotePeerRequestClose();
2186 }
2187
2188 if (data_channel->state() == DataChannel::kClosed) {
2189 rtp_data_channels_.erase(it);
2190 it = rtp_data_channels_.begin();
2191 } else {
2192 ++it;
2193 }
2194 }
2195}
2196
2197void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2198 uint32_t remote_ssrc) {
2199 rtc::scoped_refptr<DataChannel> channel(
2200 InternalCreateDataChannel(label, nullptr));
2201 if (!channel.get()) {
2202 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2203 << "CreateDataChannel failed.";
2204 return;
2205 }
2206 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002207 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2208 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002209 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002210}
2211
2212rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2213 const std::string& label,
2214 const InternalDataChannelInit* config) {
2215 if (IsClosed()) {
2216 return nullptr;
2217 }
2218 if (session_->data_channel_type() == cricket::DCT_NONE) {
2219 LOG(LS_ERROR)
2220 << "InternalCreateDataChannel: Data is not supported in this call.";
2221 return nullptr;
2222 }
2223 InternalDataChannelInit new_config =
2224 config ? (*config) : InternalDataChannelInit();
2225 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2226 if (new_config.id < 0) {
2227 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002228 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002229 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2230 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2231 return nullptr;
2232 }
2233 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2234 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2235 << "because the id is already in use or out of range.";
2236 return nullptr;
2237 }
2238 }
2239
2240 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2241 session_.get(), session_->data_channel_type(), label, new_config));
2242 if (!channel) {
2243 sid_allocator_.ReleaseSid(new_config.id);
2244 return nullptr;
2245 }
2246
2247 if (channel->data_channel_type() == cricket::DCT_RTP) {
2248 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2249 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2250 << " already exists.";
2251 return nullptr;
2252 }
2253 rtp_data_channels_[channel->label()] = channel;
2254 } else {
2255 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2256 sctp_data_channels_.push_back(channel);
2257 channel->SignalClosed.connect(this,
2258 &PeerConnection::OnSctpDataChannelClosed);
2259 }
2260
hbos82ebe022016-11-14 01:41:09 -08002261 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002262 return channel;
2263}
2264
2265bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002266#ifdef HAVE_QUIC
2267 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2268 (session_->quic_data_transport() &&
2269 session_->quic_data_transport()->HasDataChannels());
2270#else
deadbeefab9b2d12015-10-14 11:33:11 -07002271 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002272#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002273}
2274
2275void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2276 for (const auto& channel : sctp_data_channels_) {
2277 if (channel->id() < 0) {
2278 int sid;
2279 if (!sid_allocator_.AllocateSid(role, &sid)) {
2280 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2281 continue;
2282 }
2283 channel->SetSctpSid(sid);
2284 }
2285 }
2286}
2287
2288void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002289 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002290 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2291 ++it) {
2292 if (it->get() == channel) {
2293 if (channel->id() >= 0) {
2294 sid_allocator_.ReleaseSid(channel->id());
2295 }
deadbeefbd292462015-12-14 18:15:29 -08002296 // Since this method is triggered by a signal from the DataChannel,
2297 // we can't free it directly here; we need to free it asynchronously.
2298 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002299 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002300 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2301 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002302 return;
2303 }
2304 }
2305}
2306
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002307void PeerConnection::OnVoiceChannelCreated() {
2308 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2309 session_->voice_channel(), senders_, receivers_,
2310 cricket::MEDIA_TYPE_AUDIO);
2311}
2312
deadbeefab9b2d12015-10-14 11:33:11 -07002313void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002314 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2315 cricket::VoiceChannel>(
2316 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2317}
2318
2319void PeerConnection::OnVideoChannelCreated() {
2320 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2321 session_->video_channel(), senders_, receivers_,
2322 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002323}
2324
2325void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002326 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2327 cricket::VideoChannel>(
2328 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002329}
2330
2331void PeerConnection::OnDataChannelCreated() {
2332 for (const auto& channel : sctp_data_channels_) {
2333 channel->OnTransportChannelCreated();
2334 }
2335}
2336
2337void PeerConnection::OnDataChannelDestroyed() {
2338 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2339 // DataChannel may callback to us and try to modify the list.
2340 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2341 temp_rtp_dcs.swap(rtp_data_channels_);
2342 for (const auto& kv : temp_rtp_dcs) {
2343 kv.second->OnTransportChannelDestroyed();
2344 }
2345
2346 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2347 temp_sctp_dcs.swap(sctp_data_channels_);
2348 for (const auto& channel : temp_sctp_dcs) {
2349 channel->OnTransportChannelDestroyed();
2350 }
2351}
2352
2353void PeerConnection::OnDataChannelOpenMessage(
2354 const std::string& label,
2355 const InternalDataChannelInit& config) {
2356 rtc::scoped_refptr<DataChannel> channel(
2357 InternalCreateDataChannel(label, &config));
2358 if (!channel.get()) {
2359 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2360 return;
2361 }
2362
deadbeefa601f5c2016-06-06 14:27:39 -07002363 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2364 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002365 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002366}
2367
zhihuanga77e6bb2017-08-14 18:17:48 -07002368bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2369 return std::find_if(
2370 senders_.begin(), senders_.end(),
2371 [type](const rtc::scoped_refptr<
2372 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2373 return sender->media_type() == type;
2374 }) != senders_.end();
2375}
2376
deadbeefa601f5c2016-06-06 14:27:39 -07002377RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2378 auto it = std::find_if(
2379 senders_.begin(), senders_.end(),
2380 [id](const rtc::scoped_refptr<
2381 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2382 return sender->id() == id;
2383 });
2384 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002385}
2386
deadbeefa601f5c2016-06-06 14:27:39 -07002387std::vector<
2388 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002389PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2390 return std::find_if(
2391 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002392 [track](const rtc::scoped_refptr<
2393 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002394 return sender->track() == track;
2395 });
2396}
2397
deadbeefa601f5c2016-06-06 14:27:39 -07002398std::vector<rtc::scoped_refptr<
2399 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002400PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002401 return std::find_if(
2402 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002403 [track_id](const rtc::scoped_refptr<
2404 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002405 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002406 });
2407}
2408
deadbeefab9b2d12015-10-14 11:33:11 -07002409PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2410 cricket::MediaType media_type) {
2411 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2412 media_type == cricket::MEDIA_TYPE_VIDEO);
2413 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2414 : &remote_video_tracks_;
2415}
2416
2417PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2418 cricket::MediaType media_type) {
2419 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2420 media_type == cricket::MEDIA_TYPE_VIDEO);
2421 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2422 : &local_video_tracks_;
2423}
2424
2425const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2426 const PeerConnection::TrackInfos& infos,
2427 const std::string& stream_label,
2428 const std::string track_id) const {
2429 for (const TrackInfo& track_info : infos) {
2430 if (track_info.stream_label == stream_label &&
2431 track_info.track_id == track_id) {
2432 return &track_info;
2433 }
2434 }
2435 return nullptr;
2436}
2437
2438DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2439 for (const auto& channel : sctp_data_channels_) {
2440 if (channel->id() == sid) {
2441 return channel;
2442 }
2443 }
2444 return nullptr;
2445}
2446
deadbeef91dd5672016-05-18 16:55:30 -07002447bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002448 const RTCConfiguration& configuration) {
2449 cricket::ServerAddresses stun_servers;
2450 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002451 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2452 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002453 return false;
2454 }
2455
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002456 port_allocator_->Initialize();
2457
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002458 // To handle both internal and externally created port allocator, we will
2459 // enable BUNDLE here.
2460 int portallocator_flags = port_allocator_->flags();
2461 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002462 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2463 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002464 // If the disable-IPv6 flag was specified, we'll not override it
2465 // by experiment.
2466 if (configuration.disable_ipv6) {
2467 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002468 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2469 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002470 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2471 }
2472
zhihuangb09b3f92017-03-07 14:40:51 -08002473 if (configuration.disable_ipv6_on_wifi) {
2474 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2475 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2476 }
2477
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002478 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2479 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2480 LOG(LS_INFO) << "TCP candidates are disabled.";
2481 }
2482
honghaiz60347052016-05-31 18:29:12 -07002483 if (configuration.candidate_network_policy ==
2484 kCandidateNetworkPolicyLowCost) {
2485 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2486 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2487 }
2488
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002489 port_allocator_->set_flags(portallocator_flags);
2490 // No step delay is used while allocating ports.
2491 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2492 port_allocator_->set_candidate_filter(
2493 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07002494 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002495
2496 // Call this last since it may create pooled allocator sessions using the
2497 // properties set above.
2498 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002499 configuration.ice_candidate_pool_size,
2500 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002501 return true;
2502}
2503
deadbeef91dd5672016-05-18 16:55:30 -07002504bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002505 const cricket::ServerAddresses& stun_servers,
2506 const std::vector<cricket::RelayServerConfig>& turn_servers,
2507 IceTransportsType type,
2508 int candidate_pool_size,
2509 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002510 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002511 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002512 // Call this last since it may create pooled allocator sessions using the
2513 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002514 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002515 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002516}
2517
ivoc14d5dbe2016-07-04 07:06:55 -07002518bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2519 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002520 if (!event_log_) {
2521 return false;
2522 }
skvlad11a9cbf2016-10-07 11:53:05 -07002523 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002524}
2525
2526void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002527 if (event_log_) {
2528 event_log_->StopLogging();
2529 }
ivoc14d5dbe2016-07-04 07:06:55 -07002530}
nisseeaabdf62017-05-05 02:23:02 -07002531
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002532} // namespace webrtc