blob: a3981039e6cfe89554092b4c14d7f2f7b0f175e4 [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"
ivoc14d5dbe2016-07-04 07:06:55 -070022#include "webrtc/base/bind.h"
nissec80e7412017-01-11 05:56:46 -080023#include "webrtc/base/checks.h"
buildbot@webrtc.orga09a9992014-08-13 17:26:08 +000024#include "webrtc/base/logging.h"
25#include "webrtc/base/stringencode.h"
deadbeefab9b2d12015-10-14 11:33:11 -070026#include "webrtc/base/stringutils.h"
Peter Boström1a9d6152015-12-08 22:15:17 +010027#include "webrtc/base/trace_event.h"
ossuf515ab82016-12-07 04:52:58 -080028#include "webrtc/call/call.h"
skvlad11a9cbf2016-10-07 11:53:05 -070029#include "webrtc/logging/rtc_event_log/rtc_event_log.h"
deadbeef953c2ce2017-01-09 14:53:41 -080030#include "webrtc/media/sctp/sctptransport.h"
ossu7bb87ee2017-01-23 04:56:25 -080031#include "webrtc/pc/audiotrack.h"
kjellander@webrtc.org9b8df252016-02-12 06:47:59 +010032#include "webrtc/pc/channelmanager.h"
ossu7bb87ee2017-01-23 04:56:25 -080033#include "webrtc/pc/dtmfsender.h"
34#include "webrtc/pc/mediastream.h"
35#include "webrtc/pc/mediastreamobserver.h"
36#include "webrtc/pc/remoteaudiosource.h"
37#include "webrtc/pc/rtpreceiver.h"
38#include "webrtc/pc/rtpsender.h"
39#include "webrtc/pc/streamcollection.h"
40#include "webrtc/pc/videocapturertracksource.h"
41#include "webrtc/pc/videotrack.h"
42#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
136// Add the stream and RTP data channel info to |session_options|.
deadbeeffac06552015-11-25 11:26:01 -0800137void AddSendStreams(
138 cricket::MediaSessionOptions* session_options,
deadbeefa601f5c2016-06-06 14:27:39 -0700139 const std::vector<rtc::scoped_refptr<
140 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
deadbeeffac06552015-11-25 11:26:01 -0800141 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
142 rtp_data_channels) {
deadbeefab9b2d12015-10-14 11:33:11 -0700143 session_options->streams.clear();
deadbeeffac06552015-11-25 11:26:01 -0800144 for (const auto& sender : senders) {
145 session_options->AddSendStream(sender->media_type(), sender->id(),
deadbeefa601f5c2016-06-06 14:27:39 -0700146 sender->internal()->stream_id());
deadbeefab9b2d12015-10-14 11:33:11 -0700147 }
148
149 // Check for data channels.
150 for (const auto& kv : rtp_data_channels) {
151 const DataChannel* channel = kv.second;
152 if (channel->state() == DataChannel::kConnecting ||
153 channel->state() == DataChannel::kOpen) {
154 // |streamid| and |sync_label| are both set to the DataChannel label
155 // here so they can be signaled the same way as MediaStreams and Tracks.
156 // For MediaStreams, the sync_label is the MediaStream label and the
157 // track label is the same as |streamid|.
158 const std::string& streamid = channel->label();
159 const std::string& sync_label = channel->label();
160 session_options->AddSendStream(cricket::MEDIA_TYPE_DATA, streamid,
161 sync_label);
162 }
163 }
164}
165
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700166uint32_t ConvertIceTransportTypeToCandidateFilter(
167 PeerConnectionInterface::IceTransportsType type) {
168 switch (type) {
169 case PeerConnectionInterface::kNone:
170 return cricket::CF_NONE;
171 case PeerConnectionInterface::kRelay:
172 return cricket::CF_RELAY;
173 case PeerConnectionInterface::kNoHost:
174 return (cricket::CF_ALL & ~cricket::CF_HOST);
175 case PeerConnectionInterface::kAll:
176 return cricket::CF_ALL;
177 default:
nissec80e7412017-01-11 05:56:46 -0800178 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700179 }
180 return cricket::CF_NONE;
181}
182
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700183// Helper method to set a voice/video channel on all applicable senders
184// and receivers when one is created/destroyed by WebRtcSession.
185//
186// Used by On(Voice|Video)Channel(Created|Destroyed)
187template <class SENDER,
188 class RECEIVER,
189 class CHANNEL,
190 class SENDERS,
191 class RECEIVERS>
192void SetChannelOnSendersAndReceivers(CHANNEL* channel,
193 SENDERS& senders,
194 RECEIVERS& receivers,
195 cricket::MediaType media_type) {
196 for (auto& sender : senders) {
197 if (sender->media_type() == media_type) {
198 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
199 }
200 }
201 for (auto& receiver : receivers) {
202 if (receiver->media_type() == media_type) {
203 if (!channel) {
204 receiver->internal()->Stop();
205 }
206 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
207 }
208 }
209}
210
deadbeef293e9262017-01-11 12:28:30 -0800211// Helper to set an error and return from a method.
212bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
213 if (error) {
214 error->set_type(type);
215 }
216 return type == webrtc::RTCErrorType::NONE;
217}
218
deadbeef0a6c4ca2015-10-06 11:38:28 -0700219} // namespace
220
221namespace webrtc {
222
deadbeef293e9262017-01-11 12:28:30 -0800223bool PeerConnectionInterface::RTCConfiguration::operator==(
224 const PeerConnectionInterface::RTCConfiguration& o) const {
225 // This static_assert prevents us from accidentally breaking operator==.
226 struct stuff_being_tested_for_equality {
227 IceTransportsType type;
228 IceServers servers;
229 BundlePolicy bundle_policy;
230 RtcpMuxPolicy rtcp_mux_policy;
231 TcpCandidatePolicy tcp_candidate_policy;
232 CandidateNetworkPolicy candidate_network_policy;
233 int audio_jitter_buffer_max_packets;
234 bool audio_jitter_buffer_fast_accelerate;
235 int ice_connection_receiving_timeout;
236 int ice_backup_candidate_pair_ping_interval;
237 ContinualGatheringPolicy continual_gathering_policy;
238 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
239 bool prioritize_most_likely_ice_candidate_pairs;
240 struct cricket::MediaConfig media_config;
241 bool disable_ipv6;
zhihuangb09b3f92017-03-07 14:40:51 -0800242 bool disable_ipv6_on_wifi;
deadbeef293e9262017-01-11 12:28:30 -0800243 bool enable_rtp_data_channel;
244 bool enable_quic;
245 rtc::Optional<int> screencast_min_bitrate;
246 rtc::Optional<bool> combined_audio_video_bwe;
247 rtc::Optional<bool> enable_dtls_srtp;
248 int ice_candidate_pool_size;
249 bool prune_turn_ports;
250 bool presume_writable_when_fully_relayed;
251 bool enable_ice_renomination;
252 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800253 rtc::Optional<int> ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800254 };
255 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
256 "Did you add something to RTCConfiguration and forget to "
257 "update operator==?");
258 return type == o.type && servers == o.servers &&
259 bundle_policy == o.bundle_policy &&
260 rtcp_mux_policy == o.rtcp_mux_policy &&
261 tcp_candidate_policy == o.tcp_candidate_policy &&
262 candidate_network_policy == o.candidate_network_policy &&
263 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
264 audio_jitter_buffer_fast_accelerate ==
265 o.audio_jitter_buffer_fast_accelerate &&
266 ice_connection_receiving_timeout ==
267 o.ice_connection_receiving_timeout &&
268 ice_backup_candidate_pair_ping_interval ==
269 o.ice_backup_candidate_pair_ping_interval &&
270 continual_gathering_policy == o.continual_gathering_policy &&
271 certificates == o.certificates &&
272 prioritize_most_likely_ice_candidate_pairs ==
273 o.prioritize_most_likely_ice_candidate_pairs &&
274 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800275 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeef293e9262017-01-11 12:28:30 -0800276 enable_rtp_data_channel == o.enable_rtp_data_channel &&
277 enable_quic == o.enable_quic &&
278 screencast_min_bitrate == o.screencast_min_bitrate &&
279 combined_audio_video_bwe == o.combined_audio_video_bwe &&
280 enable_dtls_srtp == o.enable_dtls_srtp &&
281 ice_candidate_pool_size == o.ice_candidate_pool_size &&
282 prune_turn_ports == o.prune_turn_ports &&
283 presume_writable_when_fully_relayed ==
284 o.presume_writable_when_fully_relayed &&
285 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800286 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
287 ice_check_min_interval == o.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -0800288}
289
290bool PeerConnectionInterface::RTCConfiguration::operator!=(
291 const PeerConnectionInterface::RTCConfiguration& o) const {
292 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800293}
294
zhihuang8f65cdf2016-05-06 18:40:30 -0700295// Generate a RTCP CNAME when a PeerConnection is created.
296std::string GenerateRtcpCname() {
297 std::string cname;
298 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
299 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800300 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700301 }
302 return cname;
303}
304
htaa2a49d92016-03-04 02:51:39 -0800305bool ExtractMediaSessionOptions(
deadbeefab9b2d12015-10-14 11:33:11 -0700306 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
htaaac2dea2016-03-10 13:35:55 -0800307 bool is_offer,
deadbeefab9b2d12015-10-14 11:33:11 -0700308 cricket::MediaSessionOptions* session_options) {
309 typedef PeerConnectionInterface::RTCOfferAnswerOptions RTCOfferAnswerOptions;
310 if (!IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) ||
311 !IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video)) {
312 return false;
313 }
314
htaaac2dea2016-03-10 13:35:55 -0800315 // If constraints don't prevent us, we always accept video.
deadbeefc80741f2015-10-22 13:14:45 -0700316 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700317 session_options->recv_audio = (rtc_options.offer_to_receive_audio > 0);
htaaac2dea2016-03-10 13:35:55 -0800318 } else {
319 session_options->recv_audio = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700320 }
htaaac2dea2016-03-10 13:35:55 -0800321 // For offers, we only offer video if we have it or it's forced by options.
322 // For answers, we will always accept video (if offered).
deadbeefc80741f2015-10-22 13:14:45 -0700323 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
deadbeefab9b2d12015-10-14 11:33:11 -0700324 session_options->recv_video = (rtc_options.offer_to_receive_video > 0);
htaaac2dea2016-03-10 13:35:55 -0800325 } else if (is_offer) {
326 session_options->recv_video = false;
327 } else {
328 session_options->recv_video = true;
deadbeefab9b2d12015-10-14 11:33:11 -0700329 }
330
331 session_options->vad_enabled = rtc_options.voice_activity_detection;
deadbeefc80741f2015-10-22 13:14:45 -0700332 session_options->bundle_enabled = rtc_options.use_rtp_mux;
deadbeef0ed85b22016-02-23 17:24:52 -0800333 for (auto& kv : session_options->transport_options) {
334 kv.second.ice_restart = rtc_options.ice_restart;
335 }
deadbeefab9b2d12015-10-14 11:33:11 -0700336
337 return true;
338}
339
340bool ParseConstraintsForAnswer(const MediaConstraintsInterface* constraints,
341 cricket::MediaSessionOptions* session_options) {
342 bool value = false;
343 size_t mandatory_constraints_satisfied = 0;
344
345 // kOfferToReceiveAudio defaults to true according to spec.
346 if (!FindConstraint(constraints,
347 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
348 &mandatory_constraints_satisfied) ||
349 value) {
350 session_options->recv_audio = true;
351 }
352
353 // kOfferToReceiveVideo defaults to false according to spec. But
354 // if it is an answer and video is offered, we should still accept video
355 // per default.
356 value = false;
357 if (!FindConstraint(constraints,
358 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
359 &mandatory_constraints_satisfied) ||
360 value) {
361 session_options->recv_video = true;
362 }
363
364 if (FindConstraint(constraints,
365 MediaConstraintsInterface::kVoiceActivityDetection, &value,
366 &mandatory_constraints_satisfied)) {
367 session_options->vad_enabled = value;
368 }
369
370 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
371 &mandatory_constraints_satisfied)) {
372 session_options->bundle_enabled = value;
373 } else {
374 // kUseRtpMux defaults to true according to spec.
375 session_options->bundle_enabled = true;
376 }
deadbeefab9b2d12015-10-14 11:33:11 -0700377
deadbeef0ed85b22016-02-23 17:24:52 -0800378 bool ice_restart = false;
deadbeefab9b2d12015-10-14 11:33:11 -0700379 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
380 &value, &mandatory_constraints_satisfied)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700381 // kIceRestart defaults to false according to spec.
deadbeef0ed85b22016-02-23 17:24:52 -0800382 ice_restart = true;
383 }
384 for (auto& kv : session_options->transport_options) {
385 kv.second.ice_restart = ice_restart;
deadbeefab9b2d12015-10-14 11:33:11 -0700386 }
387
388 if (!constraints) {
389 return true;
390 }
391 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
392}
393
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000394PeerConnection::PeerConnection(PeerConnectionFactory* factory)
395 : factory_(factory),
396 observer_(NULL),
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +0000397 uma_observer_(NULL),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000398 signaling_state_(kStable),
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000399 ice_connection_state_(kIceConnectionNew),
deadbeefab9b2d12015-10-14 11:33:11 -0700400 ice_gathering_state_(kIceGatheringNew),
nisse30612762016-12-20 05:03:58 -0800401 event_log_(RtcEventLog::Create()),
zhihuang8f65cdf2016-05-06 18:40:30 -0700402 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700403 local_streams_(StreamCollection::Create()),
404 remote_streams_(StreamCollection::Create()) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000405
406PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100407 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700408 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeef70ab1a12015-09-28 16:53:55 -0700409 // Need to detach RTP senders/receivers from WebRtcSession,
410 // since it's about to be destroyed.
411 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700412 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700413 }
414 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700415 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700416 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700417 // Destroy stats_ because it depends on session_.
418 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800419 if (stats_collector_) {
420 stats_collector_->WaitForPendingRequest();
421 stats_collector_ = nullptr;
422 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700423 // Now destroy session_ before destroying other members,
424 // because its destruction fires signals (such as VoiceChannelDestroyed)
425 // which will trigger some final actions in PeerConnection...
426 session_.reset(nullptr);
deadbeef91dd5672016-05-18 16:55:30 -0700427 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700428 network_thread()->Invoke<void>(RTC_FROM_HERE,
429 [this] { port_allocator_.reset(nullptr); });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000430}
431
432bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000433 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700434 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200435 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800436 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100437 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
deadbeef293e9262017-01-11 12:28:30 -0800438 if (!allocator) {
439 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
440 << "This shouldn't happen if using PeerConnectionFactory.";
441 return false;
442 }
deadbeef653b8e02015-11-11 12:55:10 -0800443 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800444 // TODO(deadbeef): Why do we do this?
445 LOG(LS_ERROR) << "PeerConnection initialized without a "
446 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800447 return false;
448 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000449 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800450 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800451
deadbeef91dd5672016-05-18 16:55:30 -0700452 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700453 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700454 if (!network_thread()->Invoke<bool>(
455 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
456 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000457 return false;
458 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000459
skvlad11a9cbf2016-10-07 11:53:05 -0700460 media_controller_.reset(factory_->CreateMediaController(
461 configuration.media_config, event_log_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000462
zhihuang29ff8442016-07-27 11:07:25 -0700463 session_.reset(new WebRtcSession(
464 media_controller_.get(), factory_->network_thread(),
465 factory_->worker_thread(), factory_->signaling_thread(),
466 port_allocator_.get(),
467 std::unique_ptr<cricket::TransportController>(
Honghai Zhangbfd398c2016-08-30 22:07:42 -0700468 factory_->CreateTransportController(
469 port_allocator_.get(),
deadbeef953c2ce2017-01-09 14:53:41 -0800470 configuration.redetermine_role_on_ice_restart)),
471#ifdef HAVE_SCTP
472 std::unique_ptr<cricket::SctpTransportInternalFactory>(
473 new cricket::SctpTransportFactory(factory_->network_thread()))
474#else
475 nullptr
476#endif
477 ));
zhihuang29ff8442016-07-27 11:07:25 -0700478
deadbeefab9b2d12015-10-14 11:33:11 -0700479 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700480 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000481
482 // Initialize the WebRtcSession. It creates transport channels etc.
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200483 if (!session_->Initialize(factory_->options(), std::move(cert_generator),
htaa2a49d92016-03-04 02:51:39 -0800484 configuration)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000485 return false;
deadbeefab9b2d12015-10-14 11:33:11 -0700486 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000487
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000488 // Register PeerConnection as receiver of local ice candidates.
489 // All the callbacks will be posted to the application from PeerConnection.
490 session_->RegisterIceObserver(this);
491 session_->SignalState.connect(this, &PeerConnection::OnSessionStateChange);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700492 session_->SignalVoiceChannelCreated.connect(
493 this, &PeerConnection::OnVoiceChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700494 session_->SignalVoiceChannelDestroyed.connect(
495 this, &PeerConnection::OnVoiceChannelDestroyed);
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700496 session_->SignalVideoChannelCreated.connect(
497 this, &PeerConnection::OnVideoChannelCreated);
deadbeefab9b2d12015-10-14 11:33:11 -0700498 session_->SignalVideoChannelDestroyed.connect(
499 this, &PeerConnection::OnVideoChannelDestroyed);
500 session_->SignalDataChannelCreated.connect(
501 this, &PeerConnection::OnDataChannelCreated);
502 session_->SignalDataChannelDestroyed.connect(
503 this, &PeerConnection::OnDataChannelDestroyed);
504 session_->SignalDataChannelOpenMessage.connect(
505 this, &PeerConnection::OnDataChannelOpenMessage);
deadbeef46c73892016-11-16 19:42:04 -0800506
507 configuration_ = configuration;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000508 return true;
509}
510
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000511rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000512PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700513 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000514}
515
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000516rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000517PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700518 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000519}
520
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000521bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100522 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000523 if (IsClosed()) {
524 return false;
525 }
deadbeefab9b2d12015-10-14 11:33:11 -0700526 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000527 return false;
528 }
deadbeefab9b2d12015-10-14 11:33:11 -0700529
530 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800531 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
532 observer->SignalAudioTrackAdded.connect(this,
533 &PeerConnection::OnAudioTrackAdded);
534 observer->SignalAudioTrackRemoved.connect(
535 this, &PeerConnection::OnAudioTrackRemoved);
536 observer->SignalVideoTrackAdded.connect(this,
537 &PeerConnection::OnVideoTrackAdded);
538 observer->SignalVideoTrackRemoved.connect(
539 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700540 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700541
deadbeefab9b2d12015-10-14 11:33:11 -0700542 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800543 OnAudioTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700544 }
545 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800546 OnVideoTrackAdded(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700547 }
548
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000549 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000550 observer_->OnRenegotiationNeeded();
551 return true;
552}
553
554void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100555 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
deadbeefab9b2d12015-10-14 11:33:11 -0700556 for (const auto& track : local_stream->GetAudioTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800557 OnAudioTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700558 }
559 for (const auto& track : local_stream->GetVideoTracks()) {
deadbeefeb459812015-12-15 19:24:43 -0800560 OnVideoTrackRemoved(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700561 }
562
563 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800564 stream_observers_.erase(
565 std::remove_if(
566 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700567 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800568 return observer->stream()->label().compare(local_stream->label()) ==
569 0;
570 }),
571 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700572
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000573 if (IsClosed()) {
574 return;
575 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000576 observer_->OnRenegotiationNeeded();
577}
578
deadbeefe1f9d832016-01-14 15:35:42 -0800579rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
580 MediaStreamTrackInterface* track,
581 std::vector<MediaStreamInterface*> streams) {
582 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
583 if (IsClosed()) {
584 return nullptr;
585 }
586 if (streams.size() >= 2) {
587 LOG(LS_ERROR)
588 << "Adding a track with two streams is not currently supported.";
589 return nullptr;
590 }
591 // TODO(deadbeef): Support adding a track to two different senders.
592 if (FindSenderForTrack(track) != senders_.end()) {
593 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
594 return nullptr;
595 }
596
597 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -0700598 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -0800599 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700600 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800601 signaling_thread(),
602 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700603 session_->voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -0800604 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700605 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800606 }
607 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700608 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800609 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700610 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800611 }
612 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700613 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -0800614 signaling_thread(),
615 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700616 session_->video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -0800617 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700618 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -0800619 }
620 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -0700621 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -0800622 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -0700623 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -0800624 }
625 } else {
626 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
627 return rtc::scoped_refptr<RtpSenderInterface>();
628 }
629
630 senders_.push_back(new_sender);
631 observer_->OnRenegotiationNeeded();
632 return new_sender;
633}
634
635bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
636 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
637 if (IsClosed()) {
638 return false;
639 }
640
641 auto it = std::find(senders_.begin(), senders_.end(), sender);
642 if (it == senders_.end()) {
643 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
644 return false;
645 }
deadbeefa601f5c2016-06-06 14:27:39 -0700646 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -0800647 senders_.erase(it);
648
649 observer_->OnRenegotiationNeeded();
650 return true;
651}
652
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000653rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000654 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100655 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -0700656 if (IsClosed()) {
657 return nullptr;
658 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000659 if (!track) {
660 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -0800661 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000662 }
deadbeef20cb0c12017-02-01 20:27:00 -0800663 auto it = FindSenderForTrack(track);
664 if (it == senders_.end()) {
665 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
666 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000667 }
668
deadbeef20cb0c12017-02-01 20:27:00 -0800669 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000670}
671
deadbeeffac06552015-11-25 11:26:01 -0800672rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -0800673 const std::string& kind,
674 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100675 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -0700676 if (IsClosed()) {
677 return nullptr;
678 }
deadbeefa601f5c2016-06-06 14:27:39 -0700679 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800680 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700681 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700682 signaling_thread(),
683 new AudioRtpSender(session_->voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -0800684 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -0700685 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700686 signaling_thread(), new VideoRtpSender(session_->video_channel()));
deadbeeffac06552015-11-25 11:26:01 -0800687 } else {
688 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -0800689 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800690 }
deadbeefbd7d8f72015-12-18 16:58:44 -0800691 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -0700692 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -0800693 }
deadbeeffac06552015-11-25 11:26:01 -0800694 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -0800695 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -0800696}
697
deadbeef70ab1a12015-09-28 16:53:55 -0700698std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
699 const {
deadbeefa601f5c2016-06-06 14:27:39 -0700700 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
701 for (const auto& sender : senders_) {
702 ret.push_back(sender.get());
703 }
704 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700705}
706
707std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
708PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -0700709 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
710 for (const auto& receiver : receivers_) {
711 ret.push_back(receiver.get());
712 }
713 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -0700714}
715
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000716bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +0000717 MediaStreamTrackInterface* track,
718 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100719 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700720 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -0800721 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000722 LOG(LS_ERROR) << "GetStats - observer is NULL.";
723 return false;
724 }
725
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000726 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -0700727 // The StatsCollector is used to tell if a track is valid because it may
728 // remember tracks that the PeerConnection previously removed.
729 if (track && !stats_->IsValidTrack(track->id())) {
730 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
731 << track->id();
732 return false;
733 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700734 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000735 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000736 return true;
737}
738
hbos74e1a4f2016-09-15 23:33:01 -0700739void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
740 RTC_DCHECK(stats_collector_);
741 stats_collector_->GetStatsReport(callback);
742}
743
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000744PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
745 return signaling_state_;
746}
747
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000748PeerConnectionInterface::IceConnectionState
749PeerConnection::ice_connection_state() {
750 return ice_connection_state_;
751}
752
753PeerConnectionInterface::IceGatheringState
754PeerConnection::ice_gathering_state() {
755 return ice_gathering_state_;
756}
757
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000758rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000759PeerConnection::CreateDataChannel(
760 const std::string& label,
761 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100762 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -0700763#ifdef HAVE_QUIC
764 if (session_->data_channel_type() == cricket::DCT_QUIC) {
765 // TODO(zhihuang): Handle case when config is NULL.
766 if (!config) {
767 LOG(LS_ERROR) << "Missing config for QUIC data channel.";
768 return nullptr;
769 }
770 // TODO(zhihuang): Allow unreliable or ordered QUIC data channels.
771 if (!config->reliable || config->ordered) {
772 LOG(LS_ERROR) << "QUIC data channel does not implement unreliable or "
773 "ordered delivery.";
774 return nullptr;
775 }
776 return session_->quic_data_transport()->CreateDataChannel(label, config);
777 }
778#endif // HAVE_QUIC
779
deadbeefab9b2d12015-10-14 11:33:11 -0700780 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000781
kwibergd1fe2812016-04-27 06:47:29 -0700782 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +0000783 if (config) {
784 internal_config.reset(new InternalDataChannelInit(*config));
785 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000786 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -0700787 InternalCreateDataChannel(label, internal_config.get()));
788 if (!channel.get()) {
789 return nullptr;
790 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000791
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +0000792 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
793 // the first SCTP DataChannel.
794 if (session_->data_channel_type() == cricket::DCT_RTP || first_datachannel) {
795 observer_->OnRenegotiationNeeded();
796 }
wu@webrtc.org91053e72013-08-10 07:18:04 +0000797
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000798 return DataChannelProxy::Create(signaling_thread(), channel.get());
799}
800
801void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
802 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100803 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800804 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000805 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
806 return;
807 }
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000808 RTCOfferAnswerOptions options;
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000809
810 bool value;
811 size_t mandatory_constraints = 0;
812
813 if (FindConstraint(constraints,
814 MediaConstraintsInterface::kOfferToReceiveAudio,
815 &value,
816 &mandatory_constraints)) {
817 options.offer_to_receive_audio =
818 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
819 }
820
821 if (FindConstraint(constraints,
822 MediaConstraintsInterface::kOfferToReceiveVideo,
823 &value,
824 &mandatory_constraints)) {
825 options.offer_to_receive_video =
826 value ? RTCOfferAnswerOptions::kOfferToReceiveMediaTrue : 0;
827 }
828
829 if (FindConstraint(constraints,
830 MediaConstraintsInterface::kVoiceActivityDetection,
831 &value,
832 &mandatory_constraints)) {
833 options.voice_activity_detection = value;
834 }
835
836 if (FindConstraint(constraints,
837 MediaConstraintsInterface::kIceRestart,
838 &value,
839 &mandatory_constraints)) {
840 options.ice_restart = value;
841 }
842
843 if (FindConstraint(constraints,
844 MediaConstraintsInterface::kUseRtpMux,
845 &value,
846 &mandatory_constraints)) {
847 options.use_rtp_mux = value;
848 }
849
850 CreateOffer(observer, options);
851}
852
853void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
854 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100855 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
nisse7ce109a2017-01-31 00:57:56 -0800856 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +0000857 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
858 return;
859 }
deadbeefab9b2d12015-10-14 11:33:11 -0700860
861 cricket::MediaSessionOptions session_options;
862 if (!GetOptionsForOffer(options, &session_options)) {
863 std::string error = "CreateOffer called with invalid options.";
864 LOG(LS_ERROR) << error;
865 PostCreateSessionDescriptionFailure(observer, error);
866 return;
867 }
868
869 session_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000870}
871
872void PeerConnection::CreateAnswer(
873 CreateSessionDescriptionObserver* observer,
874 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100875 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800876 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000877 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
878 return;
879 }
deadbeefab9b2d12015-10-14 11:33:11 -0700880
881 cricket::MediaSessionOptions session_options;
882 if (!GetOptionsForAnswer(constraints, &session_options)) {
883 std::string error = "CreateAnswer called with invalid constraints.";
884 LOG(LS_ERROR) << error;
885 PostCreateSessionDescriptionFailure(observer, error);
886 return;
887 }
888
htaa2a49d92016-03-04 02:51:39 -0800889 session_->CreateAnswer(observer, session_options);
890}
891
892void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
893 const RTCOfferAnswerOptions& options) {
894 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -0800895 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -0800896 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
897 return;
898 }
899
900 cricket::MediaSessionOptions session_options;
901 if (!GetOptionsForAnswer(options, &session_options)) {
902 std::string error = "CreateAnswer called with invalid options.";
903 LOG(LS_ERROR) << error;
904 PostCreateSessionDescriptionFailure(observer, error);
905 return;
906 }
907
908 session_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000909}
910
911void PeerConnection::SetLocalDescription(
912 SetSessionDescriptionObserver* observer,
913 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100914 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
zhihuang29ff8442016-07-27 11:07:25 -0700915 if (IsClosed()) {
916 return;
917 }
nisse7ce109a2017-01-31 00:57:56 -0800918 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000919 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
920 return;
921 }
922 if (!desc) {
923 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
924 return;
925 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000926 // Update stats here so that we have the most recent stats for tracks and
927 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000928 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000929 std::string error;
930 if (!session_->SetLocalDescription(desc, &error)) {
931 PostSetSessionDescriptionFailure(observer, error);
932 return;
933 }
deadbeefab9b2d12015-10-14 11:33:11 -0700934
935 // If setting the description decided our SSL role, allocate any necessary
936 // SCTP sids.
937 rtc::SSLRole role;
938 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -0800939 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -0700940 AllocateSctpSids(role);
941 }
942
943 // Update state and SSRC of local MediaStreams and DataChannels based on the
944 // local session description.
945 const cricket::ContentInfo* audio_content =
946 GetFirstAudioContent(desc->description());
947 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800948 if (audio_content->rejected) {
949 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
950 } else {
951 const cricket::AudioContentDescription* audio_desc =
952 static_cast<const cricket::AudioContentDescription*>(
953 audio_content->description);
954 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
955 }
deadbeefab9b2d12015-10-14 11:33:11 -0700956 }
957
958 const cricket::ContentInfo* video_content =
959 GetFirstVideoContent(desc->description());
960 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -0800961 if (video_content->rejected) {
962 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
963 } else {
964 const cricket::VideoContentDescription* video_desc =
965 static_cast<const cricket::VideoContentDescription*>(
966 video_content->description);
967 UpdateLocalTracks(video_desc->streams(), video_desc->type());
968 }
deadbeefab9b2d12015-10-14 11:33:11 -0700969 }
970
971 const cricket::ContentInfo* data_content =
972 GetFirstDataContent(desc->description());
973 if (data_content) {
974 const cricket::DataContentDescription* data_desc =
975 static_cast<const cricket::DataContentDescription*>(
976 data_content->description);
977 if (rtc::starts_with(data_desc->protocol().data(),
978 cricket::kMediaProtocolRtpPrefix)) {
979 UpdateLocalRtpDataChannels(data_desc->streams());
980 }
981 }
982
983 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700984 signaling_thread()->Post(RTC_FROM_HERE, this,
985 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -0700986
deadbeef42a42632017-03-10 15:18:00 -0800987 // According to JSEP, after setLocalDescription, changing the candidate pool
988 // size is not allowed, and changing the set of ICE servers will not result
989 // in new candidates being gathered.
990 port_allocator_->FreezeCandidatePool();
991
deadbeefcbecd352015-09-23 11:50:27 -0700992 // MaybeStartGathering needs to be called after posting
993 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
994 // before signaling that SetLocalDescription completed.
995 session_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -0800996
997 if (desc->type() == SessionDescriptionInterface::kAnswer) {
998 // TODO(deadbeef): We already had to hop to the network thread for
999 // MaybeStartGathering...
1000 network_thread()->Invoke<void>(
1001 RTC_FROM_HERE,
1002 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1003 port_allocator_.get()));
1004 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001005}
1006
1007void PeerConnection::SetRemoteDescription(
1008 SetSessionDescriptionObserver* observer,
1009 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001010 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
zhihuang29ff8442016-07-27 11:07:25 -07001011 if (IsClosed()) {
1012 return;
1013 }
nisse7ce109a2017-01-31 00:57:56 -08001014 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001015 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1016 return;
1017 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001018 if (!desc) {
1019 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1020 return;
1021 }
1022 // Update stats here so that we have the most recent stats for tracks and
1023 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001024 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001025 std::string error;
1026 if (!session_->SetRemoteDescription(desc, &error)) {
1027 PostSetSessionDescriptionFailure(observer, error);
1028 return;
1029 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001030
deadbeefab9b2d12015-10-14 11:33:11 -07001031 // If setting the description decided our SSL role, allocate any necessary
1032 // SCTP sids.
1033 rtc::SSLRole role;
1034 if (session_->data_channel_type() == cricket::DCT_SCTP &&
deadbeef953c2ce2017-01-09 14:53:41 -08001035 session_->GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001036 AllocateSctpSids(role);
1037 }
1038
1039 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001040 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1041 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1042 const cricket::AudioContentDescription* audio_desc =
1043 GetFirstAudioContentDescription(remote_desc);
1044 const cricket::VideoContentDescription* video_desc =
1045 GetFirstVideoContentDescription(remote_desc);
1046 const cricket::DataContentDescription* data_desc =
1047 GetFirstDataContentDescription(remote_desc);
1048
1049 // Check if the descriptions include streams, just in case the peer supports
1050 // MSID, but doesn't indicate so with "a=msid-semantic".
1051 if (remote_desc->msid_supported() ||
1052 (audio_desc && !audio_desc->streams().empty()) ||
1053 (video_desc && !video_desc->streams().empty())) {
1054 remote_peer_supports_msid_ = true;
1055 }
deadbeefab9b2d12015-10-14 11:33:11 -07001056
1057 // We wait to signal new streams until we finish processing the description,
1058 // since only at that point will new streams have all their tracks.
1059 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1060
1061 // Find all audio rtp streams and create corresponding remote AudioTracks
1062 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001063 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001064 if (audio_content->rejected) {
1065 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1066 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001067 bool default_audio_track_needed =
1068 !remote_peer_supports_msid_ &&
1069 MediaContentDirectionHasSend(audio_desc->direction());
1070 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1071 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001072 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001073 }
deadbeefab9b2d12015-10-14 11:33:11 -07001074 }
1075
1076 // Find all video rtp streams and create corresponding remote VideoTracks
1077 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001078 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001079 if (video_content->rejected) {
1080 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1081 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001082 bool default_video_track_needed =
1083 !remote_peer_supports_msid_ &&
1084 MediaContentDirectionHasSend(video_desc->direction());
1085 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1086 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001087 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001088 }
deadbeefab9b2d12015-10-14 11:33:11 -07001089 }
1090
1091 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001092 if (data_desc) {
1093 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001094 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001095 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001096 }
1097 }
1098
1099 // Iterate new_streams and notify the observer about new MediaStreams.
1100 for (size_t i = 0; i < new_streams->count(); ++i) {
1101 MediaStreamInterface* new_stream = new_streams->at(i);
1102 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001103 observer_->OnAddStream(
1104 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001105 }
1106
deadbeefbda7e0b2015-12-08 17:13:40 -08001107 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001108
1109 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001110 signaling_thread()->Post(RTC_FROM_HERE, this,
1111 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001112
1113 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1114 // TODO(deadbeef): We already had to hop to the network thread for
1115 // MaybeStartGathering...
1116 network_thread()->Invoke<void>(
1117 RTC_FROM_HERE,
1118 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1119 port_allocator_.get()));
1120 }
deadbeeffc648b62015-10-13 16:42:33 -07001121}
1122
deadbeef46c73892016-11-16 19:42:04 -08001123PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1124 return configuration_;
1125}
1126
deadbeef293e9262017-01-11 12:28:30 -08001127bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1128 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001129 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001130
1131 if (session_->local_description() &&
1132 configuration.ice_candidate_pool_size !=
1133 configuration_.ice_candidate_pool_size) {
1134 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1135 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001136 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001137 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001138
deadbeef293e9262017-01-11 12:28:30 -08001139 // The simplest (and most future-compatible) way to tell if the config was
1140 // modified in an invalid way is to copy each property we do support
1141 // modifying, then use operator==. There are far more properties we don't
1142 // support modifying than those we do, and more could be added.
1143 RTCConfiguration modified_config = configuration_;
1144 modified_config.servers = configuration.servers;
1145 modified_config.type = configuration.type;
1146 modified_config.ice_candidate_pool_size =
1147 configuration.ice_candidate_pool_size;
1148 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001149 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
deadbeef293e9262017-01-11 12:28:30 -08001150 if (configuration != modified_config) {
1151 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1152 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1153 }
1154
1155 // Note that this isn't possible through chromium, since it's an unsigned
1156 // short in WebIDL.
1157 if (configuration.ice_candidate_pool_size < 0 ||
1158 configuration.ice_candidate_pool_size > UINT16_MAX) {
1159 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1160 }
1161
1162 // Parse ICE servers before hopping to network thread.
1163 cricket::ServerAddresses stun_servers;
1164 std::vector<cricket::RelayServerConfig> turn_servers;
1165 RTCErrorType parse_error =
1166 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1167 if (parse_error != RTCErrorType::NONE) {
1168 return SafeSetError(parse_error, error);
1169 }
1170
1171 // In theory this shouldn't fail.
1172 if (!network_thread()->Invoke<bool>(
1173 RTC_FROM_HERE,
1174 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1175 stun_servers, turn_servers, modified_config.type,
1176 modified_config.ice_candidate_pool_size,
1177 modified_config.prune_turn_ports))) {
1178 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1179 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1180 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001181
deadbeefd1a38b52016-12-10 13:15:33 -08001182 // As described in JSEP, calling setConfiguration with new ICE servers or
1183 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1184 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001185 if (modified_config.servers != configuration_.servers ||
1186 modified_config.type != configuration_.type ||
1187 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
deadbeefd1a38b52016-12-10 13:15:33 -08001188 session_->SetNeedsIceRestartFlag();
1189 }
skvladd1f5fda2017-02-03 16:54:05 -08001190
1191 if (modified_config.ice_check_min_interval !=
1192 configuration_.ice_check_min_interval) {
1193 session_->SetIceConfig(session_->ParseIceConfig(modified_config));
1194 }
1195
deadbeef293e9262017-01-11 12:28:30 -08001196 configuration_ = modified_config;
1197 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001198}
1199
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001200bool PeerConnection::AddIceCandidate(
1201 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001202 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001203 if (IsClosed()) {
1204 return false;
1205 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001206 return session_->ProcessIceMessage(ice_candidate);
1207}
1208
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001209bool PeerConnection::RemoveIceCandidates(
1210 const std::vector<cricket::Candidate>& candidates) {
1211 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
1212 return session_->RemoveRemoteIceCandidates(candidates);
1213}
1214
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001215void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001216 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001217 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001218
1219 if (session_) {
1220 session_->set_metrics_observer(uma_observer_);
1221 }
1222
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001223 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001224 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001225 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001226 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001227 uma_observer_->IncrementEnumCounter(
1228 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1229 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001230 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001231 uma_observer_->IncrementEnumCounter(
1232 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1233 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001234 }
1235 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001236}
1237
ivoc14d5dbe2016-07-04 07:06:55 -07001238bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1239 int64_t max_size_bytes) {
1240 return factory_->worker_thread()->Invoke<bool>(
1241 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StartRtcEventLog_w, this, file,
1242 max_size_bytes));
1243}
1244
1245void PeerConnection::StopRtcEventLog() {
1246 factory_->worker_thread()->Invoke<void>(
1247 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1248}
1249
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001250const SessionDescriptionInterface* PeerConnection::local_description() const {
1251 return session_->local_description();
1252}
1253
1254const SessionDescriptionInterface* PeerConnection::remote_description() const {
1255 return session_->remote_description();
1256}
1257
deadbeeffe4a8a42016-12-20 17:56:17 -08001258const SessionDescriptionInterface* PeerConnection::current_local_description()
1259 const {
1260 return session_->current_local_description();
1261}
1262
1263const SessionDescriptionInterface* PeerConnection::current_remote_description()
1264 const {
1265 return session_->current_remote_description();
1266}
1267
1268const SessionDescriptionInterface* PeerConnection::pending_local_description()
1269 const {
1270 return session_->pending_local_description();
1271}
1272
1273const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1274 const {
1275 return session_->pending_remote_description();
1276}
1277
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001278void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001279 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001280 // Update stats here so that we have the most recent stats for tracks and
1281 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001282 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001283
deadbeefd59daf82015-10-14 15:02:44 -07001284 session_->Close();
zhihuang77985012017-02-07 15:45:16 -08001285 event_log_.reset();
deadbeef42a42632017-03-10 15:18:00 -08001286 network_thread()->Invoke<void>(
1287 RTC_FROM_HERE,
1288 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1289 port_allocator_.get()));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001290}
1291
deadbeefd59daf82015-10-14 15:02:44 -07001292void PeerConnection::OnSessionStateChange(WebRtcSession* /*session*/,
1293 WebRtcSession::State state) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001294 switch (state) {
deadbeefd59daf82015-10-14 15:02:44 -07001295 case WebRtcSession::STATE_INIT:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001296 ChangeSignalingState(PeerConnectionInterface::kStable);
mallinath@webrtc.org19f27e62013-10-13 17:18:27 +00001297 break;
deadbeefd59daf82015-10-14 15:02:44 -07001298 case WebRtcSession::STATE_SENTOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001299 ChangeSignalingState(PeerConnectionInterface::kHaveLocalOffer);
1300 break;
deadbeefd59daf82015-10-14 15:02:44 -07001301 case WebRtcSession::STATE_SENTPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001302 ChangeSignalingState(PeerConnectionInterface::kHaveLocalPrAnswer);
1303 break;
deadbeefd59daf82015-10-14 15:02:44 -07001304 case WebRtcSession::STATE_RECEIVEDOFFER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305 ChangeSignalingState(PeerConnectionInterface::kHaveRemoteOffer);
1306 break;
deadbeefd59daf82015-10-14 15:02:44 -07001307 case WebRtcSession::STATE_RECEIVEDPRANSWER:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001308 ChangeSignalingState(PeerConnectionInterface::kHaveRemotePrAnswer);
1309 break;
deadbeefd59daf82015-10-14 15:02:44 -07001310 case WebRtcSession::STATE_INPROGRESS:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 ChangeSignalingState(PeerConnectionInterface::kStable);
1312 break;
deadbeefd59daf82015-10-14 15:02:44 -07001313 case WebRtcSession::STATE_CLOSED:
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001314 ChangeSignalingState(PeerConnectionInterface::kClosed);
1315 break;
1316 default:
1317 break;
1318 }
1319}
1320
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001321void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001323 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1324 SetSessionDescriptionMsg* param =
1325 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1326 param->observer->OnSuccess();
1327 delete param;
1328 break;
1329 }
1330 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
1331 SetSessionDescriptionMsg* param =
1332 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1333 param->observer->OnFailure(param->error);
1334 delete param;
1335 break;
1336 }
deadbeefab9b2d12015-10-14 11:33:11 -07001337 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
1338 CreateSessionDescriptionMsg* param =
1339 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
1340 param->observer->OnFailure(param->error);
1341 delete param;
1342 break;
1343 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001344 case MSG_GETSTATS: {
1345 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08001346 StatsReports reports;
1347 stats_->GetStats(param->track, &reports);
1348 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349 delete param;
1350 break;
1351 }
deadbeefbd292462015-12-14 18:15:29 -08001352 case MSG_FREE_DATACHANNELS: {
1353 sctp_data_channels_to_free_.clear();
1354 break;
1355 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356 default:
nisseeb4ca4e2017-01-12 02:24:27 -08001357 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001358 break;
1359 }
1360}
1361
deadbeefab9b2d12015-10-14 11:33:11 -07001362void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07001363 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001364 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001365 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1366 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08001367 signaling_thread(),
1368 new AudioRtpReceiver(track_id, ssrc, session_->voice_channel()));
1369 stream->AddTrack(
1370 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001371 receivers_.push_back(receiver);
1372 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1373 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1374 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001375}
1376
deadbeefab9b2d12015-10-14 11:33:11 -07001377void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01001378 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07001379 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08001380 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1381 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefa601f5c2016-06-06 14:27:39 -07001382 signaling_thread(),
deadbeefe814a0d2017-02-25 18:15:09 -08001383 new VideoRtpReceiver(track_id, factory_->worker_thread(), ssrc,
1384 session_->video_channel()));
1385 stream->AddTrack(
1386 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08001387 receivers_.push_back(receiver);
1388 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
1389 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
1390 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001391}
1392
deadbeef70ab1a12015-09-28 16:53:55 -07001393// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
1394// description.
perkjd61bf802016-03-24 03:16:19 -07001395void PeerConnection::DestroyReceiver(const std::string& track_id) {
1396 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07001397 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07001398 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07001399 << " doesn't exist.";
1400 } else {
deadbeefa601f5c2016-06-06 14:27:39 -07001401 (*it)->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -07001402 receivers_.erase(it);
1403 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001404}
1405
zstein6dfd53a2017-03-06 13:49:03 -08001406void PeerConnection::OnIceConnectionStateChange(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407 PeerConnectionInterface::IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001408 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefcbecd352015-09-23 11:50:27 -07001409 // After transitioning to "closed", ignore any additional states from
1410 // WebRtcSession (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07001411 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07001412 return;
1413 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001414 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001415 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416}
1417
1418void PeerConnection::OnIceGatheringChange(
1419 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001420 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001421 if (IsClosed()) {
1422 return;
1423 }
1424 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00001425 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001426}
1427
jbauch81bf7b02017-03-25 08:31:12 -07001428void PeerConnection::OnIceCandidate(
1429 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001430 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001431 if (IsClosed()) {
1432 return;
1433 }
jbauch81bf7b02017-03-25 08:31:12 -07001434 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001435}
1436
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001437void PeerConnection::OnIceCandidatesRemoved(
1438 const std::vector<cricket::Candidate>& candidates) {
1439 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001440 if (IsClosed()) {
1441 return;
1442 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001443 observer_->OnIceCandidatesRemoved(candidates);
1444}
1445
Peter Thatcher54360512015-07-08 11:08:35 -07001446void PeerConnection::OnIceConnectionReceivingChange(bool receiving) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07001447 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07001448 if (IsClosed()) {
1449 return;
1450 }
Peter Thatcher54360512015-07-08 11:08:35 -07001451 observer_->OnIceConnectionReceivingChange(receiving);
1452}
1453
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001454void PeerConnection::ChangeSignalingState(
1455 PeerConnectionInterface::SignalingState signaling_state) {
1456 signaling_state_ = signaling_state;
1457 if (signaling_state == kClosed) {
1458 ice_connection_state_ = kIceConnectionClosed;
1459 observer_->OnIceConnectionChange(ice_connection_state_);
1460 if (ice_gathering_state_ != kIceGatheringComplete) {
1461 ice_gathering_state_ = kIceGatheringComplete;
1462 observer_->OnIceGatheringChange(ice_gathering_state_);
1463 }
1464 }
1465 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001466}
1467
deadbeefeb459812015-12-15 19:24:43 -08001468void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
1469 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001470 if (IsClosed()) {
1471 return;
1472 }
deadbeefeb459812015-12-15 19:24:43 -08001473 auto sender = FindSenderForTrack(track);
1474 if (sender != senders_.end()) {
1475 // We already have a sender for this track, so just change the stream_id
1476 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001477 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001478 return;
1479 }
1480
1481 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001482 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1483 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001484 signaling_thread(),
1485 new AudioRtpSender(track, stream->label(), session_->voice_channel(),
1486 stats_.get()));
deadbeefeb459812015-12-15 19:24:43 -08001487 senders_.push_back(new_sender);
1488 // If the sender has already been configured in SDP, we call SetSsrc,
1489 // which will connect the sender to the underlying transport. This can
1490 // occur if a local session description that contains the ID of the sender
1491 // is set before AddStream is called. It can also occur if the local
1492 // session description is not changed and RemoveStream is called, and
1493 // later AddStream is called again with the same stream.
1494 const TrackInfo* track_info =
1495 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
1496 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001497 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001498 }
1499}
1500
1501// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
1502// indefinitely, when we have unified plan SDP.
1503void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
1504 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001505 if (IsClosed()) {
1506 return;
1507 }
deadbeefeb459812015-12-15 19:24:43 -08001508 auto sender = FindSenderForTrack(track);
1509 if (sender == senders_.end()) {
1510 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1511 << " doesn't exist.";
1512 return;
1513 }
deadbeefa601f5c2016-06-06 14:27:39 -07001514 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001515 senders_.erase(sender);
1516}
1517
1518void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
1519 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001520 if (IsClosed()) {
1521 return;
1522 }
deadbeefeb459812015-12-15 19:24:43 -08001523 auto sender = FindSenderForTrack(track);
1524 if (sender != senders_.end()) {
1525 // We already have a sender for this track, so just change the stream_id
1526 // so that it's correct in the next call to CreateOffer.
deadbeefa601f5c2016-06-06 14:27:39 -07001527 (*sender)->internal()->set_stream_id(stream->label());
deadbeefeb459812015-12-15 19:24:43 -08001528 return;
1529 }
1530
1531 // Normal case; we've never seen this track before.
deadbeefa601f5c2016-06-06 14:27:39 -07001532 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
1533 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07001534 signaling_thread(), new VideoRtpSender(track, stream->label(),
1535 session_->video_channel()));
deadbeefeb459812015-12-15 19:24:43 -08001536 senders_.push_back(new_sender);
1537 const TrackInfo* track_info =
1538 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
1539 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001540 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefeb459812015-12-15 19:24:43 -08001541 }
1542}
1543
1544void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
1545 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07001546 if (IsClosed()) {
1547 return;
1548 }
deadbeefeb459812015-12-15 19:24:43 -08001549 auto sender = FindSenderForTrack(track);
1550 if (sender == senders_.end()) {
1551 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
1552 << " doesn't exist.";
1553 return;
1554 }
deadbeefa601f5c2016-06-06 14:27:39 -07001555 (*sender)->internal()->Stop();
deadbeefeb459812015-12-15 19:24:43 -08001556 senders_.erase(sender);
1557}
1558
deadbeefab9b2d12015-10-14 11:33:11 -07001559void PeerConnection::PostSetSessionDescriptionFailure(
1560 SetSessionDescriptionObserver* observer,
1561 const std::string& error) {
1562 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
1563 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001564 signaling_thread()->Post(RTC_FROM_HERE, this,
1565 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001566}
1567
1568void PeerConnection::PostCreateSessionDescriptionFailure(
1569 CreateSessionDescriptionObserver* observer,
1570 const std::string& error) {
1571 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
1572 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001573 signaling_thread()->Post(RTC_FROM_HERE, this,
1574 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001575}
1576
1577bool PeerConnection::GetOptionsForOffer(
1578 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
1579 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001580 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1581 // ContentInfos.
1582 if (session_->local_description()) {
1583 for (const cricket::ContentInfo& content :
1584 session_->local_description()->description()->contents()) {
1585 session_options->transport_options[content.name] =
1586 cricket::TransportOptions();
1587 }
1588 }
deadbeef46c73892016-11-16 19:42:04 -08001589 session_options->enable_ice_renomination =
1590 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001591
htaaac2dea2016-03-10 13:35:55 -08001592 if (!ExtractMediaSessionOptions(rtc_options, true, session_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001593 return false;
1594 }
1595
deadbeeffac06552015-11-25 11:26:01 -08001596 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefc80741f2015-10-22 13:14:45 -07001597 // Offer to receive audio/video if the constraint is not set and there are
1598 // send streams, or we're currently receiving.
1599 if (rtc_options.offer_to_receive_audio == RTCOfferAnswerOptions::kUndefined) {
1600 session_options->recv_audio =
1601 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_AUDIO) ||
1602 !remote_audio_tracks_.empty();
1603 }
1604 if (rtc_options.offer_to_receive_video == RTCOfferAnswerOptions::kUndefined) {
1605 session_options->recv_video =
1606 session_options->HasSendMediaStream(cricket::MEDIA_TYPE_VIDEO) ||
1607 !remote_video_tracks_.empty();
1608 }
deadbeefc80741f2015-10-22 13:14:45 -07001609
zhihuang9763d562016-08-05 11:14:50 -07001610 // Intentionally unset the data channel type for RTP data channel with the
1611 // second condition. Otherwise the RTP data channels would be successfully
1612 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
1613 // when building with chromium. We want to leave RTP data channels broken, so
1614 // people won't try to use them.
1615 if (HasDataChannels() && session_->data_channel_type() != cricket::DCT_RTP) {
1616 session_options->data_channel_type = session_->data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07001617 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001618
zhihuangaf388472016-11-02 16:49:48 -07001619 session_options->bundle_enabled =
1620 session_options->bundle_enabled &&
1621 (session_options->has_audio() || session_options->has_video() ||
1622 session_options->has_data());
1623
zhihuang8f65cdf2016-05-06 18:40:30 -07001624 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07001625 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07001626 return true;
1627}
1628
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001629void PeerConnection::InitializeOptionsForAnswer(
1630 cricket::MediaSessionOptions* session_options) {
1631 session_options->recv_audio = false;
1632 session_options->recv_video = false;
deadbeef46c73892016-11-16 19:42:04 -08001633 session_options->enable_ice_renomination =
1634 configuration_.enable_ice_renomination;
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001635}
1636
htaa2a49d92016-03-04 02:51:39 -08001637void PeerConnection::FinishOptionsForAnswer(
deadbeefab9b2d12015-10-14 11:33:11 -07001638 cricket::MediaSessionOptions* session_options) {
deadbeef0ed85b22016-02-23 17:24:52 -08001639 // TODO(deadbeef): Once we have transceivers, enumerate them here instead of
1640 // ContentInfos.
1641 if (session_->remote_description()) {
1642 // Initialize the transport_options map.
1643 for (const cricket::ContentInfo& content :
1644 session_->remote_description()->description()->contents()) {
1645 session_options->transport_options[content.name] =
1646 cricket::TransportOptions();
1647 }
1648 }
deadbeeffac06552015-11-25 11:26:01 -08001649 AddSendStreams(session_options, senders_, rtp_data_channels_);
deadbeefab9b2d12015-10-14 11:33:11 -07001650 // RTP data channel is handled in MediaSessionOptions::AddStream. SCTP streams
1651 // are not signaled in the SDP so does not go through that path and must be
1652 // handled here.
zhihuang9763d562016-08-05 11:14:50 -07001653 // Intentionally unset the data channel type for RTP data channel. Otherwise
1654 // the RTP data channels would be successfully negotiated by default and the
1655 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
1656 // We want to leave RTP data channels broken, so people won't try to use them.
1657 if (session_->data_channel_type() != cricket::DCT_RTP) {
1658 session_options->data_channel_type = session_->data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07001659 }
zhihuangaf388472016-11-02 16:49:48 -07001660 session_options->bundle_enabled =
1661 session_options->bundle_enabled &&
1662 (session_options->has_audio() || session_options->has_video() ||
1663 session_options->has_data());
1664
jbauchcb560652016-08-04 05:20:32 -07001665 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08001666}
1667
1668bool PeerConnection::GetOptionsForAnswer(
1669 const MediaConstraintsInterface* constraints,
1670 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001671 InitializeOptionsForAnswer(session_options);
htaa2a49d92016-03-04 02:51:39 -08001672 if (!ParseConstraintsForAnswer(constraints, session_options)) {
1673 return false;
1674 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001675 session_options->rtcp_cname = rtcp_cname_;
1676
htaa2a49d92016-03-04 02:51:39 -08001677 FinishOptionsForAnswer(session_options);
1678 return true;
1679}
1680
1681bool PeerConnection::GetOptionsForAnswer(
1682 const RTCOfferAnswerOptions& options,
1683 cricket::MediaSessionOptions* session_options) {
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001684 InitializeOptionsForAnswer(session_options);
htaaac2dea2016-03-10 13:35:55 -08001685 if (!ExtractMediaSessionOptions(options, false, session_options)) {
htaa2a49d92016-03-04 02:51:39 -08001686 return false;
1687 }
zhihuang8f65cdf2016-05-06 18:40:30 -07001688 session_options->rtcp_cname = rtcp_cname_;
1689
htaa2a49d92016-03-04 02:51:39 -08001690 FinishOptionsForAnswer(session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07001691 return true;
1692}
1693
deadbeeffaac4972015-11-12 15:33:07 -08001694void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
1695 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08001696 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
1697 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08001698}
1699
deadbeefab9b2d12015-10-14 11:33:11 -07001700void PeerConnection::UpdateRemoteStreamsList(
1701 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08001702 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07001703 cricket::MediaType media_type,
1704 StreamCollection* new_streams) {
1705 TrackInfos* current_tracks = GetRemoteTracks(media_type);
1706
1707 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08001708 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07001709 auto track_it = current_tracks->begin();
1710 while (track_it != current_tracks->end()) {
1711 const TrackInfo& info = *track_it;
1712 const cricket::StreamParams* params =
1713 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08001714 bool track_exists = params && params->id == info.track_id;
1715 // If this is a default track, and we still need it, don't remove it.
1716 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
1717 track_exists) {
1718 ++track_it;
1719 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07001720 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
1721 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07001722 }
1723 }
1724
1725 // Find new and active tracks.
1726 for (const cricket::StreamParams& params : streams) {
1727 // The sync_label is the MediaStream label and the |stream.id| is the
1728 // track id.
1729 const std::string& stream_label = params.sync_label;
1730 const std::string& track_id = params.id;
1731 uint32_t ssrc = params.first_ssrc();
1732
1733 rtc::scoped_refptr<MediaStreamInterface> stream =
1734 remote_streams_->find(stream_label);
1735 if (!stream) {
1736 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001737 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
1738 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07001739 remote_streams_->AddStream(stream);
1740 new_streams->AddStream(stream);
1741 }
1742
1743 const TrackInfo* track_info =
1744 FindTrackInfo(*current_tracks, stream_label, track_id);
1745 if (!track_info) {
1746 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1747 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
1748 }
1749 }
deadbeefbda7e0b2015-12-08 17:13:40 -08001750
1751 // Add default track if necessary.
1752 if (default_track_needed) {
1753 rtc::scoped_refptr<MediaStreamInterface> default_stream =
1754 remote_streams_->find(kDefaultStreamLabel);
1755 if (!default_stream) {
1756 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07001757 default_stream = MediaStreamProxy::Create(
1758 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08001759 remote_streams_->AddStream(default_stream);
1760 new_streams->AddStream(default_stream);
1761 }
1762 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
1763 ? kDefaultAudioTrackLabel
1764 : kDefaultVideoTrackLabel;
1765 const TrackInfo* default_track_info =
1766 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
1767 if (!default_track_info) {
1768 current_tracks->push_back(
1769 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
1770 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
1771 }
1772 }
deadbeefab9b2d12015-10-14 11:33:11 -07001773}
1774
1775void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
1776 const std::string& track_id,
1777 uint32_t ssrc,
1778 cricket::MediaType media_type) {
1779 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1780
1781 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001782 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001783 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01001784 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001785 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08001786 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001787 }
1788}
1789
1790void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
1791 const std::string& track_id,
1792 cricket::MediaType media_type) {
1793 MediaStreamInterface* stream = remote_streams_->find(stream_label);
1794
1795 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07001796 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
1797 // will be notified which will end the AudioRtpReceiver::track().
1798 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001799 rtc::scoped_refptr<AudioTrackInterface> audio_track =
1800 stream->FindAudioTrack(track_id);
1801 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07001802 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001803 }
1804 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07001805 // Stopping or destroying a VideoRtpReceiver will end the
1806 // VideoRtpReceiver::track().
1807 DestroyReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07001808 rtc::scoped_refptr<VideoTrackInterface> video_track =
1809 stream->FindVideoTrack(track_id);
1810 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07001811 // There's no guarantee the track is still available, e.g. the track may
1812 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07001813 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07001814 }
1815 } else {
nisseede5da42017-01-12 05:15:36 -08001816 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07001817 }
1818}
1819
1820void PeerConnection::UpdateEndedRemoteMediaStreams() {
1821 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
1822 for (size_t i = 0; i < remote_streams_->count(); ++i) {
1823 MediaStreamInterface* stream = remote_streams_->at(i);
1824 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
1825 streams_to_remove.push_back(stream);
1826 }
1827 }
1828
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001829 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07001830 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001831 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001832 }
1833}
1834
deadbeefab9b2d12015-10-14 11:33:11 -07001835void PeerConnection::UpdateLocalTracks(
1836 const std::vector<cricket::StreamParams>& streams,
1837 cricket::MediaType media_type) {
1838 TrackInfos* current_tracks = GetLocalTracks(media_type);
1839
1840 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
1841 // don't match the new StreamParam.
1842 TrackInfos::iterator track_it = current_tracks->begin();
1843 while (track_it != current_tracks->end()) {
1844 const TrackInfo& info = *track_it;
1845 const cricket::StreamParams* params =
1846 cricket::GetStreamBySsrc(streams, info.ssrc);
1847 if (!params || params->id != info.track_id ||
1848 params->sync_label != info.stream_label) {
1849 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
1850 media_type);
1851 track_it = current_tracks->erase(track_it);
1852 } else {
1853 ++track_it;
1854 }
1855 }
1856
1857 // Find new and active tracks.
1858 for (const cricket::StreamParams& params : streams) {
1859 // The sync_label is the MediaStream label and the |stream.id| is the
1860 // track id.
1861 const std::string& stream_label = params.sync_label;
1862 const std::string& track_id = params.id;
1863 uint32_t ssrc = params.first_ssrc();
1864 const TrackInfo* track_info =
1865 FindTrackInfo(*current_tracks, stream_label, track_id);
1866 if (!track_info) {
1867 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
1868 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
1869 }
1870 }
1871}
1872
1873void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
1874 const std::string& track_id,
1875 uint32_t ssrc,
1876 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001877 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001878 if (!sender) {
1879 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
1880 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07001881 return;
1882 }
1883
deadbeeffac06552015-11-25 11:26:01 -08001884 if (sender->media_type() != media_type) {
1885 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1886 << " description with an unexpected media type.";
1887 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001888 }
deadbeeffac06552015-11-25 11:26:01 -08001889
1890 sender->set_stream_id(stream_label);
1891 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07001892}
1893
1894void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
1895 const std::string& track_id,
1896 uint32_t ssrc,
1897 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07001898 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08001899 if (!sender) {
1900 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07001901 // SessionDescriptions has been renegotiated.
1902 return;
1903 }
deadbeeffac06552015-11-25 11:26:01 -08001904
1905 // A sender has been removed from the SessionDescription but it's still
1906 // associated with the PeerConnection. This only occurs if the SDP doesn't
1907 // match with the calls to CreateSender, AddStream and RemoveStream.
1908 if (sender->media_type() != media_type) {
1909 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
1910 << " description with an unexpected media type.";
1911 return;
deadbeefab9b2d12015-10-14 11:33:11 -07001912 }
deadbeeffac06552015-11-25 11:26:01 -08001913
1914 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07001915}
1916
1917void PeerConnection::UpdateLocalRtpDataChannels(
1918 const cricket::StreamParamsVec& streams) {
1919 std::vector<std::string> existing_channels;
1920
1921 // Find new and active data channels.
1922 for (const cricket::StreamParams& params : streams) {
1923 // |it->sync_label| is actually the data channel label. The reason is that
1924 // we use the same naming of data channels as we do for
1925 // MediaStreams and Tracks.
1926 // For MediaStreams, the sync_label is the MediaStream label and the
1927 // track label is the same as |streamid|.
1928 const std::string& channel_label = params.sync_label;
1929 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08001930 if (data_channel_it == rtp_data_channels_.end()) {
1931 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07001932 continue;
1933 }
1934 // Set the SSRC the data channel should use for sending.
1935 data_channel_it->second->SetSendSsrc(params.first_ssrc());
1936 existing_channels.push_back(data_channel_it->first);
1937 }
1938
1939 UpdateClosingRtpDataChannels(existing_channels, true);
1940}
1941
1942void PeerConnection::UpdateRemoteRtpDataChannels(
1943 const cricket::StreamParamsVec& streams) {
1944 std::vector<std::string> existing_channels;
1945
1946 // Find new and active data channels.
1947 for (const cricket::StreamParams& params : streams) {
1948 // The data channel label is either the mslabel or the SSRC if the mslabel
1949 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
1950 std::string label = params.sync_label.empty()
1951 ? rtc::ToString(params.first_ssrc())
1952 : params.sync_label;
1953 auto data_channel_it = rtp_data_channels_.find(label);
1954 if (data_channel_it == rtp_data_channels_.end()) {
1955 // This is a new data channel.
1956 CreateRemoteRtpDataChannel(label, params.first_ssrc());
1957 } else {
1958 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
1959 }
1960 existing_channels.push_back(label);
1961 }
1962
1963 UpdateClosingRtpDataChannels(existing_channels, false);
1964}
1965
1966void PeerConnection::UpdateClosingRtpDataChannels(
1967 const std::vector<std::string>& active_channels,
1968 bool is_local_update) {
1969 auto it = rtp_data_channels_.begin();
1970 while (it != rtp_data_channels_.end()) {
1971 DataChannel* data_channel = it->second;
1972 if (std::find(active_channels.begin(), active_channels.end(),
1973 data_channel->label()) != active_channels.end()) {
1974 ++it;
1975 continue;
1976 }
1977
1978 if (is_local_update) {
1979 data_channel->SetSendSsrc(0);
1980 } else {
1981 data_channel->RemotePeerRequestClose();
1982 }
1983
1984 if (data_channel->state() == DataChannel::kClosed) {
1985 rtp_data_channels_.erase(it);
1986 it = rtp_data_channels_.begin();
1987 } else {
1988 ++it;
1989 }
1990 }
1991}
1992
1993void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
1994 uint32_t remote_ssrc) {
1995 rtc::scoped_refptr<DataChannel> channel(
1996 InternalCreateDataChannel(label, nullptr));
1997 if (!channel.get()) {
1998 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
1999 << "CreateDataChannel failed.";
2000 return;
2001 }
2002 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002003 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2004 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002005 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002006}
2007
2008rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2009 const std::string& label,
2010 const InternalDataChannelInit* config) {
2011 if (IsClosed()) {
2012 return nullptr;
2013 }
2014 if (session_->data_channel_type() == cricket::DCT_NONE) {
2015 LOG(LS_ERROR)
2016 << "InternalCreateDataChannel: Data is not supported in this call.";
2017 return nullptr;
2018 }
2019 InternalDataChannelInit new_config =
2020 config ? (*config) : InternalDataChannelInit();
2021 if (session_->data_channel_type() == cricket::DCT_SCTP) {
2022 if (new_config.id < 0) {
2023 rtc::SSLRole role;
deadbeef953c2ce2017-01-09 14:53:41 -08002024 if ((session_->GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002025 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2026 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2027 return nullptr;
2028 }
2029 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2030 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2031 << "because the id is already in use or out of range.";
2032 return nullptr;
2033 }
2034 }
2035
2036 rtc::scoped_refptr<DataChannel> channel(DataChannel::Create(
2037 session_.get(), session_->data_channel_type(), label, new_config));
2038 if (!channel) {
2039 sid_allocator_.ReleaseSid(new_config.id);
2040 return nullptr;
2041 }
2042
2043 if (channel->data_channel_type() == cricket::DCT_RTP) {
2044 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2045 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2046 << " already exists.";
2047 return nullptr;
2048 }
2049 rtp_data_channels_[channel->label()] = channel;
2050 } else {
2051 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2052 sctp_data_channels_.push_back(channel);
2053 channel->SignalClosed.connect(this,
2054 &PeerConnection::OnSctpDataChannelClosed);
2055 }
2056
hbos82ebe022016-11-14 01:41:09 -08002057 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002058 return channel;
2059}
2060
2061bool PeerConnection::HasDataChannels() const {
zhihuang9763d562016-08-05 11:14:50 -07002062#ifdef HAVE_QUIC
2063 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty() ||
2064 (session_->quic_data_transport() &&
2065 session_->quic_data_transport()->HasDataChannels());
2066#else
deadbeefab9b2d12015-10-14 11:33:11 -07002067 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
zhihuang9763d562016-08-05 11:14:50 -07002068#endif // HAVE_QUIC
deadbeefab9b2d12015-10-14 11:33:11 -07002069}
2070
2071void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2072 for (const auto& channel : sctp_data_channels_) {
2073 if (channel->id() < 0) {
2074 int sid;
2075 if (!sid_allocator_.AllocateSid(role, &sid)) {
2076 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2077 continue;
2078 }
2079 channel->SetSctpSid(sid);
2080 }
2081 }
2082}
2083
2084void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002085 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002086 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2087 ++it) {
2088 if (it->get() == channel) {
2089 if (channel->id() >= 0) {
2090 sid_allocator_.ReleaseSid(channel->id());
2091 }
deadbeefbd292462015-12-14 18:15:29 -08002092 // Since this method is triggered by a signal from the DataChannel,
2093 // we can't free it directly here; we need to free it asynchronously.
2094 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002095 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002096 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2097 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002098 return;
2099 }
2100 }
2101}
2102
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002103void PeerConnection::OnVoiceChannelCreated() {
2104 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
2105 session_->voice_channel(), senders_, receivers_,
2106 cricket::MEDIA_TYPE_AUDIO);
2107}
2108
deadbeefab9b2d12015-10-14 11:33:11 -07002109void PeerConnection::OnVoiceChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002110 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
2111 cricket::VoiceChannel>(
2112 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
2113}
2114
2115void PeerConnection::OnVideoChannelCreated() {
2116 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
2117 session_->video_channel(), senders_, receivers_,
2118 cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002119}
2120
2121void PeerConnection::OnVideoChannelDestroyed() {
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -07002122 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
2123 cricket::VideoChannel>(
2124 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
deadbeefab9b2d12015-10-14 11:33:11 -07002125}
2126
2127void PeerConnection::OnDataChannelCreated() {
2128 for (const auto& channel : sctp_data_channels_) {
2129 channel->OnTransportChannelCreated();
2130 }
2131}
2132
2133void PeerConnection::OnDataChannelDestroyed() {
2134 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2135 // DataChannel may callback to us and try to modify the list.
2136 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2137 temp_rtp_dcs.swap(rtp_data_channels_);
2138 for (const auto& kv : temp_rtp_dcs) {
2139 kv.second->OnTransportChannelDestroyed();
2140 }
2141
2142 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2143 temp_sctp_dcs.swap(sctp_data_channels_);
2144 for (const auto& channel : temp_sctp_dcs) {
2145 channel->OnTransportChannelDestroyed();
2146 }
2147}
2148
2149void PeerConnection::OnDataChannelOpenMessage(
2150 const std::string& label,
2151 const InternalDataChannelInit& config) {
2152 rtc::scoped_refptr<DataChannel> channel(
2153 InternalCreateDataChannel(label, &config));
2154 if (!channel.get()) {
2155 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2156 return;
2157 }
2158
deadbeefa601f5c2016-06-06 14:27:39 -07002159 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2160 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002161 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002162}
2163
deadbeefa601f5c2016-06-06 14:27:39 -07002164RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2165 auto it = std::find_if(
2166 senders_.begin(), senders_.end(),
2167 [id](const rtc::scoped_refptr<
2168 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2169 return sender->id() == id;
2170 });
2171 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002172}
2173
deadbeefa601f5c2016-06-06 14:27:39 -07002174std::vector<
2175 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002176PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2177 return std::find_if(
2178 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002179 [track](const rtc::scoped_refptr<
2180 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002181 return sender->track() == track;
2182 });
2183}
2184
deadbeefa601f5c2016-06-06 14:27:39 -07002185std::vector<rtc::scoped_refptr<
2186 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002187PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002188 return std::find_if(
2189 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002190 [track_id](const rtc::scoped_refptr<
2191 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07002192 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07002193 });
2194}
2195
deadbeefab9b2d12015-10-14 11:33:11 -07002196PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
2197 cricket::MediaType media_type) {
2198 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2199 media_type == cricket::MEDIA_TYPE_VIDEO);
2200 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
2201 : &remote_video_tracks_;
2202}
2203
2204PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
2205 cricket::MediaType media_type) {
2206 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
2207 media_type == cricket::MEDIA_TYPE_VIDEO);
2208 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
2209 : &local_video_tracks_;
2210}
2211
2212const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
2213 const PeerConnection::TrackInfos& infos,
2214 const std::string& stream_label,
2215 const std::string track_id) const {
2216 for (const TrackInfo& track_info : infos) {
2217 if (track_info.stream_label == stream_label &&
2218 track_info.track_id == track_id) {
2219 return &track_info;
2220 }
2221 }
2222 return nullptr;
2223}
2224
2225DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
2226 for (const auto& channel : sctp_data_channels_) {
2227 if (channel->id() == sid) {
2228 return channel;
2229 }
2230 }
2231 return nullptr;
2232}
2233
deadbeef91dd5672016-05-18 16:55:30 -07002234bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002235 const RTCConfiguration& configuration) {
2236 cricket::ServerAddresses stun_servers;
2237 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08002238 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
2239 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002240 return false;
2241 }
2242
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07002243 port_allocator_->Initialize();
2244
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002245 // To handle both internal and externally created port allocator, we will
2246 // enable BUNDLE here.
2247 int portallocator_flags = port_allocator_->flags();
2248 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08002249 cricket::PORTALLOCATOR_ENABLE_IPV6 |
2250 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002251 // If the disable-IPv6 flag was specified, we'll not override it
2252 // by experiment.
2253 if (configuration.disable_ipv6) {
2254 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08002255 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
2256 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002257 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
2258 }
2259
zhihuangb09b3f92017-03-07 14:40:51 -08002260 if (configuration.disable_ipv6_on_wifi) {
2261 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
2262 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
2263 }
2264
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002265 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
2266 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
2267 LOG(LS_INFO) << "TCP candidates are disabled.";
2268 }
2269
honghaiz60347052016-05-31 18:29:12 -07002270 if (configuration.candidate_network_policy ==
2271 kCandidateNetworkPolicyLowCost) {
2272 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
2273 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
2274 }
2275
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002276 port_allocator_->set_flags(portallocator_flags);
2277 // No step delay is used while allocating ports.
2278 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
2279 port_allocator_->set_candidate_filter(
2280 ConvertIceTransportTypeToCandidateFilter(configuration.type));
2281
2282 // Call this last since it may create pooled allocator sessions using the
2283 // properties set above.
2284 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07002285 configuration.ice_candidate_pool_size,
2286 configuration.prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002287 return true;
2288}
2289
deadbeef91dd5672016-05-18 16:55:30 -07002290bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08002291 const cricket::ServerAddresses& stun_servers,
2292 const std::vector<cricket::RelayServerConfig>& turn_servers,
2293 IceTransportsType type,
2294 int candidate_pool_size,
2295 bool prune_turn_ports) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002296 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08002297 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002298 // Call this last since it may create pooled allocator sessions using the
2299 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08002300 return port_allocator_->SetConfiguration(
deadbeef293e9262017-01-11 12:28:30 -08002301 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07002302}
2303
ivoc14d5dbe2016-07-04 07:06:55 -07002304bool PeerConnection::StartRtcEventLog_w(rtc::PlatformFile file,
2305 int64_t max_size_bytes) {
zhihuang77985012017-02-07 15:45:16 -08002306 if (!event_log_) {
2307 return false;
2308 }
skvlad11a9cbf2016-10-07 11:53:05 -07002309 return event_log_->StartLogging(file, max_size_bytes);
ivoc14d5dbe2016-07-04 07:06:55 -07002310}
2311
2312void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08002313 if (event_log_) {
2314 event_log_->StopLogging();
2315 }
ivoc14d5dbe2016-07-04 07:06:55 -07002316}
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002317} // namespace webrtc