blob: b258c1fc999c887c172d93a958d5f7c072ab3f19 [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
zhihuang1c378ed2017-08-17 14:10:50 -0700136// Add options to |[audio/video]_media_description_options| from |senders|.
137void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700138 const std::vector<rtc::scoped_refptr<
139 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700140 cricket::MediaDescriptionOptions* audio_media_description_options,
141 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700142 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700143 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
144 if (audio_media_description_options) {
145 audio_media_description_options->AddAudioSender(
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 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700155 }
zhihuang1c378ed2017-08-17 14:10:50 -0700156}
olka3c747662017-08-17 06:50:32 -0700157
zhihuang1c378ed2017-08-17 14:10:50 -0700158// Add options to |session_options| from |rtp_data_channels|.
159void AddRtpDataChannelOptions(
160 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
161 rtp_data_channels,
162 cricket::MediaDescriptionOptions* data_media_description_options) {
163 if (!data_media_description_options) {
164 return;
165 }
deadbeefab9b2d12015-10-14 11:33:11 -0700166 // Check for data channels.
167 for (const auto& kv : rtp_data_channels) {
168 const DataChannel* channel = kv.second;
169 if (channel->state() == DataChannel::kConnecting ||
170 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700171 // Legacy RTP data channels are signaled with the track/stream ID set to
172 // the data channel's label.
173 data_media_description_options->AddRtpDataChannel(channel->label(),
174 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700175 }
176 }
177}
178
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700179uint32_t ConvertIceTransportTypeToCandidateFilter(
180 PeerConnectionInterface::IceTransportsType type) {
181 switch (type) {
182 case PeerConnectionInterface::kNone:
183 return cricket::CF_NONE;
184 case PeerConnectionInterface::kRelay:
185 return cricket::CF_RELAY;
186 case PeerConnectionInterface::kNoHost:
187 return (cricket::CF_ALL & ~cricket::CF_HOST);
188 case PeerConnectionInterface::kAll:
189 return cricket::CF_ALL;
190 default:
nissec80e7412017-01-11 05:56:46 -0800191 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700192 }
193 return cricket::CF_NONE;
194}
195
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700196// Helper method to set a voice/video channel on all applicable senders
197// and receivers when one is created/destroyed by WebRtcSession.
198//
199// Used by On(Voice|Video)Channel(Created|Destroyed)
200template <class SENDER,
201 class RECEIVER,
202 class CHANNEL,
203 class SENDERS,
204 class RECEIVERS>
205void SetChannelOnSendersAndReceivers(CHANNEL* channel,
206 SENDERS& senders,
207 RECEIVERS& receivers,
208 cricket::MediaType media_type) {
209 for (auto& sender : senders) {
210 if (sender->media_type() == media_type) {
211 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
212 }
213 }
214 for (auto& receiver : receivers) {
215 if (receiver->media_type() == media_type) {
216 if (!channel) {
217 receiver->internal()->Stop();
218 }
219 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
220 }
221 }
222}
223
deadbeef293e9262017-01-11 12:28:30 -0800224// Helper to set an error and return from a method.
225bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
226 if (error) {
227 error->set_type(type);
228 }
229 return type == webrtc::RTCErrorType::NONE;
230}
231
Steve Anton038834f2017-07-14 15:59:59 -0700232bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
233 if (error_out) {
234 *error_out = std::move(error);
235 }
236 return error.ok();
237}
238
deadbeef0a6c4ca2015-10-06 11:38:28 -0700239} // namespace
240
241namespace webrtc {
242
deadbeef293e9262017-01-11 12:28:30 -0800243bool PeerConnectionInterface::RTCConfiguration::operator==(
244 const PeerConnectionInterface::RTCConfiguration& o) const {
245 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700246 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800247 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000248 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700249 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800250 BundlePolicy bundle_policy;
251 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700252 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
253 int ice_candidate_pool_size;
254 bool disable_ipv6;
255 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700256 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700257 bool enable_rtp_data_channel;
258 rtc::Optional<int> screencast_min_bitrate;
259 rtc::Optional<bool> combined_audio_video_bwe;
260 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800261 TcpCandidatePolicy tcp_candidate_policy;
262 CandidateNetworkPolicy candidate_network_policy;
263 int audio_jitter_buffer_max_packets;
264 bool audio_jitter_buffer_fast_accelerate;
265 int ice_connection_receiving_timeout;
266 int ice_backup_candidate_pair_ping_interval;
267 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800268 bool prioritize_most_likely_ice_candidate_pairs;
269 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800270 bool enable_quic;
deadbeef293e9262017-01-11 12:28:30 -0800271 bool prune_turn_ports;
272 bool presume_writable_when_fully_relayed;
273 bool enable_ice_renomination;
274 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800275 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700276 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800277 };
278 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
279 "Did you add something to RTCConfiguration and forget to "
280 "update operator==?");
281 return type == o.type && servers == o.servers &&
282 bundle_policy == o.bundle_policy &&
283 rtcp_mux_policy == o.rtcp_mux_policy &&
284 tcp_candidate_policy == o.tcp_candidate_policy &&
285 candidate_network_policy == o.candidate_network_policy &&
286 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
287 audio_jitter_buffer_fast_accelerate ==
288 o.audio_jitter_buffer_fast_accelerate &&
289 ice_connection_receiving_timeout ==
290 o.ice_connection_receiving_timeout &&
291 ice_backup_candidate_pair_ping_interval ==
292 o.ice_backup_candidate_pair_ping_interval &&
293 continual_gathering_policy == o.continual_gathering_policy &&
294 certificates == o.certificates &&
295 prioritize_most_likely_ice_candidate_pairs ==
296 o.prioritize_most_likely_ice_candidate_pairs &&
297 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800298 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700299 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800300 enable_rtp_data_channel == o.enable_rtp_data_channel &&
301 enable_quic == o.enable_quic &&
302 screencast_min_bitrate == o.screencast_min_bitrate &&
303 combined_audio_video_bwe == o.combined_audio_video_bwe &&
304 enable_dtls_srtp == o.enable_dtls_srtp &&
305 ice_candidate_pool_size == o.ice_candidate_pool_size &&
306 prune_turn_ports == o.prune_turn_ports &&
307 presume_writable_when_fully_relayed ==
308 o.presume_writable_when_fully_relayed &&
309 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800310 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700311 ice_check_min_interval == o.ice_check_min_interval &&
312 ice_regather_interval_range == o.ice_regather_interval_range;
deadbeef293e9262017-01-11 12:28:30 -0800313}
314
315bool PeerConnectionInterface::RTCConfiguration::operator!=(
316 const PeerConnectionInterface::RTCConfiguration& o) const {
317 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800318}
319
zhihuang8f65cdf2016-05-06 18:40:30 -0700320// Generate a RTCP CNAME when a PeerConnection is created.
321std::string GenerateRtcpCname() {
322 std::string cname;
323 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
324 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800325 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700326 }
327 return cname;
328}
329
zhihuang1c378ed2017-08-17 14:10:50 -0700330bool ValidateOfferAnswerOptions(
331 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
332 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
333 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700334}
335
zhihuang1c378ed2017-08-17 14:10:50 -0700336// From |rtc_options|, fill parts of |session_options| shared by all generated
337// m= sections (in other words, nothing that involves a map/array).
338void ExtractSharedMediaSessionOptions(
339 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
340 cricket::MediaSessionOptions* session_options) {
341 session_options->vad_enabled = rtc_options.voice_activity_detection;
342 session_options->bundle_enabled = rtc_options.use_rtp_mux;
343}
zhihuanga77e6bb2017-08-14 18:17:48 -0700344
zhihuang1c378ed2017-08-17 14:10:50 -0700345bool ConvertConstraintsToOfferAnswerOptions(
346 const MediaConstraintsInterface* constraints,
347 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700348 if (!constraints) {
349 return true;
350 }
zhihuang1c378ed2017-08-17 14:10:50 -0700351
352 bool value = false;
353 size_t mandatory_constraints_satisfied = 0;
354
355 if (FindConstraint(constraints,
356 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
357 &mandatory_constraints_satisfied)) {
358 offer_answer_options->offer_to_receive_audio =
359 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
360 kOfferToReceiveMediaTrue
361 : 0;
362 }
363
364 if (FindConstraint(constraints,
365 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
366 &mandatory_constraints_satisfied)) {
367 offer_answer_options->offer_to_receive_video =
368 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
369 kOfferToReceiveMediaTrue
370 : 0;
371 }
372 if (FindConstraint(constraints,
373 MediaConstraintsInterface::kVoiceActivityDetection, &value,
374 &mandatory_constraints_satisfied)) {
375 offer_answer_options->voice_activity_detection = value;
376 }
377 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
378 &mandatory_constraints_satisfied)) {
379 offer_answer_options->use_rtp_mux = value;
380 }
381 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
382 &value, &mandatory_constraints_satisfied)) {
383 offer_answer_options->ice_restart = value;
384 }
385
deadbeefab9b2d12015-10-14 11:33:11 -0700386 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
387}
388
zhihuang38ede132017-06-15 12:52:32 -0700389PeerConnection::PeerConnection(PeerConnectionFactory* factory,
390 std::unique_ptr<RtcEventLog> event_log,
391 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000392 : factory_(factory),
393 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000394 uma_observer_(NULL),
zhihuang38ede132017-06-15 12:52:32 -0700395 event_log_(std::move(event_log)),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000396 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000397 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700398 ice_gathering_state_(kIceGatheringNew),
zhihuang8f65cdf2016-05-06 18:40:30 -0700399 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700400 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700401 remote_streams_(StreamCollection::Create()),
402 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000403
404PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100405 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700406 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700407 // Need to detach RTP senders/receivers from WebRtcSession,
408 // since it's about to be destroyed.
409 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700410 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700411 }
412 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700413 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700414 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700415 // Destroy stats_ because it depends on session_.
416 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800417 if (stats_collector_) {
418 stats_collector_->WaitForPendingRequest();
419 stats_collector_ = nullptr;
420 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700421 // Now destroy session_ before destroying other members,
422 // because its destruction fires signals (such as VoiceChannelDestroyed)
423 // which will trigger some final actions in PeerConnection...
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(); });
eladalon248fd4f2017-09-06 05:18:15 -0700428 // call_ and event_log_ must be destroyed on the worker thread.
429 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
430 call_.reset();
431 event_log_.reset();
432 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000433}
434
435bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000436 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700437 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200438 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800439 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100440 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700441
442 RTCError config_error = ValidateConfiguration(configuration);
443 if (!config_error.ok()) {
444 LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
445 return false;
446 }
447
deadbeef293e9262017-01-11 12:28:30 -0800448 if (!allocator) {
449 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
450 << "This shouldn't happen if using PeerConnectionFactory.";
451 return false;
452 }
deadbeef653b8e02015-11-11 12:55:10 -0800453 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800454 // TODO(deadbeef): Why do we do this?
455 LOG(LS_ERROR) << "PeerConnection initialized without a "
456 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800457 return false;
458 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000459 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800460 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800461
deadbeef91dd5672016-05-18 16:55:30 -0700462 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700463 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700464 if (!network_thread()->Invoke<bool>(
465 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
466 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000467 return false;
468 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000469
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000470
zhihuang29ff8442016-07-27 11:07:25 -0700471 session_.reset(new WebRtcSession(
nisseeaabdf62017-05-05 02:23:02 -0700472 call_.get(), factory_->channel_manager(), configuration.media_config,
473 event_log_.get(),
474 factory_->network_thread(),
zhihuang29ff8442016-07-27 11:07:25 -0700475 factory_->worker_thread(), factory_->signaling_thread(),
476 port_allocator_.get(),
477 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700478 factory_->CreateTransportController(
479 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800480 configuration.redetermine_role_on_ice_restart)),
481#ifdef HAVE_SCTP
482 std::unique_ptr<cricket::SctpTransportInternalFactory>(
483 new cricket::SctpTransportFactory(factory_->network_thread()))
484#else
485 nullptr
486#endif
487 ));
zhihuang29ff8442016-07-27 11:07:25 -0700488
deadbeefab9b2d12015-10-14 11:33:11 -0700489 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700490 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000491
492 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200493 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800494 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000495 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700496 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000497
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000498 // Register PeerConnection as receiver of local ice candidates.
499 // All the callbacks will be posted to the application from PeerConnection.
500 session_->RegisterIceObserver(this);
501 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700502 session_->SignalVoiceChannelCreated.connect(
503 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700504 session_->SignalVoiceChannelDestroyed.connect(
505 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700506 session_->SignalVideoChannelCreated.connect(
507 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700508 session_->SignalVideoChannelDestroyed.connect(
509 this, &PeerConnection::OnVideoChannelDestroyed);
510 session_->SignalDataChannelCreated.connect(
511 this, &PeerConnection::OnDataChannelCreated);
512 session_->SignalDataChannelDestroyed.connect(
513 this, &PeerConnection::OnDataChannelDestroyed);
514 session_->SignalDataChannelOpenMessage.connect(
515 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800516
517 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000518 return true;
519}
520
Steve Anton038834f2017-07-14 15:59:59 -0700521RTCError PeerConnection::ValidateConfiguration(
522 const RTCConfiguration& config) const {
523 if (config.ice_regather_interval_range &&
524 config.continual_gathering_policy == GATHER_ONCE) {
525 return RTCError(RTCErrorType::INVALID_PARAMETER,
526 "ice_regather_interval_range specified but continual "
527 "gathering policy is GATHER_ONCE");
528 }
529 return RTCError::OK();
530}
531
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000532rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000533PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700534 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000535}
536
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000537rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000538PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700539 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000540}
541
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000542bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100543 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000544 if (IsClosed()) {
545 return false;
546 }
deadbeefab9b2d12015-10-14 11:33:11 -0700547 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000548 return false;
549 }
deadbeefab9b2d12015-10-14 11:33:11 -0700550
551 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800552 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
553 observer->SignalAudioTrackAdded.connect(this,
554 &PeerConnection::OnAudioTrackAdded);
555 observer->SignalAudioTrackRemoved.connect(
556 this, &PeerConnection::OnAudioTrackRemoved);
557 observer->SignalVideoTrackAdded.connect(this,
558 &PeerConnection::OnVideoTrackAdded);
559 observer->SignalVideoTrackRemoved.connect(
560 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700561 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700562
deadbeefab9b2d12015-10-14 11:33:11 -0700563 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700564 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700565 }
566 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700567 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700568 }
569
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000570 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000571 observer_->OnRenegotiationNeeded();
572 return true;
573}
574
575void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100576 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700577 if (!IsClosed()) {
578 for (const auto& track : local_stream->GetAudioTracks()) {
579 RemoveAudioTrack(track.get(), local_stream);
580 }
581 for (const auto& track : local_stream->GetVideoTracks()) {
582 RemoveVideoTrack(track.get(), local_stream);
583 }
deadbeefab9b2d12015-10-14 11:33:11 -0700584 }
deadbeefab9b2d12015-10-14 11:33:11 -0700585 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800586 stream_observers_.erase(
587 std::remove_if(
588 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700589 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800590 return observer->stream()->label().compare(local_stream->label()) ==
591 0;
592 }),
593 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700594
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000595 if (IsClosed()) {
596 return;
597 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000598 observer_->OnRenegotiationNeeded();
599}
600
deadbeefe1f9d832016-01-14 15:35:42 -0800601rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
602 MediaStreamTrackInterface* track,
603 std::vector<MediaStreamInterface*> streams) {
604 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
605 if (IsClosed()) {
606 return nullptr;
607 }
608 if (streams.size() >= 2) {
609 LOG(LS_ERROR)
610 << "Adding a track with two streams is not currently supported.";
611 return nullptr;
612 }
613 // TODO(deadbeef): Support adding a track to two different senders.
614 if (FindSenderForTrack(track) != senders_.end()) {
615 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
616 return nullptr;
617 }
618
619 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700620 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800621 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700622 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800623 signaling_thread(),
624 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700625 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800626 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700627 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800628 }
629 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700630 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800631 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700632 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800633 }
634 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700635 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800636 signaling_thread(),
637 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700638 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800639 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700640 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800641 }
642 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700643 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800644 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700645 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800646 }
647 } else {
648 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
649 return rtc::scoped_refptr<RtpSenderInterface>();
650 }
651
652 senders_.push_back(new_sender);
653 observer_->OnRenegotiationNeeded();
654 return new_sender;
655}
656
657bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
658 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
659 if (IsClosed()) {
660 return false;
661 }
662
663 auto it = std::find(senders_.begin(), senders_.end(), sender);
664 if (it == senders_.end()) {
665 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
666 return false;
667 }
deadbeefa601f5c2016-06-06 14:27:39 -0700668 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800669 senders_.erase(it);
670
671 observer_->OnRenegotiationNeeded();
672 return true;
673}
674
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000675rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000676 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100677 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700678 if (IsClosed()) {
679 return nullptr;
680 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000681 if (!track) {
682 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800683 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000684 }
deadbeef20cb0c12017-02-01 20:27:00 -0800685 auto it = FindSenderForTrack(track);
686 if (it == senders_.end()) {
687 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
688 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000689 }
690
deadbeef20cb0c12017-02-01 20:27:00 -0800691 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000692}
693
deadbeeffac06552015-11-25 11:26:01 -0800694rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800695 const std::string& kind,
696 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100697 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700698 if (IsClosed()) {
699 return nullptr;
700 }
deadbeefa601f5c2016-06-06 14:27:39 -0700701 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800702 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700703 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700704 signaling_thread(),
705 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800706 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700707 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700708 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800709 } else {
710 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800711 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800712 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800713 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700714 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800715 }
deadbeeffac06552015-11-25 11:26:01 -0800716 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800717 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800718}
719
deadbeef70ab1a12015-09-28 16:53:55 -0700720std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
721 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700722 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
723 for (const auto& sender : senders_) {
724 ret.push_back(sender.get());
725 }
726 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700727}
728
729std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
730PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700731 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
732 for (const auto& receiver : receivers_) {
733 ret.push_back(receiver.get());
734 }
735 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700736}
737
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000738bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000739 MediaStreamTrackInterface* track,
740 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100741 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700742 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800743 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000744 LOG(LS_ERROR) << "GetStats - observer is NULL.";
745 return false;
746 }
747
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000748 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700749 // The StatsCollector is used to tell if a track is valid because it may
750 // remember tracks that the PeerConnection previously removed.
751 if (track && !stats_->IsValidTrack(track->id())) {
752 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
753 << track->id();
754 return false;
755 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700756 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000757 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000758 return true;
759}
760
hbos74e1a4f2016-09-15 23:33:01 -0700761void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
762 RTC_DCHECK(stats_collector_);
763 stats_collector_->GetStatsReport(callback);
764}
765
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000766PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
767 return signaling_state_;
768}
769
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000770PeerConnectionInterface::IceConnectionState
771PeerConnection::ice_connection_state() {
772 return ice_connection_state_;
773}
774
775PeerConnectionInterface::IceGatheringState
776PeerConnection::ice_gathering_state() {
777 return ice_gathering_state_;
778}
779
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000780rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000781PeerConnection::CreateDataChannel(
782 const std::string& label,
783 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100784 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700785#ifdef HAVE_QUIC
786 if (session_->data_channel_type() == cricket::DCT_QUIC) {
787 // TODO(zhihuang): Handle case when config is NULL.
788 if (!config) {
789 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
790 return nullptr;
791 }
792 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
793 if (!config->reliable || config->ordered) {
794 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
795 "ordered delivery.";
796 return nullptr;
797 }
798 return session_->quic_data_transport()->CreateDataChannel(label, config);
799 }
800#endif // HAVE_QUIC
801
deadbeefab9b2d12015-10-14 11:33:11 -0700802 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000803
kwibergd1fe2812016-04-27 06:47:29 -0700804 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000805 if (config) {
806 internal_config.reset(new InternalDataChannelInit(*config));
807 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000808 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700809 InternalCreateDataChannel(label, internal_config.get()));
810 if (!channel.get()) {
811 return nullptr;
812 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000813
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000814 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
815 // the first SCTP DataChannel.
816 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
817 observer_->OnRenegotiationNeeded();
818 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000819
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000820 return DataChannelProxy::Create(signaling_thread(), channel.get());
821}
822
823void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
824 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100825 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800826 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
828 return;
829 }
zhihuang1c378ed2017-08-17 14:10:50 -0700830 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
831 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
832 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
833 // compares the mandatory fields parsed with the mandatory fields added in the
834 // |constraints| and some downstream applications might create offers with
835 // mandatory fields which would not be parsed in the helper method. For
836 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
837 // |constraints| as a mandatory field but it is not parsed.
838 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000839
zhihuang1c378ed2017-08-17 14:10:50 -0700840 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000841}
842
843void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
844 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100845 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800846 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000847 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
848 return;
849 }
deadbeefab9b2d12015-10-14 11:33:11 -0700850
zhihuang1c378ed2017-08-17 14:10:50 -0700851 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700852 std::string error = "CreateOffer called with invalid options.";
853 LOG(LS_ERROR) << error;
854 PostCreateSessionDescriptionFailure(observer, error);
855 return;
856 }
857
zhihuang1c378ed2017-08-17 14:10:50 -0700858 cricket::MediaSessionOptions session_options;
859 GetOptionsForOffer(options, &session_options);
deadbeefab9b2d12015-10-14 11:33:11 -0700860 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000861}
862
863void PeerConnection::CreateAnswer(
864 CreateSessionDescriptionObserver* observer,
865 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100866 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800867 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000868 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
869 return;
870 }
deadbeefab9b2d12015-10-14 11:33:11 -0700871
zhihuang1c378ed2017-08-17 14:10:50 -0700872 if (!session_->remote_description() ||
873 session_->remote_description()->type() !=
874 SessionDescriptionInterface::kOffer) {
875 std::string error = "CreateAnswer called without remote offer.";
876 LOG(LS_ERROR) << error;
877 PostCreateSessionDescriptionFailure(observer, error);
878 return;
879 }
880
881 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
882 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
883 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700884 std::string error = "CreateAnswer called with invalid constraints.";
885 LOG(LS_ERROR) << error;
886 PostCreateSessionDescriptionFailure(observer, error);
887 return;
888 }
889
zhihuang1c378ed2017-08-17 14:10:50 -0700890 cricket::MediaSessionOptions session_options;
891 GetOptionsForAnswer(offer_answer_options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800892 session_->CreateAnswer(observer, session_options);
893}
894
895void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
896 const RTCOfferAnswerOptions& options) {
897 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800898 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800899 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
900 return;
901 }
902
903 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -0700904 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -0800905
906 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000907}
908
909void PeerConnection::SetLocalDescription(
910 SetSessionDescriptionObserver* observer,
911 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100912 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -0700913 if (IsClosed()) {
914 return;
915 }
nisse7ce109a2017-01-31 00:57:56 -0800916 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000917 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
918 return;
919 }
920 if (!desc) {
921 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
922 return;
923 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000924 // Update stats here so that we have the most recent stats for tracks and
925 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000926 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000927 std::string error;
928 if (!session_->SetLocalDescription(desc, &error)) {
929 PostSetSessionDescriptionFailure(observer, error);
930 return;
931 }
deadbeefab9b2d12015-10-14 11:33:11 -0700932
933 // If setting the description decided our SSL role, allocate any necessary
934 // SCTP sids.
935 rtc::SSLRole role;
936 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800937 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700938 AllocateSctpSids(role);
939 }
940
941 // Update state and SSRC of local MediaStreams and DataChannels based on the
942 // local session description.
943 const cricket::ContentInfo* audio_content =
944 GetFirstAudioContent(desc->description());
945 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800946 if (audio_content->rejected) {
947 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
948 } else {
949 const cricket::AudioContentDescription* audio_desc =
950 static_cast<const cricket::AudioContentDescription*>(
951 audio_content->description);
952 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
953 }
deadbeefab9b2d12015-10-14 11:33:11 -0700954 }
955
956 const cricket::ContentInfo* video_content =
957 GetFirstVideoContent(desc->description());
958 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800959 if (video_content->rejected) {
960 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
961 } else {
962 const cricket::VideoContentDescription* video_desc =
963 static_cast<const cricket::VideoContentDescription*>(
964 video_content->description);
965 UpdateLocalTracks(video_desc->streams(), video_desc->type());
966 }
deadbeefab9b2d12015-10-14 11:33:11 -0700967 }
968
969 const cricket::ContentInfo* data_content =
970 GetFirstDataContent(desc->description());
971 if (data_content) {
972 const cricket::DataContentDescription* data_desc =
973 static_cast<const cricket::DataContentDescription*>(
974 data_content->description);
975 if (rtc::starts_with(data_desc->protocol().data(),
976 cricket::kMediaProtocolRtpPrefix)) {
977 UpdateLocalRtpDataChannels(data_desc->streams());
978 }
979 }
980
981 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700982 signaling_thread()->Post(RTC_FROM_HERE, this,
983 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700984
deadbeef42a42632017-03-10 15:18:00 -0800985 // According to JSEP, after setLocalDescription, changing the candidate pool
986 // size is not allowed, and changing the set of ICE servers will not result
987 // in new candidates being gathered.
988 port_allocator_->FreezeCandidatePool();
989
deadbeefcbecd352015-09-23 11:50:27 -0700990 // MaybeStartGathering needs to be called after posting
991 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
992 // before signaling that SetLocalDescription completed.
993 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -0800994
995 if (desc->type() == SessionDescriptionInterface::kAnswer) {
996 // TODO(deadbeef): We already had to hop to the network thread for
997 // MaybeStartGathering...
998 network_thread()->Invoke<void>(
999 RTC_FROM_HERE,
1000 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1001 port_allocator_.get()));
1002 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001003}
1004
1005void PeerConnection::SetRemoteDescription(
1006 SetSessionDescriptionObserver* observer,
1007 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001008 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001009 if (IsClosed()) {
1010 return;
1011 }
nisse7ce109a2017-01-31 00:57:56 -08001012 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001013 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1014 return;
1015 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001016 if (!desc) {
1017 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1018 return;
1019 }
1020 // Update stats here so that we have the most recent stats for tracks and
1021 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001022 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001023 std::string error;
1024 if (!session_->SetRemoteDescription(desc, &error)) {
1025 PostSetSessionDescriptionFailure(observer, error);
1026 return;
1027 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001028
deadbeefab9b2d12015-10-14 11:33:11 -07001029 // If setting the description decided our SSL role, allocate any necessary
1030 // SCTP sids.
1031 rtc::SSLRole role;
1032 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001033 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001034 AllocateSctpSids(role);
1035 }
1036
1037 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001038 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1039 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1040 const cricket::AudioContentDescription* audio_desc =
1041 GetFirstAudioContentDescription(remote_desc);
1042 const cricket::VideoContentDescription* video_desc =
1043 GetFirstVideoContentDescription(remote_desc);
1044 const cricket::DataContentDescription* data_desc =
1045 GetFirstDataContentDescription(remote_desc);
1046
1047 // Check if the descriptions include streams, just in case the peer supports
1048 // MSID, but doesn't indicate so with "a=msid-semantic".
1049 if (remote_desc->msid_supported() ||
1050 (audio_desc && !audio_desc->streams().empty()) ||
1051 (video_desc && !video_desc->streams().empty())) {
1052 remote_peer_supports_msid_ = true;
1053 }
deadbeefab9b2d12015-10-14 11:33:11 -07001054
1055 // We wait to signal new streams until we finish processing the description,
1056 // since only at that point will new streams have all their tracks.
1057 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1058
1059 // Find all audio rtp streams and create corresponding remote AudioTracks
1060 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001061 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001062 if (audio_content->rejected) {
1063 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1064 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001065 bool default_audio_track_needed =
1066 !remote_peer_supports_msid_ &&
1067 MediaContentDirectionHasSend(audio_desc->direction());
1068 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1069 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001070 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001071 }
deadbeefab9b2d12015-10-14 11:33:11 -07001072 }
1073
1074 // Find all video rtp streams and create corresponding remote VideoTracks
1075 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001076 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001077 if (video_content->rejected) {
1078 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1079 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001080 bool default_video_track_needed =
1081 !remote_peer_supports_msid_ &&
1082 MediaContentDirectionHasSend(video_desc->direction());
1083 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1084 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001085 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001086 }
deadbeefab9b2d12015-10-14 11:33:11 -07001087 }
1088
1089 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001090 if (data_desc) {
1091 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001092 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001093 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001094 }
1095 }
1096
1097 // Iterate new_streams and notify the observer about new MediaStreams.
1098 for (size_t i = 0; i < new_streams->count(); ++i) {
1099 MediaStreamInterface* new_stream = new_streams->at(i);
1100 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001101 observer_->OnAddStream(
1102 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001103 }
1104
deadbeefbda7e0b2015-12-08 17:13:40 -08001105 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001106
1107 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001108 signaling_thread()->Post(RTC_FROM_HERE, this,
1109 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001110
1111 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1112 // TODO(deadbeef): We already had to hop to the network thread for
1113 // MaybeStartGathering...
1114 network_thread()->Invoke<void>(
1115 RTC_FROM_HERE,
1116 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1117 port_allocator_.get()));
1118 }
deadbeeffc648b62015-10-13 16:42:33 -07001119}
1120
deadbeef46c73892016-11-16 19:42:04 -08001121PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1122 return configuration_;
1123}
1124
deadbeef293e9262017-01-11 12:28:30 -08001125bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1126 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001127 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001128
1129 if (session_->local_description() &&
1130 configuration.ice_candidate_pool_size !=
1131 configuration_.ice_candidate_pool_size) {
1132 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1133 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001134 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001135 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001136
deadbeef293e9262017-01-11 12:28:30 -08001137 // The simplest (and most future-compatible) way to tell if the config was
1138 // modified in an invalid way is to copy each property we do support
1139 // modifying, then use operator==. There are far more properties we don't
1140 // support modifying than those we do, and more could be added.
1141 RTCConfiguration modified_config = configuration_;
1142 modified_config.servers = configuration.servers;
1143 modified_config.type = configuration.type;
1144 modified_config.ice_candidate_pool_size =
1145 configuration.ice_candidate_pool_size;
1146 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001147 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001148 if (configuration != modified_config) {
1149 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1150 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1151 }
1152
Steve Anton038834f2017-07-14 15:59:59 -07001153 // Validate the modified configuration.
1154 RTCError validate_error = ValidateConfiguration(modified_config);
1155 if (!validate_error.ok()) {
1156 return SafeSetError(std::move(validate_error), error);
1157 }
1158
deadbeef293e9262017-01-11 12:28:30 -08001159 // Note that this isn't possible through chromium, since it's an unsigned
1160 // short in WebIDL.
1161 if (configuration.ice_candidate_pool_size < 0 ||
1162 configuration.ice_candidate_pool_size > UINT16_MAX) {
1163 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1164 }
1165
1166 // Parse ICE servers before hopping to network thread.
1167 cricket::ServerAddresses stun_servers;
1168 std::vector<cricket::RelayServerConfig> turn_servers;
1169 RTCErrorType parse_error =
1170 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1171 if (parse_error != RTCErrorType::NONE) {
1172 return SafeSetError(parse_error, error);
1173 }
1174
1175 // In theory this shouldn't fail.
1176 if (!network_thread()->Invoke<bool>(
1177 RTC_FROM_HERE,
1178 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1179 stun_servers, turn_servers, modified_config.type,
1180 modified_config.ice_candidate_pool_size,
1181 modified_config.prune_turn_ports))) {
1182 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1183 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1184 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001185
deadbeefd1a38b52016-12-10 13:15:33 -08001186 // As described in JSEP, calling setConfiguration with new ICE servers or
1187 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1188 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001189 if (modified_config.servers != configuration_.servers ||
1190 modified_config.type != configuration_.type ||
1191 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001192 session_->SetNeedsIceRestartFlag();
1193 }
skvladd1f5fda2017-02-03 16:54:05 -08001194
1195 if (modified_config.ice_check_min_interval !=
1196 configuration_.ice_check_min_interval) {
1197 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1198 }
1199
deadbeef293e9262017-01-11 12:28:30 -08001200 configuration_ = modified_config;
1201 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001202}
1203
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001204bool PeerConnection::AddIceCandidate(
1205 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001206 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001207 if (IsClosed()) {
1208 return false;
1209 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001210 return session_->ProcessIceMessage(ice_candidate);
1211}
1212
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001213bool PeerConnection::RemoveIceCandidates(
1214 const std::vector<cricket::Candidate>& candidates) {
1215 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1216 return session_->RemoveRemoteIceCandidates(candidates);
1217}
1218
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001219void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001220 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001221 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001222
1223 if (session_) {
1224 session_->set_metrics_observer(uma_observer_);
1225 }
1226
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001227 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001228 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001229 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001230 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001231 uma_observer_->IncrementEnumCounter(
1232 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1233 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001234 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001235 uma_observer_->IncrementEnumCounter(
1236 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1237 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001238 }
1239 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001240}
1241
zstein4b979802017-06-02 14:37:37 -07001242RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
1243 rtc::Thread* worker_thread = factory_->worker_thread();
1244 if (!worker_thread->IsCurrent()) {
1245 return worker_thread->Invoke<RTCError>(
1246 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1247 }
1248
1249 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1250 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1251 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1252 if (has_min && *bitrate.min_bitrate_bps < 0) {
1253 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1254 "min_bitrate_bps <= 0");
1255 }
1256 if (has_current) {
1257 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1258 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1259 "current_bitrate_bps < min_bitrate_bps");
1260 } else if (*bitrate.current_bitrate_bps < 0) {
1261 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1262 "curent_bitrate_bps < 0");
1263 }
1264 }
1265 if (has_max) {
1266 if (has_current &&
1267 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1268 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1269 "max_bitrate_bps < current_bitrate_bps");
1270 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1271 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1272 "max_bitrate_bps < min_bitrate_bps");
1273 } else if (*bitrate.max_bitrate_bps < 0) {
1274 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1275 "max_bitrate_bps < 0");
1276 }
1277 }
1278
1279 Call::Config::BitrateConfigMask mask;
1280 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1281 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1282 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1283
1284 RTC_DCHECK(call_.get());
1285 call_->SetBitrateConfigMask(mask);
1286
1287 return RTCError::OK();
1288}
1289
ivoc14d5dbe2016-07-04 07:06:55 -07001290bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1291 int64_t max_size_bytes) {
1292 return factory_->worker_thread()->Invoke<bool>(
1293 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1294 max_size_bytes));
1295}
1296
1297void PeerConnection::StopRtcEventLog() {
1298 factory_->worker_thread()->Invoke<void>(
1299 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1300}
1301
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302const SessionDescriptionInterface* PeerConnection::local_description() const {
1303 return session_->local_description();
1304}
1305
1306const SessionDescriptionInterface* PeerConnection::remote_description() const {
1307 return session_->remote_description();
1308}
1309
deadbeeffe4a8a42016-12-20 17:56:17 -08001310const SessionDescriptionInterface* PeerConnection::current_local_description()
1311 const {
1312 return session_->current_local_description();
1313}
1314
1315const SessionDescriptionInterface* PeerConnection::current_remote_description()
1316 const {
1317 return session_->current_remote_description();
1318}
1319
1320const SessionDescriptionInterface* PeerConnection::pending_local_description()
1321 const {
1322 return session_->pending_local_description();
1323}
1324
1325const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1326 const {
1327 return session_->pending_remote_description();
1328}
1329
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001330void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001331 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332 // Update stats here so that we have the most recent stats for tracks and
1333 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001334 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001335
deadbeefd59daf82015-10-14 15:02:44 -07001336 session_->Close();
deadbeef42a42632017-03-10 15:18:00 -08001337 network_thread()->Invoke<void>(
1338 RTC_FROM_HERE,
1339 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1340 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001341
eladalon248fd4f2017-09-06 05:18:15 -07001342 factory_->worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
1343 call_.reset();
1344 // The event log must outlive call (and any other object that uses it).
1345 event_log_.reset();
1346 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347}
1348
deadbeefd59daf82015-10-14 15:02:44 -07001349void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1350 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001352 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001353 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001354 break;
deadbeefd59daf82015-10-14 15:02:44 -07001355 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1357 break;
deadbeefd59daf82015-10-14 15:02:44 -07001358 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1360 break;
deadbeefd59daf82015-10-14 15:02:44 -07001361 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001362 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1363 break;
deadbeefd59daf82015-10-14 15:02:44 -07001364 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1366 break;
deadbeefd59daf82015-10-14 15:02:44 -07001367 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001368 ChangeSignalingState(PeerConnectionInterface::kStable);
1369 break;
deadbeefd59daf82015-10-14 15:02:44 -07001370 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001371 ChangeSignalingState(PeerConnectionInterface::kClosed);
1372 break;
1373 default:
1374 break;
1375 }
1376}
1377
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001378void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001379 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001380 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1381 SetSessionDescriptionMsg* param =
1382 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1383 param->observer->OnSuccess();
1384 delete param;
1385 break;
1386 }
1387 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1388 SetSessionDescriptionMsg* param =
1389 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1390 param->observer->OnFailure(param->error);
1391 delete param;
1392 break;
1393 }
deadbeefab9b2d12015-10-14 11:33:11 -07001394 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1395 CreateSessionDescriptionMsg* param =
1396 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1397 param->observer->OnFailure(param->error);
1398 delete param;
1399 break;
1400 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001401 case MSG_GETSTATS: {
1402 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001403 StatsReports reports;
1404 stats_->GetStats(param->track, &reports);
1405 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001406 delete param;
1407 break;
1408 }
deadbeefbd292462015-12-14 18:15:29 -08001409 case MSG_FREE_DATACHANNELS: {
1410 sctp_data_channels_to_free_.clear();
1411 break;
1412 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001413 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001414 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415 break;
1416 }
1417}
1418
deadbeefab9b2d12015-10-14 11:33:11 -07001419void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001420 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001421 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001422 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1423 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001424 signaling_thread(),
1425 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1426 stream->AddTrack(
1427 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001428 receivers_.push_back(receiver);
1429 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1430 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1431 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001432}
1433
deadbeefab9b2d12015-10-14 11:33:11 -07001434void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001435 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001436 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001437 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1438 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001439 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001440 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1441 session_->video_channel()));
1442 stream->AddTrack(
1443 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001444 receivers_.push_back(receiver);
1445 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1446 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1447 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001448}
1449
deadbeef70ab1a12015-09-28 16:53:55 -07001450// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1451// description.
perkjd61bf802016-03-24 03:16:19 -07001452void PeerConnection::DestroyReceiver(const std::string& track_id) {
1453 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001454 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001455 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001456 << " doesn't exist.";
1457 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001458 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001459 receivers_.erase(it);
1460 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001461}
1462
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001463void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
1464 MediaStreamInterface* stream) {
1465 RTC_DCHECK(!IsClosed());
1466 auto sender = FindSenderForTrack(track);
1467 if (sender != senders_.end()) {
1468 // We already have a sender for this track, so just change the stream_id
1469 // so that it's correct in the next call to CreateOffer.
1470 (*sender)->internal()->set_stream_id(stream->label());
1471 return;
1472 }
1473
1474 // Normal case; we've never seen this track before.
1475 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1476 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1477 signaling_thread(),
1478 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1479 stats_.get()));
1480 senders_.push_back(new_sender);
1481 // If the sender has already been configured in SDP, we call SetSsrc,
1482 // which will connect the sender to the underlying transport. This can
1483 // occur if a local session description that contains the ID of the sender
1484 // is set before AddStream is called. It can also occur if the local
1485 // session description is not changed and RemoveStream is called, and
1486 // later AddStream is called again with the same stream.
1487 const TrackInfo* track_info =
1488 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1489 if (track_info) {
1490 new_sender->internal()->SetSsrc(track_info->ssrc);
1491 }
1492}
1493
1494// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1495// indefinitely, when we have unified plan SDP.
1496void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
1497 MediaStreamInterface* stream) {
1498 RTC_DCHECK(!IsClosed());
1499 auto sender = FindSenderForTrack(track);
1500 if (sender == senders_.end()) {
1501 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1502 << " doesn't exist.";
1503 return;
1504 }
1505 (*sender)->internal()->Stop();
1506 senders_.erase(sender);
1507}
1508
1509void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
1510 MediaStreamInterface* stream) {
1511 RTC_DCHECK(!IsClosed());
1512 auto sender = FindSenderForTrack(track);
1513 if (sender != senders_.end()) {
1514 // We already have a sender for this track, so just change the stream_id
1515 // so that it's correct in the next call to CreateOffer.
1516 (*sender)->internal()->set_stream_id(stream->label());
1517 return;
1518 }
1519
1520 // Normal case; we've never seen this track before.
1521 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1522 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1523 signaling_thread(), new VideoRtpSender(track, stream->label(),
1524 session_->video_channel()));
1525 senders_.push_back(new_sender);
1526 const TrackInfo* track_info =
1527 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1528 if (track_info) {
1529 new_sender->internal()->SetSsrc(track_info->ssrc);
1530 }
1531}
1532
1533void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
1534 MediaStreamInterface* stream) {
1535 RTC_DCHECK(!IsClosed());
1536 auto sender = FindSenderForTrack(track);
1537 if (sender == senders_.end()) {
1538 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1539 << " doesn't exist.";
1540 return;
1541 }
1542 (*sender)->internal()->Stop();
1543 senders_.erase(sender);
1544}
1545
zstein6dfd53a2017-03-06 13:49:03 -08001546void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001548 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001549 // After transitioning to "closed", ignore any additional states from
1550 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001551 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001552 return;
1553 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001554 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001555 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001556}
1557
1558void PeerConnection::OnIceGatheringChange(
1559 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001560 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001561 if (IsClosed()) {
1562 return;
1563 }
1564 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001565 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001566}
1567
jbauch81bf7b02017-03-25 08:31:12 -07001568void PeerConnection::OnIceCandidate(
1569 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001570 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001571 if (IsClosed()) {
1572 return;
1573 }
jbauch81bf7b02017-03-25 08:31:12 -07001574 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001575}
1576
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001577void PeerConnection::OnIceCandidatesRemoved(
1578 const std::vector<cricket::Candidate>& candidates) {
1579 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001580 if (IsClosed()) {
1581 return;
1582 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001583 observer_->OnIceCandidatesRemoved(candidates);
1584}
1585
Peter Thatcher54360512015-07-08 11:08:35 -07001586void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001587 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001588 if (IsClosed()) {
1589 return;
1590 }
Peter Thatcher54360512015-07-08 11:08:35 -07001591 observer_->OnIceConnectionReceivingChange(receiving);
1592}
1593
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001594void PeerConnection::ChangeSignalingState(
1595 PeerConnectionInterface::SignalingState signaling_state) {
1596 signaling_state_ = signaling_state;
1597 if (signaling_state == kClosed) {
1598 ice_connection_state_ = kIceConnectionClosed;
1599 observer_->OnIceConnectionChange(ice_connection_state_);
1600 if (ice_gathering_state_ != kIceGatheringComplete) {
1601 ice_gathering_state_ = kIceGatheringComplete;
1602 observer_->OnIceGatheringChange(ice_gathering_state_);
1603 }
1604 }
1605 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001606}
1607
deadbeefeb459812015-12-15 19:24:43 -08001608void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1609 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001610 if (IsClosed()) {
1611 return;
1612 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001613 AddAudioTrack(track, stream);
1614 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001615}
1616
deadbeefeb459812015-12-15 19:24:43 -08001617void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1618 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001619 if (IsClosed()) {
1620 return;
1621 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001622 RemoveAudioTrack(track, stream);
1623 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001624}
1625
1626void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1627 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001628 if (IsClosed()) {
1629 return;
1630 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001631 AddVideoTrack(track, stream);
1632 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001633}
1634
1635void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1636 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001637 if (IsClosed()) {
1638 return;
1639 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001640 RemoveVideoTrack(track, stream);
1641 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08001642}
1643
deadbeefab9b2d12015-10-14 11:33:11 -07001644void PeerConnection::PostSetSessionDescriptionFailure(
1645 SetSessionDescriptionObserver* observer,
1646 const std::string& error) {
1647 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1648 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001649 signaling_thread()->Post(RTC_FROM_HERE, this,
1650 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001651}
1652
1653void PeerConnection::PostCreateSessionDescriptionFailure(
1654 CreateSessionDescriptionObserver* observer,
1655 const std::string& error) {
1656 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1657 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001658 signaling_thread()->Post(RTC_FROM_HERE, this,
1659 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001660}
1661
zhihuang1c378ed2017-08-17 14:10:50 -07001662void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07001663 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1664 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001665 ExtractSharedMediaSessionOptions(rtc_options, session_options);
1666
1667 // Figure out transceiver directional preferences.
1668 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1669 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1670
1671 // By default, generate sendrecv/recvonly m= sections.
1672 bool recv_audio = true;
1673 bool recv_video = true;
1674
1675 // By default, only offer a new m= section if we have media to send with it.
1676 bool offer_new_audio_description = send_audio;
1677 bool offer_new_video_description = send_video;
1678 bool offer_new_data_description = HasDataChannels();
1679
1680 // The "offer_to_receive_X" options allow those defaults to be overridden.
1681 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1682 recv_audio = (rtc_options.offer_to_receive_audio > 0);
1683 offer_new_audio_description =
1684 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
1685 }
1686 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1687 recv_video = (rtc_options.offer_to_receive_video > 0);
1688 offer_new_video_description =
1689 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
1690 }
1691
1692 rtc::Optional<size_t> audio_index;
1693 rtc::Optional<size_t> video_index;
1694 rtc::Optional<size_t> data_index;
1695 // If a current description exists, generate m= sections in the same order,
1696 // using the first audio/video/data section that appears and rejecting
1697 // extraneous ones.
deadbeef0ed85b22016-02-23 17:24:52 -08001698 if (session_->local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07001699 GenerateMediaDescriptionOptions(
1700 session_->local_description(),
1701 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1702 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1703 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001704 }
1705
zhihuang1c378ed2017-08-17 14:10:50 -07001706 // Add audio/video/data m= sections to the end if needed.
1707 if (!audio_index && offer_new_audio_description) {
1708 session_options->media_description_options.push_back(
1709 cricket::MediaDescriptionOptions(
1710 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
1711 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
1712 audio_index = rtc::Optional<size_t>(
1713 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001714 }
zhihuang1c378ed2017-08-17 14:10:50 -07001715 if (!video_index && offer_new_video_description) {
1716 session_options->media_description_options.push_back(
1717 cricket::MediaDescriptionOptions(
1718 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
1719 cricket::RtpTransceiverDirection(send_video, recv_video), false));
1720 video_index = rtc::Optional<size_t>(
1721 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07001722 }
zhihuang1c378ed2017-08-17 14:10:50 -07001723 if (!data_index && offer_new_data_description) {
1724 session_options->media_description_options.push_back(
1725 cricket::MediaDescriptionOptions(
1726 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
1727 cricket::RtpTransceiverDirection(true, true), false));
1728 data_index = rtc::Optional<size_t>(
1729 session_options->media_description_options.size() - 1);
1730 }
1731
1732 cricket::MediaDescriptionOptions* audio_media_description_options =
1733 !audio_index ? nullptr
1734 : &session_options->media_description_options[*audio_index];
1735 cricket::MediaDescriptionOptions* video_media_description_options =
1736 !video_index ? nullptr
1737 : &session_options->media_description_options[*video_index];
1738 cricket::MediaDescriptionOptions* data_media_description_options =
1739 !data_index ? nullptr
1740 : &session_options->media_description_options[*data_index];
1741
1742 // Apply ICE restart flag and renomination flag.
1743 for (auto& options : session_options->media_description_options) {
1744 options.transport_options.ice_restart = rtc_options.ice_restart;
1745 options.transport_options.enable_ice_renomination =
1746 configuration_.enable_ice_renomination;
1747 }
1748
1749 AddRtpSenderOptions(senders_, audio_media_description_options,
1750 video_media_description_options);
1751 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07001752
zhihuang9763d562016-08-05 11:14:50 -07001753 // Intentionally unset the data channel type for RTP data channel with the
1754 // second condition. Otherwise the RTP data channels would be successfully
1755 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1756 // when building with chromium. We want to leave RTP data channels broken, so
1757 // people won't try to use them.
zhihuang1c378ed2017-08-17 14:10:50 -07001758 if (!rtp_data_channels_.empty() ||
1759 session_->data_channel_type() != cricket::DCT_RTP) {
zhihuang9763d562016-08-05 11:14:50 -07001760 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001761 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001762
1763 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001764 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001765}
1766
zhihuang1c378ed2017-08-17 14:10:50 -07001767void PeerConnection::GetOptionsForAnswer(
1768 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001769 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07001770 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001771
zhihuang1c378ed2017-08-17 14:10:50 -07001772 // Figure out transceiver directional preferences.
1773 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
1774 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
1775
1776 // By default, generate sendrecv/recvonly m= sections. The direction is also
1777 // restricted by the direction in the offer.
1778 bool recv_audio = true;
1779 bool recv_video = true;
1780
1781 // The "offer_to_receive_X" options allow those defaults to be overridden.
1782 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
1783 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08001784 }
zhihuang1c378ed2017-08-17 14:10:50 -07001785 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
1786 recv_video = (rtc_options.offer_to_receive_video > 0);
1787 }
1788
1789 rtc::Optional<size_t> audio_index;
1790 rtc::Optional<size_t> video_index;
1791 rtc::Optional<size_t> data_index;
zhihuang141aacb2017-08-29 13:23:53 -07001792 if (session_->remote_description()) {
1793 // The pending remote description should be an offer.
1794 RTC_DCHECK(session_->remote_description()->type() ==
1795 SessionDescriptionInterface::kOffer);
1796 // Generate m= sections that match those in the offer.
1797 // Note that mediasession.cc will handle intersection our preferred
1798 // direction with the offered direction.
1799 GenerateMediaDescriptionOptions(
1800 session_->remote_description(),
1801 cricket::RtpTransceiverDirection(send_audio, recv_audio),
1802 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
1803 &video_index, &data_index, session_options);
1804 }
zhihuang1c378ed2017-08-17 14:10:50 -07001805
1806 cricket::MediaDescriptionOptions* audio_media_description_options =
1807 !audio_index ? nullptr
1808 : &session_options->media_description_options[*audio_index];
1809 cricket::MediaDescriptionOptions* video_media_description_options =
1810 !video_index ? nullptr
1811 : &session_options->media_description_options[*video_index];
1812 cricket::MediaDescriptionOptions* data_media_description_options =
1813 !data_index ? 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.
zhihuang1c378ed2017-08-17 14:10:50 -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
zhihuang1c378ed2017-08-17 14:10:50 -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
zhihuang1c378ed2017-08-17 14:10:50 -07001839void PeerConnection::GenerateMediaDescriptionOptions(
1840 const SessionDescriptionInterface* session_desc,
1841 cricket::RtpTransceiverDirection audio_direction,
1842 cricket::RtpTransceiverDirection video_direction,
1843 rtc::Optional<size_t>* audio_index,
1844 rtc::Optional<size_t>* video_index,
1845 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08001846 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -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) {
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 = rtc::Optional<size_t>(
1862 session_options->media_description_options.size() - 1);
1863 }
1864 } else if (IsVideoContent(&content)) {
1865 // If we already have an video m= section, reject this extra one.
1866 if (*video_index) {
1867 session_options->media_description_options.push_back(
1868 cricket::MediaDescriptionOptions(
1869 cricket::MEDIA_TYPE_VIDEO, content.name,
1870 cricket::RtpTransceiverDirection(false, false), true));
1871 } else {
1872 session_options->media_description_options.push_back(
1873 cricket::MediaDescriptionOptions(
1874 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
1875 !video_direction.send && !video_direction.recv));
1876 *video_index = rtc::Optional<size_t>(
1877 session_options->media_description_options.size() - 1);
1878 }
1879 } else {
1880 RTC_DCHECK(IsDataContent(&content));
1881 // If we already have an data m= section, reject this extra one.
1882 if (*data_index) {
1883 session_options->media_description_options.push_back(
1884 cricket::MediaDescriptionOptions(
1885 cricket::MEDIA_TYPE_DATA, content.name,
1886 cricket::RtpTransceiverDirection(false, false), true));
1887 } else {
1888 session_options->media_description_options.push_back(
1889 cricket::MediaDescriptionOptions(
1890 cricket::MEDIA_TYPE_DATA, content.name,
1891 // Direction for data sections is meaningless, but legacy
1892 // endpoints might expect sendrecv.
1893 cricket::RtpTransceiverDirection(true, true), false));
1894 *data_index = rtc::Optional<size_t>(
1895 session_options->media_description_options.size() - 1);
1896 }
1897 }
htaa2a49d92016-03-04 02:51:39 -08001898 }
deadbeefab9b2d12015-10-14 11:33:11 -07001899}
1900
deadbeeffaac4972015-11-12 15:33:07 -08001901void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1902 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001903 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1904 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001905}
1906
deadbeefab9b2d12015-10-14 11:33:11 -07001907void PeerConnection::UpdateRemoteStreamsList(
1908 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001909 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001910 cricket::MediaType media_type,
1911 StreamCollection* new_streams) {
1912 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1913
1914 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001915 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001916 auto track_it = current_tracks->begin();
1917 while (track_it != current_tracks->end()) {
1918 const TrackInfo& info = *track_it;
1919 const cricket::StreamParams* params =
1920 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001921 bool track_exists = params && params->id == info.track_id;
1922 // If this is a default track, and we still need it, don't remove it.
1923 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1924 track_exists) {
1925 ++track_it;
1926 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001927 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1928 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001929 }
1930 }
1931
1932 // Find new and active tracks.
1933 for (const cricket::StreamParams& params : streams) {
1934 // The sync_label is the MediaStream label and the |stream.id| is the
1935 // track id.
1936 const std::string& stream_label = params.sync_label;
1937 const std::string& track_id = params.id;
1938 uint32_t ssrc = params.first_ssrc();
1939
1940 rtc::scoped_refptr<MediaStreamInterface> stream =
1941 remote_streams_->find(stream_label);
1942 if (!stream) {
1943 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001944 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1945 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001946 remote_streams_->AddStream(stream);
1947 new_streams->AddStream(stream);
1948 }
1949
1950 const TrackInfo* track_info =
1951 FindTrackInfo(*current_tracks, stream_label, track_id);
1952 if (!track_info) {
1953 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1954 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1955 }
1956 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001957
1958 // Add default track if necessary.
1959 if (default_track_needed) {
1960 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1961 remote_streams_->find(kDefaultStreamLabel);
1962 if (!default_stream) {
1963 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001964 default_stream = MediaStreamProxy::Create(
1965 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001966 remote_streams_->AddStream(default_stream);
1967 new_streams->AddStream(default_stream);
1968 }
1969 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1970 ? kDefaultAudioTrackLabel
1971 : kDefaultVideoTrackLabel;
1972 const TrackInfo* default_track_info =
1973 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1974 if (!default_track_info) {
1975 current_tracks->push_back(
1976 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1977 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1978 }
1979 }
deadbeefab9b2d12015-10-14 11:33:11 -07001980}
1981
1982void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1983 const std::string& track_id,
1984 uint32_t ssrc,
1985 cricket::MediaType media_type) {
1986 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1987
1988 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001989 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001990 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001991 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001992 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08001993 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001994 }
1995}
1996
1997void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1998 const std::string& track_id,
1999 cricket::MediaType media_type) {
2000 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2001
2002 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002003 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2004 // will be notified which will end the AudioRtpReceiver::track().
2005 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002006 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2007 stream->FindAudioTrack(track_id);
2008 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002009 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002010 }
2011 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002012 // Stopping or destroying a VideoRtpReceiver will end the
2013 // VideoRtpReceiver::track().
2014 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002015 rtc::scoped_refptr<VideoTrackInterface> video_track =
2016 stream->FindVideoTrack(track_id);
2017 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002018 // There's no guarantee the track is still available, e.g. the track may
2019 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002020 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002021 }
2022 } else {
nisseede5da42017-01-12 05:15:36 -08002023 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002024 }
2025}
2026
2027void PeerConnection::UpdateEndedRemoteMediaStreams() {
2028 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2029 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2030 MediaStreamInterface* stream = remote_streams_->at(i);
2031 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2032 streams_to_remove.push_back(stream);
2033 }
2034 }
2035
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002036 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002037 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002038 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002039 }
2040}
2041
deadbeefab9b2d12015-10-14 11:33:11 -07002042void PeerConnection::UpdateLocalTracks(
2043 const std::vector<cricket::StreamParams>& streams,
2044 cricket::MediaType media_type) {
2045 TrackInfos* current_tracks = GetLocalTracks(media_type);
2046
2047 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2048 // don't match the new StreamParam.
2049 TrackInfos::iterator track_it = current_tracks->begin();
2050 while (track_it != current_tracks->end()) {
2051 const TrackInfo& info = *track_it;
2052 const cricket::StreamParams* params =
2053 cricket::GetStreamBySsrc(streams, info.ssrc);
2054 if (!params || params->id != info.track_id ||
2055 params->sync_label != info.stream_label) {
2056 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2057 media_type);
2058 track_it = current_tracks->erase(track_it);
2059 } else {
2060 ++track_it;
2061 }
2062 }
2063
2064 // Find new and active tracks.
2065 for (const cricket::StreamParams& params : streams) {
2066 // The sync_label is the MediaStream label and the |stream.id| is the
2067 // track id.
2068 const std::string& stream_label = params.sync_label;
2069 const std::string& track_id = params.id;
2070 uint32_t ssrc = params.first_ssrc();
2071 const TrackInfo* track_info =
2072 FindTrackInfo(*current_tracks, stream_label, track_id);
2073 if (!track_info) {
2074 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2075 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2076 }
2077 }
2078}
2079
2080void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2081 const std::string& track_id,
2082 uint32_t ssrc,
2083 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002084 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002085 if (!sender) {
2086 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2087 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002088 return;
2089 }
2090
deadbeeffac06552015-11-25 11:26:01 -08002091 if (sender->media_type() != media_type) {
2092 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2093 << " description with an unexpected media type.";
2094 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002095 }
deadbeeffac06552015-11-25 11:26:01 -08002096
2097 sender->set_stream_id(stream_label);
2098 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002099}
2100
2101void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2102 const std::string& track_id,
2103 uint32_t ssrc,
2104 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002105 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002106 if (!sender) {
2107 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002108 // SessionDescriptions has been renegotiated.
2109 return;
2110 }
deadbeeffac06552015-11-25 11:26:01 -08002111
2112 // A sender has been removed from the SessionDescription but it's still
2113 // associated with the PeerConnection. This only occurs if the SDP doesn't
2114 // match with the calls to CreateSender, AddStream and RemoveStream.
2115 if (sender->media_type() != media_type) {
2116 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2117 << " description with an unexpected media type.";
2118 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002119 }
deadbeeffac06552015-11-25 11:26:01 -08002120
2121 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002122}
2123
2124void PeerConnection::UpdateLocalRtpDataChannels(
2125 const cricket::StreamParamsVec& streams) {
2126 std::vector<std::string> existing_channels;
2127
2128 // Find new and active data channels.
2129 for (const cricket::StreamParams& params : streams) {
2130 // |it->sync_label| is actually the data channel label. The reason is that
2131 // we use the same naming of data channels as we do for
2132 // MediaStreams and Tracks.
2133 // For MediaStreams, the sync_label is the MediaStream label and the
2134 // track label is the same as |streamid|.
2135 const std::string& channel_label = params.sync_label;
2136 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002137 if (data_channel_it == rtp_data_channels_.end()) {
2138 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002139 continue;
2140 }
2141 // Set the SSRC the data channel should use for sending.
2142 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2143 existing_channels.push_back(data_channel_it->first);
2144 }
2145
2146 UpdateClosingRtpDataChannels(existing_channels, true);
2147}
2148
2149void PeerConnection::UpdateRemoteRtpDataChannels(
2150 const cricket::StreamParamsVec& streams) {
2151 std::vector<std::string> existing_channels;
2152
2153 // Find new and active data channels.
2154 for (const cricket::StreamParams& params : streams) {
2155 // The data channel label is either the mslabel or the SSRC if the mslabel
2156 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2157 std::string label = params.sync_label.empty()
2158 ? rtc::ToString(params.first_ssrc())
2159 : params.sync_label;
2160 auto data_channel_it = rtp_data_channels_.find(label);
2161 if (data_channel_it == rtp_data_channels_.end()) {
2162 // This is a new data channel.
2163 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2164 } else {
2165 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2166 }
2167 existing_channels.push_back(label);
2168 }
2169
2170 UpdateClosingRtpDataChannels(existing_channels, false);
2171}
2172
2173void PeerConnection::UpdateClosingRtpDataChannels(
2174 const std::vector<std::string>& active_channels,
2175 bool is_local_update) {
2176 auto it = rtp_data_channels_.begin();
2177 while (it != rtp_data_channels_.end()) {
2178 DataChannel* data_channel = it->second;
2179 if (std::find(active_channels.begin(), active_channels.end(),
2180 data_channel->label()) != active_channels.end()) {
2181 ++it;
2182 continue;
2183 }
2184
2185 if (is_local_update) {
2186 data_channel->SetSendSsrc(0);
2187 } else {
2188 data_channel->RemotePeerRequestClose();
2189 }
2190
2191 if (data_channel->state() == DataChannel::kClosed) {
2192 rtp_data_channels_.erase(it);
2193 it = rtp_data_channels_.begin();
2194 } else {
2195 ++it;
2196 }
2197 }
2198}
2199
2200void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2201 uint32_t remote_ssrc) {
2202 rtc::scoped_refptr<DataChannel> channel(
2203 InternalCreateDataChannel(label, nullptr));
2204 if (!channel.get()) {
2205 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2206 << "CreateDataChannel failed.";
2207 return;
2208 }
2209 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002210 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2211 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002212 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002213}
2214
2215rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2216 const std::string& label,
2217 const InternalDataChannelInit* config) {
2218 if (IsClosed()) {
2219 return nullptr;
2220 }
2221 if (session_->data_channel_type() == cricket::DCT_NONE) {
2222 LOG(LS_ERROR)
2223 << "InternalCreateDataChannel: Data is not supported in this call.";
2224 return nullptr;
2225 }
2226 InternalDataChannelInit new_config =
2227 config ? (*config) : InternalDataChannelInit();
2228 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2229 if (new_config.id < 0) {
2230 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002231 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002232 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2233 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2234 return nullptr;
2235 }
2236 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2237 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2238 << "because the id is already in use or out of range.";
2239 return nullptr;
2240 }
2241 }
2242
2243 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2244 session_.get(), session_->data_channel_type(), label, new_config));
2245 if (!channel) {
2246 sid_allocator_.ReleaseSid(new_config.id);
2247 return nullptr;
2248 }
2249
2250 if (channel->data_channel_type() == cricket::DCT_RTP) {
2251 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2252 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2253 << " already exists.";
2254 return nullptr;
2255 }
2256 rtp_data_channels_[channel->label()] = channel;
2257 } else {
2258 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2259 sctp_data_channels_.push_back(channel);
2260 channel->SignalClosed.connect(this,
2261 &PeerConnection::OnSctpDataChannelClosed);
2262 }
2263
hbos82ebe022016-11-14 01:41:09 -08002264 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002265 return channel;
2266}
2267
2268bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002269#ifdef HAVE_QUIC
2270 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2271 (session_->quic_data_transport() &&
2272 session_->quic_data_transport()->HasDataChannels());
2273#else
deadbeefab9b2d12015-10-14 11:33:11 -07002274 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002275#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002276}
2277
2278void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2279 for (const auto& channel : sctp_data_channels_) {
2280 if (channel->id() < 0) {
2281 int sid;
2282 if (!sid_allocator_.AllocateSid(role, &sid)) {
2283 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2284 continue;
2285 }
2286 channel->SetSctpSid(sid);
2287 }
2288 }
2289}
2290
2291void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002292 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002293 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2294 ++it) {
2295 if (it->get() == channel) {
2296 if (channel->id() >= 0) {
2297 sid_allocator_.ReleaseSid(channel->id());
2298 }
deadbeefbd292462015-12-14 18:15:29 -08002299 // Since this method is triggered by a signal from the DataChannel,
2300 // we can't free it directly here; we need to free it asynchronously.
2301 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002302 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002303 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2304 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002305 return;
2306 }
2307 }
2308}
2309
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002310void PeerConnection::OnVoiceChannelCreated() {
2311 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2312 session_->voice_channel(), senders_, receivers_,
2313 cricket::MEDIA_TYPE_AUDIO);
2314}
2315
deadbeefab9b2d12015-10-14 11:33:11 -07002316void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002317 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2318 cricket::VoiceChannel>(
2319 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2320}
2321
2322void PeerConnection::OnVideoChannelCreated() {
2323 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2324 session_->video_channel(), senders_, receivers_,
2325 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002326}
2327
2328void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002329 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2330 cricket::VideoChannel>(
2331 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002332}
2333
2334void PeerConnection::OnDataChannelCreated() {
2335 for (const auto& channel : sctp_data_channels_) {
2336 channel->OnTransportChannelCreated();
2337 }
2338}
2339
2340void PeerConnection::OnDataChannelDestroyed() {
2341 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2342 // DataChannel may callback to us and try to modify the list.
2343 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2344 temp_rtp_dcs.swap(rtp_data_channels_);
2345 for (const auto& kv : temp_rtp_dcs) {
2346 kv.second->OnTransportChannelDestroyed();
2347 }
2348
2349 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2350 temp_sctp_dcs.swap(sctp_data_channels_);
2351 for (const auto& channel : temp_sctp_dcs) {
2352 channel->OnTransportChannelDestroyed();
2353 }
2354}
2355
2356void PeerConnection::OnDataChannelOpenMessage(
2357 const std::string& label,
2358 const InternalDataChannelInit& config) {
2359 rtc::scoped_refptr<DataChannel> channel(
2360 InternalCreateDataChannel(label, &config));
2361 if (!channel.get()) {
2362 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2363 return;
2364 }
2365
deadbeefa601f5c2016-06-06 14:27:39 -07002366 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2367 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002368 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002369}
2370
zhihuang1c378ed2017-08-17 14:10:50 -07002371bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2372 return std::find_if(
2373 senders_.begin(), senders_.end(),
2374 [type](const rtc::scoped_refptr<
2375 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2376 return sender->media_type() == type;
2377 }) != senders_.end();
2378}
2379
deadbeefa601f5c2016-06-06 14:27:39 -07002380RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2381 auto it = std::find_if(
2382 senders_.begin(), senders_.end(),
2383 [id](const rtc::scoped_refptr<
2384 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2385 return sender->id() == id;
2386 });
2387 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002388}
2389
deadbeefa601f5c2016-06-06 14:27:39 -07002390std::vector<
2391 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002392PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2393 return std::find_if(
2394 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002395 [track](const rtc::scoped_refptr<
2396 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002397 return sender->track() == track;
2398 });
2399}
2400
deadbeefa601f5c2016-06-06 14:27:39 -07002401std::vector<rtc::scoped_refptr<
2402 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002403PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002404 return std::find_if(
2405 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002406 [track_id](const rtc::scoped_refptr<
2407 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002408 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002409 });
2410}
2411
deadbeefab9b2d12015-10-14 11:33:11 -07002412PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2413 cricket::MediaType media_type) {
2414 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2415 media_type == cricket::MEDIA_TYPE_VIDEO);
2416 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2417 : &remote_video_tracks_;
2418}
2419
2420PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2421 cricket::MediaType media_type) {
2422 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2423 media_type == cricket::MEDIA_TYPE_VIDEO);
2424 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2425 : &local_video_tracks_;
2426}
2427
2428const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2429 const PeerConnection::TrackInfos& infos,
2430 const std::string& stream_label,
2431 const std::string track_id) const {
2432 for (const TrackInfo& track_info : infos) {
2433 if (track_info.stream_label == stream_label &&
2434 track_info.track_id == track_id) {
2435 return &track_info;
2436 }
2437 }
2438 return nullptr;
2439}
2440
2441DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2442 for (const auto& channel : sctp_data_channels_) {
2443 if (channel->id() == sid) {
2444 return channel;
2445 }
2446 }
2447 return nullptr;
2448}
2449
deadbeef91dd5672016-05-18 16:55:30 -07002450bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002451 const RTCConfiguration& configuration) {
2452 cricket::ServerAddresses stun_servers;
2453 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002454 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2455 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002456 return false;
2457 }
2458
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002459 port_allocator_->Initialize();
2460
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002461 // To handle both internal and externally created port allocator, we will
2462 // enable BUNDLE here.
2463 int portallocator_flags = port_allocator_->flags();
2464 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002465 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2466 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002467 // If the disable-IPv6 flag was specified, we'll not override it
2468 // by experiment.
2469 if (configuration.disable_ipv6) {
2470 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002471 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2472 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002473 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2474 }
2475
zhihuangb09b3f92017-03-07 14:40:51 -08002476 if (configuration.disable_ipv6_on_wifi) {
2477 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2478 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2479 }
2480
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002481 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2482 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2483 LOG(LS_INFO) << "TCP candidates are disabled.";
2484 }
2485
honghaiz60347052016-05-31 18:29:12 -07002486 if (configuration.candidate_network_policy ==
2487 kCandidateNetworkPolicyLowCost) {
2488 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2489 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2490 }
2491
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002492 port_allocator_->set_flags(portallocator_flags);
2493 // No step delay is used while allocating ports.
2494 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2495 port_allocator_->set_candidate_filter(
2496 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07002497 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002498
2499 // Call this last since it may create pooled allocator sessions using the
2500 // properties set above.
2501 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002502 configuration.ice_candidate_pool_size,
2503 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002504 return true;
2505}
2506
deadbeef91dd5672016-05-18 16:55:30 -07002507bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002508 const cricket::ServerAddresses& stun_servers,
2509 const std::vector<cricket::RelayServerConfig>& turn_servers,
2510 IceTransportsType type,
2511 int candidate_pool_size,
2512 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002513 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002514 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002515 // Call this last since it may create pooled allocator sessions using the
2516 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002517 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002518 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002519}
2520
ivoc14d5dbe2016-07-04 07:06:55 -07002521bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2522 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002523 if (!event_log_) {
2524 return false;
2525 }
skvlad11a9cbf2016-10-07 11:53:05 -07002526 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002527}
2528
2529void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002530 if (event_log_) {
2531 event_log_->StopLogging();
2532 }
ivoc14d5dbe2016-07-04 07:06:55 -07002533}
nisseeaabdf62017-05-05 02:23:02 -07002534
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002535} // namespace webrtc