blob: fcc3af92273926735d90e8442997de5008d3a311 [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
535} // namespace
536
Henrik Boström31638672017-11-23 17:48:32 +0100537// Upon completion, posts a task to execute the callback of the
538// SetSessionDescriptionObserver asynchronously on the same thread. At this
539// point, the state of the peer connection might no longer reflect the effects
540// of the SetRemoteDescription operation, as the peer connection could have been
541// modified during the post.
542// TODO(hbos): Remove this class once we remove the version of
543// PeerConnectionInterface::SetRemoteDescription() that takes a
544// SetSessionDescriptionObserver as an argument.
545class PeerConnection::SetRemoteDescriptionObserverAdapter
546 : public rtc::RefCountedObject<SetRemoteDescriptionObserverInterface> {
547 public:
548 SetRemoteDescriptionObserverAdapter(
549 rtc::scoped_refptr<PeerConnection> pc,
550 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper)
551 : pc_(std::move(pc)), wrapper_(std::move(wrapper)) {}
552
553 // SetRemoteDescriptionObserverInterface implementation.
554 void OnSetRemoteDescriptionComplete(RTCError error) override {
555 if (error.ok())
556 pc_->PostSetSessionDescriptionSuccess(wrapper_);
557 else
558 pc_->PostSetSessionDescriptionFailure(wrapper_, error.message());
559 }
560
561 private:
562 rtc::scoped_refptr<PeerConnection> pc_;
563 rtc::scoped_refptr<SetSessionDescriptionObserver> wrapper_;
564};
565
deadbeef293e9262017-01-11 12:28:30 -0800566bool PeerConnectionInterface::RTCConfiguration::operator==(
567 const PeerConnectionInterface::RTCConfiguration& o) const {
568 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700569 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800570 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000571 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700572 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800573 BundlePolicy bundle_policy;
574 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700575 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
576 int ice_candidate_pool_size;
577 bool disable_ipv6;
578 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700579 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700580 bool enable_rtp_data_channel;
581 rtc::Optional<int> screencast_min_bitrate;
582 rtc::Optional<bool> combined_audio_video_bwe;
583 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800584 TcpCandidatePolicy tcp_candidate_policy;
585 CandidateNetworkPolicy candidate_network_policy;
586 int audio_jitter_buffer_max_packets;
587 bool audio_jitter_buffer_fast_accelerate;
588 int ice_connection_receiving_timeout;
589 int ice_backup_candidate_pair_ping_interval;
590 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800591 bool prioritize_most_likely_ice_candidate_pairs;
592 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800593 bool prune_turn_ports;
594 bool presume_writable_when_fully_relayed;
595 bool enable_ice_renomination;
596 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800597 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700598 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200599 webrtc::TurnCustomizer* turn_customizer;
Steve Anton79e79602017-11-20 10:25:56 -0800600 SdpSemantics sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800601 };
602 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
603 "Did you add something to RTCConfiguration and forget to "
604 "update operator==?");
605 return type == o.type && servers == o.servers &&
606 bundle_policy == o.bundle_policy &&
607 rtcp_mux_policy == o.rtcp_mux_policy &&
608 tcp_candidate_policy == o.tcp_candidate_policy &&
609 candidate_network_policy == o.candidate_network_policy &&
610 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
611 audio_jitter_buffer_fast_accelerate ==
612 o.audio_jitter_buffer_fast_accelerate &&
613 ice_connection_receiving_timeout ==
614 o.ice_connection_receiving_timeout &&
615 ice_backup_candidate_pair_ping_interval ==
616 o.ice_backup_candidate_pair_ping_interval &&
617 continual_gathering_policy == o.continual_gathering_policy &&
618 certificates == o.certificates &&
619 prioritize_most_likely_ice_candidate_pairs ==
620 o.prioritize_most_likely_ice_candidate_pairs &&
621 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800622 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700623 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800624 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800625 screencast_min_bitrate == o.screencast_min_bitrate &&
626 combined_audio_video_bwe == o.combined_audio_video_bwe &&
627 enable_dtls_srtp == o.enable_dtls_srtp &&
628 ice_candidate_pool_size == o.ice_candidate_pool_size &&
629 prune_turn_ports == o.prune_turn_ports &&
630 presume_writable_when_fully_relayed ==
631 o.presume_writable_when_fully_relayed &&
632 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800633 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700634 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200635 ice_regather_interval_range == o.ice_regather_interval_range &&
Steve Anton79e79602017-11-20 10:25:56 -0800636 turn_customizer == o.turn_customizer &&
637 sdp_semantics == o.sdp_semantics;
deadbeef293e9262017-01-11 12:28:30 -0800638}
639
640bool PeerConnectionInterface::RTCConfiguration::operator!=(
641 const PeerConnectionInterface::RTCConfiguration& o) const {
642 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800643}
644
zhihuang8f65cdf2016-05-06 18:40:30 -0700645// Generate a RTCP CNAME when a PeerConnection is created.
646std::string GenerateRtcpCname() {
647 std::string cname;
648 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100649 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800650 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700651 }
652 return cname;
653}
654
zhihuang1c378ed2017-08-17 14:10:50 -0700655bool ValidateOfferAnswerOptions(
656 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
657 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
658 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700659}
660
zhihuang1c378ed2017-08-17 14:10:50 -0700661// From |rtc_options|, fill parts of |session_options| shared by all generated
662// m= sections (in other words, nothing that involves a map/array).
663void ExtractSharedMediaSessionOptions(
664 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
665 cricket::MediaSessionOptions* session_options) {
666 session_options->vad_enabled = rtc_options.voice_activity_detection;
667 session_options->bundle_enabled = rtc_options.use_rtp_mux;
668}
zhihuanga77e6bb2017-08-14 18:17:48 -0700669
zhihuang1c378ed2017-08-17 14:10:50 -0700670bool ConvertConstraintsToOfferAnswerOptions(
671 const MediaConstraintsInterface* constraints,
672 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700673 if (!constraints) {
674 return true;
675 }
zhihuang1c378ed2017-08-17 14:10:50 -0700676
677 bool value = false;
678 size_t mandatory_constraints_satisfied = 0;
679
680 if (FindConstraint(constraints,
681 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
682 &mandatory_constraints_satisfied)) {
683 offer_answer_options->offer_to_receive_audio =
684 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
685 kOfferToReceiveMediaTrue
686 : 0;
687 }
688
689 if (FindConstraint(constraints,
690 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
691 &mandatory_constraints_satisfied)) {
692 offer_answer_options->offer_to_receive_video =
693 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
694 kOfferToReceiveMediaTrue
695 : 0;
696 }
697 if (FindConstraint(constraints,
698 MediaConstraintsInterface::kVoiceActivityDetection, &value,
699 &mandatory_constraints_satisfied)) {
700 offer_answer_options->voice_activity_detection = value;
701 }
702 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
703 &mandatory_constraints_satisfied)) {
704 offer_answer_options->use_rtp_mux = value;
705 }
706 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
707 &value, &mandatory_constraints_satisfied)) {
708 offer_answer_options->ice_restart = value;
709 }
710
deadbeefab9b2d12015-10-14 11:33:11 -0700711 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
712}
713
zhihuang38ede132017-06-15 12:52:32 -0700714PeerConnection::PeerConnection(PeerConnectionFactory* factory,
715 std::unique_ptr<RtcEventLog> event_log,
716 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000717 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700718 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700719 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700720 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700721 remote_streams_(StreamCollection::Create()),
722 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000723
724PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100725 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
Steve Anton4171afb2017-11-20 10:20:22 -0800726 RTC_DCHECK_RUN_ON(signaling_thread());
727
728 // Need to detach RTP transceivers from PeerConnection, since it's about to be
729 // destroyed.
730 for (auto transceiver : transceivers_) {
731 transceiver->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700732 }
Steve Anton4171afb2017-11-20 10:20:22 -0800733
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700734 // Destroy stats_ because it depends on session_.
735 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800736 if (stats_collector_) {
737 stats_collector_->WaitForPendingRequest();
738 stats_collector_ = nullptr;
739 }
Steve Anton75737c02017-11-06 10:37:17 -0800740
741 // Destroy video channels first since they may have a pointer to a voice
742 // channel.
Steve Anton4171afb2017-11-20 10:20:22 -0800743 for (auto transceiver : transceivers_) {
Steve Anton6fec8802017-12-04 10:37:29 -0800744 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
745 DestroyTransceiverChannel(transceiver);
Steve Anton4171afb2017-11-20 10:20:22 -0800746 }
Steve Anton75737c02017-11-06 10:37:17 -0800747 }
Steve Anton4171afb2017-11-20 10:20:22 -0800748 for (auto transceiver : transceivers_) {
Steve Anton6fec8802017-12-04 10:37:29 -0800749 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
750 DestroyTransceiverChannel(transceiver);
Steve Anton4171afb2017-11-20 10:20:22 -0800751 }
Steve Anton75737c02017-11-06 10:37:17 -0800752 }
Steve Anton6fec8802017-12-04 10:37:29 -0800753 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -0800754
Mirko Bonadei675513b2017-11-09 11:09:25 +0100755 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800756
757 webrtc_session_desc_factory_.reset();
758 sctp_invoker_.reset();
759 sctp_factory_.reset();
760 transport_controller_.reset();
761
deadbeef91dd5672016-05-18 16:55:30 -0700762 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700763 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700764 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700765 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700766 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700767 call_.reset();
768 event_log_.reset();
769 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000770}
771
772bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000773 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700774 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200775 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800776 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100777 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700778
779 RTCError config_error = ValidateConfiguration(configuration);
780 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100781 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700782 return false;
783 }
784
deadbeef293e9262017-01-11 12:28:30 -0800785 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100786 RTC_LOG(LS_ERROR)
787 << "PeerConnection initialized without a PortAllocator? "
788 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800789 return false;
790 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200791
deadbeef653b8e02015-11-11 12:55:10 -0800792 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800793 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100794 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
795 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800796 return false;
797 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000798 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800799 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800800
deadbeef91dd5672016-05-18 16:55:30 -0700801 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700802 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700803 if (!network_thread()->Invoke<bool>(
804 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
805 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000806 return false;
807 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000808
Steve Anton75737c02017-11-06 10:37:17 -0800809 // RFC 3264: The numeric value of the session id and version in the
810 // o line MUST be representable with a "64 bit signed integer".
811 // Due to this constraint session id |session_id_| is max limited to
812 // LLONG_MAX.
813 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
814 transport_controller_.reset(factory_->CreateTransportController(
815 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
816 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
817 transport_controller_->SignalConnectionState.connect(
818 this, &PeerConnection::OnTransportControllerConnectionState);
819 transport_controller_->SignalGatheringState.connect(
820 this, &PeerConnection::OnTransportControllerGatheringState);
821 transport_controller_->SignalCandidatesGathered.connect(
822 this, &PeerConnection::OnTransportControllerCandidatesGathered);
823 transport_controller_->SignalCandidatesRemoved.connect(
824 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
825 transport_controller_->SignalDtlsHandshakeError.connect(
826 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
827
828 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700829
deadbeefab9b2d12015-10-14 11:33:11 -0700830 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700831 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000832
Steve Antonba818672017-11-06 10:21:57 -0800833 configuration_ = configuration;
834
Steve Anton75737c02017-11-06 10:37:17 -0800835 const PeerConnectionFactoryInterface::Options& options = factory_->options();
836
837 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
838
839 // Obtain a certificate from RTCConfiguration if any were provided (optional).
840 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
841 if (!configuration.certificates.empty()) {
842 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
843 // just picking the first one. The decision should be made based on the DTLS
844 // handshake. The DTLS negotiations need to know about all certificates.
845 certificate = configuration.certificates[0];
846 }
847
Steve Antond25da372017-11-06 14:50:29 -0800848 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800849
850 if (options.disable_encryption) {
851 dtls_enabled_ = false;
852 } else {
853 // Enable DTLS by default if we have an identity store or a certificate.
854 dtls_enabled_ = (cert_generator || certificate);
855 // |configuration| can override the default |dtls_enabled_| value.
856 if (configuration.enable_dtls_srtp) {
857 dtls_enabled_ = *(configuration.enable_dtls_srtp);
858 }
859 }
860
861 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
862 // It takes precendence over the disable_sctp_data_channels
863 // PeerConnectionFactoryInterface::Options.
864 if (configuration.enable_rtp_data_channel) {
865 data_channel_type_ = cricket::DCT_RTP;
866 } else {
867 // DTLS has to be enabled to use SCTP.
868 if (!options.disable_sctp_data_channels && dtls_enabled_) {
869 data_channel_type_ = cricket::DCT_SCTP;
870 }
871 }
872
873 video_options_.screencast_min_bitrate_kbps =
874 configuration.screencast_min_bitrate;
875 audio_options_.combined_audio_video_bwe =
876 configuration.combined_audio_video_bwe;
877
878 audio_options_.audio_jitter_buffer_max_packets =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100879 configuration.audio_jitter_buffer_max_packets;
Steve Anton75737c02017-11-06 10:37:17 -0800880
881 audio_options_.audio_jitter_buffer_fast_accelerate =
Oskar Sundbom9b28a032017-11-16 10:53:30 +0100882 configuration.audio_jitter_buffer_fast_accelerate;
Steve Anton75737c02017-11-06 10:37:17 -0800883
884 // Whether the certificate generator/certificate is null or not determines
885 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
886 // the right instructions by clearing the variables if needed.
887 if (!dtls_enabled_) {
888 cert_generator.reset();
889 certificate = nullptr;
890 } else if (certificate) {
891 // Favor generated certificate over the certificate generator.
892 cert_generator.reset();
893 }
894
895 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
896 signaling_thread(), channel_manager(), this, session_id(),
897 std::move(cert_generator), certificate));
898 webrtc_session_desc_factory_->SignalCertificateReady.connect(
899 this, &PeerConnection::OnCertificateReady);
900
901 if (options.disable_encryption) {
902 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
903 }
904
905 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
906 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000907
Steve Anton4171afb2017-11-20 10:20:22 -0800908 // Add default audio/video transceivers for Plan B SDP.
909 if (!IsUnifiedPlan()) {
910 transceivers_.push_back(
911 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
912 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_AUDIO)));
913 transceivers_.push_back(
914 RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
915 signaling_thread(), new RtpTransceiver(cricket::MEDIA_TYPE_VIDEO)));
916 }
917
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918 return true;
919}
920
Steve Anton038834f2017-07-14 15:59:59 -0700921RTCError PeerConnection::ValidateConfiguration(
922 const RTCConfiguration& config) const {
923 if (config.ice_regather_interval_range &&
924 config.continual_gathering_policy == GATHER_ONCE) {
925 return RTCError(RTCErrorType::INVALID_PARAMETER,
926 "ice_regather_interval_range specified but continual "
927 "gathering policy is GATHER_ONCE");
928 }
929 return RTCError::OK();
930}
931
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000932rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000933PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700934 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000935}
936
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000937rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000938PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -0700939 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000940}
941
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +0000942bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100943 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944 if (IsClosed()) {
945 return false;
946 }
deadbeefab9b2d12015-10-14 11:33:11 -0700947 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000948 return false;
949 }
deadbeefab9b2d12015-10-14 11:33:11 -0700950
951 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800952 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
953 observer->SignalAudioTrackAdded.connect(this,
954 &PeerConnection::OnAudioTrackAdded);
955 observer->SignalAudioTrackRemoved.connect(
956 this, &PeerConnection::OnAudioTrackRemoved);
957 observer->SignalVideoTrackAdded.connect(this,
958 &PeerConnection::OnVideoTrackAdded);
959 observer->SignalVideoTrackRemoved.connect(
960 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -0700961 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -0700962
deadbeefab9b2d12015-10-14 11:33:11 -0700963 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700964 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700965 }
966 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700967 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -0700968 }
969
tommi@webrtc.org03505bc2014-07-14 20:15:26 +0000970 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000971 observer_->OnRenegotiationNeeded();
972 return true;
973}
974
975void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100976 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -0700977 if (!IsClosed()) {
978 for (const auto& track : local_stream->GetAudioTracks()) {
979 RemoveAudioTrack(track.get(), local_stream);
980 }
981 for (const auto& track : local_stream->GetVideoTracks()) {
982 RemoveVideoTrack(track.get(), local_stream);
983 }
deadbeefab9b2d12015-10-14 11:33:11 -0700984 }
deadbeefab9b2d12015-10-14 11:33:11 -0700985 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -0800986 stream_observers_.erase(
987 std::remove_if(
988 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -0700989 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -0800990 return observer->stream()->label().compare(local_stream->label()) ==
991 0;
992 }),
993 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -0700994
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000995 if (IsClosed()) {
996 return;
997 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000998 observer_->OnRenegotiationNeeded();
999}
1000
deadbeefe1f9d832016-01-14 15:35:42 -08001001rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1002 MediaStreamTrackInterface* track,
1003 std::vector<MediaStreamInterface*> streams) {
1004 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1005 if (IsClosed()) {
1006 return nullptr;
1007 }
1008 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001009 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001010 << "Adding a track with two streams is not currently supported.";
1011 return nullptr;
1012 }
Steve Anton4171afb2017-11-20 10:20:22 -08001013 if (FindSenderForTrack(track)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001014 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1015 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001016 return nullptr;
1017 }
1018
1019 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001020 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001021 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001022 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001023 signaling_thread(),
1024 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001025 voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001026 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001027 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001028 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001029 }
Steve Anton4171afb2017-11-20 10:20:22 -08001030 const RtpSenderInfo* sender_info =
1031 FindSenderInfo(local_audio_sender_infos_,
1032 new_sender->internal()->stream_id(), track->id());
1033 if (sender_info) {
1034 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001035 }
1036 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001037 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001038 signaling_thread(),
1039 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001040 video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001041 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001042 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001043 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001044 }
Steve Anton4171afb2017-11-20 10:20:22 -08001045 const RtpSenderInfo* sender_info =
1046 FindSenderInfo(local_video_sender_infos_,
1047 new_sender->internal()->stream_id(), track->id());
1048 if (sender_info) {
1049 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001050 }
1051 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001052 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1053 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001054 return rtc::scoped_refptr<RtpSenderInterface>();
1055 }
1056
deadbeefe1f9d832016-01-14 15:35:42 -08001057 observer_->OnRenegotiationNeeded();
1058 return new_sender;
1059}
1060
1061bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1062 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1063 if (IsClosed()) {
1064 return false;
1065 }
1066
Steve Anton4171afb2017-11-20 10:20:22 -08001067 bool removed;
1068 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
1069 removed = GetAudioTransceiver()->internal()->RemoveSender(sender);
1070 } else {
1071 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, sender->media_type());
1072 removed = GetVideoTransceiver()->internal()->RemoveSender(sender);
1073 }
1074 if (!removed) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001075 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1076 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001077 return false;
1078 }
deadbeefe1f9d832016-01-14 15:35:42 -08001079
1080 observer_->OnRenegotiationNeeded();
1081 return true;
1082}
1083
Steve Anton9158ef62017-11-27 13:01:52 -08001084RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1085PeerConnection::AddTransceiver(
1086 rtc::scoped_refptr<MediaStreamTrackInterface> track) {
1087 return AddTransceiver(track, RtpTransceiverInit());
1088}
1089
1090RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1091PeerConnection::AddTransceiver(
1092 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1093 const RtpTransceiverInit& init) {
1094 if (!IsUnifiedPlan()) {
1095 LOG_AND_RETURN_ERROR(
1096 RTCErrorType::INTERNAL_ERROR,
1097 "AddTransceiver only supported when Unified Plan is enabled.");
1098 }
1099 if (!track) {
1100 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, "track is null");
1101 }
1102 cricket::MediaType media_type;
1103 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
1104 media_type = cricket::MEDIA_TYPE_AUDIO;
1105 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
1106 media_type = cricket::MEDIA_TYPE_VIDEO;
1107 } else {
1108 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1109 "Track kind is not audio or video");
1110 }
1111 return AddTransceiver(media_type, track, init);
1112}
1113
1114RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1115PeerConnection::AddTransceiver(cricket::MediaType media_type) {
1116 return AddTransceiver(media_type, RtpTransceiverInit());
1117}
1118
1119RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1120PeerConnection::AddTransceiver(cricket::MediaType media_type,
1121 const RtpTransceiverInit& init) {
1122 if (!IsUnifiedPlan()) {
1123 LOG_AND_RETURN_ERROR(
1124 RTCErrorType::INTERNAL_ERROR,
1125 "AddTransceiver only supported when Unified Plan is enabled.");
1126 }
1127 if (!(media_type == cricket::MEDIA_TYPE_AUDIO ||
1128 media_type == cricket::MEDIA_TYPE_VIDEO)) {
1129 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1130 "media type is not audio or video");
1131 }
1132 return AddTransceiver(media_type, nullptr, init);
1133}
1134
1135RTCErrorOr<rtc::scoped_refptr<RtpTransceiverInterface>>
1136PeerConnection::AddTransceiver(
1137 cricket::MediaType media_type,
1138 rtc::scoped_refptr<MediaStreamTrackInterface> track,
1139 const RtpTransceiverInit& init) {
1140 RTC_DCHECK((media_type == cricket::MEDIA_TYPE_AUDIO ||
1141 media_type == cricket::MEDIA_TYPE_VIDEO));
1142 if (track) {
1143 RTC_DCHECK_EQ(media_type,
1144 (track->kind() == MediaStreamTrackInterface::kAudioKind
1145 ? cricket::MEDIA_TYPE_AUDIO
1146 : cricket::MEDIA_TYPE_VIDEO));
1147 }
1148
1149 // TODO(bugs.webrtc.org/7600): Verify init.
1150
1151 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> sender;
1152 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
1153 receiver;
1154 std::string receiver_id = rtc::CreateRandomUuid();
1155 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
1156 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1157 signaling_thread(), new AudioRtpSender(nullptr, stats_.get()));
1158 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1159 signaling_thread(), new AudioRtpReceiver(receiver_id, {}, 0, nullptr));
1160 } else {
1161 RTC_DCHECK_EQ(cricket::MEDIA_TYPE_VIDEO, media_type);
1162 sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
1163 signaling_thread(), new VideoRtpSender(nullptr));
1164 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
1165 signaling_thread(),
1166 new VideoRtpReceiver(receiver_id, {}, worker_thread(), 0, nullptr));
1167 }
1168 // TODO(bugs.webrtc.org/7600): Initializing the sender/receiver with a null
1169 // channel prevents users from calling SetParameters on them, which is needed
1170 // to be in compliance with the spec.
1171
1172 if (track) {
1173 sender->SetTrack(track);
1174 }
1175
1176 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1177 transceiver = RtpTransceiverProxyWithInternal<RtpTransceiver>::Create(
1178 signaling_thread(), new RtpTransceiver(sender, receiver));
1179 transceiver->SetDirection(init.direction);
1180
1181 transceivers_.push_back(transceiver);
1182
1183 observer_->OnRenegotiationNeeded();
1184
1185 return rtc::scoped_refptr<RtpTransceiverInterface>(transceiver);
1186}
1187
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001188rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001189 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001190 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001191 if (IsClosed()) {
1192 return nullptr;
1193 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001195 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001196 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001197 }
Steve Anton4171afb2017-11-20 10:20:22 -08001198 auto track_sender = FindSenderForTrack(track);
1199 if (!track_sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001200 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001201 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001202 }
1203
Steve Anton4171afb2017-11-20 10:20:22 -08001204 return track_sender->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001205}
1206
deadbeeffac06552015-11-25 11:26:01 -08001207rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001208 const std::string& kind,
1209 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001210 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001211 if (IsClosed()) {
1212 return nullptr;
1213 }
Steve Anton4171afb2017-11-20 10:20:22 -08001214
1215 // TODO(steveanton): Move construction of the RtpSenders to RtpTransceiver.
deadbeefa601f5c2016-06-06 14:27:39 -07001216 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001217 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001218 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001219 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08001220 GetAudioTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001221 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001222 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001223 signaling_thread(), new VideoRtpSender(video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08001224 GetVideoTransceiver()->internal()->AddSender(new_sender);
deadbeeffac06552015-11-25 11:26:01 -08001225 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001226 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
Steve Anton4171afb2017-11-20 10:20:22 -08001227 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08001228 }
Steve Anton4171afb2017-11-20 10:20:22 -08001229
deadbeefbd7d8f72015-12-18 16:58:44 -08001230 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001231 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001232 }
Steve Anton4171afb2017-11-20 10:20:22 -08001233
deadbeefe1f9d832016-01-14 15:35:42 -08001234 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001235}
1236
deadbeef70ab1a12015-09-28 16:53:55 -07001237std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1238 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001239 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001240 for (auto sender : GetSendersInternal()) {
1241 ret.push_back(sender);
deadbeefa601f5c2016-06-06 14:27:39 -07001242 }
1243 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001244}
1245
Steve Anton4171afb2017-11-20 10:20:22 -08001246std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1247PeerConnection::GetSendersInternal() const {
1248 std::vector<rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>
1249 all_senders;
1250 for (auto transceiver : transceivers_) {
1251 auto senders = transceiver->internal()->senders();
1252 all_senders.insert(all_senders.end(), senders.begin(), senders.end());
1253 }
1254 return all_senders;
1255}
1256
deadbeef70ab1a12015-09-28 16:53:55 -07001257std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1258PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001259 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
Steve Anton4171afb2017-11-20 10:20:22 -08001260 for (const auto& receiver : GetReceiversInternal()) {
1261 ret.push_back(receiver);
deadbeefa601f5c2016-06-06 14:27:39 -07001262 }
1263 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001264}
1265
Steve Anton4171afb2017-11-20 10:20:22 -08001266std::vector<
1267 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1268PeerConnection::GetReceiversInternal() const {
1269 std::vector<
1270 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>>
1271 all_receivers;
1272 for (auto transceiver : transceivers_) {
1273 auto receivers = transceiver->internal()->receivers();
1274 all_receivers.insert(all_receivers.end(), receivers.begin(),
1275 receivers.end());
1276 }
1277 return all_receivers;
1278}
1279
Steve Anton9158ef62017-11-27 13:01:52 -08001280std::vector<rtc::scoped_refptr<RtpTransceiverInterface>>
1281PeerConnection::GetTransceivers() const {
1282 RTC_DCHECK(IsUnifiedPlan());
1283 std::vector<rtc::scoped_refptr<RtpTransceiverInterface>> all_transceivers;
1284 for (auto transceiver : transceivers_) {
1285 all_transceivers.push_back(transceiver);
1286 }
1287 return all_transceivers;
1288}
1289
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001290bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001291 MediaStreamTrackInterface* track,
1292 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001293 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001294 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001295 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001296 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001297 return false;
1298 }
1299
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001300 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001301 // The StatsCollector is used to tell if a track is valid because it may
1302 // remember tracks that the PeerConnection previously removed.
1303 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001304 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1305 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001306 return false;
1307 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001308 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001309 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310 return true;
1311}
1312
hbos74e1a4f2016-09-15 23:33:01 -07001313void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1314 RTC_DCHECK(stats_collector_);
1315 stats_collector_->GetStatsReport(callback);
1316}
1317
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001318PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1319 return signaling_state_;
1320}
1321
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001322PeerConnectionInterface::IceConnectionState
1323PeerConnection::ice_connection_state() {
1324 return ice_connection_state_;
1325}
1326
1327PeerConnectionInterface::IceGatheringState
1328PeerConnection::ice_gathering_state() {
1329 return ice_gathering_state_;
1330}
1331
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001332rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001333PeerConnection::CreateDataChannel(
1334 const std::string& label,
1335 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001336 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001337
deadbeefab9b2d12015-10-14 11:33:11 -07001338 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001339
kwibergd1fe2812016-04-27 06:47:29 -07001340 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001341 if (config) {
1342 internal_config.reset(new InternalDataChannelInit(*config));
1343 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001344 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001345 InternalCreateDataChannel(label, internal_config.get()));
1346 if (!channel.get()) {
1347 return nullptr;
1348 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001349
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001350 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1351 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001352 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001353 observer_->OnRenegotiationNeeded();
1354 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001355
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356 return DataChannelProxy::Create(signaling_thread(), channel.get());
1357}
1358
1359void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1360 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001361 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001362
zhihuang1c378ed2017-08-17 14:10:50 -07001363 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1364 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1365 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1366 // compares the mandatory fields parsed with the mandatory fields added in the
1367 // |constraints| and some downstream applications might create offers with
1368 // mandatory fields which would not be parsed in the helper method. For
1369 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1370 // |constraints| as a mandatory field but it is not parsed.
1371 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001372
zhihuang1c378ed2017-08-17 14:10:50 -07001373 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001374}
1375
1376void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1377 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001378 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001379
nisse7ce109a2017-01-31 00:57:56 -08001380 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001381 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001382 return;
1383 }
deadbeefab9b2d12015-10-14 11:33:11 -07001384
Steve Anton8d3444d2017-10-20 15:30:51 -07001385 if (IsClosed()) {
1386 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001387 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001388 PostCreateSessionDescriptionFailure(observer, error);
1389 return;
1390 }
1391
zhihuang1c378ed2017-08-17 14:10:50 -07001392 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001393 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001394 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001395 PostCreateSessionDescriptionFailure(observer, error);
1396 return;
1397 }
1398
zhihuang1c378ed2017-08-17 14:10:50 -07001399 cricket::MediaSessionOptions session_options;
1400 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001401 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001402}
1403
1404void PeerConnection::CreateAnswer(
1405 CreateSessionDescriptionObserver* observer,
1406 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001407 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001408
nisse7ce109a2017-01-31 00:57:56 -08001409 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001410 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001411 return;
1412 }
deadbeefab9b2d12015-10-14 11:33:11 -07001413
zhihuang1c378ed2017-08-17 14:10:50 -07001414 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1415 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1416 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001417 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001418 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001419 PostCreateSessionDescriptionFailure(observer, error);
1420 return;
1421 }
1422
Steve Anton8d3444d2017-10-20 15:30:51 -07001423 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001424}
1425
1426void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1427 const RTCOfferAnswerOptions& options) {
1428 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001429 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001430 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001431 return;
1432 }
1433
Steve Anton8d3444d2017-10-20 15:30:51 -07001434 if (IsClosed()) {
1435 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001436 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001437 PostCreateSessionDescriptionFailure(observer, error);
1438 return;
1439 }
1440
Steve Anton75737c02017-11-06 10:37:17 -08001441 if (remote_description() &&
1442 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001443 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001444 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001445 PostCreateSessionDescriptionFailure(observer, error);
1446 return;
1447 }
1448
htaa2a49d92016-03-04 02:51:39 -08001449 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001450 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001451
Steve Antond25da372017-11-06 14:50:29 -08001452 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001453}
1454
1455void PeerConnection::SetLocalDescription(
1456 SetSessionDescriptionObserver* observer,
1457 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001458 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001459
nisse7ce109a2017-01-31 00:57:56 -08001460 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001461 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001462 return;
1463 }
Steve Anton8a006912017-12-04 15:25:56 -08001464
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001465 if (!desc) {
1466 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1467 return;
1468 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001469
Steve Anton8a006912017-12-04 15:25:56 -08001470 std::string desc_type = desc->type();
Steve Anton8d3444d2017-10-20 15:30:51 -07001471
Steve Anton8a006912017-12-04 15:25:56 -08001472 RTCError error = ApplyLocalDescription(rtc::WrapUnique(desc));
1473 // |desc| may be destroyed at this point.
1474
1475 if (!error.ok()) {
1476 std::string error_message =
1477 "Failed to set local " + desc_type + " sdp: " + error.message();
1478 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
1479 PostSetSessionDescriptionFailure(observer, std::move(error_message));
Steve Anton8d3444d2017-10-20 15:30:51 -07001480 return;
1481 }
Steve Anton8a006912017-12-04 15:25:56 -08001482 RTC_DCHECK(local_description());
1483
1484 PostSetSessionDescriptionSuccess(observer);
1485
1486 // According to JSEP, after setLocalDescription, changing the candidate pool
1487 // size is not allowed, and changing the set of ICE servers will not result
1488 // in new candidates being gathered.
1489 port_allocator_->FreezeCandidatePool();
1490
1491 // MaybeStartGathering needs to be called after posting
1492 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1493 // before signaling that SetLocalDescription completed.
1494 transport_controller_->MaybeStartGathering();
1495
1496 if (local_description()->type() == SessionDescriptionInterface::kAnswer) {
1497 // TODO(deadbeef): We already had to hop to the network thread for
1498 // MaybeStartGathering...
1499 network_thread()->Invoke<void>(
1500 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1501 port_allocator_.get()));
1502 }
1503}
1504
1505RTCError PeerConnection::ApplyLocalDescription(
1506 std::unique_ptr<SessionDescriptionInterface> desc) {
1507 RTC_DCHECK_RUN_ON(signaling_thread());
1508 RTC_DCHECK(desc);
1509
1510 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_LOCAL);
1511 if (!error.ok()) {
1512 return error;
1513 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001514
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001515 // Update stats here so that we have the most recent stats for tracks and
1516 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001517 stats_->UpdateStats(kStatsOutputLevelStandard);
Steve Anton8a006912017-12-04 15:25:56 -08001518
1519 // Update the initial_offerer flag if this session is the initial_offerer.
Steve Anton3828c062017-12-06 10:34:51 -08001520 SdpType type = desc->GetType();
Steve Anton8a006912017-12-04 15:25:56 -08001521 if (!initial_offerer_.has_value()) {
Steve Anton3828c062017-12-06 10:34:51 -08001522 initial_offerer_.emplace(type == SdpType::kOffer);
Steve Anton8a006912017-12-04 15:25:56 -08001523 if (*initial_offerer_) {
1524 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
1525 } else {
1526 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
1527 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001528 }
Steve Anton8a006912017-12-04 15:25:56 -08001529
Steve Anton3828c062017-12-06 10:34:51 -08001530 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001531 current_local_description_ = std::move(desc);
1532 pending_local_description_ = nullptr;
1533 current_remote_description_ = std::move(pending_remote_description_);
1534 } else {
1535 pending_local_description_ = std::move(desc);
1536 }
1537 // The session description to apply now must be accessed by
1538 // |local_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001539 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001540
Steve Anton8a006912017-12-04 15:25:56 -08001541 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001542 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001543 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1544 // is applied. Restore back to old description.
1545 RTCError error = CreateChannels(local_description()->description());
1546 if (!error.ok()) {
1547 return error;
1548 }
1549 }
1550
1551 // Remove unused channels if MediaContentDescription is rejected.
1552 RemoveUnusedChannels(local_description()->description());
1553
Steve Anton3828c062017-12-06 10:34:51 -08001554 error = UpdateSessionState(type, cricket::CS_LOCAL);
Steve Anton8a006912017-12-04 15:25:56 -08001555 if (!error.ok()) {
1556 return error;
1557 }
1558 if (remote_description()) {
1559 // Now that we have a local description, we can push down remote candidates.
1560 UseCandidatesInSessionDescription(remote_description());
1561 }
1562
1563 pending_ice_restarts_.clear();
1564 if (session_error() != SessionError::kNone) {
1565 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1566 }
1567
deadbeefab9b2d12015-10-14 11:33:11 -07001568 // If setting the description decided our SSL role, allocate any necessary
1569 // SCTP sids.
1570 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001571 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001572 AllocateSctpSids(role);
1573 }
1574
1575 // Update state and SSRC of local MediaStreams and DataChannels based on the
1576 // local session description.
1577 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001578 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001579 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001580 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001581 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001582 } else {
1583 const cricket::AudioContentDescription* audio_desc =
1584 static_cast<const cricket::AudioContentDescription*>(
1585 audio_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001586 UpdateLocalSenders(audio_desc->streams(), audio_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001587 }
deadbeefab9b2d12015-10-14 11:33:11 -07001588 }
1589
1590 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001591 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001592 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001593 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001594 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001595 } else {
1596 const cricket::VideoContentDescription* video_desc =
1597 static_cast<const cricket::VideoContentDescription*>(
1598 video_content->description);
Steve Anton4171afb2017-11-20 10:20:22 -08001599 UpdateLocalSenders(video_desc->streams(), video_desc->type());
deadbeeffaac4972015-11-12 15:33:07 -08001600 }
deadbeefab9b2d12015-10-14 11:33:11 -07001601 }
1602
1603 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001604 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001605 if (data_content) {
1606 const cricket::DataContentDescription* data_desc =
1607 static_cast<const cricket::DataContentDescription*>(
1608 data_content->description);
1609 if (rtc::starts_with(data_desc->protocol().data(),
1610 cricket::kMediaProtocolRtpPrefix)) {
1611 UpdateLocalRtpDataChannels(data_desc->streams());
1612 }
1613 }
1614
Steve Anton8a006912017-12-04 15:25:56 -08001615 return RTCError::OK();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001616}
1617
1618void PeerConnection::SetRemoteDescription(
Henrik Boströma4ecf552017-11-23 14:17:07 +00001619 SetSessionDescriptionObserver* observer,
1620 SessionDescriptionInterface* desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001621 SetRemoteDescription(
1622 std::unique_ptr<SessionDescriptionInterface>(desc),
1623 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface>(
1624 new SetRemoteDescriptionObserverAdapter(this, observer)));
1625}
1626
1627void PeerConnection::SetRemoteDescription(
1628 std::unique_ptr<SessionDescriptionInterface> desc,
1629 rtc::scoped_refptr<SetRemoteDescriptionObserverInterface> observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001630 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
Steve Anton8a006912017-12-04 15:25:56 -08001631
nisse7ce109a2017-01-31 00:57:56 -08001632 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001633 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001634 return;
1635 }
Steve Anton8a006912017-12-04 15:25:56 -08001636
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001637 if (!desc) {
Henrik Boström31638672017-11-23 17:48:32 +01001638 observer->OnSetRemoteDescriptionComplete(RTCError(
Steve Anton8a006912017-12-04 15:25:56 -08001639 RTCErrorType::INVALID_PARAMETER, "SessionDescription is NULL."));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001640 return;
1641 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001642
Steve Anton8a006912017-12-04 15:25:56 -08001643 std::string desc_type = desc->type();
1644
1645 RTCError error = ApplyRemoteDescription(std::move(desc));
1646 // |desc| may be destroyed at this point.
1647
1648 if (!error.ok()) {
1649 std::string error_message =
1650 "Failed to set remote " + desc_type + " sdp: " + error.message();
1651 RTC_LOG(LS_ERROR) << error_message << " (" << error.type() << ")";
Henrik Boström31638672017-11-23 17:48:32 +01001652 observer->OnSetRemoteDescriptionComplete(
Steve Anton8a006912017-12-04 15:25:56 -08001653 RTCError(error.type(), std::move(error_message)));
Steve Anton8d3444d2017-10-20 15:30:51 -07001654 return;
1655 }
1656
Steve Anton8a006912017-12-04 15:25:56 -08001657 if (remote_description()->type() == SessionDescriptionInterface::kAnswer) {
1658 // TODO(deadbeef): We already had to hop to the network thread for
1659 // MaybeStartGathering...
1660 network_thread()->Invoke<void>(
1661 RTC_FROM_HERE, rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1662 port_allocator_.get()));
1663 }
1664
1665 observer->OnSetRemoteDescriptionComplete(RTCError::OK());
1666}
1667
1668RTCError PeerConnection::ApplyRemoteDescription(
1669 std::unique_ptr<SessionDescriptionInterface> desc) {
1670 RTC_DCHECK_RUN_ON(signaling_thread());
1671 RTC_DCHECK(desc);
1672
1673 RTCError error = ValidateSessionDescription(desc.get(), cricket::CS_REMOTE);
1674 if (!error.ok()) {
1675 return error;
1676 }
1677
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001678 // Update stats here so that we have the most recent stats for tracks and
1679 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001680 stats_->UpdateStats(kStatsOutputLevelStandard);
Henrik Boström31638672017-11-23 17:48:32 +01001681 // Takes the ownership of |desc|. On success, remote_description() is updated
1682 // to reflect the description that was passed in.
Steve Anton8a006912017-12-04 15:25:56 -08001683
1684 const SessionDescriptionInterface* old_remote_description =
1685 remote_description();
1686 // Grab ownership of the description being replaced for the remainder of this
1687 // method, since it's used below as |old_remote_description|.
1688 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
Steve Anton3828c062017-12-06 10:34:51 -08001689 SdpType type = desc->GetType();
1690 if (type == SdpType::kAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08001691 replaced_remote_description = pending_remote_description_
1692 ? std::move(pending_remote_description_)
1693 : std::move(current_remote_description_);
1694 current_remote_description_ = std::move(desc);
1695 pending_remote_description_ = nullptr;
1696 current_local_description_ = std::move(pending_local_description_);
1697 } else {
1698 replaced_remote_description = std::move(pending_remote_description_);
1699 pending_remote_description_ = std::move(desc);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001700 }
Steve Anton8a006912017-12-04 15:25:56 -08001701 // The session description to apply now must be accessed by
1702 // |remote_description()|.
Henrik Boströmfdb92012017-11-09 19:55:44 +01001703 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001704
Steve Anton8a006912017-12-04 15:25:56 -08001705 // Transport and Media channels will be created only when offer is set.
Steve Anton3828c062017-12-06 10:34:51 -08001706 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001707 // TODO(mallinath) - Handle CreateChannel failure, as new local description
1708 // is applied. Restore back to old description.
1709 RTCError error = CreateChannels(remote_description()->description());
1710 if (!error.ok()) {
1711 return error;
1712 }
1713 }
1714
1715 // Remove unused channels if MediaContentDescription is rejected.
1716 RemoveUnusedChannels(remote_description()->description());
1717
1718 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
1719 // is called.
Steve Anton3828c062017-12-06 10:34:51 -08001720 error = UpdateSessionState(type, cricket::CS_REMOTE);
Steve Anton8a006912017-12-04 15:25:56 -08001721 if (!error.ok()) {
1722 return error;
1723 }
1724
1725 if (local_description() &&
1726 !UseCandidatesInSessionDescription(remote_description())) {
1727 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidCandidates);
1728 }
1729
1730 if (old_remote_description) {
1731 for (const cricket::ContentInfo& content :
1732 old_remote_description->description()->contents()) {
1733 // Check if this new SessionDescription contains new ICE ufrag and
1734 // password that indicates the remote peer requests an ICE restart.
1735 // TODO(deadbeef): When we start storing both the current and pending
1736 // remote description, this should reset pending_ice_restarts and compare
1737 // against the current description.
1738 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
1739 content.name)) {
Steve Anton3828c062017-12-06 10:34:51 -08001740 if (type == SdpType::kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08001741 pending_ice_restarts_.insert(content.name);
1742 }
1743 } else {
1744 // We retain all received candidates only if ICE is not restarted.
1745 // When ICE is restarted, all previous candidates belong to an old
1746 // generation and should not be kept.
1747 // TODO(deadbeef): This goes against the W3C spec which says the remote
1748 // description should only contain candidates from the last set remote
1749 // description plus any candidates added since then. We should remove
1750 // this once we're sure it won't break anything.
1751 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
1752 old_remote_description, content.name, mutable_remote_description());
1753 }
1754 }
1755 }
1756
1757 if (session_error() != SessionError::kNone) {
1758 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
1759 }
1760
1761 // Set the the ICE connection state to connecting since the connection may
1762 // become writable with peer reflexive candidates before any remote candidate
1763 // is signaled.
1764 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
1765 // is to have a new signal the indicates a change in checking state from the
1766 // transport and expose a new checking() member from transport that can be
1767 // read to determine the current checking state. The existing SignalConnecting
1768 // actually means "gathering candidates", so cannot be be used here.
1769 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
1770 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
1771 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
1772 }
1773
deadbeefab9b2d12015-10-14 11:33:11 -07001774 // If setting the description decided our SSL role, allocate any necessary
1775 // SCTP sids.
1776 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001777 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001778 AllocateSctpSids(role);
1779 }
1780
Henrik Boströmfdb92012017-11-09 19:55:44 +01001781 const cricket::ContentInfo* audio_content =
1782 GetFirstAudioContent(remote_description()->description());
1783 const cricket::ContentInfo* video_content =
1784 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001785 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001786 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001787 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001788 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001789 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001790 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001791
1792 // Check if the descriptions include streams, just in case the peer supports
1793 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001794 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001795 (audio_desc && !audio_desc->streams().empty()) ||
1796 (video_desc && !video_desc->streams().empty())) {
1797 remote_peer_supports_msid_ = true;
1798 }
deadbeefab9b2d12015-10-14 11:33:11 -07001799
1800 // We wait to signal new streams until we finish processing the description,
1801 // since only at that point will new streams have all their tracks.
1802 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1803
Steve Anton8d3444d2017-10-20 15:30:51 -07001804 // TODO(steveanton): When removing RTP senders/receivers in response to a
1805 // rejected media section, there is some cleanup logic that expects the voice/
1806 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001807 // would have been destroyed by the SetRemoteDescription caller above so the
Steve Anton4171afb2017-11-20 10:20:22 -08001808 // cleanup that relies on them fails to run. The RemoveSenders calls should be
Steve Anton75737c02017-11-06 10:37:17 -08001809 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001810
deadbeefab9b2d12015-10-14 11:33:11 -07001811 // Find all audio rtp streams and create corresponding remote AudioTracks
1812 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001813 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001814 if (audio_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001815 RemoveSenders(cricket::MEDIA_TYPE_AUDIO);
deadbeeffaac4972015-11-12 15:33:07 -08001816 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001817 bool default_audio_track_needed =
1818 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001819 RtpTransceiverDirectionHasSend(audio_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001820 UpdateRemoteSendersList(GetActiveStreams(audio_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001821 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001822 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001823 }
deadbeefab9b2d12015-10-14 11:33:11 -07001824 }
1825
1826 // Find all video rtp streams and create corresponding remote VideoTracks
1827 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001828 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001829 if (video_content->rejected) {
Steve Anton4171afb2017-11-20 10:20:22 -08001830 RemoveSenders(cricket::MEDIA_TYPE_VIDEO);
deadbeeffaac4972015-11-12 15:33:07 -08001831 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001832 bool default_video_track_needed =
1833 !remote_peer_supports_msid_ &&
Steve Anton4e70a722017-11-28 14:57:10 -08001834 RtpTransceiverDirectionHasSend(video_desc->direction());
Steve Anton4171afb2017-11-20 10:20:22 -08001835 UpdateRemoteSendersList(GetActiveStreams(video_desc),
deadbeefbda7e0b2015-12-08 17:13:40 -08001836 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001837 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001838 }
deadbeefab9b2d12015-10-14 11:33:11 -07001839 }
1840
1841 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001842 if (data_desc) {
1843 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001844 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001845 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001846 }
1847 }
1848
1849 // Iterate new_streams and notify the observer about new MediaStreams.
1850 for (size_t i = 0; i < new_streams->count(); ++i) {
1851 MediaStreamInterface* new_stream = new_streams->at(i);
1852 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001853 observer_->OnAddStream(
1854 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001855 }
1856
deadbeefbda7e0b2015-12-08 17:13:40 -08001857 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001858
Steve Anton8a006912017-12-04 15:25:56 -08001859 return RTCError::OK();
deadbeeffc648b62015-10-13 16:42:33 -07001860}
1861
Steve Antoned10bd92017-12-05 10:52:59 -08001862const cricket::ContentInfo* PeerConnection::FindMediaSectionForTransceiver(
1863 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
1864 transceiver,
1865 const SessionDescriptionInterface* sdesc) const {
1866 RTC_DCHECK(transceiver);
1867 RTC_DCHECK(sdesc);
1868 if (IsUnifiedPlan()) {
1869 if (!transceiver->internal()->mid()) {
1870 // This transceiver is not associated with a media section yet.
1871 return nullptr;
1872 }
1873 return sdesc->description()->GetContentByName(
1874 *transceiver->internal()->mid());
1875 } else {
1876 // Plan B only allows at most one audio and one video section, so use the
1877 // first media section of that type.
1878 return cricket::GetFirstMediaContent(sdesc->description()->contents(),
1879 transceiver->internal()->media_type());
1880 }
1881}
1882
deadbeef46c73892016-11-16 19:42:04 -08001883PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1884 return configuration_;
1885}
1886
deadbeef293e9262017-01-11 12:28:30 -08001887bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1888 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001889 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001890
Steve Anton75737c02017-11-06 10:37:17 -08001891 if (local_description() && configuration.ice_candidate_pool_size !=
1892 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001893 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1894 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001895 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001896 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001897
deadbeef293e9262017-01-11 12:28:30 -08001898 // The simplest (and most future-compatible) way to tell if the config was
1899 // modified in an invalid way is to copy each property we do support
1900 // modifying, then use operator==. There are far more properties we don't
1901 // support modifying than those we do, and more could be added.
1902 RTCConfiguration modified_config = configuration_;
1903 modified_config.servers = configuration.servers;
1904 modified_config.type = configuration.type;
1905 modified_config.ice_candidate_pool_size =
1906 configuration.ice_candidate_pool_size;
1907 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001908 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001909 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001910 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001911 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001912 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1913 }
1914
Steve Anton038834f2017-07-14 15:59:59 -07001915 // Validate the modified configuration.
1916 RTCError validate_error = ValidateConfiguration(modified_config);
1917 if (!validate_error.ok()) {
1918 return SafeSetError(std::move(validate_error), error);
1919 }
1920
deadbeef293e9262017-01-11 12:28:30 -08001921 // Note that this isn't possible through chromium, since it's an unsigned
1922 // short in WebIDL.
1923 if (configuration.ice_candidate_pool_size < 0 ||
1924 configuration.ice_candidate_pool_size > UINT16_MAX) {
1925 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1926 }
1927
1928 // Parse ICE servers before hopping to network thread.
1929 cricket::ServerAddresses stun_servers;
1930 std::vector<cricket::RelayServerConfig> turn_servers;
1931 RTCErrorType parse_error =
1932 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1933 if (parse_error != RTCErrorType::NONE) {
1934 return SafeSetError(parse_error, error);
1935 }
1936
1937 // In theory this shouldn't fail.
1938 if (!network_thread()->Invoke<bool>(
1939 RTC_FROM_HERE,
1940 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1941 stun_servers, turn_servers, modified_config.type,
1942 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001943 modified_config.prune_turn_ports,
1944 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001945 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001946 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1947 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001948
deadbeefd1a38b52016-12-10 13:15:33 -08001949 // As described in JSEP, calling setConfiguration with new ICE servers or
1950 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1951 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001952 if (modified_config.servers != configuration_.servers ||
1953 modified_config.type != configuration_.type ||
1954 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001955 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001956 }
skvladd1f5fda2017-02-03 16:54:05 -08001957
1958 if (modified_config.ice_check_min_interval !=
1959 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001960 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001961 }
1962
deadbeef293e9262017-01-11 12:28:30 -08001963 configuration_ = modified_config;
1964 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001965}
1966
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001967bool PeerConnection::AddIceCandidate(
1968 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001969 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001970 if (IsClosed()) {
1971 return false;
1972 }
Steve Antond25da372017-11-06 14:50:29 -08001973
1974 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001975 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1976 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001977 return false;
1978 }
1979
1980 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001981 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001982 return false;
1983 }
1984
1985 bool valid = false;
1986 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1987 if (!valid) {
1988 return false;
1989 }
1990
1991 // Add this candidate to the remote session description.
1992 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001993 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001994 return false;
1995 }
1996
1997 if (ready) {
1998 return UseCandidate(ice_candidate);
1999 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002000 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08002001 return true;
2002 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002003}
2004
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002005bool PeerConnection::RemoveIceCandidates(
2006 const std::vector<cricket::Candidate>& candidates) {
2007 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08002008 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002009 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
2010 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08002011 return false;
2012 }
2013
2014 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002015 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08002016 return false;
2017 }
2018
2019 size_t number_removed =
2020 mutable_remote_description()->RemoveCandidates(candidates);
2021 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002022 RTC_LOG(LS_ERROR)
2023 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2024 << "Requested " << candidates.size() << " but only " << number_removed
2025 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002026 }
2027
2028 // Remove the candidates from the transport controller.
2029 std::string error;
2030 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2031 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002032 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002033 }
2034 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002035}
2036
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002037void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002038 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002039 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002040
Steve Anton75737c02017-11-06 10:37:17 -08002041 if (transport_controller()) {
2042 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002043 }
2044
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002045 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002046 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002047 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002048 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002049 uma_observer_->IncrementEnumCounter(
2050 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2051 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002052 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002053 uma_observer_->IncrementEnumCounter(
2054 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2055 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002056 }
2057 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002058}
2059
zstein4b979802017-06-02 14:37:37 -07002060RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002061 if (!worker_thread()->IsCurrent()) {
2062 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002063 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2064 }
2065
2066 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2067 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2068 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2069 if (has_min && *bitrate.min_bitrate_bps < 0) {
2070 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2071 "min_bitrate_bps <= 0");
2072 }
2073 if (has_current) {
2074 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2075 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2076 "current_bitrate_bps < min_bitrate_bps");
2077 } else if (*bitrate.current_bitrate_bps < 0) {
2078 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2079 "curent_bitrate_bps < 0");
2080 }
2081 }
2082 if (has_max) {
2083 if (has_current &&
2084 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2085 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2086 "max_bitrate_bps < current_bitrate_bps");
2087 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2088 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2089 "max_bitrate_bps < min_bitrate_bps");
2090 } else if (*bitrate.max_bitrate_bps < 0) {
2091 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2092 "max_bitrate_bps < 0");
2093 }
2094 }
2095
2096 Call::Config::BitrateConfigMask mask;
2097 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2098 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2099 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2100
2101 RTC_DCHECK(call_.get());
2102 call_->SetBitrateConfigMask(mask);
2103
2104 return RTCError::OK();
2105}
2106
Alex Narest78609d52017-10-20 10:37:47 +02002107void PeerConnection::SetBitrateAllocationStrategy(
2108 std::unique_ptr<rtc::BitrateAllocationStrategy>
2109 bitrate_allocation_strategy) {
2110 rtc::Thread* worker_thread = factory_->worker_thread();
2111 if (!worker_thread->IsCurrent()) {
2112 rtc::BitrateAllocationStrategy* strategy_raw =
2113 bitrate_allocation_strategy.release();
2114 auto functor = [this, strategy_raw]() {
2115 call_->SetBitrateAllocationStrategy(
2116 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2117 };
2118 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2119 return;
2120 }
2121 RTC_DCHECK(call_.get());
2122 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2123}
2124
henrika5f6bf242017-11-01 11:06:56 +01002125void PeerConnection::SetAudioPlayout(bool playout) {
2126 if (!worker_thread()->IsCurrent()) {
2127 worker_thread()->Invoke<void>(
2128 RTC_FROM_HERE,
2129 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2130 return;
2131 }
2132 auto audio_state =
2133 factory_->channel_manager()->media_engine()->GetAudioState();
2134 audio_state->SetPlayout(playout);
2135}
2136
2137void PeerConnection::SetAudioRecording(bool recording) {
2138 if (!worker_thread()->IsCurrent()) {
2139 worker_thread()->Invoke<void>(
2140 RTC_FROM_HERE,
2141 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2142 return;
2143 }
2144 auto audio_state =
2145 factory_->channel_manager()->media_engine()->GetAudioState();
2146 audio_state->SetRecording(recording);
2147}
2148
Steve Anton8c0f7a72017-10-03 10:03:10 -07002149std::unique_ptr<rtc::SSLCertificate>
2150PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002151 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002152 return nullptr;
2153 }
Steve Anton75737c02017-11-06 10:37:17 -08002154 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002155}
2156
ivoc14d5dbe2016-07-04 07:06:55 -07002157bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2158 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002159 // TODO(eladalon): It would be better to not allow negative values into PC.
2160 const size_t max_size = (max_size_bytes < 0)
2161 ? RtcEventLog::kUnlimitedOutput
2162 : rtc::saturated_cast<size_t>(max_size_bytes);
2163 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002164 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2165 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002166}
2167
Bjorn Tereliusde939432017-11-20 17:38:14 +01002168bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2169 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002170 // TODO(eladalon): In C++14, this can be done with a lambda.
2171 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002172 bool operator()() {
2173 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2174 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002175 PeerConnection* const pc;
2176 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002177 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002178 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002179 return worker_thread()->Invoke<bool>(
2180 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002181}
2182
2183void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002184 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002185 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2186}
2187
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002188const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002189 return pending_local_description_ ? pending_local_description_.get()
2190 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002191}
2192
2193const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002194 return pending_remote_description_ ? pending_remote_description_.get()
2195 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002196}
2197
deadbeeffe4a8a42016-12-20 17:56:17 -08002198const SessionDescriptionInterface* PeerConnection::current_local_description()
2199 const {
Steve Anton75737c02017-11-06 10:37:17 -08002200 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002201}
2202
2203const SessionDescriptionInterface* PeerConnection::current_remote_description()
2204 const {
Steve Anton75737c02017-11-06 10:37:17 -08002205 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002206}
2207
2208const SessionDescriptionInterface* PeerConnection::pending_local_description()
2209 const {
Steve Anton75737c02017-11-06 10:37:17 -08002210 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002211}
2212
2213const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2214 const {
Steve Anton75737c02017-11-06 10:37:17 -08002215 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002216}
2217
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002218void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002219 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220 // Update stats here so that we have the most recent stats for tracks and
2221 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002222 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223
Steve Anton75737c02017-11-06 10:37:17 -08002224 ChangeSignalingState(PeerConnectionInterface::kClosed);
2225 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002226 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2227 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002228 RTC_DCHECK(!rtp_data_channel_);
2229 RTC_DCHECK(!sctp_transport_);
2230
deadbeef42a42632017-03-10 15:18:00 -08002231 network_thread()->Invoke<void>(
2232 RTC_FROM_HERE,
2233 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2234 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002235
Steve Anton978b8762017-09-29 12:15:02 -07002236 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002237 call_.reset();
2238 // The event log must outlive call (and any other object that uses it).
2239 event_log_.reset();
2240 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002241}
2242
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002243void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002244 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002245 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2246 SetSessionDescriptionMsg* param =
2247 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2248 param->observer->OnSuccess();
2249 delete param;
2250 break;
2251 }
2252 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2253 SetSessionDescriptionMsg* param =
2254 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2255 param->observer->OnFailure(param->error);
2256 delete param;
2257 break;
2258 }
deadbeefab9b2d12015-10-14 11:33:11 -07002259 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2260 CreateSessionDescriptionMsg* param =
2261 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2262 param->observer->OnFailure(param->error);
2263 delete param;
2264 break;
2265 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002266 case MSG_GETSTATS: {
2267 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002268 StatsReports reports;
2269 stats_->GetStats(param->track, &reports);
2270 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002271 delete param;
2272 break;
2273 }
deadbeefbd292462015-12-14 18:15:29 -08002274 case MSG_FREE_DATACHANNELS: {
2275 sctp_data_channels_to_free_.clear();
2276 break;
2277 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002278 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002279 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002280 break;
2281 }
2282}
2283
Steve Anton4171afb2017-11-20 10:20:22 -08002284void PeerConnection::CreateAudioReceiver(
2285 MediaStreamInterface* stream,
2286 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002287 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2288 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002289 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2290 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002291 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002292 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002293 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002294 stream->AddTrack(
2295 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002296 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002297 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002298}
2299
Steve Anton4171afb2017-11-20 10:20:22 -08002300void PeerConnection::CreateVideoReceiver(
2301 MediaStreamInterface* stream,
2302 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002303 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2304 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002305 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2306 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002307 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002308 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2309 worker_thread(), remote_sender_info.first_ssrc,
2310 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002311 stream->AddTrack(
2312 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002313 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002314 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002315}
2316
deadbeef70ab1a12015-09-28 16:53:55 -07002317// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2318// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002319rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002320 const RtpSenderInfo& remote_sender_info) {
2321 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2322 if (!receiver) {
2323 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2324 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002325 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002326 }
Steve Anton4171afb2017-11-20 10:20:22 -08002327 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2328 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2329 } else {
2330 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2331 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002332 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002333}
2334
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002335void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2336 MediaStreamInterface* stream) {
2337 RTC_DCHECK(!IsClosed());
2338 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002339 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002340 // We already have a sender for this track, so just change the stream_id
2341 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002342 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002343 return;
2344 }
2345
2346 // Normal case; we've never seen this track before.
2347 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2348 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2349 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002350 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2351 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002352 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002353 // If the sender has already been configured in SDP, we call SetSsrc,
2354 // which will connect the sender to the underlying transport. This can
2355 // occur if a local session description that contains the ID of the sender
2356 // is set before AddStream is called. It can also occur if the local
2357 // session description is not changed and RemoveStream is called, and
2358 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002359 const RtpSenderInfo* sender_info =
2360 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2361 if (sender_info) {
2362 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002363 }
2364}
2365
2366// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2367// indefinitely, when we have unified plan SDP.
2368void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2369 MediaStreamInterface* stream) {
2370 RTC_DCHECK(!IsClosed());
2371 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002372 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002373 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2374 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002375 return;
2376 }
Steve Anton4171afb2017-11-20 10:20:22 -08002377 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002378}
2379
2380void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2381 MediaStreamInterface* stream) {
2382 RTC_DCHECK(!IsClosed());
2383 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002384 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002385 // We already have a sender for this track, so just change the stream_id
2386 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002387 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002388 return;
2389 }
2390
2391 // Normal case; we've never seen this track before.
2392 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2393 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002394 signaling_thread(),
2395 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002396 GetVideoTransceiver()->internal()->AddSender(new_sender);
2397 const RtpSenderInfo* sender_info =
2398 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2399 if (sender_info) {
2400 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002401 }
2402}
2403
2404void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2405 MediaStreamInterface* stream) {
2406 RTC_DCHECK(!IsClosed());
2407 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002408 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002409 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2410 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002411 return;
2412 }
Steve Anton4171afb2017-11-20 10:20:22 -08002413 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002414}
2415
Steve Antonba818672017-11-06 10:21:57 -08002416void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002417 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002418 if (ice_connection_state_ == new_state) {
2419 return;
2420 }
2421
deadbeefcbecd352015-09-23 11:50:27 -07002422 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002423 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002424 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002425 return;
2426 }
Steve Antonba818672017-11-06 10:21:57 -08002427
Mirko Bonadei675513b2017-11-09 11:09:25 +01002428 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2429 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002430 RTC_DCHECK(ice_connection_state_ !=
2431 PeerConnectionInterface::kIceConnectionClosed);
2432
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002433 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002434 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002435}
2436
2437void PeerConnection::OnIceGatheringChange(
2438 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002439 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002440 if (IsClosed()) {
2441 return;
2442 }
2443 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002444 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002445}
2446
jbauch81bf7b02017-03-25 08:31:12 -07002447void PeerConnection::OnIceCandidate(
2448 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002449 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002450 if (IsClosed()) {
2451 return;
2452 }
jbauch81bf7b02017-03-25 08:31:12 -07002453 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002454}
2455
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002456void PeerConnection::OnIceCandidatesRemoved(
2457 const std::vector<cricket::Candidate>& candidates) {
2458 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002459 if (IsClosed()) {
2460 return;
2461 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002462 observer_->OnIceCandidatesRemoved(candidates);
2463}
2464
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002465void PeerConnection::ChangeSignalingState(
2466 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002467 RTC_DCHECK(signaling_thread()->IsCurrent());
2468 if (signaling_state_ == signaling_state) {
2469 return;
2470 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002471 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2472 << GetSignalingStateString(signaling_state_)
2473 << " New state: "
2474 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002475 signaling_state_ = signaling_state;
2476 if (signaling_state == kClosed) {
2477 ice_connection_state_ = kIceConnectionClosed;
2478 observer_->OnIceConnectionChange(ice_connection_state_);
2479 if (ice_gathering_state_ != kIceGatheringComplete) {
2480 ice_gathering_state_ = kIceGatheringComplete;
2481 observer_->OnIceGatheringChange(ice_gathering_state_);
2482 }
2483 }
2484 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002485}
2486
deadbeefeb459812015-12-15 19:24:43 -08002487void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2488 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002489 if (IsClosed()) {
2490 return;
2491 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002492 AddAudioTrack(track, stream);
2493 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002494}
2495
deadbeefeb459812015-12-15 19:24:43 -08002496void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2497 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002498 if (IsClosed()) {
2499 return;
2500 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002501 RemoveAudioTrack(track, stream);
2502 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002503}
2504
2505void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2506 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002507 if (IsClosed()) {
2508 return;
2509 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002510 AddVideoTrack(track, stream);
2511 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002512}
2513
2514void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2515 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002516 if (IsClosed()) {
2517 return;
2518 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002519 RemoveVideoTrack(track, stream);
2520 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002521}
2522
Henrik Boström31638672017-11-23 17:48:32 +01002523void PeerConnection::PostSetSessionDescriptionSuccess(
2524 SetSessionDescriptionObserver* observer) {
2525 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2526 signaling_thread()->Post(RTC_FROM_HERE, this,
2527 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2528}
2529
deadbeefab9b2d12015-10-14 11:33:11 -07002530void PeerConnection::PostSetSessionDescriptionFailure(
2531 SetSessionDescriptionObserver* observer,
2532 const std::string& error) {
2533 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2534 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002535 signaling_thread()->Post(RTC_FROM_HERE, this,
2536 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002537}
2538
2539void PeerConnection::PostCreateSessionDescriptionFailure(
2540 CreateSessionDescriptionObserver* observer,
2541 const std::string& error) {
2542 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2543 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002544 signaling_thread()->Post(RTC_FROM_HERE, this,
2545 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002546}
2547
zhihuang1c378ed2017-08-17 14:10:50 -07002548void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002549 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2550 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002551 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2552
2553 // Figure out transceiver directional preferences.
2554 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2555 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2556
2557 // By default, generate sendrecv/recvonly m= sections.
2558 bool recv_audio = true;
2559 bool recv_video = true;
2560
2561 // By default, only offer a new m= section if we have media to send with it.
2562 bool offer_new_audio_description = send_audio;
2563 bool offer_new_video_description = send_video;
2564 bool offer_new_data_description = HasDataChannels();
2565
2566 // The "offer_to_receive_X" options allow those defaults to be overridden.
2567 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2568 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2569 offer_new_audio_description =
2570 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2571 }
2572 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2573 recv_video = (rtc_options.offer_to_receive_video > 0);
2574 offer_new_video_description =
2575 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2576 }
2577
2578 rtc::Optional<size_t> audio_index;
2579 rtc::Optional<size_t> video_index;
2580 rtc::Optional<size_t> data_index;
2581 // If a current description exists, generate m= sections in the same order,
2582 // using the first audio/video/data section that appears and rejecting
2583 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002584 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002585 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002586 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002587 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2588 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2589 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002590 }
2591
zhihuang1c378ed2017-08-17 14:10:50 -07002592 // Add audio/video/data m= sections to the end if needed.
2593 if (!audio_index && offer_new_audio_description) {
2594 session_options->media_description_options.push_back(
2595 cricket::MediaDescriptionOptions(
2596 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002597 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2598 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002599 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002600 }
zhihuang1c378ed2017-08-17 14:10:50 -07002601 if (!video_index && offer_new_video_description) {
2602 session_options->media_description_options.push_back(
2603 cricket::MediaDescriptionOptions(
2604 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002605 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2606 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002607 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002608 }
zhihuang1c378ed2017-08-17 14:10:50 -07002609 if (!data_index && offer_new_data_description) {
2610 session_options->media_description_options.push_back(
2611 cricket::MediaDescriptionOptions(
2612 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002613 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002614 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002615 }
2616
2617 cricket::MediaDescriptionOptions* audio_media_description_options =
2618 !audio_index ? nullptr
2619 : &session_options->media_description_options[*audio_index];
2620 cricket::MediaDescriptionOptions* video_media_description_options =
2621 !video_index ? nullptr
2622 : &session_options->media_description_options[*video_index];
2623 cricket::MediaDescriptionOptions* data_media_description_options =
2624 !data_index ? nullptr
2625 : &session_options->media_description_options[*data_index];
2626
2627 // Apply ICE restart flag and renomination flag.
2628 for (auto& options : session_options->media_description_options) {
2629 options.transport_options.ice_restart = rtc_options.ice_restart;
2630 options.transport_options.enable_ice_renomination =
2631 configuration_.enable_ice_renomination;
2632 }
2633
Steve Anton4171afb2017-11-20 10:20:22 -08002634 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002635 video_media_description_options);
2636 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002637
zhihuang9763d562016-08-05 11:14:50 -07002638 // Intentionally unset the data channel type for RTP data channel with the
2639 // second condition. Otherwise the RTP data channels would be successfully
2640 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2641 // when building with chromium. We want to leave RTP data channels broken, so
2642 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002643 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2644 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002645 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002646
2647 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002648 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002649}
2650
zhihuang1c378ed2017-08-17 14:10:50 -07002651void PeerConnection::GetOptionsForAnswer(
2652 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002653 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002654 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002655
zhihuang1c378ed2017-08-17 14:10:50 -07002656 // Figure out transceiver directional preferences.
2657 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2658 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2659
2660 // By default, generate sendrecv/recvonly m= sections. The direction is also
2661 // restricted by the direction in the offer.
2662 bool recv_audio = true;
2663 bool recv_video = true;
2664
2665 // The "offer_to_receive_X" options allow those defaults to be overridden.
2666 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2667 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002668 }
zhihuang1c378ed2017-08-17 14:10:50 -07002669 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2670 recv_video = (rtc_options.offer_to_receive_video > 0);
2671 }
2672
2673 rtc::Optional<size_t> audio_index;
2674 rtc::Optional<size_t> video_index;
2675 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002676 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002677 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002678 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002679 SessionDescriptionInterface::kOffer);
2680 // Generate m= sections that match those in the offer.
2681 // Note that mediasession.cc will handle intersection our preferred
2682 // direction with the offered direction.
2683 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002684 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002685 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2686 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2687 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002688 }
zhihuang1c378ed2017-08-17 14:10:50 -07002689
2690 cricket::MediaDescriptionOptions* audio_media_description_options =
2691 !audio_index ? nullptr
2692 : &session_options->media_description_options[*audio_index];
2693 cricket::MediaDescriptionOptions* video_media_description_options =
2694 !video_index ? nullptr
2695 : &session_options->media_description_options[*video_index];
2696 cricket::MediaDescriptionOptions* data_media_description_options =
2697 !data_index ? nullptr
2698 : &session_options->media_description_options[*data_index];
2699
2700 // Apply ICE renomination flag.
2701 for (auto& options : session_options->media_description_options) {
2702 options.transport_options.enable_ice_renomination =
2703 configuration_.enable_ice_renomination;
2704 }
2705
Steve Anton4171afb2017-11-20 10:20:22 -08002706 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002707 video_media_description_options);
2708 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2709
zhihuang9763d562016-08-05 11:14:50 -07002710 // Intentionally unset the data channel type for RTP data channel. Otherwise
2711 // the RTP data channels would be successfully negotiated by default and the
2712 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2713 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002714 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2715 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002716 }
zhihuangaf388472016-11-02 16:49:48 -07002717
zhihuang1c378ed2017-08-17 14:10:50 -07002718 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002719 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002720}
2721
zhihuang1c378ed2017-08-17 14:10:50 -07002722void PeerConnection::GenerateMediaDescriptionOptions(
2723 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002724 RtpTransceiverDirection audio_direction,
2725 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002726 rtc::Optional<size_t>* audio_index,
2727 rtc::Optional<size_t>* video_index,
2728 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002729 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002730 for (const cricket::ContentInfo& content :
2731 session_desc->description()->contents()) {
2732 if (IsAudioContent(&content)) {
2733 // If we already have an audio m= section, reject this extra one.
2734 if (*audio_index) {
2735 session_options->media_description_options.push_back(
2736 cricket::MediaDescriptionOptions(
2737 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002738 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002739 } else {
2740 session_options->media_description_options.push_back(
2741 cricket::MediaDescriptionOptions(
2742 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002743 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002744 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002745 }
2746 } else if (IsVideoContent(&content)) {
2747 // If we already have an video m= section, reject this extra one.
2748 if (*video_index) {
2749 session_options->media_description_options.push_back(
2750 cricket::MediaDescriptionOptions(
2751 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002752 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002753 } else {
2754 session_options->media_description_options.push_back(
2755 cricket::MediaDescriptionOptions(
2756 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002757 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002758 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002759 }
2760 } else {
2761 RTC_DCHECK(IsDataContent(&content));
2762 // If we already have an data m= section, reject this extra one.
2763 if (*data_index) {
2764 session_options->media_description_options.push_back(
2765 cricket::MediaDescriptionOptions(
2766 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002767 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002768 } else {
2769 session_options->media_description_options.push_back(
2770 cricket::MediaDescriptionOptions(
2771 cricket::MEDIA_TYPE_DATA, content.name,
2772 // Direction for data sections is meaningless, but legacy
2773 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002774 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002775 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002776 }
2777 }
htaa2a49d92016-03-04 02:51:39 -08002778 }
deadbeefab9b2d12015-10-14 11:33:11 -07002779}
2780
Steve Anton4171afb2017-11-20 10:20:22 -08002781void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2782 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2783 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002784 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002785}
2786
Steve Anton4171afb2017-11-20 10:20:22 -08002787void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002788 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002789 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002790 cricket::MediaType media_type,
2791 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002792 std::vector<RtpSenderInfo>* current_senders =
2793 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002794
Steve Anton4171afb2017-11-20 10:20:22 -08002795 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002796 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002797 for (auto sender_it = current_senders->begin();
2798 sender_it != current_senders->end();
2799 /* incremented manually */) {
2800 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002801 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002802 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2803 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002804 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002805 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2806 sender_exists) {
2807 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002808 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002809 OnRemoteSenderRemoved(info, media_type);
2810 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002811 }
2812 }
2813
Steve Anton4171afb2017-11-20 10:20:22 -08002814 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002815 for (const cricket::StreamParams& params : streams) {
2816 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002817 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002818 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002819 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002820 uint32_t ssrc = params.first_ssrc();
2821
2822 rtc::scoped_refptr<MediaStreamInterface> stream =
2823 remote_streams_->find(stream_label);
2824 if (!stream) {
2825 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002826 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2827 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002828 remote_streams_->AddStream(stream);
2829 new_streams->AddStream(stream);
2830 }
2831
Steve Anton4171afb2017-11-20 10:20:22 -08002832 const RtpSenderInfo* sender_info =
2833 FindSenderInfo(*current_senders, stream_label, sender_id);
2834 if (!sender_info) {
2835 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2836 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002837 }
2838 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002839
Steve Anton4171afb2017-11-20 10:20:22 -08002840 // Add default sender if necessary.
2841 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002842 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2843 remote_streams_->find(kDefaultStreamLabel);
2844 if (!default_stream) {
2845 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002846 default_stream = MediaStreamProxy::Create(
2847 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002848 remote_streams_->AddStream(default_stream);
2849 new_streams->AddStream(default_stream);
2850 }
Steve Anton4171afb2017-11-20 10:20:22 -08002851 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2852 ? kDefaultAudioSenderId
2853 : kDefaultVideoSenderId;
2854 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2855 *current_senders, kDefaultStreamLabel, default_sender_id);
2856 if (!default_sender_info) {
2857 current_senders->push_back(
2858 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2859 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002860 }
2861 }
deadbeefab9b2d12015-10-14 11:33:11 -07002862}
2863
Steve Anton4171afb2017-11-20 10:20:22 -08002864void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2865 cricket::MediaType media_type) {
2866 MediaStreamInterface* stream =
2867 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002868
2869 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002870 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002871 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002872 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002873 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002874 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002875 }
2876}
2877
Steve Anton4171afb2017-11-20 10:20:22 -08002878void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2879 cricket::MediaType media_type) {
2880 MediaStreamInterface* stream =
2881 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002882
Henrik Boström933d8b02017-10-10 10:05:16 -07002883 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002884 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002885 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2886 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002887 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002888 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002889 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002890 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002891 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002892 }
2893 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002894 // Stopping or destroying a VideoRtpReceiver will end the
2895 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002896 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002897 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002898 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002899 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002900 // There's no guarantee the track is still available, e.g. the track may
2901 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002902 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002903 }
2904 } else {
nisseede5da42017-01-12 05:15:36 -08002905 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002906 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002907 if (receiver) {
2908 observer_->OnRemoveTrack(receiver);
2909 }
deadbeefab9b2d12015-10-14 11:33:11 -07002910}
2911
2912void PeerConnection::UpdateEndedRemoteMediaStreams() {
2913 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2914 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2915 MediaStreamInterface* stream = remote_streams_->at(i);
2916 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2917 streams_to_remove.push_back(stream);
2918 }
2919 }
2920
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002921 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002922 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002923 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002924 }
2925}
2926
Steve Anton4171afb2017-11-20 10:20:22 -08002927void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002928 const std::vector<cricket::StreamParams>& streams,
2929 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002930 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002931
2932 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2933 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002934 for (auto sender_it = current_senders->begin();
2935 sender_it != current_senders->end();
2936 /* incremented manually */) {
2937 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002938 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002939 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2940 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002941 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002942 OnLocalSenderRemoved(info, media_type);
2943 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002944 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002945 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002946 }
2947 }
2948
Steve Anton4171afb2017-11-20 10:20:22 -08002949 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002950 for (const cricket::StreamParams& params : streams) {
2951 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002952 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002953 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002954 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002955 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002956 const RtpSenderInfo* sender_info =
2957 FindSenderInfo(*current_senders, stream_label, sender_id);
2958 if (!sender_info) {
2959 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2960 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002961 }
2962 }
2963}
2964
Steve Anton4171afb2017-11-20 10:20:22 -08002965void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2966 cricket::MediaType media_type) {
2967 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002968 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002969 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2970 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002971 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002972 return;
2973 }
2974
deadbeeffac06552015-11-25 11:26:01 -08002975 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002976 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2977 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002978 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002979 }
deadbeeffac06552015-11-25 11:26:01 -08002980
Steve Anton4171afb2017-11-20 10:20:22 -08002981 sender->internal()->set_stream_id(sender_info.stream_label);
2982 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002983}
2984
Steve Anton4171afb2017-11-20 10:20:22 -08002985void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2986 cricket::MediaType media_type) {
2987 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002988 if (!sender) {
2989 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002990 // SessionDescriptions has been renegotiated.
2991 return;
2992 }
deadbeeffac06552015-11-25 11:26:01 -08002993
2994 // A sender has been removed from the SessionDescription but it's still
2995 // associated with the PeerConnection. This only occurs if the SDP doesn't
2996 // match with the calls to CreateSender, AddStream and RemoveStream.
2997 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002998 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2999 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08003000 return;
deadbeefab9b2d12015-10-14 11:33:11 -07003001 }
deadbeeffac06552015-11-25 11:26:01 -08003002
Steve Anton4171afb2017-11-20 10:20:22 -08003003 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07003004}
3005
3006void PeerConnection::UpdateLocalRtpDataChannels(
3007 const cricket::StreamParamsVec& streams) {
3008 std::vector<std::string> existing_channels;
3009
3010 // Find new and active data channels.
3011 for (const cricket::StreamParams& params : streams) {
3012 // |it->sync_label| is actually the data channel label. The reason is that
3013 // we use the same naming of data channels as we do for
3014 // MediaStreams and Tracks.
3015 // For MediaStreams, the sync_label is the MediaStream label and the
3016 // track label is the same as |streamid|.
3017 const std::string& channel_label = params.sync_label;
3018 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08003019 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003020 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003021 continue;
3022 }
3023 // Set the SSRC the data channel should use for sending.
3024 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3025 existing_channels.push_back(data_channel_it->first);
3026 }
3027
3028 UpdateClosingRtpDataChannels(existing_channels, true);
3029}
3030
3031void PeerConnection::UpdateRemoteRtpDataChannels(
3032 const cricket::StreamParamsVec& streams) {
3033 std::vector<std::string> existing_channels;
3034
3035 // Find new and active data channels.
3036 for (const cricket::StreamParams& params : streams) {
3037 // The data channel label is either the mslabel or the SSRC if the mslabel
3038 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3039 std::string label = params.sync_label.empty()
3040 ? rtc::ToString(params.first_ssrc())
3041 : params.sync_label;
3042 auto data_channel_it = rtp_data_channels_.find(label);
3043 if (data_channel_it == rtp_data_channels_.end()) {
3044 // This is a new data channel.
3045 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3046 } else {
3047 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3048 }
3049 existing_channels.push_back(label);
3050 }
3051
3052 UpdateClosingRtpDataChannels(existing_channels, false);
3053}
3054
3055void PeerConnection::UpdateClosingRtpDataChannels(
3056 const std::vector<std::string>& active_channels,
3057 bool is_local_update) {
3058 auto it = rtp_data_channels_.begin();
3059 while (it != rtp_data_channels_.end()) {
3060 DataChannel* data_channel = it->second;
3061 if (std::find(active_channels.begin(), active_channels.end(),
3062 data_channel->label()) != active_channels.end()) {
3063 ++it;
3064 continue;
3065 }
3066
3067 if (is_local_update) {
3068 data_channel->SetSendSsrc(0);
3069 } else {
3070 data_channel->RemotePeerRequestClose();
3071 }
3072
3073 if (data_channel->state() == DataChannel::kClosed) {
3074 rtp_data_channels_.erase(it);
3075 it = rtp_data_channels_.begin();
3076 } else {
3077 ++it;
3078 }
3079 }
3080}
3081
3082void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3083 uint32_t remote_ssrc) {
3084 rtc::scoped_refptr<DataChannel> channel(
3085 InternalCreateDataChannel(label, nullptr));
3086 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003087 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3088 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003089 return;
3090 }
3091 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003092 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3093 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003094 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003095}
3096
3097rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3098 const std::string& label,
3099 const InternalDataChannelInit* config) {
3100 if (IsClosed()) {
3101 return nullptr;
3102 }
Steve Anton75737c02017-11-06 10:37:17 -08003103 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003104 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003105 << "InternalCreateDataChannel: Data is not supported in this call.";
3106 return nullptr;
3107 }
3108 InternalDataChannelInit new_config =
3109 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003110 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003111 if (new_config.id < 0) {
3112 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003113 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003114 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003115 RTC_LOG(LS_ERROR)
3116 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003117 return nullptr;
3118 }
3119 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003120 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3121 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003122 return nullptr;
3123 }
3124 }
3125
Steve Anton75737c02017-11-06 10:37:17 -08003126 rtc::scoped_refptr<DataChannel> channel(
3127 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003128 if (!channel) {
3129 sid_allocator_.ReleaseSid(new_config.id);
3130 return nullptr;
3131 }
3132
3133 if (channel->data_channel_type() == cricket::DCT_RTP) {
3134 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003135 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3136 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003137 return nullptr;
3138 }
3139 rtp_data_channels_[channel->label()] = channel;
3140 } else {
3141 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3142 sctp_data_channels_.push_back(channel);
3143 channel->SignalClosed.connect(this,
3144 &PeerConnection::OnSctpDataChannelClosed);
3145 }
3146
hbos82ebe022016-11-14 01:41:09 -08003147 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003148 return channel;
3149}
3150
3151bool PeerConnection::HasDataChannels() const {
3152 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3153}
3154
3155void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3156 for (const auto& channel : sctp_data_channels_) {
3157 if (channel->id() < 0) {
3158 int sid;
3159 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003160 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003161 continue;
3162 }
3163 channel->SetSctpSid(sid);
3164 }
3165 }
3166}
3167
3168void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003169 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003170 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3171 ++it) {
3172 if (it->get() == channel) {
3173 if (channel->id() >= 0) {
3174 sid_allocator_.ReleaseSid(channel->id());
3175 }
deadbeefbd292462015-12-14 18:15:29 -08003176 // Since this method is triggered by a signal from the DataChannel,
3177 // we can't free it directly here; we need to free it asynchronously.
3178 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003179 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003180 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3181 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003182 return;
3183 }
3184 }
3185}
3186
deadbeefab9b2d12015-10-14 11:33:11 -07003187void PeerConnection::OnDataChannelDestroyed() {
3188 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3189 // DataChannel may callback to us and try to modify the list.
3190 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3191 temp_rtp_dcs.swap(rtp_data_channels_);
3192 for (const auto& kv : temp_rtp_dcs) {
3193 kv.second->OnTransportChannelDestroyed();
3194 }
3195
3196 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3197 temp_sctp_dcs.swap(sctp_data_channels_);
3198 for (const auto& channel : temp_sctp_dcs) {
3199 channel->OnTransportChannelDestroyed();
3200 }
3201}
3202
3203void PeerConnection::OnDataChannelOpenMessage(
3204 const std::string& label,
3205 const InternalDataChannelInit& config) {
3206 rtc::scoped_refptr<DataChannel> channel(
3207 InternalCreateDataChannel(label, &config));
3208 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003209 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003210 return;
3211 }
3212
deadbeefa601f5c2016-06-06 14:27:39 -07003213 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3214 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003215 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003216}
3217
Steve Anton4171afb2017-11-20 10:20:22 -08003218rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3219PeerConnection::GetAudioTransceiver() const {
3220 // This method only works with Plan B SDP, where there is a single
3221 // audio/video transceiver.
3222 RTC_DCHECK(!IsUnifiedPlan());
3223 for (auto transceiver : transceivers_) {
3224 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3225 return transceiver;
3226 }
3227 }
3228 RTC_NOTREACHED();
3229 return nullptr;
3230}
3231
3232rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3233PeerConnection::GetVideoTransceiver() const {
3234 // This method only works with Plan B SDP, where there is a single
3235 // audio/video transceiver.
3236 RTC_DCHECK(!IsUnifiedPlan());
3237 for (auto transceiver : transceivers_) {
3238 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3239 return transceiver;
3240 }
3241 }
3242 RTC_NOTREACHED();
3243 return nullptr;
3244}
3245
3246// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3247// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003248bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003249 switch (type) {
3250 case cricket::MEDIA_TYPE_AUDIO:
3251 return !GetAudioTransceiver()->internal()->senders().empty();
3252 case cricket::MEDIA_TYPE_VIDEO:
3253 return !GetVideoTransceiver()->internal()->senders().empty();
3254 case cricket::MEDIA_TYPE_DATA:
3255 return false;
3256 }
3257 RTC_NOTREACHED();
3258 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003259}
3260
Steve Anton4171afb2017-11-20 10:20:22 -08003261rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3262PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3263 for (auto transceiver : transceivers_) {
3264 for (auto sender : transceiver->internal()->senders()) {
3265 if (sender->track() == track) {
3266 return sender;
3267 }
3268 }
3269 }
3270 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003271}
3272
Steve Anton4171afb2017-11-20 10:20:22 -08003273rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3274PeerConnection::FindSenderById(const std::string& sender_id) const {
3275 for (auto transceiver : transceivers_) {
3276 for (auto sender : transceiver->internal()->senders()) {
3277 if (sender->id() == sender_id) {
3278 return sender;
3279 }
3280 }
3281 }
3282 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003283}
3284
Steve Anton4171afb2017-11-20 10:20:22 -08003285rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3286PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3287 for (auto transceiver : transceivers_) {
3288 for (auto receiver : transceiver->internal()->receivers()) {
3289 if (receiver->id() == receiver_id) {
3290 return receiver;
3291 }
3292 }
3293 }
3294 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003295}
3296
Steve Anton4171afb2017-11-20 10:20:22 -08003297std::vector<PeerConnection::RtpSenderInfo>*
3298PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3299 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3300 media_type == cricket::MEDIA_TYPE_VIDEO);
3301 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3302 ? &remote_audio_sender_infos_
3303 : &remote_video_sender_infos_;
3304}
3305
3306std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003307 cricket::MediaType media_type) {
3308 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3309 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003310 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3311 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003312}
3313
Steve Anton4171afb2017-11-20 10:20:22 -08003314const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3315 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003316 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003317 const std::string sender_id) const {
3318 for (const RtpSenderInfo& sender_info : infos) {
3319 if (sender_info.stream_label == stream_label &&
3320 sender_info.sender_id == sender_id) {
3321 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003322 }
3323 }
3324 return nullptr;
3325}
3326
3327DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3328 for (const auto& channel : sctp_data_channels_) {
3329 if (channel->id() == sid) {
3330 return channel;
3331 }
3332 }
3333 return nullptr;
3334}
3335
deadbeef91dd5672016-05-18 16:55:30 -07003336bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003337 const RTCConfiguration& configuration) {
3338 cricket::ServerAddresses stun_servers;
3339 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003340 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3341 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003342 return false;
3343 }
3344
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003345 port_allocator_->Initialize();
3346
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003347 // To handle both internal and externally created port allocator, we will
3348 // enable BUNDLE here.
3349 int portallocator_flags = port_allocator_->flags();
3350 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003351 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3352 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003353 // If the disable-IPv6 flag was specified, we'll not override it
3354 // by experiment.
3355 if (configuration.disable_ipv6) {
3356 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003357 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3358 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003359 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3360 }
3361
zhihuangb09b3f92017-03-07 14:40:51 -08003362 if (configuration.disable_ipv6_on_wifi) {
3363 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003364 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003365 }
3366
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003367 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3368 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003369 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003370 }
3371
honghaiz60347052016-05-31 18:29:12 -07003372 if (configuration.candidate_network_policy ==
3373 kCandidateNetworkPolicyLowCost) {
3374 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003375 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003376 }
3377
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003378 port_allocator_->set_flags(portallocator_flags);
3379 // No step delay is used while allocating ports.
3380 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3381 port_allocator_->set_candidate_filter(
3382 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003383 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003384
3385 // Call this last since it may create pooled allocator sessions using the
3386 // properties set above.
3387 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003388 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003389 configuration.prune_turn_ports,
3390 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003391 return true;
3392}
3393
deadbeef91dd5672016-05-18 16:55:30 -07003394bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003395 const cricket::ServerAddresses& stun_servers,
3396 const std::vector<cricket::RelayServerConfig>& turn_servers,
3397 IceTransportsType type,
3398 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003399 bool prune_turn_ports,
3400 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003401 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003402 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003403 // Call this last since it may create pooled allocator sessions using the
3404 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003405 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003406 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3407 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003408}
3409
Steve Antonba818672017-11-06 10:21:57 -08003410cricket::ChannelManager* PeerConnection::channel_manager() const {
3411 return factory_->channel_manager();
3412}
3413
3414MetricsObserverInterface* PeerConnection::metrics_observer() const {
3415 return uma_observer_;
3416}
3417
Elad Alon99c3fe52017-10-13 16:29:40 +02003418bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003419 std::unique_ptr<RtcEventLogOutput> output,
3420 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003421 if (!event_log_) {
3422 return false;
3423 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003424 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003425}
3426
3427void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003428 if (event_log_) {
3429 event_log_->StopLogging();
3430 }
ivoc14d5dbe2016-07-04 07:06:55 -07003431}
nisseeaabdf62017-05-05 02:23:02 -07003432
Steve Anton75737c02017-11-06 10:37:17 -08003433cricket::BaseChannel* PeerConnection::GetChannel(
3434 const std::string& content_name) {
3435 if (voice_channel() && voice_channel()->content_name() == content_name) {
3436 return voice_channel();
3437 }
3438 if (video_channel() && video_channel()->content_name() == content_name) {
3439 return video_channel();
3440 }
3441 if (rtp_data_channel() &&
3442 rtp_data_channel()->content_name() == content_name) {
3443 return rtp_data_channel();
3444 }
3445 return nullptr;
3446}
3447
3448bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3449 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003450 RTC_LOG(LS_INFO)
3451 << "Local and Remote descriptions must be applied to get the "
3452 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003453 return false;
3454 }
3455 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003456 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3457 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003458 return false;
3459 }
3460
3461 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3462}
3463
3464bool PeerConnection::GetSslRole(const std::string& content_name,
3465 rtc::SSLRole* role) {
3466 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003467 RTC_LOG(LS_INFO)
3468 << "Local and Remote descriptions must be applied to get the "
3469 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003470 return false;
3471 }
3472
3473 return transport_controller_->GetSslRole(GetTransportName(content_name),
3474 role);
3475}
3476
Steve Anton75737c02017-11-06 10:37:17 -08003477// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3478// vector of BaseChannel pointers instead of separate voice and video channel
3479// vectors. At that point, this will become a simple getter.
3480std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3481 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003482 if (voice_channel()) {
3483 channels.push_back(voice_channel());
3484 }
3485 if (video_channel()) {
3486 channels.push_back(video_channel());
3487 }
Steve Anton75737c02017-11-06 10:37:17 -08003488 if (rtp_data_channel_) {
3489 channels.push_back(rtp_data_channel_);
3490 }
3491 return channels;
3492}
3493
Steve Antonf8470812017-12-04 10:46:21 -08003494void PeerConnection::SetSessionError(SessionError error,
3495 const std::string& error_desc) {
3496 RTC_DCHECK_RUN_ON(signaling_thread());
3497 if (error != session_error_) {
3498 session_error_ = error;
3499 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08003500 }
3501}
3502
Steve Anton3828c062017-12-06 10:34:51 -08003503RTCError PeerConnection::UpdateSessionState(SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003504 cricket::ContentSource source) {
3505 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003506
3507 // If there's already a pending error then no state transition should happen.
3508 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08003509 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003510
3511 // If this is an answer then we know whether to BUNDLE or not. If both the
3512 // local and remote side have agreed to BUNDLE, go ahead and enable it.
Steve Anton3828c062017-12-06 10:34:51 -08003513 if (type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08003514 const cricket::ContentGroup* local_bundle =
3515 local_description()->description()->GetGroupByName(
3516 cricket::GROUP_TYPE_BUNDLE);
3517 const cricket::ContentGroup* remote_bundle =
3518 remote_description()->description()->GetGroupByName(
3519 cricket::GROUP_TYPE_BUNDLE);
3520 if (local_bundle && remote_bundle) {
3521 // The answerer decides the transport to bundle on.
3522 const cricket::ContentGroup* answer_bundle =
3523 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3524 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08003525 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3526 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08003527 }
3528 }
Steve Anton75737c02017-11-06 10:37:17 -08003529 }
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003530
3531 // Only push down the transport description after potentially enabling BUNDLE;
3532 // we don't want to push down a description on a transport about to be
3533 // destroyed.
Steve Anton3828c062017-12-06 10:34:51 -08003534 RTCError error = PushdownTransportDescription(source, type);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003535 if (!error.ok()) {
3536 return error;
3537 }
3538
3539 // If this is answer-ish we're ready to let media flow.
Steve Anton3828c062017-12-06 10:34:51 -08003540 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Antoned10bd92017-12-05 10:52:59 -08003541 EnableSending();
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003542 }
3543
3544 // Update the signaling state according to the specified state machine (see
3545 // https://w3c.github.io/webrtc-pc/#rtcsignalingstate-enum).
Steve Anton3828c062017-12-06 10:34:51 -08003546 if (type == SdpType::kOffer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003547 ChangeSignalingState(source == cricket::CS_LOCAL
3548 ? PeerConnectionInterface::kHaveLocalOffer
3549 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton3828c062017-12-06 10:34:51 -08003550 } else if (type == SdpType::kPrAnswer) {
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003551 ChangeSignalingState(source == cricket::CS_LOCAL
3552 ? PeerConnectionInterface::kHaveLocalPrAnswer
3553 : PeerConnectionInterface::kHaveRemotePrAnswer);
3554 } else {
Steve Anton3828c062017-12-06 10:34:51 -08003555 RTC_DCHECK(type == SdpType::kAnswer);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003556 ChangeSignalingState(PeerConnectionInterface::kStable);
3557 }
3558
3559 // Update internal objects according to the session description's media
3560 // descriptions.
Steve Anton3828c062017-12-06 10:34:51 -08003561 error = PushdownMediaDescription(type, source);
Steve Anton6d6a2ae2017-12-04 17:19:47 -08003562 if (!error.ok()) {
3563 SetSessionError(SessionError::kContent, error.message());
3564 }
3565 if (session_error() != SessionError::kNone) {
3566 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
3567 }
3568
Steve Anton8a006912017-12-04 15:25:56 -08003569 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003570}
3571
Steve Anton8a006912017-12-04 15:25:56 -08003572RTCError PeerConnection::PushdownMediaDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003573 SdpType type,
Steve Anton8a006912017-12-04 15:25:56 -08003574 cricket::ContentSource source) {
Steve Antoned10bd92017-12-05 10:52:59 -08003575 const SessionDescriptionInterface* sdesc =
3576 (source == cricket::CS_LOCAL ? local_description()
3577 : remote_description());
Steve Anton75737c02017-11-06 10:37:17 -08003578 RTC_DCHECK(sdesc);
Steve Antoned10bd92017-12-05 10:52:59 -08003579
3580 // Push down the new SDP media section for each audio/video transceiver.
3581 for (auto transceiver : transceivers_) {
Steve Anton75737c02017-11-06 10:37:17 -08003582 const ContentInfo* content_info =
Steve Antoned10bd92017-12-05 10:52:59 -08003583 FindMediaSectionForTransceiver(transceiver, sdesc);
3584 cricket::BaseChannel* channel = transceiver->internal()->channel();
3585 if (!channel || !content_info || content_info->rejected) {
Steve Anton75737c02017-11-06 10:37:17 -08003586 continue;
3587 }
3588 const MediaContentDescription* content_desc =
3589 static_cast<const MediaContentDescription*>(content_info->description);
Steve Antoned10bd92017-12-05 10:52:59 -08003590 if (!content_desc) {
3591 continue;
3592 }
3593 std::string error;
3594 bool success =
3595 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003596 ? channel->SetLocalContent(content_desc, type, &error)
3597 : channel->SetRemoteContent(content_desc, type, &error);
Steve Antoned10bd92017-12-05 10:52:59 -08003598 if (!success) {
3599 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
3600 }
3601 }
3602
3603 // If using the RtpDataChannel, push down the new SDP section for it too.
3604 if (rtp_data_channel_) {
3605 const ContentInfo* data_content =
3606 cricket::GetFirstDataContent(sdesc->description());
3607 if (data_content && !data_content->rejected) {
3608 const MediaContentDescription* data_desc =
3609 static_cast<const MediaContentDescription*>(
3610 data_content->description);
3611 if (data_desc) {
3612 std::string error;
3613 bool success =
3614 (source == cricket::CS_LOCAL)
Steve Anton3828c062017-12-06 10:34:51 -08003615 ? rtp_data_channel_->SetLocalContent(data_desc, type, &error)
3616 : rtp_data_channel_->SetRemoteContent(data_desc, type,
Steve Antoned10bd92017-12-05 10:52:59 -08003617 &error);
3618 if (!success) {
3619 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3620 std::move(error));
3621 }
Steve Anton75737c02017-11-06 10:37:17 -08003622 }
3623 }
3624 }
Steve Antoned10bd92017-12-05 10:52:59 -08003625
Steve Anton75737c02017-11-06 10:37:17 -08003626 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3627 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3628 if (sctp_transport_ && local_description() && remote_description() &&
3629 cricket::GetFirstDataContent(local_description()->description()) &&
3630 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08003631 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08003632 RTC_FROM_HERE,
3633 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08003634 if (!success) {
3635 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3636 "Failed to push down SCTP parameters.");
3637 }
Steve Anton75737c02017-11-06 10:37:17 -08003638 }
Steve Antoned10bd92017-12-05 10:52:59 -08003639
Steve Anton8a006912017-12-04 15:25:56 -08003640 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003641}
3642
3643bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3644 RTC_DCHECK(network_thread()->IsCurrent());
3645 RTC_DCHECK(local_description());
3646 RTC_DCHECK(remote_description());
3647 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3648 // When we support "max-message-size", that would also be pushed down here.
3649 return sctp_transport_->Start(
3650 GetSctpPort(local_description()->description()),
3651 GetSctpPort(remote_description()->description()));
3652}
3653
Steve Anton8a006912017-12-04 15:25:56 -08003654RTCError PeerConnection::PushdownTransportDescription(
3655 cricket::ContentSource source,
Steve Anton3828c062017-12-06 10:34:51 -08003656 SdpType type) {
Steve Anton8a006912017-12-04 15:25:56 -08003657 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003658
Steve Anton8a006912017-12-04 15:25:56 -08003659 const SessionDescriptionInterface* sdesc =
3660 (source == cricket::CS_LOCAL ? local_description()
3661 : remote_description());
3662 RTC_DCHECK(sdesc);
3663 for (const cricket::TransportInfo& tinfo :
3664 sdesc->description()->transport_infos()) {
3665 std::string error;
3666 bool success;
3667 if (source == cricket::CS_LOCAL) {
3668 success = transport_controller_->SetLocalTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003669 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003670 } else {
3671 success = transport_controller_->SetRemoteTransportDescription(
Steve Anton3828c062017-12-06 10:34:51 -08003672 tinfo.content_name, tinfo.description, type, &error);
Steve Anton8a006912017-12-04 15:25:56 -08003673 }
3674 if (!success) {
3675 LOG_AND_RETURN_ERROR(
3676 RTCErrorType::INVALID_PARAMETER,
3677 "Failed to push down transport description: " + error);
Steve Anton75737c02017-11-06 10:37:17 -08003678 }
3679 }
3680
Steve Anton8a006912017-12-04 15:25:56 -08003681 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003682}
3683
3684bool PeerConnection::GetTransportDescription(
3685 const SessionDescription* description,
3686 const std::string& content_name,
3687 cricket::TransportDescription* tdesc) {
3688 if (!description || !tdesc) {
3689 return false;
3690 }
3691 const TransportInfo* transport_info =
3692 description->GetTransportInfoByName(content_name);
3693 if (!transport_info) {
3694 return false;
3695 }
3696 *tdesc = transport_info->description;
3697 return true;
3698}
3699
3700bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3701 const std::string* first_content_name = bundle.FirstContentName();
3702 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003703 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003704 return false;
3705 }
3706 const std::string& transport_name = *first_content_name;
3707
3708 auto maybe_set_transport = [this, bundle,
3709 transport_name](cricket::BaseChannel* ch) {
3710 if (!ch || !bundle.HasContentName(ch->content_name())) {
Steve Antoned10bd92017-12-05 10:52:59 -08003711 return;
Steve Anton75737c02017-11-06 10:37:17 -08003712 }
3713
3714 std::string old_transport_name = ch->transport_name();
3715 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003716 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3717 << " on " << transport_name << ".";
Steve Antoned10bd92017-12-05 10:52:59 -08003718 return;
Steve Anton75737c02017-11-06 10:37:17 -08003719 }
3720
3721 cricket::DtlsTransportInternal* rtp_dtls_transport =
3722 transport_controller_->CreateDtlsTransport(
3723 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3724 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3725 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3726 if (need_rtcp) {
3727 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3728 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3729 }
3730
3731 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003732 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3733 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003734 transport_controller_->DestroyDtlsTransport(
3735 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3736 // If the channel needs rtcp, it means that the channel used to have a
3737 // rtcp transport which needs to be deleted now.
3738 if (need_rtcp) {
3739 transport_controller_->DestroyDtlsTransport(
3740 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3741 }
Steve Anton75737c02017-11-06 10:37:17 -08003742 };
3743
Steve Antoned10bd92017-12-05 10:52:59 -08003744 for (auto transceiver : transceivers_) {
3745 maybe_set_transport(transceiver->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08003746 }
Steve Antoned10bd92017-12-05 10:52:59 -08003747 maybe_set_transport(rtp_data_channel_);
3748
Steve Anton75737c02017-11-06 10:37:17 -08003749 // For SCTP, transport creation/deletion happens here instead of in the
3750 // object itself.
3751 if (sctp_transport_) {
3752 RTC_DCHECK(sctp_transport_name_);
3753 RTC_DCHECK(sctp_content_name_);
3754 if (transport_name != *sctp_transport_name_ &&
3755 bundle.HasContentName(*sctp_content_name_)) {
3756 network_thread()->Invoke<void>(
3757 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3758 transport_name));
3759 }
3760 }
3761
3762 return true;
3763}
3764
Steve Anton75737c02017-11-06 10:37:17 -08003765cricket::IceConfig PeerConnection::ParseIceConfig(
3766 const PeerConnectionInterface::RTCConfiguration& config) const {
3767 cricket::ContinualGatheringPolicy gathering_policy;
3768 // TODO(honghaiz): Add the third continual gathering policy in
3769 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3770 switch (config.continual_gathering_policy) {
3771 case PeerConnectionInterface::GATHER_ONCE:
3772 gathering_policy = cricket::GATHER_ONCE;
3773 break;
3774 case PeerConnectionInterface::GATHER_CONTINUALLY:
3775 gathering_policy = cricket::GATHER_CONTINUALLY;
3776 break;
3777 default:
3778 RTC_NOTREACHED();
3779 gathering_policy = cricket::GATHER_ONCE;
3780 }
3781 cricket::IceConfig ice_config;
3782 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3783 ice_config.prioritize_most_likely_candidate_pairs =
3784 config.prioritize_most_likely_ice_candidate_pairs;
3785 ice_config.backup_connection_ping_interval =
3786 config.ice_backup_candidate_pair_ping_interval;
3787 ice_config.continual_gathering_policy = gathering_policy;
3788 ice_config.presume_writable_when_fully_relayed =
3789 config.presume_writable_when_fully_relayed;
3790 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3791 ice_config.regather_all_networks_interval_range =
3792 config.ice_regather_interval_range;
3793 return ice_config;
3794}
3795
Steve Anton75737c02017-11-06 10:37:17 -08003796bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3797 std::string* track_id) {
3798 if (!local_description()) {
3799 return false;
3800 }
3801 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3802 track_id);
3803}
3804
3805bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3806 std::string* track_id) {
3807 if (!remote_description()) {
3808 return false;
3809 }
3810 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3811 track_id);
3812}
3813
3814bool PeerConnection::SendData(const cricket::SendDataParams& params,
3815 const rtc::CopyOnWriteBuffer& payload,
3816 cricket::SendDataResult* result) {
3817 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003818 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3819 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003820 return false;
3821 }
3822 return rtp_data_channel_
3823 ? rtp_data_channel_->SendData(params, payload, result)
3824 : network_thread()->Invoke<bool>(
3825 RTC_FROM_HERE,
3826 Bind(&cricket::SctpTransportInternal::SendData,
3827 sctp_transport_.get(), params, payload, result));
3828}
3829
3830bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3831 if (!rtp_data_channel_ && !sctp_transport_) {
3832 // Don't log an error here, because DataChannels are expected to call
3833 // ConnectDataChannel in this state. It's the only way to initially tell
3834 // whether or not the underlying transport is ready.
3835 return false;
3836 }
3837 if (rtp_data_channel_) {
3838 rtp_data_channel_->SignalReadyToSendData.connect(
3839 webrtc_data_channel, &DataChannel::OnChannelReady);
3840 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3841 &DataChannel::OnDataReceived);
3842 } else {
3843 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3844 &DataChannel::OnChannelReady);
3845 SignalSctpDataReceived.connect(webrtc_data_channel,
3846 &DataChannel::OnDataReceived);
3847 SignalSctpStreamClosedRemotely.connect(
3848 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3849 }
3850 return true;
3851}
3852
3853void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3854 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003855 RTC_LOG(LS_ERROR)
3856 << "DisconnectDataChannel called when rtp_data_channel_ and "
3857 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003858 return;
3859 }
3860 if (rtp_data_channel_) {
3861 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3862 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3863 } else {
3864 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3865 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3866 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3867 }
3868}
3869
3870void PeerConnection::AddSctpDataStream(int sid) {
3871 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003872 RTC_LOG(LS_ERROR)
3873 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003874 return;
3875 }
3876 network_thread()->Invoke<void>(
3877 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3878 sctp_transport_.get(), sid));
3879}
3880
3881void PeerConnection::RemoveSctpDataStream(int sid) {
3882 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003883 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3884 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003885 return;
3886 }
3887 network_thread()->Invoke<void>(
3888 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3889 sctp_transport_.get(), sid));
3890}
3891
3892bool PeerConnection::ReadyToSendData() const {
3893 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3894 sctp_ready_to_send_data_;
3895}
3896
3897std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3898 RTC_DCHECK(signaling_thread()->IsCurrent());
3899 ChannelNamePairs channel_name_pairs;
3900 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003901 channel_name_pairs.voice = ChannelNamePair(
3902 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003903 }
3904 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003905 channel_name_pairs.video = ChannelNamePair(
3906 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003907 }
3908 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003909 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08003910 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003911 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003912 }
3913 if (sctp_transport_) {
3914 RTC_DCHECK(sctp_content_name_);
3915 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003916 channel_name_pairs.data =
3917 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08003918 }
3919 return GetSessionStats(channel_name_pairs);
3920}
3921
3922std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3923 const ChannelNamePairs& channel_name_pairs) {
3924 if (network_thread()->IsCurrent()) {
3925 return GetSessionStats_n(channel_name_pairs);
3926 }
3927 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3928 RTC_FROM_HERE,
3929 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3930}
3931
3932bool PeerConnection::GetLocalCertificate(
3933 const std::string& transport_name,
3934 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
3935 return transport_controller_->GetLocalCertificate(transport_name,
3936 certificate);
3937}
3938
3939std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
3940 const std::string& transport_name) {
3941 return transport_controller_->GetRemoteSSLCertificate(transport_name);
3942}
3943
3944cricket::DataChannelType PeerConnection::data_channel_type() const {
3945 return data_channel_type_;
3946}
3947
3948bool PeerConnection::IceRestartPending(const std::string& content_name) const {
3949 return pending_ice_restarts_.find(content_name) !=
3950 pending_ice_restarts_.end();
3951}
3952
Steve Anton75737c02017-11-06 10:37:17 -08003953bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
3954 return transport_controller_->NeedsIceRestart(content_name);
3955}
3956
3957void PeerConnection::OnCertificateReady(
3958 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
3959 transport_controller_->SetLocalCertificate(certificate);
3960}
3961
3962void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08003963 SetSessionError(SessionError::kTransport,
3964 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08003965}
3966
3967void PeerConnection::OnTransportControllerConnectionState(
3968 cricket::IceConnectionState state) {
3969 switch (state) {
3970 case cricket::kIceConnectionConnecting:
3971 // If the current state is Connected or Completed, then there were
3972 // writable channels but now there are not, so the next state must
3973 // be Disconnected.
3974 // kIceConnectionConnecting is currently used as the default,
3975 // un-connected state by the TransportController, so its only use is
3976 // detecting disconnections.
3977 if (ice_connection_state_ ==
3978 PeerConnectionInterface::kIceConnectionConnected ||
3979 ice_connection_state_ ==
3980 PeerConnectionInterface::kIceConnectionCompleted) {
3981 SetIceConnectionState(
3982 PeerConnectionInterface::kIceConnectionDisconnected);
3983 }
3984 break;
3985 case cricket::kIceConnectionFailed:
3986 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
3987 break;
3988 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003989 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
3990 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08003991 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3992 break;
3993 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003994 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
3995 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08003996 if (ice_connection_state_ !=
3997 PeerConnectionInterface::kIceConnectionConnected) {
3998 // If jumping directly from "checking" to "connected",
3999 // signal "connected" first.
4000 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
4001 }
4002 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
4003 if (metrics_observer()) {
4004 ReportTransportStats();
4005 }
4006 break;
4007 default:
4008 RTC_NOTREACHED();
4009 }
4010}
4011
4012void PeerConnection::OnTransportControllerCandidatesGathered(
4013 const std::string& transport_name,
4014 const cricket::Candidates& candidates) {
4015 RTC_DCHECK(signaling_thread()->IsCurrent());
4016 int sdp_mline_index;
4017 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004018 RTC_LOG(LS_ERROR)
4019 << "OnTransportControllerCandidatesGathered: content name "
4020 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08004021 return;
4022 }
4023
4024 for (cricket::Candidates::const_iterator citer = candidates.begin();
4025 citer != candidates.end(); ++citer) {
4026 // Use transport_name as the candidate media id.
4027 std::unique_ptr<JsepIceCandidate> candidate(
4028 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
4029 if (local_description()) {
4030 mutable_local_description()->AddCandidate(candidate.get());
4031 }
4032 OnIceCandidate(std::move(candidate));
4033 }
4034}
4035
4036void PeerConnection::OnTransportControllerCandidatesRemoved(
4037 const std::vector<cricket::Candidate>& candidates) {
4038 RTC_DCHECK(signaling_thread()->IsCurrent());
4039 // Sanity check.
4040 for (const cricket::Candidate& candidate : candidates) {
4041 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004042 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4043 << "empty content name in candidate "
4044 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004045 return;
4046 }
4047 }
4048
4049 if (local_description()) {
4050 mutable_local_description()->RemoveCandidates(candidates);
4051 }
4052 OnIceCandidatesRemoved(candidates);
4053}
4054
4055void PeerConnection::OnTransportControllerDtlsHandshakeError(
4056 rtc::SSLHandshakeError error) {
4057 if (metrics_observer()) {
4058 metrics_observer()->IncrementEnumCounter(
4059 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4060 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4061 }
4062}
4063
Steve Antoned10bd92017-12-05 10:52:59 -08004064void PeerConnection::EnableSending() {
4065 for (auto transceiver : transceivers_) {
4066 cricket::BaseChannel* channel = transceiver->internal()->channel();
4067 if (channel && !channel->enabled()) {
4068 channel->Enable(true);
4069 }
Steve Anton75737c02017-11-06 10:37:17 -08004070 }
4071
Steve Anton4171afb2017-11-20 10:20:22 -08004072 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004073 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004074 }
Steve Anton75737c02017-11-06 10:37:17 -08004075}
4076
4077// Returns the media index for a local ice candidate given the content name.
4078bool PeerConnection::GetLocalCandidateMediaIndex(
4079 const std::string& content_name,
4080 int* sdp_mline_index) {
4081 if (!local_description() || !sdp_mline_index) {
4082 return false;
4083 }
4084
4085 bool content_found = false;
4086 const ContentInfos& contents = local_description()->description()->contents();
4087 for (size_t index = 0; index < contents.size(); ++index) {
4088 if (contents[index].name == content_name) {
4089 *sdp_mline_index = static_cast<int>(index);
4090 content_found = true;
4091 break;
4092 }
4093 }
4094 return content_found;
4095}
4096
4097bool PeerConnection::UseCandidatesInSessionDescription(
4098 const SessionDescriptionInterface* remote_desc) {
4099 if (!remote_desc) {
4100 return true;
4101 }
4102 bool ret = true;
4103
4104 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4105 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4106 for (size_t n = 0; n < candidates->count(); ++n) {
4107 const IceCandidateInterface* candidate = candidates->at(n);
4108 bool valid = false;
4109 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4110 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004111 RTC_LOG(LS_INFO)
4112 << "UseCandidatesInSessionDescription: Not ready to use "
4113 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004114 }
4115 continue;
4116 }
4117 ret = UseCandidate(candidate);
4118 if (!ret) {
4119 break;
4120 }
4121 }
4122 }
4123 return ret;
4124}
4125
4126bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4127 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4128 size_t remote_content_size =
4129 remote_description()->description()->contents().size();
4130 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004131 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004132 return false;
4133 }
4134
4135 cricket::ContentInfo content =
4136 remote_description()->description()->contents()[mediacontent_index];
4137 std::vector<cricket::Candidate> candidates;
4138 candidates.push_back(candidate->candidate());
4139 // Invoking BaseSession method to handle remote candidates.
4140 std::string error;
4141 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4142 &error)) {
4143 // Candidates successfully submitted for checking.
4144 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4145 ice_connection_state_ ==
4146 PeerConnectionInterface::kIceConnectionDisconnected) {
4147 // If state is New, then the session has just gotten its first remote ICE
4148 // candidates, so go to Checking.
4149 // If state is Disconnected, the session is re-using old candidates or
4150 // receiving additional ones, so go to Checking.
4151 // If state is Connected, stay Connected.
4152 // TODO(bemasc): If state is Connected, and the new candidates are for a
4153 // newly added transport, then the state actually _should_ move to
4154 // checking. Add a way to distinguish that case.
4155 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4156 }
4157 // TODO(bemasc): If state is Completed, go back to Connected.
4158 } else {
4159 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004160 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004161 }
4162 }
4163 return true;
4164}
4165
4166void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004167 // Destroy video channel first since it may have a pointer to the
4168 // voice channel.
4169 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004170 if (!video_info || video_info->rejected) {
4171 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004172 }
4173
Steve Anton6fec8802017-12-04 10:37:29 -08004174 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4175 if (!audio_info || audio_info->rejected) {
4176 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004177 }
4178
4179 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4180 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004181 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004182 }
4183}
4184
Steve Antoneda6ccd2017-12-04 10:21:55 -08004185std::string PeerConnection::GetTransportNameForMediaSection(
4186 const std::string& mid,
4187 const cricket::ContentGroup* bundle_group) const {
4188 if (!bundle_group) {
4189 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004190 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004191 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004192 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004193 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004194 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004195 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004196 if (!bundle_group->HasContentName(mid)) {
4197 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4198 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004199 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004200 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4201 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004202}
4203
Steve Anton8a006912017-12-04 15:25:56 -08004204RTCError PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004205 RTC_DCHECK(desc);
4206
Steve Anton75737c02017-11-06 10:37:17 -08004207 const cricket::ContentGroup* bundle_group = nullptr;
4208 if (configuration_.bundle_policy ==
4209 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4210 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4211 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004212 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4213 "max-bundle configured but session description "
4214 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004215 }
4216 }
4217
Steve Antoneda6ccd2017-12-04 10:21:55 -08004218 // Creating the media channels and transport proxies.
4219 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4220 if (voice && !voice->rejected &&
4221 !GetAudioTransceiver()->internal()->channel()) {
4222 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4223 voice->name,
4224 GetTransportNameForMediaSection(voice->name, bundle_group));
4225 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004226 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4227 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004228 }
4229 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4230 }
4231
Steve Anton75737c02017-11-06 10:37:17 -08004232 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004233 if (video && !video->rejected &&
4234 !GetVideoTransceiver()->internal()->channel()) {
4235 cricket::VideoChannel* video_channel = CreateVideoChannel(
4236 video->name,
4237 GetTransportNameForMediaSection(video->name, bundle_group));
4238 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004239 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4240 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004241 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004242 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004243 }
4244
4245 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4246 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4247 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004248 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4249 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004250 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4251 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004252 }
4253 }
4254
Steve Anton8a006912017-12-04 15:25:56 -08004255 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004256}
4257
Steve Anton4171afb2017-11-20 10:20:22 -08004258// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004259cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4260 const std::string& mid,
4261 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004262 cricket::DtlsTransportInternal* rtp_dtls_transport =
4263 transport_controller_->CreateDtlsTransport(
4264 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4265 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4266 if (configuration_.rtcp_mux_policy !=
4267 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4268 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4269 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4270 }
4271
4272 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4273 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004274 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4275 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004276 if (!voice_channel) {
4277 transport_controller_->DestroyDtlsTransport(
4278 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4279 if (rtcp_dtls_transport) {
4280 transport_controller_->DestroyDtlsTransport(
4281 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4282 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004283 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004284 }
Steve Anton75737c02017-11-06 10:37:17 -08004285 voice_channel->SignalRtcpMuxFullyActive.connect(
4286 this, &PeerConnection::DestroyRtcpTransport_n);
4287 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4288 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004289 voice_channel->SignalSentPacket.connect(this,
4290 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004291
Steve Antoneda6ccd2017-12-04 10:21:55 -08004292 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004293}
4294
Steve Anton4171afb2017-11-20 10:20:22 -08004295// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004296cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4297 const std::string& mid,
4298 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004299 cricket::DtlsTransportInternal* rtp_dtls_transport =
4300 transport_controller_->CreateDtlsTransport(
4301 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4302 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4303 if (configuration_.rtcp_mux_policy !=
4304 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4305 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4306 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4307 }
4308
4309 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4310 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004311 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4312 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004313
4314 if (!video_channel) {
4315 transport_controller_->DestroyDtlsTransport(
4316 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4317 if (rtcp_dtls_transport) {
4318 transport_controller_->DestroyDtlsTransport(
4319 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4320 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004321 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004322 }
Steve Anton75737c02017-11-06 10:37:17 -08004323 video_channel->SignalRtcpMuxFullyActive.connect(
4324 this, &PeerConnection::DestroyRtcpTransport_n);
4325 video_channel->SignalDtlsSrtpSetupFailure.connect(
4326 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004327 video_channel->SignalSentPacket.connect(this,
4328 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004329
Steve Antoneda6ccd2017-12-04 10:21:55 -08004330 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004331}
4332
Steve Antoneda6ccd2017-12-04 10:21:55 -08004333bool PeerConnection::CreateDataChannel(const std::string& mid,
4334 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004335 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4336 if (sctp) {
4337 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004338 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004339 << "Trying to create SCTP transport, but didn't compile with "
4340 "SCTP support (HAVE_SCTP)";
4341 return false;
4342 }
4343 if (!network_thread()->Invoke<bool>(
4344 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004345 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004346 return false;
4347 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004348 for (const auto& channel : sctp_data_channels_) {
4349 channel->OnTransportChannelCreated();
4350 }
Steve Anton75737c02017-11-06 10:37:17 -08004351 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004352 cricket::DtlsTransportInternal* rtp_dtls_transport =
4353 transport_controller_->CreateDtlsTransport(
4354 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4355 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4356 if (configuration_.rtcp_mux_policy !=
4357 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4358 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4359 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4360 }
4361
4362 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4363 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004364 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004365
4366 if (!rtp_data_channel_) {
4367 transport_controller_->DestroyDtlsTransport(
4368 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4369 if (rtcp_dtls_transport) {
4370 transport_controller_->DestroyDtlsTransport(
4371 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4372 }
4373 return false;
4374 }
4375
4376 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4377 this, &PeerConnection::DestroyRtcpTransport_n);
4378 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4379 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4380 rtp_data_channel_->SignalSentPacket.connect(
4381 this, &PeerConnection::OnSentPacket_w);
4382 }
4383
Steve Anton75737c02017-11-06 10:37:17 -08004384 return true;
4385}
4386
4387Call::Stats PeerConnection::GetCallStats() {
4388 if (!worker_thread()->IsCurrent()) {
4389 return worker_thread()->Invoke<Call::Stats>(
4390 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4391 }
4392 if (call_) {
4393 return call_->GetStats();
4394 } else {
4395 return Call::Stats();
4396 }
4397}
4398
4399std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4400 const ChannelNamePairs& channel_name_pairs) {
4401 RTC_DCHECK(network_thread()->IsCurrent());
4402 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4403 for (const auto channel_name_pair :
4404 {&channel_name_pairs.voice, &channel_name_pairs.video,
4405 &channel_name_pairs.data}) {
4406 if (*channel_name_pair) {
4407 cricket::TransportStats transport_stats;
4408 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4409 &transport_stats)) {
4410 return nullptr;
4411 }
4412 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4413 (*channel_name_pair)->transport_name;
4414 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4415 std::move(transport_stats);
4416 }
4417 }
4418 return session_stats;
4419}
4420
4421bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4422 const std::string& transport_name) {
4423 RTC_DCHECK(network_thread()->IsCurrent());
4424 RTC_DCHECK(sctp_factory_);
4425 cricket::DtlsTransportInternal* tc =
4426 transport_controller_->CreateDtlsTransport_n(
4427 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4428 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4429 RTC_DCHECK(sctp_transport_);
4430 sctp_invoker_.reset(new rtc::AsyncInvoker());
4431 sctp_transport_->SignalReadyToSendData.connect(
4432 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4433 sctp_transport_->SignalDataReceived.connect(
4434 this, &PeerConnection::OnSctpTransportDataReceived_n);
4435 sctp_transport_->SignalStreamClosedRemotely.connect(
4436 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004437 sctp_transport_name_ = transport_name;
4438 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004439 return true;
4440}
4441
4442void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4443 RTC_DCHECK(network_thread()->IsCurrent());
4444 RTC_DCHECK(sctp_transport_);
4445 RTC_DCHECK(sctp_transport_name_);
4446 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004447 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004448 cricket::DtlsTransportInternal* tc =
4449 transport_controller_->CreateDtlsTransport_n(
4450 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4451 sctp_transport_->SetTransportChannel(tc);
4452 transport_controller_->DestroyDtlsTransport_n(
4453 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4454}
4455
4456void PeerConnection::DestroySctpTransport_n() {
4457 RTC_DCHECK(network_thread()->IsCurrent());
4458 sctp_transport_.reset(nullptr);
4459 sctp_content_name_.reset();
4460 sctp_transport_name_.reset();
4461 sctp_invoker_.reset(nullptr);
4462 sctp_ready_to_send_data_ = false;
4463}
4464
4465void PeerConnection::OnSctpTransportReadyToSendData_n() {
4466 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4467 RTC_DCHECK(network_thread()->IsCurrent());
4468 // Note: Cannot use rtc::Bind here because it will grab a reference to
4469 // PeerConnection and potentially cause PeerConnection to live longer than
4470 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4471 // be destroyed before PeerConnection is destroyed, and at that point all
4472 // pending tasks will be cleared.
4473 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4474 OnSctpTransportReadyToSendData_s(true);
4475 });
4476}
4477
4478void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4479 RTC_DCHECK(signaling_thread()->IsCurrent());
4480 sctp_ready_to_send_data_ = ready;
4481 SignalSctpReadyToSendData(ready);
4482}
4483
4484void PeerConnection::OnSctpTransportDataReceived_n(
4485 const cricket::ReceiveDataParams& params,
4486 const rtc::CopyOnWriteBuffer& payload) {
4487 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4488 RTC_DCHECK(network_thread()->IsCurrent());
4489 // Note: Cannot use rtc::Bind here because it will grab a reference to
4490 // PeerConnection and potentially cause PeerConnection to live longer than
4491 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4492 // be destroyed before PeerConnection is destroyed, and at that point all
4493 // pending tasks will be cleared.
4494 sctp_invoker_->AsyncInvoke<void>(
4495 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4496 OnSctpTransportDataReceived_s(params, payload);
4497 });
4498}
4499
4500void PeerConnection::OnSctpTransportDataReceived_s(
4501 const cricket::ReceiveDataParams& params,
4502 const rtc::CopyOnWriteBuffer& payload) {
4503 RTC_DCHECK(signaling_thread()->IsCurrent());
4504 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4505 // Received OPEN message; parse and signal that a new data channel should
4506 // be created.
4507 std::string label;
4508 InternalDataChannelInit config;
4509 config.id = params.ssrc;
4510 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004511 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4512 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004513 return;
4514 }
4515 config.open_handshake_role = InternalDataChannelInit::kAcker;
4516 OnDataChannelOpenMessage(label, config);
4517 } else {
4518 // Otherwise just forward the signal.
4519 SignalSctpDataReceived(params, payload);
4520 }
4521}
4522
4523void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4524 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4525 RTC_DCHECK(network_thread()->IsCurrent());
4526 sctp_invoker_->AsyncInvoke<void>(
4527 RTC_FROM_HERE, signaling_thread(),
4528 rtc::Bind(&sigslot::signal1<int>::operator(),
4529 &SignalSctpStreamClosedRemotely, sid));
4530}
4531
4532// Returns false if bundle is enabled and rtcp_mux is disabled.
4533bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4534 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4535 if (!bundle_enabled)
4536 return true;
4537
4538 const cricket::ContentGroup* bundle_group =
4539 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4540 RTC_DCHECK(bundle_group != NULL);
4541
4542 const cricket::ContentInfos& contents = desc->contents();
4543 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4544 citer != contents.end(); ++citer) {
4545 const cricket::ContentInfo* content = (&*citer);
4546 RTC_DCHECK(content != NULL);
4547 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4548 content->type == cricket::NS_JINGLE_RTP) {
4549 if (!HasRtcpMuxEnabled(content))
4550 return false;
4551 }
4552 }
4553 // RTCP-MUX is enabled in all the contents.
4554 return true;
4555}
4556
4557bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4558 const cricket::MediaContentDescription* description =
4559 static_cast<cricket::MediaContentDescription*>(content->description);
4560 return description->rtcp_mux();
4561}
4562
Steve Anton8a006912017-12-04 15:25:56 -08004563RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08004564 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08004565 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08004566 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08004567 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08004568 }
4569
4570 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08004571 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08004572 }
4573
Steve Anton3828c062017-12-06 10:34:51 -08004574 SdpType type = sdesc->GetType();
4575 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(type)) ||
4576 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(type))) {
Steve Anton8a006912017-12-04 15:25:56 -08004577 LOG_AND_RETURN_ERROR(
4578 RTCErrorType::INVALID_PARAMETER,
4579 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08004580 }
4581
4582 // Verify crypto settings.
4583 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08004584 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4585 dtls_enabled_) {
4586 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
4587 if (!crypto_error.ok()) {
4588 return crypto_error;
4589 }
Steve Anton75737c02017-11-06 10:37:17 -08004590 }
4591
4592 // Verify ice-ufrag and ice-pwd.
4593 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004594 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4595 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08004596 }
4597
4598 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004599 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4600 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08004601 }
4602
4603 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4604 // m-lines that do not rtcp-mux enabled.
4605
4606 // Verify m-lines in Answer when compared against Offer.
Steve Anton3828c062017-12-06 10:34:51 -08004607 if (type == SdpType::kPrAnswer || type == SdpType::kAnswer) {
Steve Anton75737c02017-11-06 10:37:17 -08004608 const cricket::SessionDescription* offer_desc =
4609 (source == cricket::CS_LOCAL) ? remote_description()->description()
4610 : local_description()->description();
4611 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4612 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004613 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4614 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004615 }
4616 } else {
4617 const cricket::SessionDescription* current_desc = nullptr;
4618 if (source == cricket::CS_LOCAL && local_description()) {
4619 current_desc = local_description()->description();
4620 } else if (source == cricket::CS_REMOTE && remote_description()) {
4621 current_desc = remote_description()->description();
4622 }
4623 // The re-offers should respect the order of m= sections in current
4624 // description. See RFC3264 Section 8 paragraph 4 for more details.
4625 if (current_desc &&
4626 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004627 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4628 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08004629 }
4630 }
4631
Steve Anton8a006912017-12-04 15:25:56 -08004632 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004633}
4634
Steve Anton3828c062017-12-06 10:34:51 -08004635bool PeerConnection::ExpectSetLocalDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004636 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004637 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004638 return (state == PeerConnectionInterface::kStable) ||
4639 (state == PeerConnectionInterface::kHaveLocalOffer);
Steve Anton20393062017-12-04 16:24:52 -08004640 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004641 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004642 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4643 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4644 }
4645}
4646
Steve Anton3828c062017-12-06 10:34:51 -08004647bool PeerConnection::ExpectSetRemoteDescription(SdpType type) {
Steve Anton75737c02017-11-06 10:37:17 -08004648 PeerConnectionInterface::SignalingState state = signaling_state();
Steve Anton3828c062017-12-06 10:34:51 -08004649 if (type == SdpType::kOffer) {
Steve Anton75737c02017-11-06 10:37:17 -08004650 return (state == PeerConnectionInterface::kStable) ||
4651 (state == PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton20393062017-12-04 16:24:52 -08004652 } else {
Steve Anton3828c062017-12-06 10:34:51 -08004653 RTC_DCHECK(type == SdpType::kPrAnswer || type == SdpType::kAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004654 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4655 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4656 }
4657}
4658
Steve Antonf8470812017-12-04 10:46:21 -08004659const char* PeerConnection::SessionErrorToString(SessionError error) const {
4660 switch (error) {
4661 case SessionError::kNone:
4662 return "ERROR_NONE";
4663 case SessionError::kContent:
4664 return "ERROR_CONTENT";
4665 case SessionError::kTransport:
4666 return "ERROR_TRANSPORT";
4667 }
4668 RTC_NOTREACHED();
4669 return "";
4670}
4671
Steve Anton75737c02017-11-06 10:37:17 -08004672std::string PeerConnection::GetSessionErrorMsg() {
4673 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08004674 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
4675 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004676 return desc.str();
4677}
4678
4679// We need to check the local/remote description for the Transport instead of
4680// the session, because a new Transport added during renegotiation may have
4681// them unset while the session has them set from the previous negotiation.
4682// Not doing so may trigger the auto generation of transport description and
4683// mess up DTLS identity information, ICE credential, etc.
4684bool PeerConnection::ReadyToUseRemoteCandidate(
4685 const IceCandidateInterface* candidate,
4686 const SessionDescriptionInterface* remote_desc,
4687 bool* valid) {
4688 *valid = true;
4689
4690 const SessionDescriptionInterface* current_remote_desc =
4691 remote_desc ? remote_desc : remote_description();
4692
4693 if (!current_remote_desc) {
4694 return false;
4695 }
4696
4697 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4698 size_t remote_content_size =
4699 current_remote_desc->description()->contents().size();
4700 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004701 RTC_LOG(LS_ERROR)
4702 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4703 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004704
4705 *valid = false;
4706 return false;
4707 }
4708
4709 cricket::ContentInfo content =
4710 current_remote_desc->description()->contents()[mediacontent_index];
4711
4712 const std::string transport_name = GetTransportName(content.name);
4713 if (transport_name.empty()) {
4714 return false;
4715 }
4716 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4717}
4718
4719bool PeerConnection::SrtpRequired() const {
4720 return dtls_enabled_ ||
4721 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4722}
4723
4724void PeerConnection::OnTransportControllerGatheringState(
4725 cricket::IceGatheringState state) {
4726 RTC_DCHECK(signaling_thread()->IsCurrent());
4727 if (state == cricket::kIceGatheringGathering) {
4728 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4729 } else if (state == cricket::kIceGatheringComplete) {
4730 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4731 }
4732}
4733
4734void PeerConnection::ReportTransportStats() {
4735 // Use a set so we don't report the same stats twice if two channels share
4736 // a transport.
4737 std::set<std::string> transport_names;
4738 if (voice_channel()) {
4739 transport_names.insert(voice_channel()->transport_name());
4740 }
4741 if (video_channel()) {
4742 transport_names.insert(video_channel()->transport_name());
4743 }
4744 if (rtp_data_channel()) {
4745 transport_names.insert(rtp_data_channel()->transport_name());
4746 }
4747 if (sctp_transport_name_) {
4748 transport_names.insert(*sctp_transport_name_);
4749 }
4750 for (const auto& name : transport_names) {
4751 cricket::TransportStats stats;
4752 if (transport_controller_->GetStats(name, &stats)) {
4753 ReportBestConnectionState(stats);
4754 ReportNegotiatedCiphers(stats);
4755 }
4756 }
4757}
4758// Walk through the ConnectionInfos to gather best connection usage
4759// for IPv4 and IPv6.
4760void PeerConnection::ReportBestConnectionState(
4761 const cricket::TransportStats& stats) {
4762 RTC_DCHECK(metrics_observer());
4763 for (cricket::TransportChannelStatsList::const_iterator it =
4764 stats.channel_stats.begin();
4765 it != stats.channel_stats.end(); ++it) {
4766 for (cricket::ConnectionInfos::const_iterator it_info =
4767 it->connection_infos.begin();
4768 it_info != it->connection_infos.end(); ++it_info) {
4769 if (!it_info->best_connection) {
4770 continue;
4771 }
4772
4773 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4774 const cricket::Candidate& local = it_info->local_candidate;
4775 const cricket::Candidate& remote = it_info->remote_candidate;
4776
4777 // Increment the counter for IceCandidatePairType.
4778 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4779 (local.type() == RELAY_PORT_TYPE &&
4780 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4781 type = kEnumCounterIceCandidatePairTypeTcp;
4782 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4783 type = kEnumCounterIceCandidatePairTypeUdp;
4784 } else {
4785 RTC_CHECK(0);
4786 }
4787 metrics_observer()->IncrementEnumCounter(
4788 type, GetIceCandidatePairCounter(local, remote),
4789 kIceCandidatePairMax);
4790
4791 // Increment the counter for IP type.
4792 if (local.address().family() == AF_INET) {
4793 metrics_observer()->IncrementEnumCounter(
4794 kEnumCounterAddressFamily, kBestConnections_IPv4,
4795 kPeerConnectionAddressFamilyCounter_Max);
4796
4797 } else if (local.address().family() == AF_INET6) {
4798 metrics_observer()->IncrementEnumCounter(
4799 kEnumCounterAddressFamily, kBestConnections_IPv6,
4800 kPeerConnectionAddressFamilyCounter_Max);
4801 } else {
4802 RTC_CHECK(0);
4803 }
4804
4805 return;
4806 }
4807 }
4808}
4809
4810void PeerConnection::ReportNegotiatedCiphers(
4811 const cricket::TransportStats& stats) {
4812 RTC_DCHECK(metrics_observer());
4813 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4814 return;
4815 }
4816
4817 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4818 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4819 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4820 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4821 return;
4822 }
4823
4824 PeerConnectionEnumCounterType srtp_counter_type;
4825 PeerConnectionEnumCounterType ssl_counter_type;
4826 if (stats.transport_name == cricket::CN_AUDIO) {
4827 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4828 ssl_counter_type = kEnumCounterAudioSslCipher;
4829 } else if (stats.transport_name == cricket::CN_VIDEO) {
4830 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4831 ssl_counter_type = kEnumCounterVideoSslCipher;
4832 } else if (stats.transport_name == cricket::CN_DATA) {
4833 srtp_counter_type = kEnumCounterDataSrtpCipher;
4834 ssl_counter_type = kEnumCounterDataSslCipher;
4835 } else {
4836 RTC_NOTREACHED();
4837 return;
4838 }
4839
4840 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4841 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4842 srtp_crypto_suite);
4843 }
4844 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4845 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4846 ssl_cipher_suite);
4847 }
4848}
4849
4850void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4851 RTC_DCHECK(worker_thread()->IsCurrent());
4852 RTC_DCHECK(call_);
4853 call_->OnSentPacket(sent_packet);
4854}
4855
4856const std::string PeerConnection::GetTransportName(
4857 const std::string& content_name) {
4858 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004859 if (channel) {
4860 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004861 }
Steve Anton6fec8802017-12-04 10:37:29 -08004862 if (sctp_transport_) {
4863 RTC_DCHECK(sctp_content_name_);
4864 RTC_DCHECK(sctp_transport_name_);
4865 if (content_name == *sctp_content_name_) {
4866 return *sctp_transport_name_;
4867 }
4868 }
4869 // Return an empty string if failed to retrieve the transport name.
4870 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004871}
4872
4873void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4874 RTC_DCHECK(network_thread()->IsCurrent());
4875 transport_controller_->DestroyDtlsTransport_n(
4876 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4877}
4878
Steve Anton6fec8802017-12-04 10:37:29 -08004879void PeerConnection::DestroyTransceiverChannel(
4880 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4881 transceiver) {
4882 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08004883
Steve Anton6fec8802017-12-04 10:37:29 -08004884 cricket::BaseChannel* channel = transceiver->internal()->channel();
4885 if (channel) {
4886 transceiver->internal()->SetChannel(nullptr);
4887 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08004888 }
4889}
4890
4891void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08004892 if (rtp_data_channel_) {
4893 OnDataChannelDestroyed();
4894 DestroyBaseChannel(rtp_data_channel_);
4895 rtp_data_channel_ = nullptr;
4896 }
4897
4898 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
4899 // grab a reference to this PeerConnection. If this is called from the
4900 // PeerConnection destructor, the RefCountedObject vtable will have already
4901 // been destroyed (since it is a subclass of PeerConnection) and using
4902 // rtc::Bind will cause "Pure virtual function called" error to appear.
4903
4904 if (sctp_transport_) {
4905 OnDataChannelDestroyed();
4906 network_thread()->Invoke<void>(RTC_FROM_HERE,
4907 [this] { DestroySctpTransport_n(); });
4908 }
4909}
4910
4911void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
4912 RTC_DCHECK(channel);
4913 RTC_DCHECK(channel->rtp_dtls_transport());
4914
4915 // Need to cache these before destroying the base channel so that we do not
4916 // access uninitialized memory.
4917 const std::string transport_name =
4918 channel->rtp_dtls_transport()->transport_name();
4919 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
4920
4921 switch (channel->media_type()) {
4922 case cricket::MEDIA_TYPE_AUDIO:
4923 channel_manager()->DestroyVoiceChannel(
4924 static_cast<cricket::VoiceChannel*>(channel));
4925 break;
4926 case cricket::MEDIA_TYPE_VIDEO:
4927 channel_manager()->DestroyVideoChannel(
4928 static_cast<cricket::VideoChannel*>(channel));
4929 break;
4930 case cricket::MEDIA_TYPE_DATA:
4931 channel_manager()->DestroyRtpDataChannel(
4932 static_cast<cricket::RtpDataChannel*>(channel));
4933 break;
4934 default:
4935 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
4936 break;
4937 }
4938
4939 // |channel| can no longer be used.
4940
Steve Anton75737c02017-11-06 10:37:17 -08004941 transport_controller_->DestroyDtlsTransport(
4942 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4943 if (need_to_delete_rtcp) {
4944 transport_controller_->DestroyDtlsTransport(
4945 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4946 }
4947}
4948
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004949} // namespace webrtc