blob: 5c0da406796e752da969f807459f8accbc8ee763 [file] [log] [blame]
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001/*
kjellanderb24317b2016-02-10 07:54:43 -08002 * Copyright 2012 The WebRTC project authors. All Rights Reserved.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00003 *
kjellanderb24317b2016-02-10 07:54:43 -08004 * Use of this source code is governed by a BSD-style license
5 * that can be found in the LICENSE file in the root of the source
6 * tree. An additional intellectual property rights grant can be found
7 * in the file PATENTS. All contributing project authors may
8 * be found in the AUTHORS file in the root of the source tree.
henrike@webrtc.org28e20752013-07-10 00:45:36 +00009 */
10
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020011#include "pc/peerconnection.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000012
deadbeefeb459812015-12-15 19:24:43 -080013#include <algorithm>
Steve Anton75737c02017-11-06 10:37:17 -080014#include <set>
kwiberg0eb15ed2015-12-17 03:04:15 -080015#include <utility>
16#include <vector>
henrike@webrtc.org28e20752013-07-10 00:45:36 +000017
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020018#include "api/jsepicecandidate.h"
19#include "api/jsepsessiondescription.h"
20#include "api/mediaconstraintsinterface.h"
21#include "api/mediastreamproxy.h"
22#include "api/mediastreamtrackproxy.h"
23#include "call/call.h"
Elad Alon83ccca12017-10-04 13:18:26 +020024#include "logging/rtc_event_log/output/rtc_event_log_output_file.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020025#include "logging/rtc_event_log/rtc_event_log.h"
26#include "media/sctp/sctptransport.h"
27#include "pc/audiotrack.h"
Steve Anton75737c02017-11-06 10:37:17 -080028#include "pc/channel.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020029#include "pc/channelmanager.h"
30#include "pc/dtmfsender.h"
31#include "pc/mediastream.h"
32#include "pc/mediastreamobserver.h"
33#include "pc/remoteaudiosource.h"
Steve Anton1d03a752017-11-27 14:30:09 -080034#include "pc/rtpmediautils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020035#include "pc/rtpreceiver.h"
36#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080037#include "pc/sctputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020038#include "pc/streamcollection.h"
39#include "pc/videocapturertracksource.h"
40#include "pc/videotrack.h"
41#include "rtc_base/bind.h"
42#include "rtc_base/checks.h"
43#include "rtc_base/logging.h"
Karl Wiberge40468b2017-11-22 10:42:26 +010044#include "rtc_base/numerics/safe_conversions.h"
Elad Alon83ccca12017-10-04 13:18:26 +020045#include "rtc_base/ptr_util.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020046#include "rtc_base/stringencode.h"
47#include "rtc_base/stringutils.h"
48#include "rtc_base/trace_event.h"
49#include "system_wrappers/include/clock.h"
50#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000051
Steve Anton75737c02017-11-06 10:37:17 -080052using cricket::ContentInfo;
53using cricket::ContentInfos;
54using cricket::MediaContentDescription;
55using cricket::SessionDescription;
56using cricket::TransportInfo;
57
58using cricket::LOCAL_PORT_TYPE;
59using cricket::STUN_PORT_TYPE;
60using cricket::RELAY_PORT_TYPE;
61using cricket::PRFLX_PORT_TYPE;
62
Steve Antonba818672017-11-06 10:21:57 -080063namespace webrtc {
64
Steve Anton75737c02017-11-06 10:37:17 -080065// Error messages
66const char kBundleWithoutRtcpMux[] =
67 "rtcp-mux must be enabled when BUNDLE "
68 "is enabled.";
Steve Anton75737c02017-11-06 10:37:17 -080069const char kInvalidCandidates[] = "Description contains invalid candidates.";
70const char kInvalidSdp[] = "Invalid session description.";
71const char kMlineMismatchInAnswer[] =
72 "The order of m-lines in answer doesn't match order in offer. Rejecting "
73 "answer.";
74const char kMlineMismatchInSubsequentOffer[] =
75 "The order of m-lines in subsequent offer doesn't match order from "
76 "previous offer/answer.";
Steve Anton75737c02017-11-06 10:37:17 -080077const char kSdpWithoutDtlsFingerprint[] =
78 "Called with SDP without DTLS fingerprint.";
79const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
80const char kSdpWithoutIceUfragPwd[] =
81 "Called with SDP without ice-ufrag and ice-pwd.";
82const char kSessionError[] = "Session error code: ";
83const char kSessionErrorDesc[] = "Session error description: ";
84const char kDtlsSrtpSetupFailureRtp[] =
85 "Couldn't set up DTLS-SRTP on RTP channel.";
86const char kDtlsSrtpSetupFailureRtcp[] =
87 "Couldn't set up DTLS-SRTP on RTCP channel.";
88const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000089
Steve Anton75737c02017-11-06 10:37:17 -080090namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000091
deadbeefab9b2d12015-10-14 11:33:11 -070092static const char kDefaultStreamLabel[] = "default";
Steve Anton4171afb2017-11-20 10:20:22 -080093static const char kDefaultAudioSenderId[] = "defaulta0";
94static const char kDefaultVideoSenderId[] = "defaultv0";
deadbeefab9b2d12015-10-14 11:33:11 -070095
zhihuang8f65cdf2016-05-06 18:40:30 -070096// The length of RTCP CNAMEs.
97static const int kRtcpCnameLength = 16;
98
henrike@webrtc.org28e20752013-07-10 00:45:36 +000099enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000100 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000101 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700102 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000103 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800104 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000105};
106
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000107struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000108 explicit SetSessionDescriptionMsg(
109 webrtc::SetSessionDescriptionObserver* observer)
110 : observer(observer) {
111 }
112
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000113 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000114 std::string error;
115};
116
deadbeefab9b2d12015-10-14 11:33:11 -0700117struct CreateSessionDescriptionMsg : public rtc::MessageData {
118 explicit CreateSessionDescriptionMsg(
119 webrtc::CreateSessionDescriptionObserver* observer)
120 : observer(observer) {}
121
122 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
123 std::string error;
124};
125
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000126struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000127 GetStatsMsg(webrtc::StatsObserver* observer,
128 webrtc::MediaStreamTrackInterface* track)
129 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000130 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000131 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000132 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000133};
134
deadbeefab9b2d12015-10-14 11:33:11 -0700135// Check if we can send |new_stream| on a PeerConnection.
136bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
137 webrtc::MediaStreamInterface* new_stream) {
138 if (!new_stream || !current_streams) {
139 return false;
140 }
141 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100142 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
143 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700144 return false;
145 }
146 return true;
147}
148
deadbeef5e97fb52015-10-15 12:49:08 -0700149// If the direction is "recvonly" or "inactive", treat the description
150// as containing no streams.
151// See: https://code.google.com/p/webrtc/issues/detail?id=5054
152std::vector<cricket::StreamParams> GetActiveStreams(
153 const cricket::MediaContentDescription* desc) {
Steve Anton4e70a722017-11-28 14:57:10 -0800154 return RtpTransceiverDirectionHasSend(desc->direction())
deadbeef5e97fb52015-10-15 12:49:08 -0700155 ? desc->streams()
156 : std::vector<cricket::StreamParams>();
157}
158
deadbeefab9b2d12015-10-14 11:33:11 -0700159bool IsValidOfferToReceiveMedia(int value) {
160 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
161 return (value >= Options::kUndefined) &&
162 (value <= Options::kMaxOfferToReceiveMedia);
163}
164
zhihuang1c378ed2017-08-17 14:10:50 -0700165// Add options to |[audio/video]_media_description_options| from |senders|.
166void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700167 const std::vector<rtc::scoped_refptr<
168 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700169 cricket::MediaDescriptionOptions* audio_media_description_options,
170 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700171 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700172 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
173 if (audio_media_description_options) {
174 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700175 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700176 }
177 } else {
178 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
179 if (video_media_description_options) {
180 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700181 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700182 }
183 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700184 }
zhihuang1c378ed2017-08-17 14:10:50 -0700185}
olka3c747662017-08-17 06:50:32 -0700186
zhihuang1c378ed2017-08-17 14:10:50 -0700187// Add options to |session_options| from |rtp_data_channels|.
188void AddRtpDataChannelOptions(
189 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
190 rtp_data_channels,
191 cricket::MediaDescriptionOptions* data_media_description_options) {
192 if (!data_media_description_options) {
193 return;
194 }
deadbeefab9b2d12015-10-14 11:33:11 -0700195 // Check for data channels.
196 for (const auto& kv : rtp_data_channels) {
197 const DataChannel* channel = kv.second;
198 if (channel->state() == DataChannel::kConnecting ||
199 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700200 // Legacy RTP data channels are signaled with the track/stream ID set to
201 // the data channel's label.
202 data_media_description_options->AddRtpDataChannel(channel->label(),
203 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700204 }
205 }
206}
207
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700208uint32_t ConvertIceTransportTypeToCandidateFilter(
209 PeerConnectionInterface::IceTransportsType type) {
210 switch (type) {
211 case PeerConnectionInterface::kNone:
212 return cricket::CF_NONE;
213 case PeerConnectionInterface::kRelay:
214 return cricket::CF_RELAY;
215 case PeerConnectionInterface::kNoHost:
216 return (cricket::CF_ALL & ~cricket::CF_HOST);
217 case PeerConnectionInterface::kAll:
218 return cricket::CF_ALL;
219 default:
nissec80e7412017-01-11 05:56:46 -0800220 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700221 }
222 return cricket::CF_NONE;
223}
224
deadbeef293e9262017-01-11 12:28:30 -0800225// Helper to set an error and return from a method.
226bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
227 if (error) {
228 error->set_type(type);
229 }
230 return type == webrtc::RTCErrorType::NONE;
231}
232
Steve Anton038834f2017-07-14 15:59:59 -0700233bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
234 if (error_out) {
235 *error_out = std::move(error);
236 }
237 return error.ok();
238}
239
Steve Antonba818672017-11-06 10:21:57 -0800240std::string GetSignalingStateString(
241 PeerConnectionInterface::SignalingState state) {
242 switch (state) {
243 case PeerConnectionInterface::kStable:
244 return "kStable";
245 case PeerConnectionInterface::kHaveLocalOffer:
246 return "kHaveLocalOffer";
247 case PeerConnectionInterface::kHaveLocalPrAnswer:
248 return "kHavePrAnswer";
249 case PeerConnectionInterface::kHaveRemoteOffer:
250 return "kHaveRemoteOffer";
251 case PeerConnectionInterface::kHaveRemotePrAnswer:
252 return "kHaveRemotePrAnswer";
253 case PeerConnectionInterface::kClosed:
254 return "kClosed";
255 }
256 RTC_NOTREACHED();
257 return "";
258}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700259
Steve Anton75737c02017-11-06 10:37:17 -0800260IceCandidatePairType GetIceCandidatePairCounter(
261 const cricket::Candidate& local,
262 const cricket::Candidate& remote) {
263 const auto& l = local.type();
264 const auto& r = remote.type();
265 const auto& host = LOCAL_PORT_TYPE;
266 const auto& srflx = STUN_PORT_TYPE;
267 const auto& relay = RELAY_PORT_TYPE;
268 const auto& prflx = PRFLX_PORT_TYPE;
269 if (l == host && r == host) {
270 bool local_private = IPIsPrivate(local.address().ipaddr());
271 bool remote_private = IPIsPrivate(remote.address().ipaddr());
272 if (local_private) {
273 if (remote_private) {
274 return kIceCandidatePairHostPrivateHostPrivate;
275 } else {
276 return kIceCandidatePairHostPrivateHostPublic;
277 }
278 } else {
279 if (remote_private) {
280 return kIceCandidatePairHostPublicHostPrivate;
281 } else {
282 return kIceCandidatePairHostPublicHostPublic;
283 }
284 }
285 }
286 if (l == host && r == srflx)
287 return kIceCandidatePairHostSrflx;
288 if (l == host && r == relay)
289 return kIceCandidatePairHostRelay;
290 if (l == host && r == prflx)
291 return kIceCandidatePairHostPrflx;
292 if (l == srflx && r == host)
293 return kIceCandidatePairSrflxHost;
294 if (l == srflx && r == srflx)
295 return kIceCandidatePairSrflxSrflx;
296 if (l == srflx && r == relay)
297 return kIceCandidatePairSrflxRelay;
298 if (l == srflx && r == prflx)
299 return kIceCandidatePairSrflxPrflx;
300 if (l == relay && r == host)
301 return kIceCandidatePairRelayHost;
302 if (l == relay && r == srflx)
303 return kIceCandidatePairRelaySrflx;
304 if (l == relay && r == relay)
305 return kIceCandidatePairRelayRelay;
306 if (l == relay && r == prflx)
307 return kIceCandidatePairRelayPrflx;
308 if (l == prflx && r == host)
309 return kIceCandidatePairPrflxHost;
310 if (l == prflx && r == srflx)
311 return kIceCandidatePairPrflxSrflx;
312 if (l == prflx && r == relay)
313 return kIceCandidatePairPrflxRelay;
314 return kIceCandidatePairMax;
315}
316
317// Verify that the order of media sections in |new_desc| matches
318// |existing_desc|. The number of m= sections in |new_desc| should be no less
319// than |existing_desc|.
320bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
321 const SessionDescription* new_desc) {
322 if (!existing_desc || !new_desc) {
323 return false;
324 }
325
326 if (existing_desc->contents().size() > new_desc->contents().size()) {
327 return false;
328 }
329
330 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
331 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
332 return false;
333 }
334 const MediaContentDescription* new_desc_mdesc =
335 static_cast<const MediaContentDescription*>(
336 new_desc->contents()[i].description);
337 const MediaContentDescription* existing_desc_mdesc =
338 static_cast<const MediaContentDescription*>(
339 existing_desc->contents()[i].description);
340 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
341 return false;
342 }
343 }
344 return true;
345}
346
347bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
348 const SessionDescription* desc2) {
349 if (!desc1 || !desc2) {
350 return false;
351 }
352 return desc1->contents().size() == desc2->contents().size();
353}
354
355// Checks that each non-rejected content has SDES crypto keys or a DTLS
356// fingerprint, unless it's in a BUNDLE group, in which case only the
357// BUNDLE-tag section (first media section/description in the BUNDLE group)
358// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
359// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
360// by Channel's |srtp_required| check.
Steve Anton8a006912017-12-04 15:25:56 -0800361RTCError VerifyCrypto(const SessionDescription* desc, bool dtls_enabled) {
Steve Anton75737c02017-11-06 10:37:17 -0800362 const cricket::ContentGroup* bundle =
363 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800364 for (const cricket::ContentInfo& content_info : desc->contents()) {
365 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800366 continue;
367 }
Steve Anton8a006912017-12-04 15:25:56 -0800368 const std::string& mid = content_info.name;
369 if (bundle && bundle->HasContentName(mid) &&
370 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800371 // This isn't the first media section in the BUNDLE group, so it's not
372 // required to have crypto attributes, since only the crypto attributes
373 // from the first section actually get used.
374 continue;
375 }
376
377 // If the content isn't rejected or bundled into another m= section, crypto
378 // must be present.
379 const MediaContentDescription* media =
Steve Anton8a006912017-12-04 15:25:56 -0800380 static_cast<const MediaContentDescription*>(content_info.description);
381 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800382 if (!media || !tinfo) {
383 // Something is not right.
Steve Anton8a006912017-12-04 15:25:56 -0800384 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -0800385 }
386 if (dtls_enabled) {
387 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100388 RTC_LOG(LS_WARNING)
389 << "Session description must have DTLS fingerprint if "
390 "DTLS enabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800391 return RTCError(RTCErrorType::INVALID_PARAMETER,
392 kSdpWithoutDtlsFingerprint);
Steve Anton75737c02017-11-06 10:37:17 -0800393 }
394 } else {
395 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100396 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800397 << "Session description must have SDES when DTLS disabled.";
Steve Anton8a006912017-12-04 15:25:56 -0800398 return RTCError(RTCErrorType::INVALID_PARAMETER, kSdpWithoutSdesCrypto);
Steve Anton75737c02017-11-06 10:37:17 -0800399 }
400 }
401 }
Steve Anton8a006912017-12-04 15:25:56 -0800402 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -0800403}
404
405// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
406// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
407// media section/description in the BUNDLE group) needs a ufrag and pwd.
408bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
409 const cricket::ContentGroup* bundle =
410 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
Steve Anton8a006912017-12-04 15:25:56 -0800411 for (const cricket::ContentInfo& content_info : desc->contents()) {
412 if (content_info.rejected) {
Steve Anton75737c02017-11-06 10:37:17 -0800413 continue;
414 }
Steve Anton8a006912017-12-04 15:25:56 -0800415 const std::string& mid = content_info.name;
416 if (bundle && bundle->HasContentName(mid) &&
417 mid != *(bundle->FirstContentName())) {
Steve Anton75737c02017-11-06 10:37:17 -0800418 // This isn't the first media section in the BUNDLE group, so it's not
419 // required to have ufrag/password, since only the ufrag/password from
420 // the first section actually get used.
421 continue;
422 }
423
424 // If the content isn't rejected or bundled into another m= section,
425 // ice-ufrag and ice-pwd must be present.
Steve Anton8a006912017-12-04 15:25:56 -0800426 const TransportInfo* tinfo = desc->GetTransportInfoByName(mid);
Steve Anton75737c02017-11-06 10:37:17 -0800427 if (!tinfo) {
428 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100429 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800430 return false;
431 }
432 if (tinfo->description.ice_ufrag.empty() ||
433 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100434 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800435 return false;
436 }
437 }
438 return true;
439}
440
441bool GetTrackIdBySsrc(const SessionDescription* session_description,
442 uint32_t ssrc,
443 std::string* track_id) {
444 RTC_DCHECK(track_id != NULL);
445
446 const cricket::ContentInfo* audio_info =
447 cricket::GetFirstAudioContent(session_description);
448 if (audio_info) {
449 const cricket::MediaContentDescription* audio_content =
450 static_cast<const cricket::MediaContentDescription*>(
451 audio_info->description);
452
453 const auto* found =
454 cricket::GetStreamBySsrc(audio_content->streams(), ssrc);
455 if (found) {
456 *track_id = found->id;
457 return true;
458 }
459 }
460
461 const cricket::ContentInfo* video_info =
462 cricket::GetFirstVideoContent(session_description);
463 if (video_info) {
464 const cricket::MediaContentDescription* video_content =
465 static_cast<const cricket::MediaContentDescription*>(
466 video_info->description);
467
468 const auto* found =
469 cricket::GetStreamBySsrc(video_content->streams(), ssrc);
470 if (found) {
471 *track_id = found->id;
472 return true;
473 }
474 }
475 return false;
476}
477
478// Get the SCTP port out of a SessionDescription.
479// Return -1 if not found.
480int GetSctpPort(const SessionDescription* session_description) {
481 const ContentInfo* content_info = GetFirstDataContent(session_description);
482 RTC_DCHECK(content_info);
483 if (!content_info) {
484 return -1;
485 }
486 const cricket::DataContentDescription* data =
487 static_cast<const cricket::DataContentDescription*>(
488 (content_info->description));
489 std::string value;
490 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
491 cricket::kGoogleSctpDataCodecName);
492 for (const cricket::DataCodec& codec : data->codecs()) {
493 if (!codec.Matches(match_pattern)) {
494 continue;
495 }
496 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
497 return rtc::FromString<int>(value);
498 }
499 }
500 return -1;
501}
502
Steve Anton75737c02017-11-06 10:37:17 -0800503// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
504bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
505 const SessionDescriptionInterface* new_desc,
506 const std::string& content_name) {
507 if (!old_desc) {
508 return false;
509 }
510 const SessionDescription* new_sd = new_desc->description();
511 const SessionDescription* old_sd = old_desc->description();
512 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
513 if (!cinfo || cinfo->rejected) {
514 return false;
515 }
516 // If the content isn't rejected, check if ufrag and password has changed.
517 const cricket::TransportDescription* new_transport_desc =
518 new_sd->GetTransportDescriptionByName(content_name);
519 const cricket::TransportDescription* old_transport_desc =
520 old_sd->GetTransportDescriptionByName(content_name);
521 if (!new_transport_desc || !old_transport_desc) {
522 // No transport description exists. This is not an ICE restart.
523 return false;
524 }
525 if (cricket::IceCredentialsChanged(
526 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
527 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100528 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
529 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800530 return true;
531 }
532 return false;
533}
534
Steve Anton20393062017-12-04 16:24:52 -0800535// Converts from SessionDescriptionInterface type to cricket::ContentAction.
536cricket::ContentAction ContentActionFromSessionType(
537 const std::string& session_type) {
538 if (session_type == SessionDescriptionInterface::kOffer) {
539 return cricket::CA_OFFER;
540 } else if (session_type == SessionDescriptionInterface::kPrAnswer) {
541 return cricket::CA_PRANSWER;
542 } else if (session_type == SessionDescriptionInterface::kAnswer) {
543 return cricket::CA_ANSWER;
544 }
545 RTC_NOTREACHED() << "unknown action type";
546 return cricket::CA_OFFER;
547}
548
Steve Anton75737c02017-11-06 10:37:17 -0800549} // namespace
550
Henrik Boström31638672017-11-23 17:48:32 +0100551// Upon completion, posts a task to execute the callback of the
552// SetSessionDescriptionObserver asynchronously on the same thread. At this
553// point, the state of the peer connection might no longer reflect the effects
554// of the SetRemoteDescription operation, as the peer connection could have been
555// modified during the post.
556// TODO(hbos): Remove this class once we remove the version of
557// PeerConnectionInterface::SetRemoteDescription() that takes a
558// SetSessionDescriptionObserver as an argument.
559class PeerConnection::SetRemoteDescriptionObserverAdapter
560 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
561 public:
562 SetRemoteDescriptionObserverAdapter(
563 rtc::scoped_refptr<PeerConnection> pc,
564 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
565 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
566
567 // SetRemoteDescriptionObserverInterface implementation.
568 void OnSetRemoteDescriptionComplete(RTCError error) override {
569 if (error.ok())
570 pc_->PostSetSessionDescriptionSuccess(wrapper_);
571 else
572 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
573 }
574
575 private:
576 rtc::scoped_refptr<PeerConnection> pc_;
577 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
578};
579
deadbeef293e9262017-01-11 12:28:30 -0800580bool PeerConnectionInterface::RTCConfiguration::operator==(
581 const PeerConnectionInterface::RTCConfiguration& o) const {
582 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700583 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800584 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000585 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700586 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800587 BundlePolicy bundle_policy;
588 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700589 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
590 int ice_candidate_pool_size;
591 bool disable_ipv6;
592 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700593 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700594 bool enable_rtp_data_channel;
595 rtc::Optional<int> screencast_min_bitrate;
596 rtc::Optional<bool> combined_audio_video_bwe;
597 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800598 TcpCandidatePolicy tcp_candidate_policy;
599 CandidateNetworkPolicy candidate_network_policy;
600 int audio_jitter_buffer_max_packets;
601 bool audio_jitter_buffer_fast_accelerate;
602 int ice_connection_receiving_timeout;
603 int ice_backup_candidate_pair_ping_interval;
604 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800605 bool prioritize_most_likely_ice_candidate_pairs;
606 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800607 bool prune_turn_ports;
608 bool presume_writable_when_fully_relayed;
609 bool enable_ice_renomination;
610 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800611 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700612 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200613 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800614 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800615 };
616 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
617 "Did you add something to RTCConfiguration and forget to "
618 "update operator==?");
619 return type == o.type && servers == o.servers &&
620 bundle_policy == o.bundle_policy &&
621 rtcp_mux_policy == o.rtcp_mux_policy &&
622 tcp_candidate_policy == o.tcp_candidate_policy &&
623 candidate_network_policy == o.candidate_network_policy &&
624 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
625 audio_jitter_buffer_fast_accelerate ==
626 o.audio_jitter_buffer_fast_accelerate &&
627 ice_connection_receiving_timeout ==
628 o.ice_connection_receiving_timeout &&
629 ice_backup_candidate_pair_ping_interval ==
630 o.ice_backup_candidate_pair_ping_interval &&
631 continual_gathering_policy == o.continual_gathering_policy &&
632 certificates == o.certificates &&
633 prioritize_most_likely_ice_candidate_pairs ==
634 o.prioritize_most_likely_ice_candidate_pairs &&
635 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800636 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700637 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800638 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800639 screencast_min_bitrate == o.screencast_min_bitrate &&
640 combined_audio_video_bwe == o.combined_audio_video_bwe &&
641 enable_dtls_srtp == o.enable_dtls_srtp &&
642 ice_candidate_pool_size == o.ice_candidate_pool_size &&
643 prune_turn_ports == o.prune_turn_ports &&
644 presume_writable_when_fully_relayed ==
645 o.presume_writable_when_fully_relayed &&
646 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800647 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700648 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200649 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800650 turn_customizer == o.turn_customizer &&
651 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800652}
653
654bool PeerConnectionInterface::RTCConfiguration::operator!=(
655 const PeerConnectionInterface::RTCConfiguration& o) const {
656 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800657}
658
zhihuang8f65cdf2016-05-06 18:40:30 -0700659// Generate a RTCP CNAME when a PeerConnection is created.
660std::string GenerateRtcpCname() {
661 std::string cname;
662 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100663 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800664 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700665 }
666 return cname;
667}
668
zhihuang1c378ed2017-08-17 14:10:50 -0700669bool ValidateOfferAnswerOptions(
670 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
671 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
672 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700673}
674
zhihuang1c378ed2017-08-17 14:10:50 -0700675// From |rtc_options|, fill parts of |session_options| shared by all generated
676// m= sections (in other words, nothing that involves a map/array).
677void ExtractSharedMediaSessionOptions(
678 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
679 cricket::MediaSessionOptions* session_options) {
680 session_options->vad_enabled = rtc_options.voice_activity_detection;
681 session_options->bundle_enabled = rtc_options.use_rtp_mux;
682}
zhihuanga77e6bb2017-08-14 18:17:48 -0700683
zhihuang1c378ed2017-08-17 14:10:50 -0700684bool ConvertConstraintsToOfferAnswerOptions(
685 const MediaConstraintsInterface* constraints,
686 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700687 if (!constraints) {
688 return true;
689 }
zhihuang1c378ed2017-08-17 14:10:50 -0700690
691 bool value = false;
692 size_t mandatory_constraints_satisfied = 0;
693
694 if (FindConstraint(constraints,
695 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
696 &mandatory_constraints_satisfied)) {
697 offer_answer_options->offer_to_receive_audio =
698 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
699 kOfferToReceiveMediaTrue
700 : 0;
701 }
702
703 if (FindConstraint(constraints,
704 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
705 &mandatory_constraints_satisfied)) {
706 offer_answer_options->offer_to_receive_video =
707 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
708 kOfferToReceiveMediaTrue
709 : 0;
710 }
711 if (FindConstraint(constraints,
712 MediaConstraintsInterface::kVoiceActivityDetection, &value,
713 &mandatory_constraints_satisfied)) {
714 offer_answer_options->voice_activity_detection = value;
715 }
716 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
717 &mandatory_constraints_satisfied)) {
718 offer_answer_options->use_rtp_mux = value;
719 }
720 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
721 &value, &mandatory_constraints_satisfied)) {
722 offer_answer_options->ice_restart = value;
723 }
724
deadbeefab9b2d12015-10-14 11:33:11 -0700725 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
726}
727
zhihuang38ede132017-06-15 12:52:32 -0700728PeerConnection::PeerConnection(PeerConnectionFactory* factory,
729 std::unique_ptr<RtcEventLog> event_log,
730 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000731 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700732 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700733 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700734 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700735 remote_streams_(StreamCollection::Create()),
736 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000737
738PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100739 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800740 RTC_DCHECK_RUN_ON(signaling_thread());
741
742 // Need to detach RTP transceivers from PeerConnection, since it's about to be
743 // destroyed.
744 for (auto transceiver : transceivers_) {
745 transceiver->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700746 }
Steve Anton4171afb2017-11-20 10:20:22 -0800747
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700748 // Destroy stats_ because it depends on session_.
749 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800750 if (stats_collector_) {
751 stats_collector_->WaitForPendingRequest();
752 stats_collector_ = nullptr;
753 }
Steve Anton75737c02017-11-06 10:37:17 -0800754
755 // Destroy video channels first since they may have a pointer to a voice
756 // channel.
Steve Anton4171afb2017-11-20 10:20:22 -0800757 for (auto transceiver : transceivers_) {
Steve Anton6fec8802017-12-04 10:37:29 -0800758 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
759 DestroyTransceiverChannel(transceiver);
Steve Anton4171afb2017-11-20 10:20:22 -0800760 }
Steve Anton75737c02017-11-06 10:37:17 -0800761 }
Steve Anton4171afb2017-11-20 10:20:22 -0800762 for (auto transceiver : transceivers_) {
Steve Anton6fec8802017-12-04 10:37:29 -0800763 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
764 DestroyTransceiverChannel(transceiver);
Steve Anton4171afb2017-11-20 10:20:22 -0800765 }
Steve Anton75737c02017-11-06 10:37:17 -0800766 }
Steve Anton6fec8802017-12-04 10:37:29 -0800767 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -0800768
Mirko Bonadei675513b2017-11-09 11:09:25 +0100769 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800770
771 webrtc_session_desc_factory_.reset();
772 sctp_invoker_.reset();
773 sctp_factory_.reset();
774 transport_controller_.reset();
775
deadbeef91dd5672016-05-18 16:55:30 -0700776 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700777 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700778 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700779 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700780 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700781 call_.reset();
782 event_log_.reset();
783 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000784}
785
786bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000787 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700788 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200789 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800790 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100791 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700792
793 RTCError config_error = ValidateConfiguration(configuration);
794 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100795 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700796 return false;
797 }
798
deadbeef293e9262017-01-11 12:28:30 -0800799 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100800 RTC_LOG(LS_ERROR)
801 << "PeerConnection initialized without a PortAllocator? "
802 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800803 return false;
804 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200805
deadbeef653b8e02015-11-11 12:55:10 -0800806 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800807 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100808 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
809 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800810 return false;
811 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000812 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800813 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800814
deadbeef91dd5672016-05-18 16:55:30 -0700815 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700816 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700817 if (!network_thread()->Invoke<bool>(
818 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
819 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000820 return false;
821 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000822
Steve Anton75737c02017-11-06 10:37:17 -0800823 // RFC 3264: The numeric value of the session id and version in the
824 // o line MUST be representable with a "64 bit signed integer".
825 // Due to this constraint session id |session_id_| is max limited to
826 // LLONG_MAX.
827 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
828 transport_controller_.reset(factory_->CreateTransportController(
829 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
830 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
831 transport_controller_->SignalConnectionState.connect(
832 this, &PeerConnection::OnTransportControllerConnectionState);
833 transport_controller_->SignalGatheringState.connect(
834 this, &PeerConnection::OnTransportControllerGatheringState);
835 transport_controller_->SignalCandidatesGathered.connect(
836 this, &PeerConnection::OnTransportControllerCandidatesGathered);
837 transport_controller_->SignalCandidatesRemoved.connect(
838 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
839 transport_controller_->SignalDtlsHandshakeError.connect(
840 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
841
842 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700843
deadbeefab9b2d12015-10-14 11:33:11 -0700844 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700845 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000846
Steve Antonba818672017-11-06 10:21:57 -0800847 configuration_ = configuration;
848
Steve Anton75737c02017-11-06 10:37:17 -0800849 const PeerConnectionFactoryInterface::Options& options = factory_->options();
850
851 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
852
853 // Obtain a certificate from RTCConfiguration if any were provided (optional).
854 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
855 if (!configuration.certificates.empty()) {
856 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
857 // just picking the first one. The decision should be made based on the DTLS
858 // handshake. The DTLS negotiations need to know about all certificates.
859 certificate = configuration.certificates[0];
860 }
861
Steve Antond25da372017-11-06 14:50:29 -0800862 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800863
864 if (options.disable_encryption) {
865 dtls_enabled_ = false;
866 } else {
867 // Enable DTLS by default if we have an identity store or a certificate.
868 dtls_enabled_ = (cert_generator || certificate);
869 // |configuration| can override the default |dtls_enabled_| value.
870 if (configuration.enable_dtls_srtp) {
871 dtls_enabled_ = *(configuration.enable_dtls_srtp);
872 }
873 }
874
875 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
876 // It takes precendence over the disable_sctp_data_channels
877 // PeerConnectionFactoryInterface::Options.
878 if (configuration.enable_rtp_data_channel) {
879 data_channel_type_ = cricket::DCT_RTP;
880 } else {
881 // DTLS has to be enabled to use SCTP.
882 if (!options.disable_sctp_data_channels && dtls_enabled_) {
883 data_channel_type_ = cricket::DCT_SCTP;
884 }
885 }
886
887 video_options_.screencast_min_bitrate_kbps =
888 configuration.screencast_min_bitrate;
889 audio_options_.combined_audio_video_bwe =
890 configuration.combined_audio_video_bwe;
891
892 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100893 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800894
895 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100896 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800897
898 // Whether the certificate generator/certificate is null or not determines
899 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
900 // the right instructions by clearing the variables if needed.
901 if (!dtls_enabled_) {
902 cert_generator.reset();
903 certificate = nullptr;
904 } else if (certificate) {
905 // Favor generated certificate over the certificate generator.
906 cert_generator.reset();
907 }
908
909 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
910 signaling_thread(), channel_manager(), this, session_id(),
911 std::move(cert_generator), certificate));
912 webrtc_session_desc_factory_->SignalCertificateReady.connect(
913 this, &PeerConnection::OnCertificateReady);
914
915 if (options.disable_encryption) {
916 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
917 }
918
919 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
920 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000921
Steve Anton4171afb2017-11-20 10:20:22 -0800922 // Add default audio/video transceivers for Plan B SDP.
923 if (!IsUnifiedPlan()) {
924 transceivers_.push_back(
925 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
926 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
927 transceivers_.push_back(
928 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
929 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
930 }
931
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000932 return true;
933}
934
Steve Anton038834f2017-07-14 15:59:59 -0700935RTCError PeerConnection::ValidateConfiguration(
936 const RTCConfiguration& config) const {
937 if (config.ice_regather_interval_range &&
938 config.continual_gathering_policy == GATHER_ONCE) {
939 return RTCError(RTCErrorType::INVALID_PARAMETER,
940 "ice_regather_interval_range specified but continual "
941 "gathering policy is GATHER_ONCE");
942 }
943 return RTCError::OK();
944}
945
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000946rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000947PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700948 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000949}
950
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000951rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000952PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700953 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000954}
955
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000956bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100957 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000958 if (IsClosed()) {
959 return false;
960 }
deadbeefab9b2d12015-10-14 11:33:11 -0700961 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000962 return false;
963 }
deadbeefab9b2d12015-10-14 11:33:11 -0700964
965 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800966 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
967 observer->SignalAudioTrackAdded.connect(this,
968 &PeerConnection::OnAudioTrackAdded);
969 observer->SignalAudioTrackRemoved.connect(
970 this, &PeerConnection::OnAudioTrackRemoved);
971 observer->SignalVideoTrackAdded.connect(this,
972 &PeerConnection::OnVideoTrackAdded);
973 observer->SignalVideoTrackRemoved.connect(
974 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700975 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700976
deadbeefab9b2d12015-10-14 11:33:11 -0700977 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700978 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700979 }
980 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700981 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700982 }
983
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000984 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000985 observer_->OnRenegotiationNeeded();
986 return true;
987}
988
989void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100990 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700991 if (!IsClosed()) {
992 for (const auto& track : local_stream->GetAudioTracks()) {
993 RemoveAudioTrack(track.get(), local_stream);
994 }
995 for (const auto& track : local_stream->GetVideoTracks()) {
996 RemoveVideoTrack(track.get(), local_stream);
997 }
deadbeefab9b2d12015-10-14 11:33:11 -0700998 }
deadbeefab9b2d12015-10-14 11:33:11 -0700999 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001000 stream_observers_.erase(
1001 std::remove_if(
1002 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001003 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001004 return observer->stream()->label().compare(local_stream->label()) ==
1005 0;
1006 }),
1007 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001008
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001009 if (IsClosed()) {
1010 return;
1011 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001012 observer_->OnRenegotiationNeeded();
1013}
1014
deadbeefe1f9d832016-01-14 15:35:42 -08001015rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1016 MediaStreamTrackInterface* track,
1017 std::vector<MediaStreamInterface*> streams) {
1018 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1019 if (IsClosed()) {
1020 return nullptr;
1021 }
1022 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001023 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001024 << "Adding a track with two streams is not currently supported.";
1025 return nullptr;
1026 }
Steve Anton4171afb2017-11-20 10:20:22 -08001027 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001028 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1029 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001030 return nullptr;
1031 }
1032
1033 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001034 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001035 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001036 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001037 signaling_thread(),
1038 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001039 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001040 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001041 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001042 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001043 }
Steve Anton4171afb2017-11-20 10:20:22 -08001044 const RtpSenderInfo* sender_info =
1045 FindSenderInfo(local_audio_sender_infos_,
1046 new_sender->internal()->stream_id(), track->id());
1047 if (sender_info) {
1048 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001049 }
1050 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001051 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001052 signaling_thread(),
1053 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001054 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001055 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001056 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001057 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001058 }
Steve Anton4171afb2017-11-20 10:20:22 -08001059 const RtpSenderInfo* sender_info =
1060 FindSenderInfo(local_video_sender_infos_,
1061 new_sender->internal()->stream_id(), track->id());
1062 if (sender_info) {
1063 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001064 }
1065 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001066 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1067 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001068 return rtc::scoped_refptr<RtpSenderInterface>();
1069 }
1070
deadbeefe1f9d832016-01-14 15:35:42 -08001071 observer_->OnRenegotiationNeeded();
1072 return new_sender;
1073}
1074
1075bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1076 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1077 if (IsClosed()) {
1078 return false;
1079 }
1080
Steve Anton4171afb2017-11-20 10:20:22 -08001081 bool removed;
1082 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1083 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1084 } else {
1085 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1086 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1087 }
1088 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001089 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1090 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001091 return false;
1092 }
deadbeefe1f9d832016-01-14 15:35:42 -08001093
1094 observer_->OnRenegotiationNeeded();
1095 return true;
1096}
1097
Steve Anton9158ef62017-11-27 13:01:52 -08001098RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1099PeerConnection::AddTransceiver(
1100 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1101 return AddTransceiver(track, RtpTransceiverInit());
1102}
1103
1104RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1105PeerConnection::AddTransceiver(
1106 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1107 const RtpTransceiverInit& init) {
1108 if (!IsUnifiedPlan()) {
1109 LOG_AND_RETURN_ERROR(
1110 RTCErrorType::INTERNAL_ERROR,
1111 "AddTransceiver only supported when Unified Plan is enabled.");
1112 }
1113 if (!track) {
1114 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1115 }
1116 cricket::MediaType media_type;
1117 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1118 media_type = cricket::MEDIA_TYPE_AUDIO;
1119 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1120 media_type = cricket::MEDIA_TYPE_VIDEO;
1121 } else {
1122 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1123 "Track kind is not audio or video");
1124 }
1125 return AddTransceiver(media_type, track, init);
1126}
1127
1128RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1129PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1130 return AddTransceiver(media_type, RtpTransceiverInit());
1131}
1132
1133RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1134PeerConnection::AddTransceiver(cricket::MediaType media_type,
1135 const RtpTransceiverInit& init) {
1136 if (!IsUnifiedPlan()) {
1137 LOG_AND_RETURN_ERROR(
1138 RTCErrorType::INTERNAL_ERROR,
1139 "AddTransceiver only supported when Unified Plan is enabled.");
1140 }
1141 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1142 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1143 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1144 "media type is not audio or video");
1145 }
1146 return AddTransceiver(media_type, nullptr, init);
1147}
1148
1149RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1150PeerConnection::AddTransceiver(
1151 cricket::MediaType media_type,
1152 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1153 const RtpTransceiverInit& init) {
1154 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1155 media_type == cricket::MEDIA_TYPE_VIDEO));
1156 if (track) {
1157 RTC_DCHECK_EQ(media_type,
1158 (track->kind() == MediaStreamTrackInterface::kAudioKind
1159 ? cricket::MEDIA_TYPE_AUDIO
1160 : cricket::MEDIA_TYPE_VIDEO));
1161 }
1162
1163 // TODO(bugs.webrtc.org/7600): Verify init.
1164
1165 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1166 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1167 receiver;
1168 std::string receiver_id = rtc::CreateRandomUuid();
1169 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1170 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1171 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1172 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1173 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1174 } else {
1175 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1176 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1177 signaling_thread(), new VideoRtpSender(nullptr));
1178 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1179 signaling_thread(),
1180 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1181 }
1182 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1183 // channel prevents users from calling SetParameters on them, which is needed
1184 // to be in compliance with the spec.
1185
1186 if (track) {
1187 sender->SetTrack(track);
1188 }
1189
1190 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1191 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1192 signaling_thread(), new RtpTransceiver(sender, receiver));
1193 transceiver->SetDirection(init.direction);
1194
1195 transceivers_.push_back(transceiver);
1196
1197 observer_->OnRenegotiationNeeded();
1198
1199 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1200}
1201
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001202rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001203 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001204 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001205 if (IsClosed()) {
1206 return nullptr;
1207 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001208 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001209 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001210 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001211 }
Steve Anton4171afb2017-11-20 10:20:22 -08001212 auto track_sender = FindSenderForTrack(track);
1213 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001214 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001215 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001216 }
1217
Steve Anton4171afb2017-11-20 10:20:22 -08001218 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001219}
1220
deadbeeffac06552015-11-25 11:26:01 -08001221rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001222 const std::string& kind,
1223 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001224 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001225 if (IsClosed()) {
1226 return nullptr;
1227 }
Steve Anton4171afb2017-11-20 10:20:22 -08001228
1229 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001230 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001231 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001232 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001233 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001234 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001235 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001236 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001237 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001238 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001239 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001240 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001241 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001242 }
Steve Anton4171afb2017-11-20 10:20:22 -08001243
deadbeefbd7d8f72015-12-18 16:58:44 -08001244 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001245 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001246 }
Steve Anton4171afb2017-11-20 10:20:22 -08001247
deadbeefe1f9d832016-01-14 15:35:42 -08001248 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001249}
1250
deadbeef70ab1a12015-09-28 16:53:55 -07001251std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1252 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001253 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001254 for (auto sender : GetSendersInternal()) {
1255 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001256 }
1257 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001258}
1259
Steve Anton4171afb2017-11-20 10:20:22 -08001260std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1261PeerConnection::GetSendersInternal() const {
1262 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1263 all_senders;
1264 for (auto transceiver : transceivers_) {
1265 auto senders = transceiver->internal()->senders();
1266 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1267 }
1268 return all_senders;
1269}
1270
deadbeef70ab1a12015-09-28 16:53:55 -07001271std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1272PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001273 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001274 for (const auto& receiver : GetReceiversInternal()) {
1275 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001276 }
1277 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001278}
1279
Steve Anton4171afb2017-11-20 10:20:22 -08001280std::vector<
1281 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1282PeerConnection::GetReceiversInternal() const {
1283 std::vector<
1284 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1285 all_receivers;
1286 for (auto transceiver : transceivers_) {
1287 auto receivers = transceiver->internal()->receivers();
1288 all_receivers.insert(all_receivers.end(), receivers.begin(),
1289 receivers.end());
1290 }
1291 return all_receivers;
1292}
1293
Steve Anton9158ef62017-11-27 13:01:52 -08001294std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1295PeerConnection::GetTransceivers() const {
1296 RTC_DCHECK(IsUnifiedPlan());
1297 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1298 for (auto transceiver : transceivers_) {
1299 all_transceivers.push_back(transceiver);
1300 }
1301 return all_transceivers;
1302}
1303
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001304bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001305 MediaStreamTrackInterface* track,
1306 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001307 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001308 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001309 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001310 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001311 return false;
1312 }
1313
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001314 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001315 // The StatsCollector is used to tell if a track is valid because it may
1316 // remember tracks that the PeerConnection previously removed.
1317 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001318 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1319 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001320 return false;
1321 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001322 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001323 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001324 return true;
1325}
1326
hbos74e1a4f2016-09-15 23:33:01 -07001327void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1328 RTC_DCHECK(stats_collector_);
1329 stats_collector_->GetStatsReport(callback);
1330}
1331
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001332PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1333 return signaling_state_;
1334}
1335
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001336PeerConnectionInterface::IceConnectionState
1337PeerConnection::ice_connection_state() {
1338 return ice_connection_state_;
1339}
1340
1341PeerConnectionInterface::IceGatheringState
1342PeerConnection::ice_gathering_state() {
1343 return ice_gathering_state_;
1344}
1345
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001346rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001347PeerConnection::CreateDataChannel(
1348 const std::string& label,
1349 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001350 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001351
deadbeefab9b2d12015-10-14 11:33:11 -07001352 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001353
kwibergd1fe2812016-04-27 06:47:29 -07001354 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001355 if (config) {
1356 internal_config.reset(new InternalDataChannelInit(*config));
1357 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001358 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001359 InternalCreateDataChannel(label, internal_config.get()));
1360 if (!channel.get()) {
1361 return nullptr;
1362 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001363
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001364 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1365 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001366 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001367 observer_->OnRenegotiationNeeded();
1368 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001369
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001370 return DataChannelProxy::Create(signaling_thread(), channel.get());
1371}
1372
1373void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1374 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001375 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001376
zhihuang1c378ed2017-08-17 14:10:50 -07001377 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1378 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1379 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1380 // compares the mandatory fields parsed with the mandatory fields added in the
1381 // |constraints| and some downstream applications might create offers with
1382 // mandatory fields which would not be parsed in the helper method. For
1383 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1384 // |constraints| as a mandatory field but it is not parsed.
1385 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001386
zhihuang1c378ed2017-08-17 14:10:50 -07001387 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001388}
1389
1390void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1391 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001392 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001393
nisse7ce109a2017-01-31 00:57:56 -08001394 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001395 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001396 return;
1397 }
deadbeefab9b2d12015-10-14 11:33:11 -07001398
Steve Anton8d3444d2017-10-20 15:30:51 -07001399 if (IsClosed()) {
1400 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001401 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001402 PostCreateSessionDescriptionFailure(observer, error);
1403 return;
1404 }
1405
zhihuang1c378ed2017-08-17 14:10:50 -07001406 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001407 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001408 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001409 PostCreateSessionDescriptionFailure(observer, error);
1410 return;
1411 }
1412
zhihuang1c378ed2017-08-17 14:10:50 -07001413 cricket::MediaSessionOptions session_options;
1414 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001415 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001416}
1417
1418void PeerConnection::CreateAnswer(
1419 CreateSessionDescriptionObserver* observer,
1420 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001421 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001422
nisse7ce109a2017-01-31 00:57:56 -08001423 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001424 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001425 return;
1426 }
deadbeefab9b2d12015-10-14 11:33:11 -07001427
zhihuang1c378ed2017-08-17 14:10:50 -07001428 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1429 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1430 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001431 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001432 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001433 PostCreateSessionDescriptionFailure(observer, error);
1434 return;
1435 }
1436
Steve Anton8d3444d2017-10-20 15:30:51 -07001437 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001438}
1439
1440void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1441 const RTCOfferAnswerOptions& options) {
1442 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001443 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001444 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001445 return;
1446 }
1447
Steve Anton8d3444d2017-10-20 15:30:51 -07001448 if (IsClosed()) {
1449 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001450 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001451 PostCreateSessionDescriptionFailure(observer, error);
1452 return;
1453 }
1454
Steve Anton75737c02017-11-06 10:37:17 -08001455 if (remote_description() &&
1456 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001457 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001458 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001459 PostCreateSessionDescriptionFailure(observer, error);
1460 return;
1461 }
1462
htaa2a49d92016-03-04 02:51:39 -08001463 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001464 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001465
Steve Antond25da372017-11-06 14:50:29 -08001466 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001467}
1468
1469void PeerConnection::SetLocalDescription(
1470 SetSessionDescriptionObserver* observer,
1471 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001472 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001473
nisse7ce109a2017-01-31 00:57:56 -08001474 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001475 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001476 return;
1477 }
Steve Anton8a006912017-12-04 15:25:56 -08001478
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001479 if (!desc) {
1480 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1481 return;
1482 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001483
Steve Anton8a006912017-12-04 15:25:56 -08001484 std::string desc_type = desc->type();
Steve Anton8d3444d2017-10-20 15:30:51 -07001485
Steve Anton8a006912017-12-04 15:25:56 -08001486 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1487 // |desc| may be destroyed at this point.
1488
1489 if (!error.ok()) {
1490 std::string error_message =
1491 "Failed to set local " + desc_type + " sdp: " + error.message();
1492 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1493 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001494 return;
1495 }
Steve Anton8a006912017-12-04 15:25:56 -08001496 RTC_DCHECK(local_description());
1497
1498 PostSetSessionDescriptionSuccess(observer);
1499
1500 // According to JSEP, after setLocalDescription, changing the candidate pool
1501 // size is not allowed, and changing the set of ICE servers will not result
1502 // in new candidates being gathered.
1503 port_allocator_->FreezeCandidatePool();
1504
1505 // MaybeStartGathering needs to be called after posting
1506 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1507 // before signaling that SetLocalDescription completed.
1508 transport_controller_->MaybeStartGathering();
1509
1510 if (local_description()->type() == SessionDescriptionInterface::kAnswer) {
1511 // TODO(deadbeef): We already had to hop to the network thread for
1512 // MaybeStartGathering...
1513 network_thread()->Invoke<void>(
1514 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1515 port_allocator_.get()));
1516 }
1517}
1518
1519RTCError PeerConnection::ApplyLocalDescription(
1520 std::unique_ptr<SessionDescriptionInterface> desc) {
1521 RTC_DCHECK_RUN_ON(signaling_thread());
1522 RTC_DCHECK(desc);
1523
1524 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1525 if (!error.ok()) {
1526 return error;
1527 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001528
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001529 // Update stats here so that we have the most recent stats for tracks and
1530 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001531 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001532
1533 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton20393062017-12-04 16:24:52 -08001534 cricket::ContentAction action = ContentActionFromSessionType(desc->type());
Steve Anton8a006912017-12-04 15:25:56 -08001535 if (!initial_offerer_.has_value()) {
Steve Anton20393062017-12-04 16:24:52 -08001536 initial_offerer_.emplace(action == cricket::CA_OFFER);
Steve Anton8a006912017-12-04 15:25:56 -08001537 if (*initial_offerer_) {
1538 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1539 } else {
1540 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1541 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001542 }
Steve Anton8a006912017-12-04 15:25:56 -08001543
Steve Anton20393062017-12-04 16:24:52 -08001544 if (action == cricket::CA_ANSWER) {
Steve Anton8a006912017-12-04 15:25:56 -08001545 current_local_description_ = std::move(desc);
1546 pending_local_description_ = nullptr;
1547 current_remote_description_ = std::move(pending_remote_description_);
1548 } else {
1549 pending_local_description_ = std::move(desc);
1550 }
1551 // The session description to apply now must be accessed by
1552 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001553 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001554
Steve Anton8a006912017-12-04 15:25:56 -08001555 // Transport and Media channels will be created only when offer is set.
Steve Anton20393062017-12-04 16:24:52 -08001556 if (action == cricket::CA_OFFER) {
Steve Anton8a006912017-12-04 15:25:56 -08001557 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1558 // is applied. Restore back to old description.
1559 RTCError error = CreateChannels(local_description()->description());
1560 if (!error.ok()) {
1561 return error;
1562 }
1563 }
1564
1565 // Remove unused channels if MediaContentDescription is rejected.
1566 RemoveUnusedChannels(local_description()->description());
1567
1568 error = UpdateSessionState(action, cricket::CS_LOCAL);
1569 if (!error.ok()) {
1570 return error;
1571 }
1572 if (remote_description()) {
1573 // Now that we have a local description, we can push down remote candidates.
1574 UseCandidatesInSessionDescription(remote_description());
1575 }
1576
1577 pending_ice_restarts_.clear();
1578 if (session_error() != SessionError::kNone) {
1579 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1580 }
1581
deadbeefab9b2d12015-10-14 11:33:11 -07001582 // If setting the description decided our SSL role, allocate any necessary
1583 // SCTP sids.
1584 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001585 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001586 AllocateSctpSids(role);
1587 }
1588
1589 // Update state and SSRC of local MediaStreams and DataChannels based on the
1590 // local session description.
1591 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001592 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001593 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001594 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001595 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001596 } else {
1597 const cricket::AudioContentDescription* audio_desc =
1598 static_cast<const cricket::AudioContentDescription*>(
1599 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001600 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001601 }
deadbeefab9b2d12015-10-14 11:33:11 -07001602 }
1603
1604 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001605 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001606 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001607 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001608 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001609 } else {
1610 const cricket::VideoContentDescription* video_desc =
1611 static_cast<const cricket::VideoContentDescription*>(
1612 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001613 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001614 }
deadbeefab9b2d12015-10-14 11:33:11 -07001615 }
1616
1617 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001618 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001619 if (data_content) {
1620 const cricket::DataContentDescription* data_desc =
1621 static_cast<const cricket::DataContentDescription*>(
1622 data_content->description);
1623 if (rtc::starts_with(data_desc->protocol().data(),
1624 cricket::kMediaProtocolRtpPrefix)) {
1625 UpdateLocalRtpDataChannels(data_desc->streams());
1626 }
1627 }
1628
Steve Anton8a006912017-12-04 15:25:56 -08001629 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001630}
1631
1632void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001633 SetSessionDescriptionObserver* observer,
1634 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001635 SetRemoteDescription(
1636 std::unique_ptr<SessionDescriptionInterface>(desc),
1637 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1638 new SetRemoteDescriptionObserverAdapter(this, observer)));
1639}
1640
1641void PeerConnection::SetRemoteDescription(
1642 std::unique_ptr<SessionDescriptionInterface> desc,
1643 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001644 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001645
nisse7ce109a2017-01-31 00:57:56 -08001646 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001647 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001648 return;
1649 }
Steve Anton8a006912017-12-04 15:25:56 -08001650
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001651 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001652 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001653 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001654 return;
1655 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001656
Steve Anton8a006912017-12-04 15:25:56 -08001657 std::string desc_type = desc->type();
1658
1659 RTCError error = ApplyRemoteDescription(std::move(desc));
1660 // |desc| may be destroyed at this point.
1661
1662 if (!error.ok()) {
1663 std::string error_message =
1664 "Failed to set remote " + desc_type + " sdp: " + error.message();
1665 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001666 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001667 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001668 return;
1669 }
1670
Steve Anton8a006912017-12-04 15:25:56 -08001671 if (remote_description()->type() == SessionDescriptionInterface::kAnswer) {
1672 // TODO(deadbeef): We already had to hop to the network thread for
1673 // MaybeStartGathering...
1674 network_thread()->Invoke<void>(
1675 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1676 port_allocator_.get()));
1677 }
1678
1679 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1680}
1681
1682RTCError PeerConnection::ApplyRemoteDescription(
1683 std::unique_ptr<SessionDescriptionInterface> desc) {
1684 RTC_DCHECK_RUN_ON(signaling_thread());
1685 RTC_DCHECK(desc);
1686
1687 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1688 if (!error.ok()) {
1689 return error;
1690 }
1691
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001692 // Update stats here so that we have the most recent stats for tracks and
1693 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001694 stats_->UpdateStats(kStatsOutputLevelStandard);
Henrik Boström31638672017-11-23 17:48:32 +01001695 // Takes the ownership of |desc|. On success, remote_description() is updated
1696 // to reflect the description that was passed in.
Steve Anton8a006912017-12-04 15:25:56 -08001697
1698 const SessionDescriptionInterface* old_remote_description =
1699 remote_description();
1700 // Grab ownership of the description being replaced for the remainder of this
1701 // method, since it's used below as |old_remote_description|.
1702 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton20393062017-12-04 16:24:52 -08001703 cricket::ContentAction action = ContentActionFromSessionType(desc->type());
1704 if (action == cricket::CA_ANSWER) {
Steve Anton8a006912017-12-04 15:25:56 -08001705 replaced_remote_description = pending_remote_description_
1706 ? std::move(pending_remote_description_)
1707 : std::move(current_remote_description_);
1708 current_remote_description_ = std::move(desc);
1709 pending_remote_description_ = nullptr;
1710 current_local_description_ = std::move(pending_local_description_);
1711 } else {
1712 replaced_remote_description = std::move(pending_remote_description_);
1713 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001714 }
Steve Anton8a006912017-12-04 15:25:56 -08001715 // The session description to apply now must be accessed by
1716 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001717 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001718
Steve Anton8a006912017-12-04 15:25:56 -08001719 // Transport and Media channels will be created only when offer is set.
Steve Anton20393062017-12-04 16:24:52 -08001720 if (action == cricket::CA_OFFER) {
Steve Anton8a006912017-12-04 15:25:56 -08001721 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1722 // is applied. Restore back to old description.
1723 RTCError error = CreateChannels(remote_description()->description());
1724 if (!error.ok()) {
1725 return error;
1726 }
1727 }
1728
1729 // Remove unused channels if MediaContentDescription is rejected.
1730 RemoveUnusedChannels(remote_description()->description());
1731
1732 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1733 // is called.
1734 error = UpdateSessionState(action, cricket::CS_REMOTE);
1735 if (!error.ok()) {
1736 return error;
1737 }
1738
1739 if (local_description() &&
1740 !UseCandidatesInSessionDescription(remote_description())) {
1741 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1742 }
1743
1744 if (old_remote_description) {
1745 for (const cricket::ContentInfo& content :
1746 old_remote_description->description()->contents()) {
1747 // Check if this new SessionDescription contains new ICE ufrag and
1748 // password that indicates the remote peer requests an ICE restart.
1749 // TODO(deadbeef): When we start storing both the current and pending
1750 // remote description, this should reset pending_ice_restarts and compare
1751 // against the current description.
1752 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1753 content.name)) {
Steve Anton20393062017-12-04 16:24:52 -08001754 if (action == cricket::CA_OFFER) {
Steve Anton8a006912017-12-04 15:25:56 -08001755 pending_ice_restarts_.insert(content.name);
1756 }
1757 } else {
1758 // We retain all received candidates only if ICE is not restarted.
1759 // When ICE is restarted, all previous candidates belong to an old
1760 // generation and should not be kept.
1761 // TODO(deadbeef): This goes against the W3C spec which says the remote
1762 // description should only contain candidates from the last set remote
1763 // description plus any candidates added since then. We should remove
1764 // this once we're sure it won't break anything.
1765 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1766 old_remote_description, content.name, mutable_remote_description());
1767 }
1768 }
1769 }
1770
1771 if (session_error() != SessionError::kNone) {
1772 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1773 }
1774
1775 // Set the the ICE connection state to connecting since the connection may
1776 // become writable with peer reflexive candidates before any remote candidate
1777 // is signaled.
1778 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1779 // is to have a new signal the indicates a change in checking state from the
1780 // transport and expose a new checking() member from transport that can be
1781 // read to determine the current checking state. The existing SignalConnecting
1782 // actually means "gathering candidates", so cannot be be used here.
1783 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
1784 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1785 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1786 }
1787
deadbeefab9b2d12015-10-14 11:33:11 -07001788 // If setting the description decided our SSL role, allocate any necessary
1789 // SCTP sids.
1790 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001791 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001792 AllocateSctpSids(role);
1793 }
1794
Henrik Boströmfdb92012017-11-09 19:55:44 +01001795 const cricket::ContentInfo* audio_content =
1796 GetFirstAudioContent(remote_description()->description());
1797 const cricket::ContentInfo* video_content =
1798 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001799 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001800 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001801 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001802 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001803 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001804 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001805
1806 // Check if the descriptions include streams, just in case the peer supports
1807 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001808 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001809 (audio_desc && !audio_desc->streams().empty()) ||
1810 (video_desc && !video_desc->streams().empty())) {
1811 remote_peer_supports_msid_ = true;
1812 }
deadbeefab9b2d12015-10-14 11:33:11 -07001813
1814 // We wait to signal new streams until we finish processing the description,
1815 // since only at that point will new streams have all their tracks.
1816 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1817
Steve Anton8d3444d2017-10-20 15:30:51 -07001818 // TODO(steveanton): When removing RTP senders/receivers in response to a
1819 // rejected media section, there is some cleanup logic that expects the voice/
1820 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001821 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001822 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001823 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001824
deadbeefab9b2d12015-10-14 11:33:11 -07001825 // Find all audio rtp streams and create corresponding remote AudioTracks
1826 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001827 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001828 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001829 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001830 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001831 bool default_audio_track_needed =
1832 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001833 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001834 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001835 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001836 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001837 }
deadbeefab9b2d12015-10-14 11:33:11 -07001838 }
1839
1840 // Find all video rtp streams and create corresponding remote VideoTracks
1841 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001842 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001843 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001844 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001845 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001846 bool default_video_track_needed =
1847 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001848 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001849 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001850 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001851 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001852 }
deadbeefab9b2d12015-10-14 11:33:11 -07001853 }
1854
1855 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001856 if (data_desc) {
1857 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001858 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001859 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001860 }
1861 }
1862
1863 // Iterate new_streams and notify the observer about new MediaStreams.
1864 for (size_t i = 0; i < new_streams->count(); ++i) {
1865 MediaStreamInterface* new_stream = new_streams->at(i);
1866 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001867 observer_->OnAddStream(
1868 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001869 }
1870
deadbeefbda7e0b2015-12-08 17:13:40 -08001871 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001872
Steve Anton8a006912017-12-04 15:25:56 -08001873 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07001874}
1875
deadbeef46c73892016-11-16 19:42:04 -08001876PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1877 return configuration_;
1878}
1879
deadbeef293e9262017-01-11 12:28:30 -08001880bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1881 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001882 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001883
Steve Anton75737c02017-11-06 10:37:17 -08001884 if (local_description() && configuration.ice_candidate_pool_size !=
1885 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001886 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1887 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001888 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001889 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001890
deadbeef293e9262017-01-11 12:28:30 -08001891 // The simplest (and most future-compatible) way to tell if the config was
1892 // modified in an invalid way is to copy each property we do support
1893 // modifying, then use operator==. There are far more properties we don't
1894 // support modifying than those we do, and more could be added.
1895 RTCConfiguration modified_config = configuration_;
1896 modified_config.servers = configuration.servers;
1897 modified_config.type = configuration.type;
1898 modified_config.ice_candidate_pool_size =
1899 configuration.ice_candidate_pool_size;
1900 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001901 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001902 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001903 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001904 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001905 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1906 }
1907
Steve Anton038834f2017-07-14 15:59:59 -07001908 // Validate the modified configuration.
1909 RTCError validate_error = ValidateConfiguration(modified_config);
1910 if (!validate_error.ok()) {
1911 return SafeSetError(std::move(validate_error), error);
1912 }
1913
deadbeef293e9262017-01-11 12:28:30 -08001914 // Note that this isn't possible through chromium, since it's an unsigned
1915 // short in WebIDL.
1916 if (configuration.ice_candidate_pool_size < 0 ||
1917 configuration.ice_candidate_pool_size > UINT16_MAX) {
1918 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1919 }
1920
1921 // Parse ICE servers before hopping to network thread.
1922 cricket::ServerAddresses stun_servers;
1923 std::vector<cricket::RelayServerConfig> turn_servers;
1924 RTCErrorType parse_error =
1925 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1926 if (parse_error != RTCErrorType::NONE) {
1927 return SafeSetError(parse_error, error);
1928 }
1929
1930 // In theory this shouldn't fail.
1931 if (!network_thread()->Invoke<bool>(
1932 RTC_FROM_HERE,
1933 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1934 stun_servers, turn_servers, modified_config.type,
1935 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001936 modified_config.prune_turn_ports,
1937 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001938 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001939 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1940 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001941
deadbeefd1a38b52016-12-10 13:15:33 -08001942 // As described in JSEP, calling setConfiguration with new ICE servers or
1943 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1944 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001945 if (modified_config.servers != configuration_.servers ||
1946 modified_config.type != configuration_.type ||
1947 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001948 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001949 }
skvladd1f5fda2017-02-03 16:54:05 -08001950
1951 if (modified_config.ice_check_min_interval !=
1952 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001953 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001954 }
1955
deadbeef293e9262017-01-11 12:28:30 -08001956 configuration_ = modified_config;
1957 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001958}
1959
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960bool PeerConnection::AddIceCandidate(
1961 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001962 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001963 if (IsClosed()) {
1964 return false;
1965 }
Steve Antond25da372017-11-06 14:50:29 -08001966
1967 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001968 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1969 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001970 return false;
1971 }
1972
1973 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001974 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001975 return false;
1976 }
1977
1978 bool valid = false;
1979 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1980 if (!valid) {
1981 return false;
1982 }
1983
1984 // Add this candidate to the remote session description.
1985 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001986 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001987 return false;
1988 }
1989
1990 if (ready) {
1991 return UseCandidate(ice_candidate);
1992 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001993 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001994 return true;
1995 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001996}
1997
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001998bool PeerConnection::RemoveIceCandidates(
1999 const std::vector<cricket::Candidate>& candidates) {
2000 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002001 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002002 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2003 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002004 return false;
2005 }
2006
2007 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002008 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002009 return false;
2010 }
2011
2012 size_t number_removed =
2013 mutable_remote_description()->RemoveCandidates(candidates);
2014 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002015 RTC_LOG(LS_ERROR)
2016 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2017 << "Requested " << candidates.size() << " but only " << number_removed
2018 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002019 }
2020
2021 // Remove the candidates from the transport controller.
2022 std::string error;
2023 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2024 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002025 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002026 }
2027 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002028}
2029
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002030void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002031 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002032 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002033
Steve Anton75737c02017-11-06 10:37:17 -08002034 if (transport_controller()) {
2035 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002036 }
2037
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002038 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002039 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002040 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002041 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002042 uma_observer_->IncrementEnumCounter(
2043 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2044 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002045 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002046 uma_observer_->IncrementEnumCounter(
2047 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2048 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002049 }
2050 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002051}
2052
zstein4b979802017-06-02 14:37:37 -07002053RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002054 if (!worker_thread()->IsCurrent()) {
2055 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002056 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2057 }
2058
2059 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2060 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2061 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2062 if (has_min && *bitrate.min_bitrate_bps < 0) {
2063 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2064 "min_bitrate_bps <= 0");
2065 }
2066 if (has_current) {
2067 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2068 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2069 "current_bitrate_bps < min_bitrate_bps");
2070 } else if (*bitrate.current_bitrate_bps < 0) {
2071 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2072 "curent_bitrate_bps < 0");
2073 }
2074 }
2075 if (has_max) {
2076 if (has_current &&
2077 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2078 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2079 "max_bitrate_bps < current_bitrate_bps");
2080 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2081 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2082 "max_bitrate_bps < min_bitrate_bps");
2083 } else if (*bitrate.max_bitrate_bps < 0) {
2084 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2085 "max_bitrate_bps < 0");
2086 }
2087 }
2088
2089 Call::Config::BitrateConfigMask mask;
2090 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2091 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2092 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2093
2094 RTC_DCHECK(call_.get());
2095 call_->SetBitrateConfigMask(mask);
2096
2097 return RTCError::OK();
2098}
2099
Alex Narest78609d52017-10-20 10:37:47 +02002100void PeerConnection::SetBitrateAllocationStrategy(
2101 std::unique_ptr<rtc::BitrateAllocationStrategy>
2102 bitrate_allocation_strategy) {
2103 rtc::Thread* worker_thread = factory_->worker_thread();
2104 if (!worker_thread->IsCurrent()) {
2105 rtc::BitrateAllocationStrategy* strategy_raw =
2106 bitrate_allocation_strategy.release();
2107 auto functor = [this, strategy_raw]() {
2108 call_->SetBitrateAllocationStrategy(
2109 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2110 };
2111 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2112 return;
2113 }
2114 RTC_DCHECK(call_.get());
2115 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2116}
2117
henrika5f6bf242017-11-01 11:06:56 +01002118void PeerConnection::SetAudioPlayout(bool playout) {
2119 if (!worker_thread()->IsCurrent()) {
2120 worker_thread()->Invoke<void>(
2121 RTC_FROM_HERE,
2122 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2123 return;
2124 }
2125 auto audio_state =
2126 factory_->channel_manager()->media_engine()->GetAudioState();
2127 audio_state->SetPlayout(playout);
2128}
2129
2130void PeerConnection::SetAudioRecording(bool recording) {
2131 if (!worker_thread()->IsCurrent()) {
2132 worker_thread()->Invoke<void>(
2133 RTC_FROM_HERE,
2134 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2135 return;
2136 }
2137 auto audio_state =
2138 factory_->channel_manager()->media_engine()->GetAudioState();
2139 audio_state->SetRecording(recording);
2140}
2141
Steve Anton8c0f7a72017-10-03 10:03:10 -07002142std::unique_ptr<rtc::SSLCertificate>
2143PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002144 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002145 return nullptr;
2146 }
Steve Anton75737c02017-11-06 10:37:17 -08002147 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002148}
2149
ivoc14d5dbe2016-07-04 07:06:55 -07002150bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2151 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002152 // TODO(eladalon): It would be better to not allow negative values into PC.
2153 const size_t max_size = (max_size_bytes < 0)
2154 ? RtcEventLog::kUnlimitedOutput
2155 : rtc::saturated_cast<size_t>(max_size_bytes);
2156 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002157 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2158 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002159}
2160
Bjorn Tereliusde939432017-11-20 17:38:14 +01002161bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2162 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002163 // TODO(eladalon): In C++14, this can be done with a lambda.
2164 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002165 bool operator()() {
2166 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2167 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002168 PeerConnection* const pc;
2169 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002170 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002171 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002172 return worker_thread()->Invoke<bool>(
2173 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002174}
2175
2176void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002177 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002178 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2179}
2180
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002181const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002182 return pending_local_description_ ? pending_local_description_.get()
2183 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002184}
2185
2186const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002187 return pending_remote_description_ ? pending_remote_description_.get()
2188 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189}
2190
deadbeeffe4a8a42016-12-20 17:56:17 -08002191const SessionDescriptionInterface* PeerConnection::current_local_description()
2192 const {
Steve Anton75737c02017-11-06 10:37:17 -08002193 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002194}
2195
2196const SessionDescriptionInterface* PeerConnection::current_remote_description()
2197 const {
Steve Anton75737c02017-11-06 10:37:17 -08002198 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002199}
2200
2201const SessionDescriptionInterface* PeerConnection::pending_local_description()
2202 const {
Steve Anton75737c02017-11-06 10:37:17 -08002203 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002204}
2205
2206const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2207 const {
Steve Anton75737c02017-11-06 10:37:17 -08002208 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002209}
2210
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002211void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002212 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213 // Update stats here so that we have the most recent stats for tracks and
2214 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002215 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002216
Steve Anton75737c02017-11-06 10:37:17 -08002217 ChangeSignalingState(PeerConnectionInterface::kClosed);
2218 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002219 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2220 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002221 RTC_DCHECK(!rtp_data_channel_);
2222 RTC_DCHECK(!sctp_transport_);
2223
deadbeef42a42632017-03-10 15:18:00 -08002224 network_thread()->Invoke<void>(
2225 RTC_FROM_HERE,
2226 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2227 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002228
Steve Anton978b8762017-09-29 12:15:02 -07002229 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002230 call_.reset();
2231 // The event log must outlive call (and any other object that uses it).
2232 event_log_.reset();
2233 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002234}
2235
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002236void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002237 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002238 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2239 SetSessionDescriptionMsg* param =
2240 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2241 param->observer->OnSuccess();
2242 delete param;
2243 break;
2244 }
2245 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2246 SetSessionDescriptionMsg* param =
2247 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2248 param->observer->OnFailure(param->error);
2249 delete param;
2250 break;
2251 }
deadbeefab9b2d12015-10-14 11:33:11 -07002252 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2253 CreateSessionDescriptionMsg* param =
2254 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2255 param->observer->OnFailure(param->error);
2256 delete param;
2257 break;
2258 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 case MSG_GETSTATS: {
2260 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002261 StatsReports reports;
2262 stats_->GetStats(param->track, &reports);
2263 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002264 delete param;
2265 break;
2266 }
deadbeefbd292462015-12-14 18:15:29 -08002267 case MSG_FREE_DATACHANNELS: {
2268 sctp_data_channels_to_free_.clear();
2269 break;
2270 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002271 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002272 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002273 break;
2274 }
2275}
2276
Steve Anton4171afb2017-11-20 10:20:22 -08002277void PeerConnection::CreateAudioReceiver(
2278 MediaStreamInterface* stream,
2279 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002280 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2281 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002282 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2283 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002284 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002285 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002286 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002287 stream->AddTrack(
2288 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002289 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002290 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002291}
2292
Steve Anton4171afb2017-11-20 10:20:22 -08002293void PeerConnection::CreateVideoReceiver(
2294 MediaStreamInterface* stream,
2295 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002296 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2297 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002298 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2299 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002300 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002301 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2302 worker_thread(), remote_sender_info.first_ssrc,
2303 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002304 stream->AddTrack(
2305 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002306 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002307 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002308}
2309
deadbeef70ab1a12015-09-28 16:53:55 -07002310// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2311// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002312rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002313 const RtpSenderInfo& remote_sender_info) {
2314 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2315 if (!receiver) {
2316 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2317 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002318 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002319 }
Steve Anton4171afb2017-11-20 10:20:22 -08002320 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2321 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2322 } else {
2323 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2324 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002325 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002326}
2327
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002328void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2329 MediaStreamInterface* stream) {
2330 RTC_DCHECK(!IsClosed());
2331 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002332 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002333 // We already have a sender for this track, so just change the stream_id
2334 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002335 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002336 return;
2337 }
2338
2339 // Normal case; we've never seen this track before.
2340 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2341 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2342 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002343 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2344 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002345 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002346 // If the sender has already been configured in SDP, we call SetSsrc,
2347 // which will connect the sender to the underlying transport. This can
2348 // occur if a local session description that contains the ID of the sender
2349 // is set before AddStream is called. It can also occur if the local
2350 // session description is not changed and RemoveStream is called, and
2351 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002352 const RtpSenderInfo* sender_info =
2353 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2354 if (sender_info) {
2355 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002356 }
2357}
2358
2359// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2360// indefinitely, when we have unified plan SDP.
2361void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2362 MediaStreamInterface* stream) {
2363 RTC_DCHECK(!IsClosed());
2364 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002365 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002366 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2367 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002368 return;
2369 }
Steve Anton4171afb2017-11-20 10:20:22 -08002370 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002371}
2372
2373void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2374 MediaStreamInterface* stream) {
2375 RTC_DCHECK(!IsClosed());
2376 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002377 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002378 // We already have a sender for this track, so just change the stream_id
2379 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002380 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002381 return;
2382 }
2383
2384 // Normal case; we've never seen this track before.
2385 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2386 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002387 signaling_thread(),
2388 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002389 GetVideoTransceiver()->internal()->AddSender(new_sender);
2390 const RtpSenderInfo* sender_info =
2391 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2392 if (sender_info) {
2393 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002394 }
2395}
2396
2397void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2398 MediaStreamInterface* stream) {
2399 RTC_DCHECK(!IsClosed());
2400 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002401 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002402 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2403 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002404 return;
2405 }
Steve Anton4171afb2017-11-20 10:20:22 -08002406 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002407}
2408
Steve Antonba818672017-11-06 10:21:57 -08002409void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002410 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002411 if (ice_connection_state_ == new_state) {
2412 return;
2413 }
2414
deadbeefcbecd352015-09-23 11:50:27 -07002415 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002416 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002417 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002418 return;
2419 }
Steve Antonba818672017-11-06 10:21:57 -08002420
Mirko Bonadei675513b2017-11-09 11:09:25 +01002421 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2422 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002423 RTC_DCHECK(ice_connection_state_ !=
2424 PeerConnectionInterface::kIceConnectionClosed);
2425
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002426 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002427 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002428}
2429
2430void PeerConnection::OnIceGatheringChange(
2431 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002432 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002433 if (IsClosed()) {
2434 return;
2435 }
2436 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002437 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002438}
2439
jbauch81bf7b02017-03-25 08:31:12 -07002440void PeerConnection::OnIceCandidate(
2441 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002442 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002443 if (IsClosed()) {
2444 return;
2445 }
jbauch81bf7b02017-03-25 08:31:12 -07002446 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002447}
2448
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002449void PeerConnection::OnIceCandidatesRemoved(
2450 const std::vector<cricket::Candidate>& candidates) {
2451 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002452 if (IsClosed()) {
2453 return;
2454 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002455 observer_->OnIceCandidatesRemoved(candidates);
2456}
2457
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002458void PeerConnection::ChangeSignalingState(
2459 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002460 RTC_DCHECK(signaling_thread()->IsCurrent());
2461 if (signaling_state_ == signaling_state) {
2462 return;
2463 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002464 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2465 << GetSignalingStateString(signaling_state_)
2466 << " New state: "
2467 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002468 signaling_state_ = signaling_state;
2469 if (signaling_state == kClosed) {
2470 ice_connection_state_ = kIceConnectionClosed;
2471 observer_->OnIceConnectionChange(ice_connection_state_);
2472 if (ice_gathering_state_ != kIceGatheringComplete) {
2473 ice_gathering_state_ = kIceGatheringComplete;
2474 observer_->OnIceGatheringChange(ice_gathering_state_);
2475 }
2476 }
2477 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002478}
2479
deadbeefeb459812015-12-15 19:24:43 -08002480void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2481 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002482 if (IsClosed()) {
2483 return;
2484 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002485 AddAudioTrack(track, stream);
2486 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002487}
2488
deadbeefeb459812015-12-15 19:24:43 -08002489void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2490 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002491 if (IsClosed()) {
2492 return;
2493 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002494 RemoveAudioTrack(track, stream);
2495 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002496}
2497
2498void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2499 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002500 if (IsClosed()) {
2501 return;
2502 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002503 AddVideoTrack(track, stream);
2504 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002505}
2506
2507void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2508 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002509 if (IsClosed()) {
2510 return;
2511 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002512 RemoveVideoTrack(track, stream);
2513 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002514}
2515
Henrik Boström31638672017-11-23 17:48:32 +01002516void PeerConnection::PostSetSessionDescriptionSuccess(
2517 SetSessionDescriptionObserver* observer) {
2518 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2519 signaling_thread()->Post(RTC_FROM_HERE, this,
2520 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2521}
2522
deadbeefab9b2d12015-10-14 11:33:11 -07002523void PeerConnection::PostSetSessionDescriptionFailure(
2524 SetSessionDescriptionObserver* observer,
2525 const std::string& error) {
2526 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2527 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002528 signaling_thread()->Post(RTC_FROM_HERE, this,
2529 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002530}
2531
2532void PeerConnection::PostCreateSessionDescriptionFailure(
2533 CreateSessionDescriptionObserver* observer,
2534 const std::string& error) {
2535 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2536 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002537 signaling_thread()->Post(RTC_FROM_HERE, this,
2538 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002539}
2540
zhihuang1c378ed2017-08-17 14:10:50 -07002541void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002542 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2543 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002544 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2545
2546 // Figure out transceiver directional preferences.
2547 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2548 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2549
2550 // By default, generate sendrecv/recvonly m= sections.
2551 bool recv_audio = true;
2552 bool recv_video = true;
2553
2554 // By default, only offer a new m= section if we have media to send with it.
2555 bool offer_new_audio_description = send_audio;
2556 bool offer_new_video_description = send_video;
2557 bool offer_new_data_description = HasDataChannels();
2558
2559 // The "offer_to_receive_X" options allow those defaults to be overridden.
2560 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2561 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2562 offer_new_audio_description =
2563 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2564 }
2565 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2566 recv_video = (rtc_options.offer_to_receive_video > 0);
2567 offer_new_video_description =
2568 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2569 }
2570
2571 rtc::Optional<size_t> audio_index;
2572 rtc::Optional<size_t> video_index;
2573 rtc::Optional<size_t> data_index;
2574 // If a current description exists, generate m= sections in the same order,
2575 // using the first audio/video/data section that appears and rejecting
2576 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002577 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002578 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002579 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002580 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2581 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2582 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002583 }
2584
zhihuang1c378ed2017-08-17 14:10:50 -07002585 // Add audio/video/data m= sections to the end if needed.
2586 if (!audio_index && offer_new_audio_description) {
2587 session_options->media_description_options.push_back(
2588 cricket::MediaDescriptionOptions(
2589 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002590 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2591 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002592 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002593 }
zhihuang1c378ed2017-08-17 14:10:50 -07002594 if (!video_index && offer_new_video_description) {
2595 session_options->media_description_options.push_back(
2596 cricket::MediaDescriptionOptions(
2597 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002598 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2599 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002600 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002601 }
zhihuang1c378ed2017-08-17 14:10:50 -07002602 if (!data_index && offer_new_data_description) {
2603 session_options->media_description_options.push_back(
2604 cricket::MediaDescriptionOptions(
2605 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002606 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002607 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002608 }
2609
2610 cricket::MediaDescriptionOptions* audio_media_description_options =
2611 !audio_index ? nullptr
2612 : &session_options->media_description_options[*audio_index];
2613 cricket::MediaDescriptionOptions* video_media_description_options =
2614 !video_index ? nullptr
2615 : &session_options->media_description_options[*video_index];
2616 cricket::MediaDescriptionOptions* data_media_description_options =
2617 !data_index ? nullptr
2618 : &session_options->media_description_options[*data_index];
2619
2620 // Apply ICE restart flag and renomination flag.
2621 for (auto& options : session_options->media_description_options) {
2622 options.transport_options.ice_restart = rtc_options.ice_restart;
2623 options.transport_options.enable_ice_renomination =
2624 configuration_.enable_ice_renomination;
2625 }
2626
Steve Anton4171afb2017-11-20 10:20:22 -08002627 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002628 video_media_description_options);
2629 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002630
zhihuang9763d562016-08-05 11:14:50 -07002631 // Intentionally unset the data channel type for RTP data channel with the
2632 // second condition. Otherwise the RTP data channels would be successfully
2633 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2634 // when building with chromium. We want to leave RTP data channels broken, so
2635 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002636 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2637 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002638 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002639
2640 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002641 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002642}
2643
zhihuang1c378ed2017-08-17 14:10:50 -07002644void PeerConnection::GetOptionsForAnswer(
2645 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002646 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002647 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002648
zhihuang1c378ed2017-08-17 14:10:50 -07002649 // Figure out transceiver directional preferences.
2650 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2651 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2652
2653 // By default, generate sendrecv/recvonly m= sections. The direction is also
2654 // restricted by the direction in the offer.
2655 bool recv_audio = true;
2656 bool recv_video = true;
2657
2658 // The "offer_to_receive_X" options allow those defaults to be overridden.
2659 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2660 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002661 }
zhihuang1c378ed2017-08-17 14:10:50 -07002662 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2663 recv_video = (rtc_options.offer_to_receive_video > 0);
2664 }
2665
2666 rtc::Optional<size_t> audio_index;
2667 rtc::Optional<size_t> video_index;
2668 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002669 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002670 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002671 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002672 SessionDescriptionInterface::kOffer);
2673 // Generate m= sections that match those in the offer.
2674 // Note that mediasession.cc will handle intersection our preferred
2675 // direction with the offered direction.
2676 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002677 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002678 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2679 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2680 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002681 }
zhihuang1c378ed2017-08-17 14:10:50 -07002682
2683 cricket::MediaDescriptionOptions* audio_media_description_options =
2684 !audio_index ? nullptr
2685 : &session_options->media_description_options[*audio_index];
2686 cricket::MediaDescriptionOptions* video_media_description_options =
2687 !video_index ? nullptr
2688 : &session_options->media_description_options[*video_index];
2689 cricket::MediaDescriptionOptions* data_media_description_options =
2690 !data_index ? nullptr
2691 : &session_options->media_description_options[*data_index];
2692
2693 // Apply ICE renomination flag.
2694 for (auto& options : session_options->media_description_options) {
2695 options.transport_options.enable_ice_renomination =
2696 configuration_.enable_ice_renomination;
2697 }
2698
Steve Anton4171afb2017-11-20 10:20:22 -08002699 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002700 video_media_description_options);
2701 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2702
zhihuang9763d562016-08-05 11:14:50 -07002703 // Intentionally unset the data channel type for RTP data channel. Otherwise
2704 // the RTP data channels would be successfully negotiated by default and the
2705 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2706 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002707 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2708 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002709 }
zhihuangaf388472016-11-02 16:49:48 -07002710
zhihuang1c378ed2017-08-17 14:10:50 -07002711 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002712 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002713}
2714
zhihuang1c378ed2017-08-17 14:10:50 -07002715void PeerConnection::GenerateMediaDescriptionOptions(
2716 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002717 RtpTransceiverDirection audio_direction,
2718 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002719 rtc::Optional<size_t>* audio_index,
2720 rtc::Optional<size_t>* video_index,
2721 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002722 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002723 for (const cricket::ContentInfo& content :
2724 session_desc->description()->contents()) {
2725 if (IsAudioContent(&content)) {
2726 // If we already have an audio m= section, reject this extra one.
2727 if (*audio_index) {
2728 session_options->media_description_options.push_back(
2729 cricket::MediaDescriptionOptions(
2730 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002731 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002732 } else {
2733 session_options->media_description_options.push_back(
2734 cricket::MediaDescriptionOptions(
2735 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002736 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002737 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002738 }
2739 } else if (IsVideoContent(&content)) {
2740 // If we already have an video m= section, reject this extra one.
2741 if (*video_index) {
2742 session_options->media_description_options.push_back(
2743 cricket::MediaDescriptionOptions(
2744 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002745 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002746 } else {
2747 session_options->media_description_options.push_back(
2748 cricket::MediaDescriptionOptions(
2749 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002750 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002751 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002752 }
2753 } else {
2754 RTC_DCHECK(IsDataContent(&content));
2755 // If we already have an data m= section, reject this extra one.
2756 if (*data_index) {
2757 session_options->media_description_options.push_back(
2758 cricket::MediaDescriptionOptions(
2759 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002760 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002761 } else {
2762 session_options->media_description_options.push_back(
2763 cricket::MediaDescriptionOptions(
2764 cricket::MEDIA_TYPE_DATA, content.name,
2765 // Direction for data sections is meaningless, but legacy
2766 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002767 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002768 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002769 }
2770 }
htaa2a49d92016-03-04 02:51:39 -08002771 }
deadbeefab9b2d12015-10-14 11:33:11 -07002772}
2773
Steve Anton4171afb2017-11-20 10:20:22 -08002774void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2775 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2776 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002777 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002778}
2779
Steve Anton4171afb2017-11-20 10:20:22 -08002780void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002781 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002782 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002783 cricket::MediaType media_type,
2784 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002785 std::vector<RtpSenderInfo>* current_senders =
2786 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002787
Steve Anton4171afb2017-11-20 10:20:22 -08002788 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002789 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002790 for (auto sender_it = current_senders->begin();
2791 sender_it != current_senders->end();
2792 /* incremented manually */) {
2793 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002794 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002795 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2796 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002797 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002798 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2799 sender_exists) {
2800 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002801 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002802 OnRemoteSenderRemoved(info, media_type);
2803 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002804 }
2805 }
2806
Steve Anton4171afb2017-11-20 10:20:22 -08002807 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002808 for (const cricket::StreamParams& params : streams) {
2809 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002810 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002811 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002812 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002813 uint32_t ssrc = params.first_ssrc();
2814
2815 rtc::scoped_refptr<MediaStreamInterface> stream =
2816 remote_streams_->find(stream_label);
2817 if (!stream) {
2818 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002819 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2820 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002821 remote_streams_->AddStream(stream);
2822 new_streams->AddStream(stream);
2823 }
2824
Steve Anton4171afb2017-11-20 10:20:22 -08002825 const RtpSenderInfo* sender_info =
2826 FindSenderInfo(*current_senders, stream_label, sender_id);
2827 if (!sender_info) {
2828 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2829 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002830 }
2831 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002832
Steve Anton4171afb2017-11-20 10:20:22 -08002833 // Add default sender if necessary.
2834 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002835 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2836 remote_streams_->find(kDefaultStreamLabel);
2837 if (!default_stream) {
2838 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002839 default_stream = MediaStreamProxy::Create(
2840 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002841 remote_streams_->AddStream(default_stream);
2842 new_streams->AddStream(default_stream);
2843 }
Steve Anton4171afb2017-11-20 10:20:22 -08002844 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2845 ? kDefaultAudioSenderId
2846 : kDefaultVideoSenderId;
2847 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2848 *current_senders, kDefaultStreamLabel, default_sender_id);
2849 if (!default_sender_info) {
2850 current_senders->push_back(
2851 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2852 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002853 }
2854 }
deadbeefab9b2d12015-10-14 11:33:11 -07002855}
2856
Steve Anton4171afb2017-11-20 10:20:22 -08002857void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2858 cricket::MediaType media_type) {
2859 MediaStreamInterface* stream =
2860 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002861
2862 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002863 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002864 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002865 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002866 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002867 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002868 }
2869}
2870
Steve Anton4171afb2017-11-20 10:20:22 -08002871void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2872 cricket::MediaType media_type) {
2873 MediaStreamInterface* stream =
2874 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002875
Henrik Boström933d8b02017-10-10 10:05:16 -07002876 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002877 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002878 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2879 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002880 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002881 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002882 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002883 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002884 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002885 }
2886 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002887 // Stopping or destroying a VideoRtpReceiver will end the
2888 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002889 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002890 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002891 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002892 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002893 // There's no guarantee the track is still available, e.g. the track may
2894 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002895 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002896 }
2897 } else {
nisseede5da42017-01-12 05:15:36 -08002898 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002899 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002900 if (receiver) {
2901 observer_->OnRemoveTrack(receiver);
2902 }
deadbeefab9b2d12015-10-14 11:33:11 -07002903}
2904
2905void PeerConnection::UpdateEndedRemoteMediaStreams() {
2906 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2907 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2908 MediaStreamInterface* stream = remote_streams_->at(i);
2909 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2910 streams_to_remove.push_back(stream);
2911 }
2912 }
2913
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002914 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002915 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002916 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002917 }
2918}
2919
Steve Anton4171afb2017-11-20 10:20:22 -08002920void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002921 const std::vector<cricket::StreamParams>& streams,
2922 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002923 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002924
2925 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2926 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002927 for (auto sender_it = current_senders->begin();
2928 sender_it != current_senders->end();
2929 /* incremented manually */) {
2930 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002931 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002932 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2933 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002934 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002935 OnLocalSenderRemoved(info, media_type);
2936 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002937 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002938 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002939 }
2940 }
2941
Steve Anton4171afb2017-11-20 10:20:22 -08002942 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002943 for (const cricket::StreamParams& params : streams) {
2944 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002945 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002946 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002947 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002948 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002949 const RtpSenderInfo* sender_info =
2950 FindSenderInfo(*current_senders, stream_label, sender_id);
2951 if (!sender_info) {
2952 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2953 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002954 }
2955 }
2956}
2957
Steve Anton4171afb2017-11-20 10:20:22 -08002958void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2959 cricket::MediaType media_type) {
2960 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002961 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002962 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2963 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002964 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002965 return;
2966 }
2967
deadbeeffac06552015-11-25 11:26:01 -08002968 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002969 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2970 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002971 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002972 }
deadbeeffac06552015-11-25 11:26:01 -08002973
Steve Anton4171afb2017-11-20 10:20:22 -08002974 sender->internal()->set_stream_id(sender_info.stream_label);
2975 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002976}
2977
Steve Anton4171afb2017-11-20 10:20:22 -08002978void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2979 cricket::MediaType media_type) {
2980 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002981 if (!sender) {
2982 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002983 // SessionDescriptions has been renegotiated.
2984 return;
2985 }
deadbeeffac06552015-11-25 11:26:01 -08002986
2987 // A sender has been removed from the SessionDescription but it's still
2988 // associated with the PeerConnection. This only occurs if the SDP doesn't
2989 // match with the calls to CreateSender, AddStream and RemoveStream.
2990 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002991 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2992 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002993 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002994 }
deadbeeffac06552015-11-25 11:26:01 -08002995
Steve Anton4171afb2017-11-20 10:20:22 -08002996 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002997}
2998
2999void PeerConnection::UpdateLocalRtpDataChannels(
3000 const cricket::StreamParamsVec& streams) {
3001 std::vector<std::string> existing_channels;
3002
3003 // Find new and active data channels.
3004 for (const cricket::StreamParams& params : streams) {
3005 // |it->sync_label| is actually the data channel label. The reason is that
3006 // we use the same naming of data channels as we do for
3007 // MediaStreams and Tracks.
3008 // For MediaStreams, the sync_label is the MediaStream label and the
3009 // track label is the same as |streamid|.
3010 const std::string& channel_label = params.sync_label;
3011 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003012 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003013 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003014 continue;
3015 }
3016 // Set the SSRC the data channel should use for sending.
3017 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3018 existing_channels.push_back(data_channel_it->first);
3019 }
3020
3021 UpdateClosingRtpDataChannels(existing_channels, true);
3022}
3023
3024void PeerConnection::UpdateRemoteRtpDataChannels(
3025 const cricket::StreamParamsVec& streams) {
3026 std::vector<std::string> existing_channels;
3027
3028 // Find new and active data channels.
3029 for (const cricket::StreamParams& params : streams) {
3030 // The data channel label is either the mslabel or the SSRC if the mslabel
3031 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3032 std::string label = params.sync_label.empty()
3033 ? rtc::ToString(params.first_ssrc())
3034 : params.sync_label;
3035 auto data_channel_it = rtp_data_channels_.find(label);
3036 if (data_channel_it == rtp_data_channels_.end()) {
3037 // This is a new data channel.
3038 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3039 } else {
3040 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3041 }
3042 existing_channels.push_back(label);
3043 }
3044
3045 UpdateClosingRtpDataChannels(existing_channels, false);
3046}
3047
3048void PeerConnection::UpdateClosingRtpDataChannels(
3049 const std::vector<std::string>& active_channels,
3050 bool is_local_update) {
3051 auto it = rtp_data_channels_.begin();
3052 while (it != rtp_data_channels_.end()) {
3053 DataChannel* data_channel = it->second;
3054 if (std::find(active_channels.begin(), active_channels.end(),
3055 data_channel->label()) != active_channels.end()) {
3056 ++it;
3057 continue;
3058 }
3059
3060 if (is_local_update) {
3061 data_channel->SetSendSsrc(0);
3062 } else {
3063 data_channel->RemotePeerRequestClose();
3064 }
3065
3066 if (data_channel->state() == DataChannel::kClosed) {
3067 rtp_data_channels_.erase(it);
3068 it = rtp_data_channels_.begin();
3069 } else {
3070 ++it;
3071 }
3072 }
3073}
3074
3075void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3076 uint32_t remote_ssrc) {
3077 rtc::scoped_refptr<DataChannel> channel(
3078 InternalCreateDataChannel(label, nullptr));
3079 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003080 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3081 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003082 return;
3083 }
3084 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003085 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3086 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003087 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003088}
3089
3090rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3091 const std::string& label,
3092 const InternalDataChannelInit* config) {
3093 if (IsClosed()) {
3094 return nullptr;
3095 }
Steve Anton75737c02017-11-06 10:37:17 -08003096 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003097 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003098 << "InternalCreateDataChannel: Data is not supported in this call.";
3099 return nullptr;
3100 }
3101 InternalDataChannelInit new_config =
3102 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003103 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003104 if (new_config.id < 0) {
3105 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003106 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003107 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003108 RTC_LOG(LS_ERROR)
3109 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003110 return nullptr;
3111 }
3112 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003113 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3114 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003115 return nullptr;
3116 }
3117 }
3118
Steve Anton75737c02017-11-06 10:37:17 -08003119 rtc::scoped_refptr<DataChannel> channel(
3120 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003121 if (!channel) {
3122 sid_allocator_.ReleaseSid(new_config.id);
3123 return nullptr;
3124 }
3125
3126 if (channel->data_channel_type() == cricket::DCT_RTP) {
3127 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003128 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3129 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003130 return nullptr;
3131 }
3132 rtp_data_channels_[channel->label()] = channel;
3133 } else {
3134 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3135 sctp_data_channels_.push_back(channel);
3136 channel->SignalClosed.connect(this,
3137 &PeerConnection::OnSctpDataChannelClosed);
3138 }
3139
hbos82ebe022016-11-14 01:41:09 -08003140 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003141 return channel;
3142}
3143
3144bool PeerConnection::HasDataChannels() const {
3145 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3146}
3147
3148void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3149 for (const auto& channel : sctp_data_channels_) {
3150 if (channel->id() < 0) {
3151 int sid;
3152 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003153 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003154 continue;
3155 }
3156 channel->SetSctpSid(sid);
3157 }
3158 }
3159}
3160
3161void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003162 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003163 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3164 ++it) {
3165 if (it->get() == channel) {
3166 if (channel->id() >= 0) {
3167 sid_allocator_.ReleaseSid(channel->id());
3168 }
deadbeefbd292462015-12-14 18:15:29 -08003169 // Since this method is triggered by a signal from the DataChannel,
3170 // we can't free it directly here; we need to free it asynchronously.
3171 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003172 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003173 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3174 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003175 return;
3176 }
3177 }
3178}
3179
deadbeefab9b2d12015-10-14 11:33:11 -07003180void PeerConnection::OnDataChannelDestroyed() {
3181 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3182 // DataChannel may callback to us and try to modify the list.
3183 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3184 temp_rtp_dcs.swap(rtp_data_channels_);
3185 for (const auto& kv : temp_rtp_dcs) {
3186 kv.second->OnTransportChannelDestroyed();
3187 }
3188
3189 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3190 temp_sctp_dcs.swap(sctp_data_channels_);
3191 for (const auto& channel : temp_sctp_dcs) {
3192 channel->OnTransportChannelDestroyed();
3193 }
3194}
3195
3196void PeerConnection::OnDataChannelOpenMessage(
3197 const std::string& label,
3198 const InternalDataChannelInit& config) {
3199 rtc::scoped_refptr<DataChannel> channel(
3200 InternalCreateDataChannel(label, &config));
3201 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003202 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003203 return;
3204 }
3205
deadbeefa601f5c2016-06-06 14:27:39 -07003206 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3207 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003208 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003209}
3210
Steve Anton4171afb2017-11-20 10:20:22 -08003211rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3212PeerConnection::GetAudioTransceiver() const {
3213 // This method only works with Plan B SDP, where there is a single
3214 // audio/video transceiver.
3215 RTC_DCHECK(!IsUnifiedPlan());
3216 for (auto transceiver : transceivers_) {
3217 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3218 return transceiver;
3219 }
3220 }
3221 RTC_NOTREACHED();
3222 return nullptr;
3223}
3224
3225rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3226PeerConnection::GetVideoTransceiver() const {
3227 // This method only works with Plan B SDP, where there is a single
3228 // audio/video transceiver.
3229 RTC_DCHECK(!IsUnifiedPlan());
3230 for (auto transceiver : transceivers_) {
3231 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3232 return transceiver;
3233 }
3234 }
3235 RTC_NOTREACHED();
3236 return nullptr;
3237}
3238
3239// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3240// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003241bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003242 switch (type) {
3243 case cricket::MEDIA_TYPE_AUDIO:
3244 return !GetAudioTransceiver()->internal()->senders().empty();
3245 case cricket::MEDIA_TYPE_VIDEO:
3246 return !GetVideoTransceiver()->internal()->senders().empty();
3247 case cricket::MEDIA_TYPE_DATA:
3248 return false;
3249 }
3250 RTC_NOTREACHED();
3251 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003252}
3253
Steve Anton4171afb2017-11-20 10:20:22 -08003254rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3255PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3256 for (auto transceiver : transceivers_) {
3257 for (auto sender : transceiver->internal()->senders()) {
3258 if (sender->track() == track) {
3259 return sender;
3260 }
3261 }
3262 }
3263 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003264}
3265
Steve Anton4171afb2017-11-20 10:20:22 -08003266rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3267PeerConnection::FindSenderById(const std::string& sender_id) const {
3268 for (auto transceiver : transceivers_) {
3269 for (auto sender : transceiver->internal()->senders()) {
3270 if (sender->id() == sender_id) {
3271 return sender;
3272 }
3273 }
3274 }
3275 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003276}
3277
Steve Anton4171afb2017-11-20 10:20:22 -08003278rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3279PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3280 for (auto transceiver : transceivers_) {
3281 for (auto receiver : transceiver->internal()->receivers()) {
3282 if (receiver->id() == receiver_id) {
3283 return receiver;
3284 }
3285 }
3286 }
3287 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003288}
3289
Steve Anton4171afb2017-11-20 10:20:22 -08003290std::vector<PeerConnection::RtpSenderInfo>*
3291PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3292 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3293 media_type == cricket::MEDIA_TYPE_VIDEO);
3294 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3295 ? &remote_audio_sender_infos_
3296 : &remote_video_sender_infos_;
3297}
3298
3299std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003300 cricket::MediaType media_type) {
3301 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3302 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003303 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3304 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003305}
3306
Steve Anton4171afb2017-11-20 10:20:22 -08003307const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3308 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003309 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003310 const std::string sender_id) const {
3311 for (const RtpSenderInfo& sender_info : infos) {
3312 if (sender_info.stream_label == stream_label &&
3313 sender_info.sender_id == sender_id) {
3314 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003315 }
3316 }
3317 return nullptr;
3318}
3319
3320DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3321 for (const auto& channel : sctp_data_channels_) {
3322 if (channel->id() == sid) {
3323 return channel;
3324 }
3325 }
3326 return nullptr;
3327}
3328
deadbeef91dd5672016-05-18 16:55:30 -07003329bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003330 const RTCConfiguration& configuration) {
3331 cricket::ServerAddresses stun_servers;
3332 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003333 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3334 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003335 return false;
3336 }
3337
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003338 port_allocator_->Initialize();
3339
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003340 // To handle both internal and externally created port allocator, we will
3341 // enable BUNDLE here.
3342 int portallocator_flags = port_allocator_->flags();
3343 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003344 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3345 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003346 // If the disable-IPv6 flag was specified, we'll not override it
3347 // by experiment.
3348 if (configuration.disable_ipv6) {
3349 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003350 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3351 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003352 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3353 }
3354
zhihuangb09b3f92017-03-07 14:40:51 -08003355 if (configuration.disable_ipv6_on_wifi) {
3356 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003357 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003358 }
3359
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003360 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3361 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003362 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003363 }
3364
honghaiz60347052016-05-31 18:29:12 -07003365 if (configuration.candidate_network_policy ==
3366 kCandidateNetworkPolicyLowCost) {
3367 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003368 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003369 }
3370
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003371 port_allocator_->set_flags(portallocator_flags);
3372 // No step delay is used while allocating ports.
3373 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3374 port_allocator_->set_candidate_filter(
3375 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003376 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003377
3378 // Call this last since it may create pooled allocator sessions using the
3379 // properties set above.
3380 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003381 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003382 configuration.prune_turn_ports,
3383 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003384 return true;
3385}
3386
deadbeef91dd5672016-05-18 16:55:30 -07003387bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003388 const cricket::ServerAddresses& stun_servers,
3389 const std::vector<cricket::RelayServerConfig>& turn_servers,
3390 IceTransportsType type,
3391 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003392 bool prune_turn_ports,
3393 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003394 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003395 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003396 // Call this last since it may create pooled allocator sessions using the
3397 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003398 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003399 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3400 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003401}
3402
Steve Antonba818672017-11-06 10:21:57 -08003403cricket::ChannelManager* PeerConnection::channel_manager() const {
3404 return factory_->channel_manager();
3405}
3406
3407MetricsObserverInterface* PeerConnection::metrics_observer() const {
3408 return uma_observer_;
3409}
3410
Elad Alon99c3fe52017-10-13 16:29:40 +02003411bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003412 std::unique_ptr<RtcEventLogOutput> output,
3413 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003414 if (!event_log_) {
3415 return false;
3416 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003417 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003418}
3419
3420void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003421 if (event_log_) {
3422 event_log_->StopLogging();
3423 }
ivoc14d5dbe2016-07-04 07:06:55 -07003424}
nisseeaabdf62017-05-05 02:23:02 -07003425
Steve Anton75737c02017-11-06 10:37:17 -08003426cricket::BaseChannel* PeerConnection::GetChannel(
3427 const std::string& content_name) {
3428 if (voice_channel() && voice_channel()->content_name() == content_name) {
3429 return voice_channel();
3430 }
3431 if (video_channel() && video_channel()->content_name() == content_name) {
3432 return video_channel();
3433 }
3434 if (rtp_data_channel() &&
3435 rtp_data_channel()->content_name() == content_name) {
3436 return rtp_data_channel();
3437 }
3438 return nullptr;
3439}
3440
3441bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3442 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003443 RTC_LOG(LS_INFO)
3444 << "Local and Remote descriptions must be applied to get the "
3445 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003446 return false;
3447 }
3448 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003449 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3450 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003451 return false;
3452 }
3453
3454 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3455}
3456
3457bool PeerConnection::GetSslRole(const std::string& content_name,
3458 rtc::SSLRole* role) {
3459 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003460 RTC_LOG(LS_INFO)
3461 << "Local and Remote descriptions must be applied to get the "
3462 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003463 return false;
3464 }
3465
3466 return transport_controller_->GetSslRole(GetTransportName(content_name),
3467 role);
3468}
3469
Steve Anton75737c02017-11-06 10:37:17 -08003470// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3471// vector of BaseChannel pointers instead of separate voice and video channel
3472// vectors. At that point, this will become a simple getter.
3473std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3474 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003475 if (voice_channel()) {
3476 channels.push_back(voice_channel());
3477 }
3478 if (video_channel()) {
3479 channels.push_back(video_channel());
3480 }
Steve Anton75737c02017-11-06 10:37:17 -08003481 if (rtp_data_channel_) {
3482 channels.push_back(rtp_data_channel_);
3483 }
3484 return channels;
3485}
3486
Steve Antonf8470812017-12-04 10:46:21 -08003487void PeerConnection::SetSessionError(SessionError error,
3488 const std::string& error_desc) {
3489 RTC_DCHECK_RUN_ON(signaling_thread());
3490 if (error != session_error_) {
3491 session_error_ = error;
3492 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08003493 }
3494}
3495
Steve Anton20393062017-12-04 16:24:52 -08003496RTCError PeerConnection::UpdateSessionState(cricket::ContentAction action,
Steve Anton8a006912017-12-04 15:25:56 -08003497 cricket::ContentSource source) {
3498 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003499
3500 // If there's already a pending error then no state transition should happen.
3501 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08003502 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003503
3504 // If this is an answer then we know whether to BUNDLE or not. If both the
3505 // local and remote side have agreed to BUNDLE, go ahead and enable it.
3506 if (action == cricket::CA_ANSWER) {
Steve Anton75737c02017-11-06 10:37:17 -08003507 const cricket::ContentGroup* local_bundle =
3508 local_description()->description()->GetGroupByName(
3509 cricket::GROUP_TYPE_BUNDLE);
3510 const cricket::ContentGroup* remote_bundle =
3511 remote_description()->description()->GetGroupByName(
3512 cricket::GROUP_TYPE_BUNDLE);
3513 if (local_bundle && remote_bundle) {
3514 // The answerer decides the transport to bundle on.
3515 const cricket::ContentGroup* answer_bundle =
3516 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3517 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08003518 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3519 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08003520 }
3521 }
Steve Anton75737c02017-11-06 10:37:17 -08003522 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003523
3524 // Only push down the transport description after potentially enabling BUNDLE;
3525 // we don't want to push down a description on a transport about to be
3526 // destroyed.
3527 RTCError error = PushdownTransportDescription(source, action);
3528 if (!error.ok()) {
3529 return error;
3530 }
3531
3532 // If this is answer-ish we're ready to let media flow.
3533 if (action == cricket::CA_ANSWER || action == cricket::CA_PRANSWER) {
3534 EnableChannels();
3535 }
3536
3537 // Update the signaling state according to the specified state machine (see
3538 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
3539 if (action == cricket::CA_OFFER) {
3540 ChangeSignalingState(source == cricket::CS_LOCAL
3541 ? PeerConnectionInterface::kHaveLocalOffer
3542 : PeerConnectionInterface::kHaveRemoteOffer);
3543 } else if (action == cricket::CA_PRANSWER) {
3544 ChangeSignalingState(source == cricket::CS_LOCAL
3545 ? PeerConnectionInterface::kHaveLocalPrAnswer
3546 : PeerConnectionInterface::kHaveRemotePrAnswer);
3547 } else {
3548 RTC_DCHECK_EQ(action, cricket::CA_ANSWER);
3549 ChangeSignalingState(PeerConnectionInterface::kStable);
3550 }
3551
3552 // Update internal objects according to the session description's media
3553 // descriptions.
3554 error = PushdownMediaDescription(action, source);
3555 if (!error.ok()) {
3556 SetSessionError(SessionError::kContent, error.message());
3557 }
3558 if (session_error() != SessionError::kNone) {
3559 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3560 }
3561
Steve Anton8a006912017-12-04 15:25:56 -08003562 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003563}
3564
Steve Anton8a006912017-12-04 15:25:56 -08003565RTCError PeerConnection::PushdownMediaDescription(
3566 cricket::ContentAction action,
3567 cricket::ContentSource source) {
Steve Anton75737c02017-11-06 10:37:17 -08003568 const SessionDescription* sdesc =
3569 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3570 ->description();
3571 RTC_DCHECK(sdesc);
Steve Anton75737c02017-11-06 10:37:17 -08003572 for (auto* channel : Channels()) {
3573 // TODO(steveanton): Add support for multiple channels of the same type.
3574 const ContentInfo* content_info =
3575 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3576 if (!content_info) {
3577 continue;
3578 }
3579 const MediaContentDescription* content_desc =
3580 static_cast<const MediaContentDescription*>(content_info->description);
3581 if (content_desc && !content_info->rejected) {
Steve Anton8a006912017-12-04 15:25:56 -08003582 std::string error;
3583 bool success =
3584 (source == cricket::CS_LOCAL)
3585 ? channel->SetLocalContent(content_desc, action, &error)
3586 : channel->SetRemoteContent(content_desc, action, &error);
Steve Anton75737c02017-11-06 10:37:17 -08003587 if (!success) {
Steve Anton8a006912017-12-04 15:25:56 -08003588 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
Steve Anton75737c02017-11-06 10:37:17 -08003589 }
3590 }
3591 }
3592 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3593 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3594 if (sctp_transport_ && local_description() && remote_description() &&
3595 cricket::GetFirstDataContent(local_description()->description()) &&
3596 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08003597 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08003598 RTC_FROM_HERE,
3599 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08003600 if (!success) {
3601 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3602 "Failed to push down SCTP parameters.");
3603 }
Steve Anton75737c02017-11-06 10:37:17 -08003604 }
Steve Anton8a006912017-12-04 15:25:56 -08003605 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003606}
3607
3608bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3609 RTC_DCHECK(network_thread()->IsCurrent());
3610 RTC_DCHECK(local_description());
3611 RTC_DCHECK(remote_description());
3612 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3613 // When we support "max-message-size", that would also be pushed down here.
3614 return sctp_transport_->Start(
3615 GetSctpPort(local_description()->description()),
3616 GetSctpPort(remote_description()->description()));
3617}
3618
Steve Anton8a006912017-12-04 15:25:56 -08003619RTCError PeerConnection::PushdownTransportDescription(
3620 cricket::ContentSource source,
3621 cricket::ContentAction action) {
3622 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003623
Steve Anton8a006912017-12-04 15:25:56 -08003624 const SessionDescriptionInterface* sdesc =
3625 (source == cricket::CS_LOCAL ? local_description()
3626 : remote_description());
3627 RTC_DCHECK(sdesc);
3628 for (const cricket::TransportInfo& tinfo :
3629 sdesc->description()->transport_infos()) {
3630 std::string error;
3631 bool success;
3632 if (source == cricket::CS_LOCAL) {
3633 success = transport_controller_->SetLocalTransportDescription(
3634 tinfo.content_name, tinfo.description, action, &error);
3635 } else {
3636 success = transport_controller_->SetRemoteTransportDescription(
3637 tinfo.content_name, tinfo.description, action, &error);
3638 }
3639 if (!success) {
3640 LOG_AND_RETURN_ERROR(
3641 RTCErrorType::INVALID_PARAMETER,
3642 "Failed to push down transport description: " + error);
Steve Anton75737c02017-11-06 10:37:17 -08003643 }
3644 }
3645
Steve Anton8a006912017-12-04 15:25:56 -08003646 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003647}
3648
3649bool PeerConnection::GetTransportDescription(
3650 const SessionDescription* description,
3651 const std::string& content_name,
3652 cricket::TransportDescription* tdesc) {
3653 if (!description || !tdesc) {
3654 return false;
3655 }
3656 const TransportInfo* transport_info =
3657 description->GetTransportInfoByName(content_name);
3658 if (!transport_info) {
3659 return false;
3660 }
3661 *tdesc = transport_info->description;
3662 return true;
3663}
3664
3665bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3666 const std::string* first_content_name = bundle.FirstContentName();
3667 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003668 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003669 return false;
3670 }
3671 const std::string& transport_name = *first_content_name;
3672
3673 auto maybe_set_transport = [this, bundle,
3674 transport_name](cricket::BaseChannel* ch) {
3675 if (!ch || !bundle.HasContentName(ch->content_name())) {
3676 return true;
3677 }
3678
3679 std::string old_transport_name = ch->transport_name();
3680 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003681 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3682 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003683 return true;
3684 }
3685
3686 cricket::DtlsTransportInternal* rtp_dtls_transport =
3687 transport_controller_->CreateDtlsTransport(
3688 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3689 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3690 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3691 if (need_rtcp) {
3692 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3693 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3694 }
3695
3696 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003697 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3698 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003699 transport_controller_->DestroyDtlsTransport(
3700 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3701 // If the channel needs rtcp, it means that the channel used to have a
3702 // rtcp transport which needs to be deleted now.
3703 if (need_rtcp) {
3704 transport_controller_->DestroyDtlsTransport(
3705 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3706 }
3707 return true;
3708 };
3709
3710 if (!maybe_set_transport(voice_channel()) ||
3711 !maybe_set_transport(video_channel()) ||
3712 !maybe_set_transport(rtp_data_channel())) {
3713 return false;
3714 }
3715 // For SCTP, transport creation/deletion happens here instead of in the
3716 // object itself.
3717 if (sctp_transport_) {
3718 RTC_DCHECK(sctp_transport_name_);
3719 RTC_DCHECK(sctp_content_name_);
3720 if (transport_name != *sctp_transport_name_ &&
3721 bundle.HasContentName(*sctp_content_name_)) {
3722 network_thread()->Invoke<void>(
3723 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3724 transport_name));
3725 }
3726 }
3727
3728 return true;
3729}
3730
Steve Anton75737c02017-11-06 10:37:17 -08003731cricket::IceConfig PeerConnection::ParseIceConfig(
3732 const PeerConnectionInterface::RTCConfiguration& config) const {
3733 cricket::ContinualGatheringPolicy gathering_policy;
3734 // TODO(honghaiz): Add the third continual gathering policy in
3735 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3736 switch (config.continual_gathering_policy) {
3737 case PeerConnectionInterface::GATHER_ONCE:
3738 gathering_policy = cricket::GATHER_ONCE;
3739 break;
3740 case PeerConnectionInterface::GATHER_CONTINUALLY:
3741 gathering_policy = cricket::GATHER_CONTINUALLY;
3742 break;
3743 default:
3744 RTC_NOTREACHED();
3745 gathering_policy = cricket::GATHER_ONCE;
3746 }
3747 cricket::IceConfig ice_config;
3748 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3749 ice_config.prioritize_most_likely_candidate_pairs =
3750 config.prioritize_most_likely_ice_candidate_pairs;
3751 ice_config.backup_connection_ping_interval =
3752 config.ice_backup_candidate_pair_ping_interval;
3753 ice_config.continual_gathering_policy = gathering_policy;
3754 ice_config.presume_writable_when_fully_relayed =
3755 config.presume_writable_when_fully_relayed;
3756 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3757 ice_config.regather_all_networks_interval_range =
3758 config.ice_regather_interval_range;
3759 return ice_config;
3760}
3761
Steve Anton75737c02017-11-06 10:37:17 -08003762bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3763 std::string* track_id) {
3764 if (!local_description()) {
3765 return false;
3766 }
3767 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3768 track_id);
3769}
3770
3771bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3772 std::string* track_id) {
3773 if (!remote_description()) {
3774 return false;
3775 }
3776 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3777 track_id);
3778}
3779
3780bool PeerConnection::SendData(const cricket::SendDataParams& params,
3781 const rtc::CopyOnWriteBuffer& payload,
3782 cricket::SendDataResult* result) {
3783 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003784 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3785 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003786 return false;
3787 }
3788 return rtp_data_channel_
3789 ? rtp_data_channel_->SendData(params, payload, result)
3790 : network_thread()->Invoke<bool>(
3791 RTC_FROM_HERE,
3792 Bind(&cricket::SctpTransportInternal::SendData,
3793 sctp_transport_.get(), params, payload, result));
3794}
3795
3796bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3797 if (!rtp_data_channel_ && !sctp_transport_) {
3798 // Don't log an error here, because DataChannels are expected to call
3799 // ConnectDataChannel in this state. It's the only way to initially tell
3800 // whether or not the underlying transport is ready.
3801 return false;
3802 }
3803 if (rtp_data_channel_) {
3804 rtp_data_channel_->SignalReadyToSendData.connect(
3805 webrtc_data_channel, &DataChannel::OnChannelReady);
3806 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3807 &DataChannel::OnDataReceived);
3808 } else {
3809 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3810 &DataChannel::OnChannelReady);
3811 SignalSctpDataReceived.connect(webrtc_data_channel,
3812 &DataChannel::OnDataReceived);
3813 SignalSctpStreamClosedRemotely.connect(
3814 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3815 }
3816 return true;
3817}
3818
3819void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3820 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003821 RTC_LOG(LS_ERROR)
3822 << "DisconnectDataChannel called when rtp_data_channel_ and "
3823 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003824 return;
3825 }
3826 if (rtp_data_channel_) {
3827 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3828 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3829 } else {
3830 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3831 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3832 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3833 }
3834}
3835
3836void PeerConnection::AddSctpDataStream(int sid) {
3837 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003838 RTC_LOG(LS_ERROR)
3839 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003840 return;
3841 }
3842 network_thread()->Invoke<void>(
3843 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3844 sctp_transport_.get(), sid));
3845}
3846
3847void PeerConnection::RemoveSctpDataStream(int sid) {
3848 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003849 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3850 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003851 return;
3852 }
3853 network_thread()->Invoke<void>(
3854 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3855 sctp_transport_.get(), sid));
3856}
3857
3858bool PeerConnection::ReadyToSendData() const {
3859 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3860 sctp_ready_to_send_data_;
3861}
3862
3863std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3864 RTC_DCHECK(signaling_thread()->IsCurrent());
3865 ChannelNamePairs channel_name_pairs;
3866 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003867 channel_name_pairs.voice = ChannelNamePair(
3868 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003869 }
3870 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003871 channel_name_pairs.video = ChannelNamePair(
3872 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003873 }
3874 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003875 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08003876 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003877 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003878 }
3879 if (sctp_transport_) {
3880 RTC_DCHECK(sctp_content_name_);
3881 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003882 channel_name_pairs.data =
3883 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08003884 }
3885 return GetSessionStats(channel_name_pairs);
3886}
3887
3888std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3889 const ChannelNamePairs& channel_name_pairs) {
3890 if (network_thread()->IsCurrent()) {
3891 return GetSessionStats_n(channel_name_pairs);
3892 }
3893 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3894 RTC_FROM_HERE,
3895 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3896}
3897
3898bool PeerConnection::GetLocalCertificate(
3899 const std::string& transport_name,
3900 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
3901 return transport_controller_->GetLocalCertificate(transport_name,
3902 certificate);
3903}
3904
3905std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
3906 const std::string& transport_name) {
3907 return transport_controller_->GetRemoteSSLCertificate(transport_name);
3908}
3909
3910cricket::DataChannelType PeerConnection::data_channel_type() const {
3911 return data_channel_type_;
3912}
3913
3914bool PeerConnection::IceRestartPending(const std::string& content_name) const {
3915 return pending_ice_restarts_.find(content_name) !=
3916 pending_ice_restarts_.end();
3917}
3918
Steve Anton75737c02017-11-06 10:37:17 -08003919bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
3920 return transport_controller_->NeedsIceRestart(content_name);
3921}
3922
3923void PeerConnection::OnCertificateReady(
3924 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
3925 transport_controller_->SetLocalCertificate(certificate);
3926}
3927
3928void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08003929 SetSessionError(SessionError::kTransport,
3930 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08003931}
3932
3933void PeerConnection::OnTransportControllerConnectionState(
3934 cricket::IceConnectionState state) {
3935 switch (state) {
3936 case cricket::kIceConnectionConnecting:
3937 // If the current state is Connected or Completed, then there were
3938 // writable channels but now there are not, so the next state must
3939 // be Disconnected.
3940 // kIceConnectionConnecting is currently used as the default,
3941 // un-connected state by the TransportController, so its only use is
3942 // detecting disconnections.
3943 if (ice_connection_state_ ==
3944 PeerConnectionInterface::kIceConnectionConnected ||
3945 ice_connection_state_ ==
3946 PeerConnectionInterface::kIceConnectionCompleted) {
3947 SetIceConnectionState(
3948 PeerConnectionInterface::kIceConnectionDisconnected);
3949 }
3950 break;
3951 case cricket::kIceConnectionFailed:
3952 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
3953 break;
3954 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003955 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
3956 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08003957 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3958 break;
3959 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003960 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
3961 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08003962 if (ice_connection_state_ !=
3963 PeerConnectionInterface::kIceConnectionConnected) {
3964 // If jumping directly from "checking" to "connected",
3965 // signal "connected" first.
3966 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3967 }
3968 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
3969 if (metrics_observer()) {
3970 ReportTransportStats();
3971 }
3972 break;
3973 default:
3974 RTC_NOTREACHED();
3975 }
3976}
3977
3978void PeerConnection::OnTransportControllerCandidatesGathered(
3979 const std::string& transport_name,
3980 const cricket::Candidates& candidates) {
3981 RTC_DCHECK(signaling_thread()->IsCurrent());
3982 int sdp_mline_index;
3983 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003984 RTC_LOG(LS_ERROR)
3985 << "OnTransportControllerCandidatesGathered: content name "
3986 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08003987 return;
3988 }
3989
3990 for (cricket::Candidates::const_iterator citer = candidates.begin();
3991 citer != candidates.end(); ++citer) {
3992 // Use transport_name as the candidate media id.
3993 std::unique_ptr<JsepIceCandidate> candidate(
3994 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
3995 if (local_description()) {
3996 mutable_local_description()->AddCandidate(candidate.get());
3997 }
3998 OnIceCandidate(std::move(candidate));
3999 }
4000}
4001
4002void PeerConnection::OnTransportControllerCandidatesRemoved(
4003 const std::vector<cricket::Candidate>& candidates) {
4004 RTC_DCHECK(signaling_thread()->IsCurrent());
4005 // Sanity check.
4006 for (const cricket::Candidate& candidate : candidates) {
4007 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004008 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4009 << "empty content name in candidate "
4010 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004011 return;
4012 }
4013 }
4014
4015 if (local_description()) {
4016 mutable_local_description()->RemoveCandidates(candidates);
4017 }
4018 OnIceCandidatesRemoved(candidates);
4019}
4020
4021void PeerConnection::OnTransportControllerDtlsHandshakeError(
4022 rtc::SSLHandshakeError error) {
4023 if (metrics_observer()) {
4024 metrics_observer()->IncrementEnumCounter(
4025 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4026 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4027 }
4028}
4029
4030// Enabling voice and video (and RTP data) channels.
4031void PeerConnection::EnableChannels() {
Steve Anton4171afb2017-11-20 10:20:22 -08004032 if (voice_channel() && !voice_channel()->enabled()) {
4033 voice_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004034 }
4035
Steve Anton4171afb2017-11-20 10:20:22 -08004036 if (video_channel() && !video_channel()->enabled()) {
4037 video_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004038 }
4039
Steve Anton4171afb2017-11-20 10:20:22 -08004040 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004041 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004042 }
Steve Anton75737c02017-11-06 10:37:17 -08004043}
4044
4045// Returns the media index for a local ice candidate given the content name.
4046bool PeerConnection::GetLocalCandidateMediaIndex(
4047 const std::string& content_name,
4048 int* sdp_mline_index) {
4049 if (!local_description() || !sdp_mline_index) {
4050 return false;
4051 }
4052
4053 bool content_found = false;
4054 const ContentInfos& contents = local_description()->description()->contents();
4055 for (size_t index = 0; index < contents.size(); ++index) {
4056 if (contents[index].name == content_name) {
4057 *sdp_mline_index = static_cast<int>(index);
4058 content_found = true;
4059 break;
4060 }
4061 }
4062 return content_found;
4063}
4064
4065bool PeerConnection::UseCandidatesInSessionDescription(
4066 const SessionDescriptionInterface* remote_desc) {
4067 if (!remote_desc) {
4068 return true;
4069 }
4070 bool ret = true;
4071
4072 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4073 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4074 for (size_t n = 0; n < candidates->count(); ++n) {
4075 const IceCandidateInterface* candidate = candidates->at(n);
4076 bool valid = false;
4077 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4078 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004079 RTC_LOG(LS_INFO)
4080 << "UseCandidatesInSessionDescription: Not ready to use "
4081 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004082 }
4083 continue;
4084 }
4085 ret = UseCandidate(candidate);
4086 if (!ret) {
4087 break;
4088 }
4089 }
4090 }
4091 return ret;
4092}
4093
4094bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4095 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4096 size_t remote_content_size =
4097 remote_description()->description()->contents().size();
4098 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004099 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004100 return false;
4101 }
4102
4103 cricket::ContentInfo content =
4104 remote_description()->description()->contents()[mediacontent_index];
4105 std::vector<cricket::Candidate> candidates;
4106 candidates.push_back(candidate->candidate());
4107 // Invoking BaseSession method to handle remote candidates.
4108 std::string error;
4109 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4110 &error)) {
4111 // Candidates successfully submitted for checking.
4112 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4113 ice_connection_state_ ==
4114 PeerConnectionInterface::kIceConnectionDisconnected) {
4115 // If state is New, then the session has just gotten its first remote ICE
4116 // candidates, so go to Checking.
4117 // If state is Disconnected, the session is re-using old candidates or
4118 // receiving additional ones, so go to Checking.
4119 // If state is Connected, stay Connected.
4120 // TODO(bemasc): If state is Connected, and the new candidates are for a
4121 // newly added transport, then the state actually _should_ move to
4122 // checking. Add a way to distinguish that case.
4123 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4124 }
4125 // TODO(bemasc): If state is Completed, go back to Connected.
4126 } else {
4127 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004128 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004129 }
4130 }
4131 return true;
4132}
4133
4134void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004135 // Destroy video channel first since it may have a pointer to the
4136 // voice channel.
4137 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004138 if (!video_info || video_info->rejected) {
4139 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004140 }
4141
Steve Anton6fec8802017-12-04 10:37:29 -08004142 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4143 if (!audio_info || audio_info->rejected) {
4144 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004145 }
4146
4147 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4148 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004149 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004150 }
4151}
4152
Steve Antoneda6ccd2017-12-04 10:21:55 -08004153std::string PeerConnection::GetTransportNameForMediaSection(
4154 const std::string& mid,
4155 const cricket::ContentGroup* bundle_group) const {
4156 if (!bundle_group) {
4157 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004158 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004159 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004160 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004161 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004162 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004163 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004164 if (!bundle_group->HasContentName(mid)) {
4165 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4166 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004167 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004168 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4169 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004170}
4171
Steve Anton8a006912017-12-04 15:25:56 -08004172RTCError PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004173 RTC_DCHECK(desc);
4174
Steve Anton75737c02017-11-06 10:37:17 -08004175 const cricket::ContentGroup* bundle_group = nullptr;
4176 if (configuration_.bundle_policy ==
4177 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4178 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4179 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004180 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4181 "max-bundle configured but session description "
4182 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004183 }
4184 }
4185
Steve Antoneda6ccd2017-12-04 10:21:55 -08004186 // Creating the media channels and transport proxies.
4187 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4188 if (voice && !voice->rejected &&
4189 !GetAudioTransceiver()->internal()->channel()) {
4190 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4191 voice->name,
4192 GetTransportNameForMediaSection(voice->name, bundle_group));
4193 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004194 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4195 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004196 }
4197 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4198 }
4199
Steve Anton75737c02017-11-06 10:37:17 -08004200 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004201 if (video && !video->rejected &&
4202 !GetVideoTransceiver()->internal()->channel()) {
4203 cricket::VideoChannel* video_channel = CreateVideoChannel(
4204 video->name,
4205 GetTransportNameForMediaSection(video->name, bundle_group));
4206 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004207 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4208 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004209 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004210 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004211 }
4212
4213 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4214 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4215 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004216 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4217 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004218 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4219 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004220 }
4221 }
4222
Steve Anton8a006912017-12-04 15:25:56 -08004223 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004224}
4225
Steve Anton4171afb2017-11-20 10:20:22 -08004226// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004227cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4228 const std::string& mid,
4229 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004230 cricket::DtlsTransportInternal* rtp_dtls_transport =
4231 transport_controller_->CreateDtlsTransport(
4232 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4233 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4234 if (configuration_.rtcp_mux_policy !=
4235 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4236 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4237 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4238 }
4239
4240 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4241 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004242 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4243 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004244 if (!voice_channel) {
4245 transport_controller_->DestroyDtlsTransport(
4246 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4247 if (rtcp_dtls_transport) {
4248 transport_controller_->DestroyDtlsTransport(
4249 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4250 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004251 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004252 }
Steve Anton75737c02017-11-06 10:37:17 -08004253 voice_channel->SignalRtcpMuxFullyActive.connect(
4254 this, &PeerConnection::DestroyRtcpTransport_n);
4255 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4256 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004257 voice_channel->SignalSentPacket.connect(this,
4258 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004259
Steve Antoneda6ccd2017-12-04 10:21:55 -08004260 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004261}
4262
Steve Anton4171afb2017-11-20 10:20:22 -08004263// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004264cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4265 const std::string& mid,
4266 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004267 cricket::DtlsTransportInternal* rtp_dtls_transport =
4268 transport_controller_->CreateDtlsTransport(
4269 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4270 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4271 if (configuration_.rtcp_mux_policy !=
4272 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4273 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4274 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4275 }
4276
4277 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4278 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004279 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4280 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004281
4282 if (!video_channel) {
4283 transport_controller_->DestroyDtlsTransport(
4284 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4285 if (rtcp_dtls_transport) {
4286 transport_controller_->DestroyDtlsTransport(
4287 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4288 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004289 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004290 }
Steve Anton75737c02017-11-06 10:37:17 -08004291 video_channel->SignalRtcpMuxFullyActive.connect(
4292 this, &PeerConnection::DestroyRtcpTransport_n);
4293 video_channel->SignalDtlsSrtpSetupFailure.connect(
4294 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004295 video_channel->SignalSentPacket.connect(this,
4296 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004297
Steve Antoneda6ccd2017-12-04 10:21:55 -08004298 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004299}
4300
Steve Antoneda6ccd2017-12-04 10:21:55 -08004301bool PeerConnection::CreateDataChannel(const std::string& mid,
4302 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004303 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4304 if (sctp) {
4305 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004306 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004307 << "Trying to create SCTP transport, but didn't compile with "
4308 "SCTP support (HAVE_SCTP)";
4309 return false;
4310 }
4311 if (!network_thread()->Invoke<bool>(
4312 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004313 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004314 return false;
4315 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004316 for (const auto& channel : sctp_data_channels_) {
4317 channel->OnTransportChannelCreated();
4318 }
Steve Anton75737c02017-11-06 10:37:17 -08004319 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004320 cricket::DtlsTransportInternal* rtp_dtls_transport =
4321 transport_controller_->CreateDtlsTransport(
4322 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4323 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4324 if (configuration_.rtcp_mux_policy !=
4325 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4326 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4327 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4328 }
4329
4330 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4331 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004332 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004333
4334 if (!rtp_data_channel_) {
4335 transport_controller_->DestroyDtlsTransport(
4336 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4337 if (rtcp_dtls_transport) {
4338 transport_controller_->DestroyDtlsTransport(
4339 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4340 }
4341 return false;
4342 }
4343
4344 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4345 this, &PeerConnection::DestroyRtcpTransport_n);
4346 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4347 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4348 rtp_data_channel_->SignalSentPacket.connect(
4349 this, &PeerConnection::OnSentPacket_w);
4350 }
4351
Steve Anton75737c02017-11-06 10:37:17 -08004352 return true;
4353}
4354
4355Call::Stats PeerConnection::GetCallStats() {
4356 if (!worker_thread()->IsCurrent()) {
4357 return worker_thread()->Invoke<Call::Stats>(
4358 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4359 }
4360 if (call_) {
4361 return call_->GetStats();
4362 } else {
4363 return Call::Stats();
4364 }
4365}
4366
4367std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4368 const ChannelNamePairs& channel_name_pairs) {
4369 RTC_DCHECK(network_thread()->IsCurrent());
4370 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4371 for (const auto channel_name_pair :
4372 {&channel_name_pairs.voice, &channel_name_pairs.video,
4373 &channel_name_pairs.data}) {
4374 if (*channel_name_pair) {
4375 cricket::TransportStats transport_stats;
4376 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4377 &transport_stats)) {
4378 return nullptr;
4379 }
4380 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4381 (*channel_name_pair)->transport_name;
4382 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4383 std::move(transport_stats);
4384 }
4385 }
4386 return session_stats;
4387}
4388
4389bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4390 const std::string& transport_name) {
4391 RTC_DCHECK(network_thread()->IsCurrent());
4392 RTC_DCHECK(sctp_factory_);
4393 cricket::DtlsTransportInternal* tc =
4394 transport_controller_->CreateDtlsTransport_n(
4395 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4396 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4397 RTC_DCHECK(sctp_transport_);
4398 sctp_invoker_.reset(new rtc::AsyncInvoker());
4399 sctp_transport_->SignalReadyToSendData.connect(
4400 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4401 sctp_transport_->SignalDataReceived.connect(
4402 this, &PeerConnection::OnSctpTransportDataReceived_n);
4403 sctp_transport_->SignalStreamClosedRemotely.connect(
4404 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004405 sctp_transport_name_ = transport_name;
4406 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004407 return true;
4408}
4409
4410void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4411 RTC_DCHECK(network_thread()->IsCurrent());
4412 RTC_DCHECK(sctp_transport_);
4413 RTC_DCHECK(sctp_transport_name_);
4414 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004415 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004416 cricket::DtlsTransportInternal* tc =
4417 transport_controller_->CreateDtlsTransport_n(
4418 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4419 sctp_transport_->SetTransportChannel(tc);
4420 transport_controller_->DestroyDtlsTransport_n(
4421 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4422}
4423
4424void PeerConnection::DestroySctpTransport_n() {
4425 RTC_DCHECK(network_thread()->IsCurrent());
4426 sctp_transport_.reset(nullptr);
4427 sctp_content_name_.reset();
4428 sctp_transport_name_.reset();
4429 sctp_invoker_.reset(nullptr);
4430 sctp_ready_to_send_data_ = false;
4431}
4432
4433void PeerConnection::OnSctpTransportReadyToSendData_n() {
4434 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4435 RTC_DCHECK(network_thread()->IsCurrent());
4436 // Note: Cannot use rtc::Bind here because it will grab a reference to
4437 // PeerConnection and potentially cause PeerConnection to live longer than
4438 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4439 // be destroyed before PeerConnection is destroyed, and at that point all
4440 // pending tasks will be cleared.
4441 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4442 OnSctpTransportReadyToSendData_s(true);
4443 });
4444}
4445
4446void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4447 RTC_DCHECK(signaling_thread()->IsCurrent());
4448 sctp_ready_to_send_data_ = ready;
4449 SignalSctpReadyToSendData(ready);
4450}
4451
4452void PeerConnection::OnSctpTransportDataReceived_n(
4453 const cricket::ReceiveDataParams& params,
4454 const rtc::CopyOnWriteBuffer& payload) {
4455 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4456 RTC_DCHECK(network_thread()->IsCurrent());
4457 // Note: Cannot use rtc::Bind here because it will grab a reference to
4458 // PeerConnection and potentially cause PeerConnection to live longer than
4459 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4460 // be destroyed before PeerConnection is destroyed, and at that point all
4461 // pending tasks will be cleared.
4462 sctp_invoker_->AsyncInvoke<void>(
4463 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4464 OnSctpTransportDataReceived_s(params, payload);
4465 });
4466}
4467
4468void PeerConnection::OnSctpTransportDataReceived_s(
4469 const cricket::ReceiveDataParams& params,
4470 const rtc::CopyOnWriteBuffer& payload) {
4471 RTC_DCHECK(signaling_thread()->IsCurrent());
4472 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4473 // Received OPEN message; parse and signal that a new data channel should
4474 // be created.
4475 std::string label;
4476 InternalDataChannelInit config;
4477 config.id = params.ssrc;
4478 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004479 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4480 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004481 return;
4482 }
4483 config.open_handshake_role = InternalDataChannelInit::kAcker;
4484 OnDataChannelOpenMessage(label, config);
4485 } else {
4486 // Otherwise just forward the signal.
4487 SignalSctpDataReceived(params, payload);
4488 }
4489}
4490
4491void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4492 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4493 RTC_DCHECK(network_thread()->IsCurrent());
4494 sctp_invoker_->AsyncInvoke<void>(
4495 RTC_FROM_HERE, signaling_thread(),
4496 rtc::Bind(&sigslot::signal1<int>::operator(),
4497 &SignalSctpStreamClosedRemotely, sid));
4498}
4499
4500// Returns false if bundle is enabled and rtcp_mux is disabled.
4501bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4502 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4503 if (!bundle_enabled)
4504 return true;
4505
4506 const cricket::ContentGroup* bundle_group =
4507 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4508 RTC_DCHECK(bundle_group != NULL);
4509
4510 const cricket::ContentInfos& contents = desc->contents();
4511 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4512 citer != contents.end(); ++citer) {
4513 const cricket::ContentInfo* content = (&*citer);
4514 RTC_DCHECK(content != NULL);
4515 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4516 content->type == cricket::NS_JINGLE_RTP) {
4517 if (!HasRtcpMuxEnabled(content))
4518 return false;
4519 }
4520 }
4521 // RTCP-MUX is enabled in all the contents.
4522 return true;
4523}
4524
4525bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4526 const cricket::MediaContentDescription* description =
4527 static_cast<cricket::MediaContentDescription*>(content->description);
4528 return description->rtcp_mux();
4529}
4530
Steve Anton8a006912017-12-04 15:25:56 -08004531RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08004532 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08004533 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08004534 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08004535 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08004536 }
4537
4538 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08004539 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08004540 }
4541
Steve Anton20393062017-12-04 16:24:52 -08004542 cricket::ContentAction action = ContentActionFromSessionType(sdesc->type());
Steve Anton8a006912017-12-04 15:25:56 -08004543 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(action)) ||
4544 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(action))) {
4545 LOG_AND_RETURN_ERROR(
4546 RTCErrorType::INVALID_PARAMETER,
4547 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08004548 }
4549
4550 // Verify crypto settings.
4551 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08004552 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4553 dtls_enabled_) {
4554 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
4555 if (!crypto_error.ok()) {
4556 return crypto_error;
4557 }
Steve Anton75737c02017-11-06 10:37:17 -08004558 }
4559
4560 // Verify ice-ufrag and ice-pwd.
4561 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004562 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4563 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08004564 }
4565
4566 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004567 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4568 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08004569 }
4570
4571 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4572 // m-lines that do not rtcp-mux enabled.
4573
4574 // Verify m-lines in Answer when compared against Offer.
Steve Anton20393062017-12-04 16:24:52 -08004575 if (action == cricket::CA_ANSWER || action == cricket::CA_PRANSWER) {
Steve Anton75737c02017-11-06 10:37:17 -08004576 const cricket::SessionDescription* offer_desc =
4577 (source == cricket::CS_LOCAL) ? remote_description()->description()
4578 : local_description()->description();
4579 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4580 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004581 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4582 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004583 }
4584 } else {
4585 const cricket::SessionDescription* current_desc = nullptr;
4586 if (source == cricket::CS_LOCAL && local_description()) {
4587 current_desc = local_description()->description();
4588 } else if (source == cricket::CS_REMOTE && remote_description()) {
4589 current_desc = remote_description()->description();
4590 }
4591 // The re-offers should respect the order of m= sections in current
4592 // description. See RFC3264 Section 8 paragraph 4 for more details.
4593 if (current_desc &&
4594 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004595 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4596 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08004597 }
4598 }
4599
Steve Anton8a006912017-12-04 15:25:56 -08004600 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004601}
4602
Steve Anton20393062017-12-04 16:24:52 -08004603bool PeerConnection::ExpectSetLocalDescription(cricket::ContentAction action) {
Steve Anton75737c02017-11-06 10:37:17 -08004604 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton20393062017-12-04 16:24:52 -08004605 if (action == cricket::CA_OFFER) {
Steve Anton75737c02017-11-06 10:37:17 -08004606 return (state == PeerConnectionInterface::kStable) ||
4607 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08004608 } else {
4609 RTC_DCHECK(action == cricket::CA_ANSWER || action == cricket::CA_PRANSWER);
Steve Anton75737c02017-11-06 10:37:17 -08004610 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4611 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4612 }
4613}
4614
Steve Anton20393062017-12-04 16:24:52 -08004615bool PeerConnection::ExpectSetRemoteDescription(cricket::ContentAction action) {
Steve Anton75737c02017-11-06 10:37:17 -08004616 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton20393062017-12-04 16:24:52 -08004617 if (action == cricket::CA_OFFER) {
Steve Anton75737c02017-11-06 10:37:17 -08004618 return (state == PeerConnectionInterface::kStable) ||
4619 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08004620 } else {
4621 RTC_DCHECK(action == cricket::CA_ANSWER || action == cricket::CA_PRANSWER);
Steve Anton75737c02017-11-06 10:37:17 -08004622 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4623 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4624 }
4625}
4626
Steve Antonf8470812017-12-04 10:46:21 -08004627const char* PeerConnection::SessionErrorToString(SessionError error) const {
4628 switch (error) {
4629 case SessionError::kNone:
4630 return "ERROR_NONE";
4631 case SessionError::kContent:
4632 return "ERROR_CONTENT";
4633 case SessionError::kTransport:
4634 return "ERROR_TRANSPORT";
4635 }
4636 RTC_NOTREACHED();
4637 return "";
4638}
4639
Steve Anton75737c02017-11-06 10:37:17 -08004640std::string PeerConnection::GetSessionErrorMsg() {
4641 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08004642 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
4643 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004644 return desc.str();
4645}
4646
4647// We need to check the local/remote description for the Transport instead of
4648// the session, because a new Transport added during renegotiation may have
4649// them unset while the session has them set from the previous negotiation.
4650// Not doing so may trigger the auto generation of transport description and
4651// mess up DTLS identity information, ICE credential, etc.
4652bool PeerConnection::ReadyToUseRemoteCandidate(
4653 const IceCandidateInterface* candidate,
4654 const SessionDescriptionInterface* remote_desc,
4655 bool* valid) {
4656 *valid = true;
4657
4658 const SessionDescriptionInterface* current_remote_desc =
4659 remote_desc ? remote_desc : remote_description();
4660
4661 if (!current_remote_desc) {
4662 return false;
4663 }
4664
4665 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4666 size_t remote_content_size =
4667 current_remote_desc->description()->contents().size();
4668 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004669 RTC_LOG(LS_ERROR)
4670 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4671 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004672
4673 *valid = false;
4674 return false;
4675 }
4676
4677 cricket::ContentInfo content =
4678 current_remote_desc->description()->contents()[mediacontent_index];
4679
4680 const std::string transport_name = GetTransportName(content.name);
4681 if (transport_name.empty()) {
4682 return false;
4683 }
4684 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4685}
4686
4687bool PeerConnection::SrtpRequired() const {
4688 return dtls_enabled_ ||
4689 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4690}
4691
4692void PeerConnection::OnTransportControllerGatheringState(
4693 cricket::IceGatheringState state) {
4694 RTC_DCHECK(signaling_thread()->IsCurrent());
4695 if (state == cricket::kIceGatheringGathering) {
4696 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4697 } else if (state == cricket::kIceGatheringComplete) {
4698 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4699 }
4700}
4701
4702void PeerConnection::ReportTransportStats() {
4703 // Use a set so we don't report the same stats twice if two channels share
4704 // a transport.
4705 std::set<std::string> transport_names;
4706 if (voice_channel()) {
4707 transport_names.insert(voice_channel()->transport_name());
4708 }
4709 if (video_channel()) {
4710 transport_names.insert(video_channel()->transport_name());
4711 }
4712 if (rtp_data_channel()) {
4713 transport_names.insert(rtp_data_channel()->transport_name());
4714 }
4715 if (sctp_transport_name_) {
4716 transport_names.insert(*sctp_transport_name_);
4717 }
4718 for (const auto& name : transport_names) {
4719 cricket::TransportStats stats;
4720 if (transport_controller_->GetStats(name, &stats)) {
4721 ReportBestConnectionState(stats);
4722 ReportNegotiatedCiphers(stats);
4723 }
4724 }
4725}
4726// Walk through the ConnectionInfos to gather best connection usage
4727// for IPv4 and IPv6.
4728void PeerConnection::ReportBestConnectionState(
4729 const cricket::TransportStats& stats) {
4730 RTC_DCHECK(metrics_observer());
4731 for (cricket::TransportChannelStatsList::const_iterator it =
4732 stats.channel_stats.begin();
4733 it != stats.channel_stats.end(); ++it) {
4734 for (cricket::ConnectionInfos::const_iterator it_info =
4735 it->connection_infos.begin();
4736 it_info != it->connection_infos.end(); ++it_info) {
4737 if (!it_info->best_connection) {
4738 continue;
4739 }
4740
4741 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4742 const cricket::Candidate& local = it_info->local_candidate;
4743 const cricket::Candidate& remote = it_info->remote_candidate;
4744
4745 // Increment the counter for IceCandidatePairType.
4746 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4747 (local.type() == RELAY_PORT_TYPE &&
4748 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4749 type = kEnumCounterIceCandidatePairTypeTcp;
4750 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4751 type = kEnumCounterIceCandidatePairTypeUdp;
4752 } else {
4753 RTC_CHECK(0);
4754 }
4755 metrics_observer()->IncrementEnumCounter(
4756 type, GetIceCandidatePairCounter(local, remote),
4757 kIceCandidatePairMax);
4758
4759 // Increment the counter for IP type.
4760 if (local.address().family() == AF_INET) {
4761 metrics_observer()->IncrementEnumCounter(
4762 kEnumCounterAddressFamily, kBestConnections_IPv4,
4763 kPeerConnectionAddressFamilyCounter_Max);
4764
4765 } else if (local.address().family() == AF_INET6) {
4766 metrics_observer()->IncrementEnumCounter(
4767 kEnumCounterAddressFamily, kBestConnections_IPv6,
4768 kPeerConnectionAddressFamilyCounter_Max);
4769 } else {
4770 RTC_CHECK(0);
4771 }
4772
4773 return;
4774 }
4775 }
4776}
4777
4778void PeerConnection::ReportNegotiatedCiphers(
4779 const cricket::TransportStats& stats) {
4780 RTC_DCHECK(metrics_observer());
4781 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4782 return;
4783 }
4784
4785 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4786 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4787 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4788 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4789 return;
4790 }
4791
4792 PeerConnectionEnumCounterType srtp_counter_type;
4793 PeerConnectionEnumCounterType ssl_counter_type;
4794 if (stats.transport_name == cricket::CN_AUDIO) {
4795 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4796 ssl_counter_type = kEnumCounterAudioSslCipher;
4797 } else if (stats.transport_name == cricket::CN_VIDEO) {
4798 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4799 ssl_counter_type = kEnumCounterVideoSslCipher;
4800 } else if (stats.transport_name == cricket::CN_DATA) {
4801 srtp_counter_type = kEnumCounterDataSrtpCipher;
4802 ssl_counter_type = kEnumCounterDataSslCipher;
4803 } else {
4804 RTC_NOTREACHED();
4805 return;
4806 }
4807
4808 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4809 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4810 srtp_crypto_suite);
4811 }
4812 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4813 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4814 ssl_cipher_suite);
4815 }
4816}
4817
4818void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4819 RTC_DCHECK(worker_thread()->IsCurrent());
4820 RTC_DCHECK(call_);
4821 call_->OnSentPacket(sent_packet);
4822}
4823
4824const std::string PeerConnection::GetTransportName(
4825 const std::string& content_name) {
4826 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004827 if (channel) {
4828 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004829 }
Steve Anton6fec8802017-12-04 10:37:29 -08004830 if (sctp_transport_) {
4831 RTC_DCHECK(sctp_content_name_);
4832 RTC_DCHECK(sctp_transport_name_);
4833 if (content_name == *sctp_content_name_) {
4834 return *sctp_transport_name_;
4835 }
4836 }
4837 // Return an empty string if failed to retrieve the transport name.
4838 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004839}
4840
4841void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4842 RTC_DCHECK(network_thread()->IsCurrent());
4843 transport_controller_->DestroyDtlsTransport_n(
4844 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4845}
4846
Steve Anton6fec8802017-12-04 10:37:29 -08004847void PeerConnection::DestroyTransceiverChannel(
4848 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4849 transceiver) {
4850 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08004851
Steve Anton6fec8802017-12-04 10:37:29 -08004852 cricket::BaseChannel* channel = transceiver->internal()->channel();
4853 if (channel) {
4854 transceiver->internal()->SetChannel(nullptr);
4855 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08004856 }
4857}
4858
4859void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08004860 if (rtp_data_channel_) {
4861 OnDataChannelDestroyed();
4862 DestroyBaseChannel(rtp_data_channel_);
4863 rtp_data_channel_ = nullptr;
4864 }
4865
4866 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
4867 // grab a reference to this PeerConnection. If this is called from the
4868 // PeerConnection destructor, the RefCountedObject vtable will have already
4869 // been destroyed (since it is a subclass of PeerConnection) and using
4870 // rtc::Bind will cause "Pure virtual function called" error to appear.
4871
4872 if (sctp_transport_) {
4873 OnDataChannelDestroyed();
4874 network_thread()->Invoke<void>(RTC_FROM_HERE,
4875 [this] { DestroySctpTransport_n(); });
4876 }
4877}
4878
4879void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
4880 RTC_DCHECK(channel);
4881 RTC_DCHECK(channel->rtp_dtls_transport());
4882
4883 // Need to cache these before destroying the base channel so that we do not
4884 // access uninitialized memory.
4885 const std::string transport_name =
4886 channel->rtp_dtls_transport()->transport_name();
4887 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
4888
4889 switch (channel->media_type()) {
4890 case cricket::MEDIA_TYPE_AUDIO:
4891 channel_manager()->DestroyVoiceChannel(
4892 static_cast<cricket::VoiceChannel*>(channel));
4893 break;
4894 case cricket::MEDIA_TYPE_VIDEO:
4895 channel_manager()->DestroyVideoChannel(
4896 static_cast<cricket::VideoChannel*>(channel));
4897 break;
4898 case cricket::MEDIA_TYPE_DATA:
4899 channel_manager()->DestroyRtpDataChannel(
4900 static_cast<cricket::RtpDataChannel*>(channel));
4901 break;
4902 default:
4903 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
4904 break;
4905 }
4906
4907 // |channel| can no longer be used.
4908
Steve Anton75737c02017-11-06 10:37:17 -08004909 transport_controller_->DestroyDtlsTransport(
4910 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4911 if (need_to_delete_rtcp) {
4912 transport_controller_->DestroyDtlsTransport(
4913 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4914 }
4915}
4916
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004917} // namespace webrtc