blob: 176cc4bb6838795d293134f8dd80cf3b6fcccb5b [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.
1520 Action action = GetAction(desc->type());
1521 if (!initial_offerer_.has_value()) {
1522 initial_offerer_.emplace(action == kOffer);
1523 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
1530 if (action == kAnswer) {
1531 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.
1542 if (action == kOffer) {
1543 // 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
1554 error = UpdateSessionState(action, cricket::CS_LOCAL);
1555 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;
1689 Action action = GetAction(desc->type());
1690 if (action == kAnswer) {
1691 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.
1706 if (action == kOffer) {
1707 // 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.
1720 error = UpdateSessionState(action, cricket::CS_REMOTE);
1721 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)) {
1740 if (action == kOffer) {
1741 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
deadbeef46c73892016-11-16 19:42:04 -08001862PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1863 return configuration_;
1864}
1865
deadbeef293e9262017-01-11 12:28:30 -08001866bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1867 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001868 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001869
Steve Anton75737c02017-11-06 10:37:17 -08001870 if (local_description() && configuration.ice_candidate_pool_size !=
1871 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001872 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1873 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001874 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001875 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001876
deadbeef293e9262017-01-11 12:28:30 -08001877 // The simplest (and most future-compatible) way to tell if the config was
1878 // modified in an invalid way is to copy each property we do support
1879 // modifying, then use operator==. There are far more properties we don't
1880 // support modifying than those we do, and more could be added.
1881 RTCConfiguration modified_config = configuration_;
1882 modified_config.servers = configuration.servers;
1883 modified_config.type = configuration.type;
1884 modified_config.ice_candidate_pool_size =
1885 configuration.ice_candidate_pool_size;
1886 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001887 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001888 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001889 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001890 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001891 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1892 }
1893
Steve Anton038834f2017-07-14 15:59:59 -07001894 // Validate the modified configuration.
1895 RTCError validate_error = ValidateConfiguration(modified_config);
1896 if (!validate_error.ok()) {
1897 return SafeSetError(std::move(validate_error), error);
1898 }
1899
deadbeef293e9262017-01-11 12:28:30 -08001900 // Note that this isn't possible through chromium, since it's an unsigned
1901 // short in WebIDL.
1902 if (configuration.ice_candidate_pool_size < 0 ||
1903 configuration.ice_candidate_pool_size > UINT16_MAX) {
1904 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1905 }
1906
1907 // Parse ICE servers before hopping to network thread.
1908 cricket::ServerAddresses stun_servers;
1909 std::vector<cricket::RelayServerConfig> turn_servers;
1910 RTCErrorType parse_error =
1911 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1912 if (parse_error != RTCErrorType::NONE) {
1913 return SafeSetError(parse_error, error);
1914 }
1915
1916 // In theory this shouldn't fail.
1917 if (!network_thread()->Invoke<bool>(
1918 RTC_FROM_HERE,
1919 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1920 stun_servers, turn_servers, modified_config.type,
1921 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001922 modified_config.prune_turn_ports,
1923 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001924 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001925 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1926 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001927
deadbeefd1a38b52016-12-10 13:15:33 -08001928 // As described in JSEP, calling setConfiguration with new ICE servers or
1929 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1930 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001931 if (modified_config.servers != configuration_.servers ||
1932 modified_config.type != configuration_.type ||
1933 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001934 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001935 }
skvladd1f5fda2017-02-03 16:54:05 -08001936
1937 if (modified_config.ice_check_min_interval !=
1938 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001939 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001940 }
1941
deadbeef293e9262017-01-11 12:28:30 -08001942 configuration_ = modified_config;
1943 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001944}
1945
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001946bool PeerConnection::AddIceCandidate(
1947 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001948 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001949 if (IsClosed()) {
1950 return false;
1951 }
Steve Antond25da372017-11-06 14:50:29 -08001952
1953 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001954 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1955 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001956 return false;
1957 }
1958
1959 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001960 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001961 return false;
1962 }
1963
1964 bool valid = false;
1965 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1966 if (!valid) {
1967 return false;
1968 }
1969
1970 // Add this candidate to the remote session description.
1971 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001972 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001973 return false;
1974 }
1975
1976 if (ready) {
1977 return UseCandidate(ice_candidate);
1978 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001979 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001980 return true;
1981 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001982}
1983
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001984bool PeerConnection::RemoveIceCandidates(
1985 const std::vector<cricket::Candidate>& candidates) {
1986 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001987 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001988 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1989 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001990 return false;
1991 }
1992
1993 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001994 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08001995 return false;
1996 }
1997
1998 size_t number_removed =
1999 mutable_remote_description()->RemoveCandidates(candidates);
2000 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002001 RTC_LOG(LS_ERROR)
2002 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
2003 << "Requested " << candidates.size() << " but only " << number_removed
2004 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08002005 }
2006
2007 // Remove the candidates from the transport controller.
2008 std::string error;
2009 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
2010 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002011 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08002012 }
2013 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002014}
2015
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002016void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01002017 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002018 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002019
Steve Anton75737c02017-11-06 10:37:17 -08002020 if (transport_controller()) {
2021 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00002022 }
2023
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002024 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08002025 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07002026 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002027 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002028 uma_observer_->IncrementEnumCounter(
2029 kEnumCounterAddressFamily, kPeerConnection_IPv6,
2030 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00002031 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07002032 uma_observer_->IncrementEnumCounter(
2033 kEnumCounterAddressFamily, kPeerConnection_IPv4,
2034 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00002035 }
2036 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00002037}
2038
zstein4b979802017-06-02 14:37:37 -07002039RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07002040 if (!worker_thread()->IsCurrent()) {
2041 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07002042 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
2043 }
2044
2045 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
2046 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
2047 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
2048 if (has_min && *bitrate.min_bitrate_bps < 0) {
2049 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2050 "min_bitrate_bps <= 0");
2051 }
2052 if (has_current) {
2053 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
2054 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2055 "current_bitrate_bps < min_bitrate_bps");
2056 } else if (*bitrate.current_bitrate_bps < 0) {
2057 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2058 "curent_bitrate_bps < 0");
2059 }
2060 }
2061 if (has_max) {
2062 if (has_current &&
2063 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
2064 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2065 "max_bitrate_bps < current_bitrate_bps");
2066 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
2067 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2068 "max_bitrate_bps < min_bitrate_bps");
2069 } else if (*bitrate.max_bitrate_bps < 0) {
2070 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
2071 "max_bitrate_bps < 0");
2072 }
2073 }
2074
2075 Call::Config::BitrateConfigMask mask;
2076 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
2077 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
2078 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
2079
2080 RTC_DCHECK(call_.get());
2081 call_->SetBitrateConfigMask(mask);
2082
2083 return RTCError::OK();
2084}
2085
Alex Narest78609d52017-10-20 10:37:47 +02002086void PeerConnection::SetBitrateAllocationStrategy(
2087 std::unique_ptr<rtc::BitrateAllocationStrategy>
2088 bitrate_allocation_strategy) {
2089 rtc::Thread* worker_thread = factory_->worker_thread();
2090 if (!worker_thread->IsCurrent()) {
2091 rtc::BitrateAllocationStrategy* strategy_raw =
2092 bitrate_allocation_strategy.release();
2093 auto functor = [this, strategy_raw]() {
2094 call_->SetBitrateAllocationStrategy(
2095 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
2096 };
2097 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
2098 return;
2099 }
2100 RTC_DCHECK(call_.get());
2101 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
2102}
2103
henrika5f6bf242017-11-01 11:06:56 +01002104void PeerConnection::SetAudioPlayout(bool playout) {
2105 if (!worker_thread()->IsCurrent()) {
2106 worker_thread()->Invoke<void>(
2107 RTC_FROM_HERE,
2108 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
2109 return;
2110 }
2111 auto audio_state =
2112 factory_->channel_manager()->media_engine()->GetAudioState();
2113 audio_state->SetPlayout(playout);
2114}
2115
2116void PeerConnection::SetAudioRecording(bool recording) {
2117 if (!worker_thread()->IsCurrent()) {
2118 worker_thread()->Invoke<void>(
2119 RTC_FROM_HERE,
2120 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
2121 return;
2122 }
2123 auto audio_state =
2124 factory_->channel_manager()->media_engine()->GetAudioState();
2125 audio_state->SetRecording(recording);
2126}
2127
Steve Anton8c0f7a72017-10-03 10:03:10 -07002128std::unique_ptr<rtc::SSLCertificate>
2129PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08002130 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07002131 return nullptr;
2132 }
Steve Anton75737c02017-11-06 10:37:17 -08002133 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07002134}
2135
ivoc14d5dbe2016-07-04 07:06:55 -07002136bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
2137 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02002138 // TODO(eladalon): It would be better to not allow negative values into PC.
2139 const size_t max_size = (max_size_bytes < 0)
2140 ? RtcEventLog::kUnlimitedOutput
2141 : rtc::saturated_cast<size_t>(max_size_bytes);
2142 return StartRtcEventLog(
Bjorn Tereliusde939432017-11-20 17:38:14 +01002143 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size),
2144 webrtc::RtcEventLog::kImmediateOutput);
Elad Alon99c3fe52017-10-13 16:29:40 +02002145}
2146
Bjorn Tereliusde939432017-11-20 17:38:14 +01002147bool PeerConnection::StartRtcEventLog(std::unique_ptr<RtcEventLogOutput> output,
2148 int64_t output_period_ms) {
Karl Wibergd6b48192017-10-16 23:01:06 +02002149 // TODO(eladalon): In C++14, this can be done with a lambda.
2150 struct Functor {
Bjorn Tereliusde939432017-11-20 17:38:14 +01002151 bool operator()() {
2152 return pc->StartRtcEventLog_w(std::move(output), output_period_ms);
2153 }
Karl Wibergd6b48192017-10-16 23:01:06 +02002154 PeerConnection* const pc;
2155 std::unique_ptr<RtcEventLogOutput> output;
Bjorn Tereliusde939432017-11-20 17:38:14 +01002156 const int64_t output_period_ms;
Elad Alon99c3fe52017-10-13 16:29:40 +02002157 };
Bjorn Tereliusde939432017-11-20 17:38:14 +01002158 return worker_thread()->Invoke<bool>(
2159 RTC_FROM_HERE, Functor{this, std::move(output), output_period_ms});
ivoc14d5dbe2016-07-04 07:06:55 -07002160}
2161
2162void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07002163 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07002164 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
2165}
2166
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002167const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002168 return pending_local_description_ ? pending_local_description_.get()
2169 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002170}
2171
2172const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08002173 return pending_remote_description_ ? pending_remote_description_.get()
2174 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002175}
2176
deadbeeffe4a8a42016-12-20 17:56:17 -08002177const SessionDescriptionInterface* PeerConnection::current_local_description()
2178 const {
Steve Anton75737c02017-11-06 10:37:17 -08002179 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002180}
2181
2182const SessionDescriptionInterface* PeerConnection::current_remote_description()
2183 const {
Steve Anton75737c02017-11-06 10:37:17 -08002184 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002185}
2186
2187const SessionDescriptionInterface* PeerConnection::pending_local_description()
2188 const {
Steve Anton75737c02017-11-06 10:37:17 -08002189 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002190}
2191
2192const SessionDescriptionInterface* PeerConnection::pending_remote_description()
2193 const {
Steve Anton75737c02017-11-06 10:37:17 -08002194 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08002195}
2196
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002197void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01002198 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002199 // Update stats here so that we have the most recent stats for tracks and
2200 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00002201 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202
Steve Anton75737c02017-11-06 10:37:17 -08002203 ChangeSignalingState(PeerConnectionInterface::kClosed);
2204 RemoveUnusedChannels(nullptr);
Steve Anton4171afb2017-11-20 10:20:22 -08002205 RTC_DCHECK(!GetAudioTransceiver()->internal()->channel());
2206 RTC_DCHECK(!GetVideoTransceiver()->internal()->channel());
Steve Anton75737c02017-11-06 10:37:17 -08002207 RTC_DCHECK(!rtp_data_channel_);
2208 RTC_DCHECK(!sctp_transport_);
2209
deadbeef42a42632017-03-10 15:18:00 -08002210 network_thread()->Invoke<void>(
2211 RTC_FROM_HERE,
2212 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
2213 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07002214
Steve Anton978b8762017-09-29 12:15:02 -07002215 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002216 call_.reset();
2217 // The event log must outlive call (and any other object that uses it).
2218 event_log_.reset();
2219 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002220}
2221
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002222void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002223 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002224 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2225 SetSessionDescriptionMsg* param =
2226 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2227 param->observer->OnSuccess();
2228 delete param;
2229 break;
2230 }
2231 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2232 SetSessionDescriptionMsg* param =
2233 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2234 param->observer->OnFailure(param->error);
2235 delete param;
2236 break;
2237 }
deadbeefab9b2d12015-10-14 11:33:11 -07002238 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2239 CreateSessionDescriptionMsg* param =
2240 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2241 param->observer->OnFailure(param->error);
2242 delete param;
2243 break;
2244 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002245 case MSG_GETSTATS: {
2246 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002247 StatsReports reports;
2248 stats_->GetStats(param->track, &reports);
2249 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002250 delete param;
2251 break;
2252 }
deadbeefbd292462015-12-14 18:15:29 -08002253 case MSG_FREE_DATACHANNELS: {
2254 sctp_data_channels_to_free_.clear();
2255 break;
2256 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002257 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002258 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002259 break;
2260 }
2261}
2262
Steve Anton4171afb2017-11-20 10:20:22 -08002263void PeerConnection::CreateAudioReceiver(
2264 MediaStreamInterface* stream,
2265 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002266 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2267 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002268 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2269 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002270 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002271 new AudioRtpReceiver(remote_sender_info.sender_id, streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002272 remote_sender_info.first_ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002273 stream->AddTrack(
2274 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002275 GetAudioTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002276 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002277}
2278
Steve Anton4171afb2017-11-20 10:20:22 -08002279void PeerConnection::CreateVideoReceiver(
2280 MediaStreamInterface* stream,
2281 const RtpSenderInfo& remote_sender_info) {
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002282 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2283 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
zhihuang81c3a032016-11-17 12:06:24 -08002284 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2285 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton4171afb2017-11-20 10:20:22 -08002286 signaling_thread(),
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002287 new VideoRtpReceiver(remote_sender_info.sender_id, streams,
2288 worker_thread(), remote_sender_info.first_ssrc,
2289 video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002290 stream->AddTrack(
2291 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002292 GetVideoTransceiver()->internal()->AddReceiver(receiver);
Henrik Boström9e6fd2b2017-11-21 13:41:51 +01002293 observer_->OnAddTrack(receiver, std::move(streams));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002294}
2295
deadbeef70ab1a12015-09-28 16:53:55 -07002296// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2297// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002298rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
Steve Anton4171afb2017-11-20 10:20:22 -08002299 const RtpSenderInfo& remote_sender_info) {
2300 auto receiver = FindReceiverById(remote_sender_info.sender_id);
2301 if (!receiver) {
2302 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id "
2303 << remote_sender_info.sender_id << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002304 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002305 }
Steve Anton4171afb2017-11-20 10:20:22 -08002306 if (receiver->media_type() == cricket::MEDIA_TYPE_AUDIO) {
2307 GetAudioTransceiver()->internal()->RemoveReceiver(receiver);
2308 } else {
2309 GetVideoTransceiver()->internal()->RemoveReceiver(receiver);
2310 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002311 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002312}
2313
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002314void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2315 MediaStreamInterface* stream) {
2316 RTC_DCHECK(!IsClosed());
2317 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002318 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002319 // We already have a sender for this track, so just change the stream_id
2320 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002321 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002322 return;
2323 }
2324
2325 // Normal case; we've never seen this track before.
2326 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2327 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2328 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002329 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2330 stats_.get()));
Steve Anton4171afb2017-11-20 10:20:22 -08002331 GetAudioTransceiver()->internal()->AddSender(new_sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002332 // If the sender has already been configured in SDP, we call SetSsrc,
2333 // which will connect the sender to the underlying transport. This can
2334 // occur if a local session description that contains the ID of the sender
2335 // is set before AddStream is called. It can also occur if the local
2336 // session description is not changed and RemoveStream is called, and
2337 // later AddStream is called again with the same stream.
Steve Anton4171afb2017-11-20 10:20:22 -08002338 const RtpSenderInfo* sender_info =
2339 FindSenderInfo(local_audio_sender_infos_, stream->label(), track->id());
2340 if (sender_info) {
2341 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002342 }
2343}
2344
2345// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2346// indefinitely, when we have unified plan SDP.
2347void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2348 MediaStreamInterface* stream) {
2349 RTC_DCHECK(!IsClosed());
2350 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002351 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002352 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2353 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002354 return;
2355 }
Steve Anton4171afb2017-11-20 10:20:22 -08002356 GetAudioTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002357}
2358
2359void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2360 MediaStreamInterface* stream) {
2361 RTC_DCHECK(!IsClosed());
2362 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002363 if (sender) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002364 // We already have a sender for this track, so just change the stream_id
2365 // so that it's correct in the next call to CreateOffer.
Steve Anton4171afb2017-11-20 10:20:22 -08002366 sender->internal()->set_stream_id(stream->label());
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002367 return;
2368 }
2369
2370 // Normal case; we've never seen this track before.
2371 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2372 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002373 signaling_thread(),
2374 new VideoRtpSender(track, {stream->label()}, video_channel()));
Steve Anton4171afb2017-11-20 10:20:22 -08002375 GetVideoTransceiver()->internal()->AddSender(new_sender);
2376 const RtpSenderInfo* sender_info =
2377 FindSenderInfo(local_video_sender_infos_, stream->label(), track->id());
2378 if (sender_info) {
2379 new_sender->internal()->SetSsrc(sender_info->first_ssrc);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002380 }
2381}
2382
2383void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2384 MediaStreamInterface* stream) {
2385 RTC_DCHECK(!IsClosed());
2386 auto sender = FindSenderForTrack(track);
Steve Anton4171afb2017-11-20 10:20:22 -08002387 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002388 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2389 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002390 return;
2391 }
Steve Anton4171afb2017-11-20 10:20:22 -08002392 GetVideoTransceiver()->internal()->RemoveSender(sender);
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002393}
2394
Steve Antonba818672017-11-06 10:21:57 -08002395void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002396 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002397 if (ice_connection_state_ == new_state) {
2398 return;
2399 }
2400
deadbeefcbecd352015-09-23 11:50:27 -07002401 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002402 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002403 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002404 return;
2405 }
Steve Antonba818672017-11-06 10:21:57 -08002406
Mirko Bonadei675513b2017-11-09 11:09:25 +01002407 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2408 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002409 RTC_DCHECK(ice_connection_state_ !=
2410 PeerConnectionInterface::kIceConnectionClosed);
2411
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002412 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002413 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002414}
2415
2416void PeerConnection::OnIceGatheringChange(
2417 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002418 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002419 if (IsClosed()) {
2420 return;
2421 }
2422 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002423 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002424}
2425
jbauch81bf7b02017-03-25 08:31:12 -07002426void PeerConnection::OnIceCandidate(
2427 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002428 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002429 if (IsClosed()) {
2430 return;
2431 }
jbauch81bf7b02017-03-25 08:31:12 -07002432 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002433}
2434
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002435void PeerConnection::OnIceCandidatesRemoved(
2436 const std::vector<cricket::Candidate>& candidates) {
2437 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002438 if (IsClosed()) {
2439 return;
2440 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002441 observer_->OnIceCandidatesRemoved(candidates);
2442}
2443
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002444void PeerConnection::ChangeSignalingState(
2445 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002446 RTC_DCHECK(signaling_thread()->IsCurrent());
2447 if (signaling_state_ == signaling_state) {
2448 return;
2449 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002450 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2451 << GetSignalingStateString(signaling_state_)
2452 << " New state: "
2453 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002454 signaling_state_ = signaling_state;
2455 if (signaling_state == kClosed) {
2456 ice_connection_state_ = kIceConnectionClosed;
2457 observer_->OnIceConnectionChange(ice_connection_state_);
2458 if (ice_gathering_state_ != kIceGatheringComplete) {
2459 ice_gathering_state_ = kIceGatheringComplete;
2460 observer_->OnIceGatheringChange(ice_gathering_state_);
2461 }
2462 }
2463 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002464}
2465
deadbeefeb459812015-12-15 19:24:43 -08002466void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2467 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002468 if (IsClosed()) {
2469 return;
2470 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002471 AddAudioTrack(track, stream);
2472 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002473}
2474
deadbeefeb459812015-12-15 19:24:43 -08002475void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2476 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002477 if (IsClosed()) {
2478 return;
2479 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002480 RemoveAudioTrack(track, stream);
2481 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002482}
2483
2484void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2485 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002486 if (IsClosed()) {
2487 return;
2488 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002489 AddVideoTrack(track, stream);
2490 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002491}
2492
2493void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2494 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002495 if (IsClosed()) {
2496 return;
2497 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002498 RemoveVideoTrack(track, stream);
2499 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002500}
2501
Henrik Boström31638672017-11-23 17:48:32 +01002502void PeerConnection::PostSetSessionDescriptionSuccess(
2503 SetSessionDescriptionObserver* observer) {
2504 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2505 signaling_thread()->Post(RTC_FROM_HERE, this,
2506 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
2507}
2508
deadbeefab9b2d12015-10-14 11:33:11 -07002509void PeerConnection::PostSetSessionDescriptionFailure(
2510 SetSessionDescriptionObserver* observer,
2511 const std::string& error) {
2512 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2513 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002514 signaling_thread()->Post(RTC_FROM_HERE, this,
2515 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002516}
2517
2518void PeerConnection::PostCreateSessionDescriptionFailure(
2519 CreateSessionDescriptionObserver* observer,
2520 const std::string& error) {
2521 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2522 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002523 signaling_thread()->Post(RTC_FROM_HERE, this,
2524 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002525}
2526
zhihuang1c378ed2017-08-17 14:10:50 -07002527void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002528 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2529 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002530 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2531
2532 // Figure out transceiver directional preferences.
2533 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2534 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2535
2536 // By default, generate sendrecv/recvonly m= sections.
2537 bool recv_audio = true;
2538 bool recv_video = true;
2539
2540 // By default, only offer a new m= section if we have media to send with it.
2541 bool offer_new_audio_description = send_audio;
2542 bool offer_new_video_description = send_video;
2543 bool offer_new_data_description = HasDataChannels();
2544
2545 // The "offer_to_receive_X" options allow those defaults to be overridden.
2546 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2547 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2548 offer_new_audio_description =
2549 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2550 }
2551 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2552 recv_video = (rtc_options.offer_to_receive_video > 0);
2553 offer_new_video_description =
2554 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2555 }
2556
2557 rtc::Optional<size_t> audio_index;
2558 rtc::Optional<size_t> video_index;
2559 rtc::Optional<size_t> data_index;
2560 // If a current description exists, generate m= sections in the same order,
2561 // using the first audio/video/data section that appears and rejecting
2562 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002563 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002564 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002565 local_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002566 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2567 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2568 &audio_index, &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002569 }
2570
zhihuang1c378ed2017-08-17 14:10:50 -07002571 // Add audio/video/data m= sections to the end if needed.
2572 if (!audio_index && offer_new_audio_description) {
2573 session_options->media_description_options.push_back(
2574 cricket::MediaDescriptionOptions(
2575 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
Steve Anton1d03a752017-11-27 14:30:09 -08002576 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2577 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002578 audio_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002579 }
zhihuang1c378ed2017-08-17 14:10:50 -07002580 if (!video_index && offer_new_video_description) {
2581 session_options->media_description_options.push_back(
2582 cricket::MediaDescriptionOptions(
2583 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
Steve Anton1d03a752017-11-27 14:30:09 -08002584 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2585 false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002586 video_index = session_options->media_description_options.size() - 1;
deadbeefc80741f2015-10-22 13:14:45 -07002587 }
zhihuang1c378ed2017-08-17 14:10:50 -07002588 if (!data_index && offer_new_data_description) {
2589 session_options->media_description_options.push_back(
2590 cricket::MediaDescriptionOptions(
2591 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
Steve Anton1d03a752017-11-27 14:30:09 -08002592 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002593 data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002594 }
2595
2596 cricket::MediaDescriptionOptions* audio_media_description_options =
2597 !audio_index ? nullptr
2598 : &session_options->media_description_options[*audio_index];
2599 cricket::MediaDescriptionOptions* video_media_description_options =
2600 !video_index ? nullptr
2601 : &session_options->media_description_options[*video_index];
2602 cricket::MediaDescriptionOptions* data_media_description_options =
2603 !data_index ? nullptr
2604 : &session_options->media_description_options[*data_index];
2605
2606 // Apply ICE restart flag and renomination flag.
2607 for (auto& options : session_options->media_description_options) {
2608 options.transport_options.ice_restart = rtc_options.ice_restart;
2609 options.transport_options.enable_ice_renomination =
2610 configuration_.enable_ice_renomination;
2611 }
2612
Steve Anton4171afb2017-11-20 10:20:22 -08002613 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002614 video_media_description_options);
2615 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002616
zhihuang9763d562016-08-05 11:14:50 -07002617 // Intentionally unset the data channel type for RTP data channel with the
2618 // second condition. Otherwise the RTP data channels would be successfully
2619 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2620 // when building with chromium. We want to leave RTP data channels broken, so
2621 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002622 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2623 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002624 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002625
2626 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002627 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002628}
2629
zhihuang1c378ed2017-08-17 14:10:50 -07002630void PeerConnection::GetOptionsForAnswer(
2631 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002632 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002633 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002634
zhihuang1c378ed2017-08-17 14:10:50 -07002635 // Figure out transceiver directional preferences.
2636 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2637 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2638
2639 // By default, generate sendrecv/recvonly m= sections. The direction is also
2640 // restricted by the direction in the offer.
2641 bool recv_audio = true;
2642 bool recv_video = true;
2643
2644 // The "offer_to_receive_X" options allow those defaults to be overridden.
2645 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2646 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002647 }
zhihuang1c378ed2017-08-17 14:10:50 -07002648 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2649 recv_video = (rtc_options.offer_to_receive_video > 0);
2650 }
2651
2652 rtc::Optional<size_t> audio_index;
2653 rtc::Optional<size_t> video_index;
2654 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002655 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002656 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002657 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002658 SessionDescriptionInterface::kOffer);
2659 // Generate m= sections that match those in the offer.
2660 // Note that mediasession.cc will handle intersection our preferred
2661 // direction with the offered direction.
2662 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002663 remote_description(),
Steve Anton1d03a752017-11-27 14:30:09 -08002664 RtpTransceiverDirectionFromSendRecv(send_audio, recv_audio),
2665 RtpTransceiverDirectionFromSendRecv(send_video, recv_video),
2666 &audio_index, &video_index, &data_index, session_options);
zhihuang141aacb2017-08-29 13:23:53 -07002667 }
zhihuang1c378ed2017-08-17 14:10:50 -07002668
2669 cricket::MediaDescriptionOptions* audio_media_description_options =
2670 !audio_index ? nullptr
2671 : &session_options->media_description_options[*audio_index];
2672 cricket::MediaDescriptionOptions* video_media_description_options =
2673 !video_index ? nullptr
2674 : &session_options->media_description_options[*video_index];
2675 cricket::MediaDescriptionOptions* data_media_description_options =
2676 !data_index ? nullptr
2677 : &session_options->media_description_options[*data_index];
2678
2679 // Apply ICE renomination flag.
2680 for (auto& options : session_options->media_description_options) {
2681 options.transport_options.enable_ice_renomination =
2682 configuration_.enable_ice_renomination;
2683 }
2684
Steve Anton4171afb2017-11-20 10:20:22 -08002685 AddRtpSenderOptions(GetSendersInternal(), audio_media_description_options,
zhihuang1c378ed2017-08-17 14:10:50 -07002686 video_media_description_options);
2687 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2688
zhihuang9763d562016-08-05 11:14:50 -07002689 // Intentionally unset the data channel type for RTP data channel. Otherwise
2690 // the RTP data channels would be successfully negotiated by default and the
2691 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2692 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002693 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2694 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002695 }
zhihuangaf388472016-11-02 16:49:48 -07002696
zhihuang1c378ed2017-08-17 14:10:50 -07002697 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002698 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002699}
2700
zhihuang1c378ed2017-08-17 14:10:50 -07002701void PeerConnection::GenerateMediaDescriptionOptions(
2702 const SessionDescriptionInterface* session_desc,
Steve Anton1d03a752017-11-27 14:30:09 -08002703 RtpTransceiverDirection audio_direction,
2704 RtpTransceiverDirection video_direction,
zhihuang1c378ed2017-08-17 14:10:50 -07002705 rtc::Optional<size_t>* audio_index,
2706 rtc::Optional<size_t>* video_index,
2707 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002708 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002709 for (const cricket::ContentInfo& content :
2710 session_desc->description()->contents()) {
2711 if (IsAudioContent(&content)) {
2712 // If we already have an audio m= section, reject this extra one.
2713 if (*audio_index) {
2714 session_options->media_description_options.push_back(
2715 cricket::MediaDescriptionOptions(
2716 cricket::MEDIA_TYPE_AUDIO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002717 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002718 } else {
2719 session_options->media_description_options.push_back(
2720 cricket::MediaDescriptionOptions(
2721 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002722 audio_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002723 *audio_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002724 }
2725 } else if (IsVideoContent(&content)) {
2726 // If we already have an video m= section, reject this extra one.
2727 if (*video_index) {
2728 session_options->media_description_options.push_back(
2729 cricket::MediaDescriptionOptions(
2730 cricket::MEDIA_TYPE_VIDEO, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002731 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002732 } else {
2733 session_options->media_description_options.push_back(
2734 cricket::MediaDescriptionOptions(
2735 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
Steve Anton1d03a752017-11-27 14:30:09 -08002736 video_direction == RtpTransceiverDirection::kInactive));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002737 *video_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002738 }
2739 } else {
2740 RTC_DCHECK(IsDataContent(&content));
2741 // If we already have an data m= section, reject this extra one.
2742 if (*data_index) {
2743 session_options->media_description_options.push_back(
2744 cricket::MediaDescriptionOptions(
2745 cricket::MEDIA_TYPE_DATA, content.name,
Steve Anton1d03a752017-11-27 14:30:09 -08002746 RtpTransceiverDirection::kInactive, true));
zhihuang1c378ed2017-08-17 14:10:50 -07002747 } else {
2748 session_options->media_description_options.push_back(
2749 cricket::MediaDescriptionOptions(
2750 cricket::MEDIA_TYPE_DATA, content.name,
2751 // Direction for data sections is meaningless, but legacy
2752 // endpoints might expect sendrecv.
Steve Anton1d03a752017-11-27 14:30:09 -08002753 RtpTransceiverDirection::kSendRecv, false));
Oskar Sundbom9b28a032017-11-16 10:53:30 +01002754 *data_index = session_options->media_description_options.size() - 1;
zhihuang1c378ed2017-08-17 14:10:50 -07002755 }
2756 }
htaa2a49d92016-03-04 02:51:39 -08002757 }
deadbeefab9b2d12015-10-14 11:33:11 -07002758}
2759
Steve Anton4171afb2017-11-20 10:20:22 -08002760void PeerConnection::RemoveSenders(cricket::MediaType media_type) {
2761 UpdateLocalSenders(std::vector<cricket::StreamParams>(), media_type);
2762 UpdateRemoteSendersList(std::vector<cricket::StreamParams>(), false,
deadbeefbda7e0b2015-12-08 17:13:40 -08002763 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002764}
2765
Steve Anton4171afb2017-11-20 10:20:22 -08002766void PeerConnection::UpdateRemoteSendersList(
deadbeefab9b2d12015-10-14 11:33:11 -07002767 const cricket::StreamParamsVec& streams,
Steve Anton4171afb2017-11-20 10:20:22 -08002768 bool default_sender_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002769 cricket::MediaType media_type,
2770 StreamCollection* new_streams) {
Steve Anton4171afb2017-11-20 10:20:22 -08002771 std::vector<RtpSenderInfo>* current_senders =
2772 GetRemoteSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002773
Steve Anton4171afb2017-11-20 10:20:22 -08002774 // Find removed senders. I.e., senders where the sender id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002775 // the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002776 for (auto sender_it = current_senders->begin();
2777 sender_it != current_senders->end();
2778 /* incremented manually */) {
2779 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002780 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002781 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2782 bool sender_exists = params && params->id == info.sender_id;
deadbeefbda7e0b2015-12-08 17:13:40 -08002783 // If this is a default track, and we still need it, don't remove it.
Steve Anton4171afb2017-11-20 10:20:22 -08002784 if ((info.stream_label == kDefaultStreamLabel && default_sender_needed) ||
2785 sender_exists) {
2786 ++sender_it;
deadbeefbda7e0b2015-12-08 17:13:40 -08002787 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002788 OnRemoteSenderRemoved(info, media_type);
2789 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002790 }
2791 }
2792
Steve Anton4171afb2017-11-20 10:20:22 -08002793 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002794 for (const cricket::StreamParams& params : streams) {
2795 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002796 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002797 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002798 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002799 uint32_t ssrc = params.first_ssrc();
2800
2801 rtc::scoped_refptr<MediaStreamInterface> stream =
2802 remote_streams_->find(stream_label);
2803 if (!stream) {
2804 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002805 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2806 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002807 remote_streams_->AddStream(stream);
2808 new_streams->AddStream(stream);
2809 }
2810
Steve Anton4171afb2017-11-20 10:20:22 -08002811 const RtpSenderInfo* sender_info =
2812 FindSenderInfo(*current_senders, stream_label, sender_id);
2813 if (!sender_info) {
2814 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2815 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002816 }
2817 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002818
Steve Anton4171afb2017-11-20 10:20:22 -08002819 // Add default sender if necessary.
2820 if (default_sender_needed) {
deadbeefbda7e0b2015-12-08 17:13:40 -08002821 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2822 remote_streams_->find(kDefaultStreamLabel);
2823 if (!default_stream) {
2824 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002825 default_stream = MediaStreamProxy::Create(
2826 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002827 remote_streams_->AddStream(default_stream);
2828 new_streams->AddStream(default_stream);
2829 }
Steve Anton4171afb2017-11-20 10:20:22 -08002830 std::string default_sender_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2831 ? kDefaultAudioSenderId
2832 : kDefaultVideoSenderId;
2833 const RtpSenderInfo* default_sender_info = FindSenderInfo(
2834 *current_senders, kDefaultStreamLabel, default_sender_id);
2835 if (!default_sender_info) {
2836 current_senders->push_back(
2837 RtpSenderInfo(kDefaultStreamLabel, default_sender_id, 0));
2838 OnRemoteSenderAdded(current_senders->back(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002839 }
2840 }
deadbeefab9b2d12015-10-14 11:33:11 -07002841}
2842
Steve Anton4171afb2017-11-20 10:20:22 -08002843void PeerConnection::OnRemoteSenderAdded(const RtpSenderInfo& sender_info,
2844 cricket::MediaType media_type) {
2845 MediaStreamInterface* stream =
2846 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002847
2848 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002849 CreateAudioReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002850 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
Steve Anton4171afb2017-11-20 10:20:22 -08002851 CreateVideoReceiver(stream, sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002852 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002853 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002854 }
2855}
2856
Steve Anton4171afb2017-11-20 10:20:22 -08002857void PeerConnection::OnRemoteSenderRemoved(const RtpSenderInfo& sender_info,
2858 cricket::MediaType media_type) {
2859 MediaStreamInterface* stream =
2860 remote_streams_->find(sender_info.stream_label);
deadbeefab9b2d12015-10-14 11:33:11 -07002861
Henrik Boström933d8b02017-10-10 10:05:16 -07002862 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002863 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002864 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2865 // will be notified which will end the AudioRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002866 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002867 rtc::scoped_refptr<AudioTrackInterface> audio_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002868 stream->FindAudioTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002869 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002870 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002871 }
2872 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002873 // Stopping or destroying a VideoRtpReceiver will end the
2874 // VideoRtpReceiver::track().
Steve Anton4171afb2017-11-20 10:20:22 -08002875 receiver = RemoveAndStopReceiver(sender_info);
deadbeefab9b2d12015-10-14 11:33:11 -07002876 rtc::scoped_refptr<VideoTrackInterface> video_track =
Steve Anton4171afb2017-11-20 10:20:22 -08002877 stream->FindVideoTrack(sender_info.sender_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002878 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002879 // There's no guarantee the track is still available, e.g. the track may
2880 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002881 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002882 }
2883 } else {
nisseede5da42017-01-12 05:15:36 -08002884 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002885 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002886 if (receiver) {
2887 observer_->OnRemoveTrack(receiver);
2888 }
deadbeefab9b2d12015-10-14 11:33:11 -07002889}
2890
2891void PeerConnection::UpdateEndedRemoteMediaStreams() {
2892 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2893 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2894 MediaStreamInterface* stream = remote_streams_->at(i);
2895 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2896 streams_to_remove.push_back(stream);
2897 }
2898 }
2899
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002900 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002901 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002902 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002903 }
2904}
2905
Steve Anton4171afb2017-11-20 10:20:22 -08002906void PeerConnection::UpdateLocalSenders(
deadbeefab9b2d12015-10-14 11:33:11 -07002907 const std::vector<cricket::StreamParams>& streams,
2908 cricket::MediaType media_type) {
Steve Anton4171afb2017-11-20 10:20:22 -08002909 std::vector<RtpSenderInfo>* current_senders = GetLocalSenderInfos(media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002910
2911 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2912 // don't match the new StreamParam.
Steve Anton4171afb2017-11-20 10:20:22 -08002913 for (auto sender_it = current_senders->begin();
2914 sender_it != current_senders->end();
2915 /* incremented manually */) {
2916 const RtpSenderInfo& info = *sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002917 const cricket::StreamParams* params =
Steve Anton4171afb2017-11-20 10:20:22 -08002918 cricket::GetStreamBySsrc(streams, info.first_ssrc);
2919 if (!params || params->id != info.sender_id ||
deadbeefab9b2d12015-10-14 11:33:11 -07002920 params->sync_label != info.stream_label) {
Steve Anton4171afb2017-11-20 10:20:22 -08002921 OnLocalSenderRemoved(info, media_type);
2922 sender_it = current_senders->erase(sender_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002923 } else {
Steve Anton4171afb2017-11-20 10:20:22 -08002924 ++sender_it;
deadbeefab9b2d12015-10-14 11:33:11 -07002925 }
2926 }
2927
Steve Anton4171afb2017-11-20 10:20:22 -08002928 // Find new and active senders.
deadbeefab9b2d12015-10-14 11:33:11 -07002929 for (const cricket::StreamParams& params : streams) {
2930 // The sync_label is the MediaStream label and the |stream.id| is the
Steve Anton4171afb2017-11-20 10:20:22 -08002931 // sender id.
deadbeefab9b2d12015-10-14 11:33:11 -07002932 const std::string& stream_label = params.sync_label;
Steve Anton4171afb2017-11-20 10:20:22 -08002933 const std::string& sender_id = params.id;
deadbeefab9b2d12015-10-14 11:33:11 -07002934 uint32_t ssrc = params.first_ssrc();
Steve Anton4171afb2017-11-20 10:20:22 -08002935 const RtpSenderInfo* sender_info =
2936 FindSenderInfo(*current_senders, stream_label, sender_id);
2937 if (!sender_info) {
2938 current_senders->push_back(RtpSenderInfo(stream_label, sender_id, ssrc));
2939 OnLocalSenderAdded(current_senders->back(), media_type);
deadbeefab9b2d12015-10-14 11:33:11 -07002940 }
2941 }
2942}
2943
Steve Anton4171afb2017-11-20 10:20:22 -08002944void PeerConnection::OnLocalSenderAdded(const RtpSenderInfo& sender_info,
2945 cricket::MediaType media_type) {
2946 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002947 if (!sender) {
Steve Anton4171afb2017-11-20 10:20:22 -08002948 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id "
2949 << sender_info.sender_id
Mirko Bonadei675513b2017-11-09 11:09:25 +01002950 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002951 return;
2952 }
2953
deadbeeffac06552015-11-25 11:26:01 -08002954 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002955 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2956 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002957 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002958 }
deadbeeffac06552015-11-25 11:26:01 -08002959
Steve Anton4171afb2017-11-20 10:20:22 -08002960 sender->internal()->set_stream_id(sender_info.stream_label);
2961 sender->internal()->SetSsrc(sender_info.first_ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002962}
2963
Steve Anton4171afb2017-11-20 10:20:22 -08002964void PeerConnection::OnLocalSenderRemoved(const RtpSenderInfo& sender_info,
2965 cricket::MediaType media_type) {
2966 auto sender = FindSenderById(sender_info.sender_id);
deadbeeffac06552015-11-25 11:26:01 -08002967 if (!sender) {
2968 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002969 // SessionDescriptions has been renegotiated.
2970 return;
2971 }
deadbeeffac06552015-11-25 11:26:01 -08002972
2973 // A sender has been removed from the SessionDescription but it's still
2974 // associated with the PeerConnection. This only occurs if the SDP doesn't
2975 // match with the calls to CreateSender, AddStream and RemoveStream.
2976 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002977 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2978 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002979 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002980 }
deadbeeffac06552015-11-25 11:26:01 -08002981
Steve Anton4171afb2017-11-20 10:20:22 -08002982 sender->internal()->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002983}
2984
2985void PeerConnection::UpdateLocalRtpDataChannels(
2986 const cricket::StreamParamsVec& streams) {
2987 std::vector<std::string> existing_channels;
2988
2989 // Find new and active data channels.
2990 for (const cricket::StreamParams& params : streams) {
2991 // |it->sync_label| is actually the data channel label. The reason is that
2992 // we use the same naming of data channels as we do for
2993 // MediaStreams and Tracks.
2994 // For MediaStreams, the sync_label is the MediaStream label and the
2995 // track label is the same as |streamid|.
2996 const std::string& channel_label = params.sync_label;
2997 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002998 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002999 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07003000 continue;
3001 }
3002 // Set the SSRC the data channel should use for sending.
3003 data_channel_it->second->SetSendSsrc(params.first_ssrc());
3004 existing_channels.push_back(data_channel_it->first);
3005 }
3006
3007 UpdateClosingRtpDataChannels(existing_channels, true);
3008}
3009
3010void PeerConnection::UpdateRemoteRtpDataChannels(
3011 const cricket::StreamParamsVec& streams) {
3012 std::vector<std::string> existing_channels;
3013
3014 // Find new and active data channels.
3015 for (const cricket::StreamParams& params : streams) {
3016 // The data channel label is either the mslabel or the SSRC if the mslabel
3017 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
3018 std::string label = params.sync_label.empty()
3019 ? rtc::ToString(params.first_ssrc())
3020 : params.sync_label;
3021 auto data_channel_it = rtp_data_channels_.find(label);
3022 if (data_channel_it == rtp_data_channels_.end()) {
3023 // This is a new data channel.
3024 CreateRemoteRtpDataChannel(label, params.first_ssrc());
3025 } else {
3026 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
3027 }
3028 existing_channels.push_back(label);
3029 }
3030
3031 UpdateClosingRtpDataChannels(existing_channels, false);
3032}
3033
3034void PeerConnection::UpdateClosingRtpDataChannels(
3035 const std::vector<std::string>& active_channels,
3036 bool is_local_update) {
3037 auto it = rtp_data_channels_.begin();
3038 while (it != rtp_data_channels_.end()) {
3039 DataChannel* data_channel = it->second;
3040 if (std::find(active_channels.begin(), active_channels.end(),
3041 data_channel->label()) != active_channels.end()) {
3042 ++it;
3043 continue;
3044 }
3045
3046 if (is_local_update) {
3047 data_channel->SetSendSsrc(0);
3048 } else {
3049 data_channel->RemotePeerRequestClose();
3050 }
3051
3052 if (data_channel->state() == DataChannel::kClosed) {
3053 rtp_data_channels_.erase(it);
3054 it = rtp_data_channels_.begin();
3055 } else {
3056 ++it;
3057 }
3058 }
3059}
3060
3061void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
3062 uint32_t remote_ssrc) {
3063 rtc::scoped_refptr<DataChannel> channel(
3064 InternalCreateDataChannel(label, nullptr));
3065 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003066 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
3067 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07003068 return;
3069 }
3070 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07003071 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3072 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003073 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003074}
3075
3076rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
3077 const std::string& label,
3078 const InternalDataChannelInit* config) {
3079 if (IsClosed()) {
3080 return nullptr;
3081 }
Steve Anton75737c02017-11-06 10:37:17 -08003082 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003083 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07003084 << "InternalCreateDataChannel: Data is not supported in this call.";
3085 return nullptr;
3086 }
3087 InternalDataChannelInit new_config =
3088 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08003089 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07003090 if (new_config.id < 0) {
3091 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08003092 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07003093 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003094 RTC_LOG(LS_ERROR)
3095 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07003096 return nullptr;
3097 }
3098 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003099 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
3100 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07003101 return nullptr;
3102 }
3103 }
3104
Steve Anton75737c02017-11-06 10:37:17 -08003105 rtc::scoped_refptr<DataChannel> channel(
3106 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07003107 if (!channel) {
3108 sid_allocator_.ReleaseSid(new_config.id);
3109 return nullptr;
3110 }
3111
3112 if (channel->data_channel_type() == cricket::DCT_RTP) {
3113 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003114 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
3115 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07003116 return nullptr;
3117 }
3118 rtp_data_channels_[channel->label()] = channel;
3119 } else {
3120 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
3121 sctp_data_channels_.push_back(channel);
3122 channel->SignalClosed.connect(this,
3123 &PeerConnection::OnSctpDataChannelClosed);
3124 }
3125
hbos82ebe022016-11-14 01:41:09 -08003126 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07003127 return channel;
3128}
3129
3130bool PeerConnection::HasDataChannels() const {
3131 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
3132}
3133
3134void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
3135 for (const auto& channel : sctp_data_channels_) {
3136 if (channel->id() < 0) {
3137 int sid;
3138 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003139 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07003140 continue;
3141 }
3142 channel->SetSctpSid(sid);
3143 }
3144 }
3145}
3146
3147void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08003148 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07003149 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
3150 ++it) {
3151 if (it->get() == channel) {
3152 if (channel->id() >= 0) {
3153 sid_allocator_.ReleaseSid(channel->id());
3154 }
deadbeefbd292462015-12-14 18:15:29 -08003155 // Since this method is triggered by a signal from the DataChannel,
3156 // we can't free it directly here; we need to free it asynchronously.
3157 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07003158 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07003159 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
3160 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07003161 return;
3162 }
3163 }
3164}
3165
deadbeefab9b2d12015-10-14 11:33:11 -07003166void PeerConnection::OnDataChannelDestroyed() {
3167 // Use a temporary copy of the RTP/SCTP DataChannel list because the
3168 // DataChannel may callback to us and try to modify the list.
3169 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
3170 temp_rtp_dcs.swap(rtp_data_channels_);
3171 for (const auto& kv : temp_rtp_dcs) {
3172 kv.second->OnTransportChannelDestroyed();
3173 }
3174
3175 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
3176 temp_sctp_dcs.swap(sctp_data_channels_);
3177 for (const auto& channel : temp_sctp_dcs) {
3178 channel->OnTransportChannelDestroyed();
3179 }
3180}
3181
3182void PeerConnection::OnDataChannelOpenMessage(
3183 const std::string& label,
3184 const InternalDataChannelInit& config) {
3185 rtc::scoped_refptr<DataChannel> channel(
3186 InternalCreateDataChannel(label, &config));
3187 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003188 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07003189 return;
3190 }
3191
deadbeefa601f5c2016-06-06 14:27:39 -07003192 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
3193 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07003194 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07003195}
3196
Steve Anton4171afb2017-11-20 10:20:22 -08003197rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3198PeerConnection::GetAudioTransceiver() const {
3199 // This method only works with Plan B SDP, where there is a single
3200 // audio/video transceiver.
3201 RTC_DCHECK(!IsUnifiedPlan());
3202 for (auto transceiver : transceivers_) {
3203 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_AUDIO) {
3204 return transceiver;
3205 }
3206 }
3207 RTC_NOTREACHED();
3208 return nullptr;
3209}
3210
3211rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
3212PeerConnection::GetVideoTransceiver() const {
3213 // This method only works with Plan B SDP, where there is a single
3214 // audio/video transceiver.
3215 RTC_DCHECK(!IsUnifiedPlan());
3216 for (auto transceiver : transceivers_) {
3217 if (transceiver->internal()->media_type() == cricket::MEDIA_TYPE_VIDEO) {
3218 return transceiver;
3219 }
3220 }
3221 RTC_NOTREACHED();
3222 return nullptr;
3223}
3224
3225// TODO(bugs.webrtc.org/7600): Remove this when multiple transceivers with
3226// individual transceiver directions are supported.
zhihuang1c378ed2017-08-17 14:10:50 -07003227bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
Steve Anton4171afb2017-11-20 10:20:22 -08003228 switch (type) {
3229 case cricket::MEDIA_TYPE_AUDIO:
3230 return !GetAudioTransceiver()->internal()->senders().empty();
3231 case cricket::MEDIA_TYPE_VIDEO:
3232 return !GetVideoTransceiver()->internal()->senders().empty();
3233 case cricket::MEDIA_TYPE_DATA:
3234 return false;
3235 }
3236 RTC_NOTREACHED();
3237 return false;
zhihuang1c378ed2017-08-17 14:10:50 -07003238}
3239
Steve Anton4171afb2017-11-20 10:20:22 -08003240rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3241PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) const {
3242 for (auto transceiver : transceivers_) {
3243 for (auto sender : transceiver->internal()->senders()) {
3244 if (sender->track() == track) {
3245 return sender;
3246 }
3247 }
3248 }
3249 return nullptr;
deadbeeffac06552015-11-25 11:26:01 -08003250}
3251
Steve Anton4171afb2017-11-20 10:20:22 -08003252rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>
3253PeerConnection::FindSenderById(const std::string& sender_id) const {
3254 for (auto transceiver : transceivers_) {
3255 for (auto sender : transceiver->internal()->senders()) {
3256 if (sender->id() == sender_id) {
3257 return sender;
3258 }
3259 }
3260 }
3261 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003262}
3263
Steve Anton4171afb2017-11-20 10:20:22 -08003264rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
3265PeerConnection::FindReceiverById(const std::string& receiver_id) const {
3266 for (auto transceiver : transceivers_) {
3267 for (auto receiver : transceiver->internal()->receivers()) {
3268 if (receiver->id() == receiver_id) {
3269 return receiver;
3270 }
3271 }
3272 }
3273 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07003274}
3275
Steve Anton4171afb2017-11-20 10:20:22 -08003276std::vector<PeerConnection::RtpSenderInfo>*
3277PeerConnection::GetRemoteSenderInfos(cricket::MediaType media_type) {
3278 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3279 media_type == cricket::MEDIA_TYPE_VIDEO);
3280 return (media_type == cricket::MEDIA_TYPE_AUDIO)
3281 ? &remote_audio_sender_infos_
3282 : &remote_video_sender_infos_;
3283}
3284
3285std::vector<PeerConnection::RtpSenderInfo>* PeerConnection::GetLocalSenderInfos(
deadbeefab9b2d12015-10-14 11:33:11 -07003286 cricket::MediaType media_type) {
3287 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3288 media_type == cricket::MEDIA_TYPE_VIDEO);
Steve Anton4171afb2017-11-20 10:20:22 -08003289 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_sender_infos_
3290 : &local_video_sender_infos_;
deadbeefab9b2d12015-10-14 11:33:11 -07003291}
3292
Steve Anton4171afb2017-11-20 10:20:22 -08003293const PeerConnection::RtpSenderInfo* PeerConnection::FindSenderInfo(
3294 const std::vector<PeerConnection::RtpSenderInfo>& infos,
deadbeefab9b2d12015-10-14 11:33:11 -07003295 const std::string& stream_label,
Steve Anton4171afb2017-11-20 10:20:22 -08003296 const std::string sender_id) const {
3297 for (const RtpSenderInfo& sender_info : infos) {
3298 if (sender_info.stream_label == stream_label &&
3299 sender_info.sender_id == sender_id) {
3300 return &sender_info;
deadbeefab9b2d12015-10-14 11:33:11 -07003301 }
3302 }
3303 return nullptr;
3304}
3305
3306DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3307 for (const auto& channel : sctp_data_channels_) {
3308 if (channel->id() == sid) {
3309 return channel;
3310 }
3311 }
3312 return nullptr;
3313}
3314
deadbeef91dd5672016-05-18 16:55:30 -07003315bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003316 const RTCConfiguration& configuration) {
3317 cricket::ServerAddresses stun_servers;
3318 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003319 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3320 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003321 return false;
3322 }
3323
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003324 port_allocator_->Initialize();
3325
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003326 // To handle both internal and externally created port allocator, we will
3327 // enable BUNDLE here.
3328 int portallocator_flags = port_allocator_->flags();
3329 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003330 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3331 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003332 // If the disable-IPv6 flag was specified, we'll not override it
3333 // by experiment.
3334 if (configuration.disable_ipv6) {
3335 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003336 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3337 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003338 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3339 }
3340
zhihuangb09b3f92017-03-07 14:40:51 -08003341 if (configuration.disable_ipv6_on_wifi) {
3342 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003343 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003344 }
3345
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003346 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3347 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003348 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003349 }
3350
honghaiz60347052016-05-31 18:29:12 -07003351 if (configuration.candidate_network_policy ==
3352 kCandidateNetworkPolicyLowCost) {
3353 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003354 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003355 }
3356
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003357 port_allocator_->set_flags(portallocator_flags);
3358 // No step delay is used while allocating ports.
3359 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3360 port_allocator_->set_candidate_filter(
3361 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003362 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003363
3364 // Call this last since it may create pooled allocator sessions using the
3365 // properties set above.
3366 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003367 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003368 configuration.prune_turn_ports,
3369 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003370 return true;
3371}
3372
deadbeef91dd5672016-05-18 16:55:30 -07003373bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003374 const cricket::ServerAddresses& stun_servers,
3375 const std::vector<cricket::RelayServerConfig>& turn_servers,
3376 IceTransportsType type,
3377 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003378 bool prune_turn_ports,
3379 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003380 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003381 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003382 // Call this last since it may create pooled allocator sessions using the
3383 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003384 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003385 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3386 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003387}
3388
Steve Antonba818672017-11-06 10:21:57 -08003389cricket::ChannelManager* PeerConnection::channel_manager() const {
3390 return factory_->channel_manager();
3391}
3392
3393MetricsObserverInterface* PeerConnection::metrics_observer() const {
3394 return uma_observer_;
3395}
3396
Elad Alon99c3fe52017-10-13 16:29:40 +02003397bool PeerConnection::StartRtcEventLog_w(
Bjorn Tereliusde939432017-11-20 17:38:14 +01003398 std::unique_ptr<RtcEventLogOutput> output,
3399 int64_t output_period_ms) {
zhihuang77985012017-02-07 15:45:16 -08003400 if (!event_log_) {
3401 return false;
3402 }
Bjorn Tereliusde939432017-11-20 17:38:14 +01003403 return event_log_->StartLogging(std::move(output), output_period_ms);
ivoc14d5dbe2016-07-04 07:06:55 -07003404}
3405
3406void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003407 if (event_log_) {
3408 event_log_->StopLogging();
3409 }
ivoc14d5dbe2016-07-04 07:06:55 -07003410}
nisseeaabdf62017-05-05 02:23:02 -07003411
Steve Anton75737c02017-11-06 10:37:17 -08003412cricket::BaseChannel* PeerConnection::GetChannel(
3413 const std::string& content_name) {
3414 if (voice_channel() && voice_channel()->content_name() == content_name) {
3415 return voice_channel();
3416 }
3417 if (video_channel() && video_channel()->content_name() == content_name) {
3418 return video_channel();
3419 }
3420 if (rtp_data_channel() &&
3421 rtp_data_channel()->content_name() == content_name) {
3422 return rtp_data_channel();
3423 }
3424 return nullptr;
3425}
3426
3427bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3428 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003429 RTC_LOG(LS_INFO)
3430 << "Local and Remote descriptions must be applied to get the "
3431 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003432 return false;
3433 }
3434 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003435 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3436 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003437 return false;
3438 }
3439
3440 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3441}
3442
3443bool PeerConnection::GetSslRole(const std::string& content_name,
3444 rtc::SSLRole* role) {
3445 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003446 RTC_LOG(LS_INFO)
3447 << "Local and Remote descriptions must be applied to get the "
3448 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003449 return false;
3450 }
3451
3452 return transport_controller_->GetSslRole(GetTransportName(content_name),
3453 role);
3454}
3455
Steve Anton75737c02017-11-06 10:37:17 -08003456// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3457// vector of BaseChannel pointers instead of separate voice and video channel
3458// vectors. At that point, this will become a simple getter.
3459std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3460 std::vector<cricket::BaseChannel*> channels;
Steve Anton4171afb2017-11-20 10:20:22 -08003461 if (voice_channel()) {
3462 channels.push_back(voice_channel());
3463 }
3464 if (video_channel()) {
3465 channels.push_back(video_channel());
3466 }
Steve Anton75737c02017-11-06 10:37:17 -08003467 if (rtp_data_channel_) {
3468 channels.push_back(rtp_data_channel_);
3469 }
3470 return channels;
3471}
3472
Steve Antonf8470812017-12-04 10:46:21 -08003473void PeerConnection::SetSessionError(SessionError error,
3474 const std::string& error_desc) {
3475 RTC_DCHECK_RUN_ON(signaling_thread());
3476 if (error != session_error_) {
3477 session_error_ = error;
3478 session_error_desc_ = error_desc;
Steve Anton75737c02017-11-06 10:37:17 -08003479 }
3480}
3481
Steve Anton8a006912017-12-04 15:25:56 -08003482RTCError PeerConnection::UpdateSessionState(Action action,
3483 cricket::ContentSource source) {
3484 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003485
3486 // If there's already a pending error then no state transition should happen.
3487 // But all call-sites should be verifying this before calling us!
Steve Antonf8470812017-12-04 10:46:21 -08003488 RTC_DCHECK(session_error() == SessionError::kNone);
Steve Anton75737c02017-11-06 10:37:17 -08003489 std::string td_err;
3490 if (action == kOffer) {
Steve Anton8a006912017-12-04 15:25:56 -08003491 RTCError error = PushdownTransportDescription(source, cricket::CA_OFFER);
3492 if (!error.ok()) {
3493 return error;
Steve Anton75737c02017-11-06 10:37:17 -08003494 }
3495 ChangeSignalingState(source == cricket::CS_LOCAL
3496 ? PeerConnectionInterface::kHaveLocalOffer
3497 : PeerConnectionInterface::kHaveRemoteOffer);
Steve Anton8a006912017-12-04 15:25:56 -08003498 error = PushdownMediaDescription(cricket::CA_OFFER, source);
3499 if (!error.ok()) {
3500 SetSessionError(SessionError::kContent, error.message());
Steve Anton75737c02017-11-06 10:37:17 -08003501 }
Steve Antonf8470812017-12-04 10:46:21 -08003502 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08003503 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08003504 }
3505 } else if (action == kPrAnswer) {
Steve Anton8a006912017-12-04 15:25:56 -08003506 RTCError error = PushdownTransportDescription(source, cricket::CA_PRANSWER);
3507 if (!error.ok()) {
3508 return error;
Steve Anton75737c02017-11-06 10:37:17 -08003509 }
3510 EnableChannels();
3511 ChangeSignalingState(source == cricket::CS_LOCAL
3512 ? PeerConnectionInterface::kHaveLocalPrAnswer
3513 : PeerConnectionInterface::kHaveRemotePrAnswer);
Steve Anton8a006912017-12-04 15:25:56 -08003514 error = PushdownMediaDescription(cricket::CA_PRANSWER, source);
3515 if (!error.ok()) {
3516 SetSessionError(SessionError::kContent, error.message());
Steve Anton75737c02017-11-06 10:37:17 -08003517 }
Steve Antonf8470812017-12-04 10:46:21 -08003518 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08003519 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08003520 }
3521 } else if (action == kAnswer) {
3522 const cricket::ContentGroup* local_bundle =
3523 local_description()->description()->GetGroupByName(
3524 cricket::GROUP_TYPE_BUNDLE);
3525 const cricket::ContentGroup* remote_bundle =
3526 remote_description()->description()->GetGroupByName(
3527 cricket::GROUP_TYPE_BUNDLE);
3528 if (local_bundle && remote_bundle) {
3529 // The answerer decides the transport to bundle on.
3530 const cricket::ContentGroup* answer_bundle =
3531 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3532 if (!EnableBundle(*answer_bundle)) {
Steve Anton8a006912017-12-04 15:25:56 -08003533 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
3534 kEnableBundleFailed);
Steve Anton75737c02017-11-06 10:37:17 -08003535 }
3536 }
3537 // Only push down the transport description after enabling BUNDLE; we don't
3538 // want to push down a description on a transport about to be destroyed.
Steve Anton8a006912017-12-04 15:25:56 -08003539 RTCError error = PushdownTransportDescription(source, cricket::CA_ANSWER);
3540 if (!error.ok()) {
3541 return error;
Steve Anton75737c02017-11-06 10:37:17 -08003542 }
3543 EnableChannels();
3544 ChangeSignalingState(PeerConnectionInterface::kStable);
Steve Anton8a006912017-12-04 15:25:56 -08003545 error = PushdownMediaDescription(cricket::CA_ANSWER, source);
3546 if (!error.ok()) {
3547 SetSessionError(SessionError::kContent, error.message());
Steve Anton75737c02017-11-06 10:37:17 -08003548 }
Steve Antonf8470812017-12-04 10:46:21 -08003549 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08003550 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08003551 }
3552 }
Steve Anton8a006912017-12-04 15:25:56 -08003553 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003554}
3555
3556PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3557 if (type == SessionDescriptionInterface::kOffer) {
3558 return PeerConnection::kOffer;
3559 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3560 return PeerConnection::kPrAnswer;
3561 } else if (type == SessionDescriptionInterface::kAnswer) {
3562 return PeerConnection::kAnswer;
3563 }
3564 RTC_NOTREACHED() << "unknown action type";
3565 return PeerConnection::kOffer;
3566}
3567
Steve Anton8a006912017-12-04 15:25:56 -08003568RTCError PeerConnection::PushdownMediaDescription(
3569 cricket::ContentAction action,
3570 cricket::ContentSource source) {
Steve Anton75737c02017-11-06 10:37:17 -08003571 const SessionDescription* sdesc =
3572 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3573 ->description();
3574 RTC_DCHECK(sdesc);
Steve Anton75737c02017-11-06 10:37:17 -08003575 for (auto* channel : Channels()) {
3576 // TODO(steveanton): Add support for multiple channels of the same type.
3577 const ContentInfo* content_info =
3578 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3579 if (!content_info) {
3580 continue;
3581 }
3582 const MediaContentDescription* content_desc =
3583 static_cast<const MediaContentDescription*>(content_info->description);
3584 if (content_desc && !content_info->rejected) {
Steve Anton8a006912017-12-04 15:25:56 -08003585 std::string error;
3586 bool success =
3587 (source == cricket::CS_LOCAL)
3588 ? channel->SetLocalContent(content_desc, action, &error)
3589 : channel->SetRemoteContent(content_desc, action, &error);
Steve Anton75737c02017-11-06 10:37:17 -08003590 if (!success) {
Steve Anton8a006912017-12-04 15:25:56 -08003591 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, std::move(error));
Steve Anton75737c02017-11-06 10:37:17 -08003592 }
3593 }
3594 }
3595 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3596 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3597 if (sctp_transport_ && local_description() && remote_description() &&
3598 cricket::GetFirstDataContent(local_description()->description()) &&
3599 cricket::GetFirstDataContent(remote_description()->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08003600 bool success = network_thread()->Invoke<bool>(
Steve Anton75737c02017-11-06 10:37:17 -08003601 RTC_FROM_HERE,
3602 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
Steve Anton8a006912017-12-04 15:25:56 -08003603 if (!success) {
3604 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
3605 "Failed to push down SCTP parameters.");
3606 }
Steve Anton75737c02017-11-06 10:37:17 -08003607 }
Steve Anton8a006912017-12-04 15:25:56 -08003608 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003609}
3610
3611bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3612 RTC_DCHECK(network_thread()->IsCurrent());
3613 RTC_DCHECK(local_description());
3614 RTC_DCHECK(remote_description());
3615 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3616 // When we support "max-message-size", that would also be pushed down here.
3617 return sctp_transport_->Start(
3618 GetSctpPort(local_description()->description()),
3619 GetSctpPort(remote_description()->description()));
3620}
3621
Steve Anton8a006912017-12-04 15:25:56 -08003622RTCError PeerConnection::PushdownTransportDescription(
3623 cricket::ContentSource source,
3624 cricket::ContentAction action) {
3625 RTC_DCHECK_RUN_ON(signaling_thread());
Steve Anton75737c02017-11-06 10:37:17 -08003626
Steve Anton8a006912017-12-04 15:25:56 -08003627 const SessionDescriptionInterface* sdesc =
3628 (source == cricket::CS_LOCAL ? local_description()
3629 : remote_description());
3630 RTC_DCHECK(sdesc);
3631 for (const cricket::TransportInfo& tinfo :
3632 sdesc->description()->transport_infos()) {
3633 std::string error;
3634 bool success;
3635 if (source == cricket::CS_LOCAL) {
3636 success = transport_controller_->SetLocalTransportDescription(
3637 tinfo.content_name, tinfo.description, action, &error);
3638 } else {
3639 success = transport_controller_->SetRemoteTransportDescription(
3640 tinfo.content_name, tinfo.description, action, &error);
3641 }
3642 if (!success) {
3643 LOG_AND_RETURN_ERROR(
3644 RTCErrorType::INVALID_PARAMETER,
3645 "Failed to push down transport description: " + error);
Steve Anton75737c02017-11-06 10:37:17 -08003646 }
3647 }
3648
Steve Anton8a006912017-12-04 15:25:56 -08003649 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08003650}
3651
3652bool PeerConnection::GetTransportDescription(
3653 const SessionDescription* description,
3654 const std::string& content_name,
3655 cricket::TransportDescription* tdesc) {
3656 if (!description || !tdesc) {
3657 return false;
3658 }
3659 const TransportInfo* transport_info =
3660 description->GetTransportInfoByName(content_name);
3661 if (!transport_info) {
3662 return false;
3663 }
3664 *tdesc = transport_info->description;
3665 return true;
3666}
3667
3668bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3669 const std::string* first_content_name = bundle.FirstContentName();
3670 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003671 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003672 return false;
3673 }
3674 const std::string& transport_name = *first_content_name;
3675
3676 auto maybe_set_transport = [this, bundle,
3677 transport_name](cricket::BaseChannel* ch) {
3678 if (!ch || !bundle.HasContentName(ch->content_name())) {
3679 return true;
3680 }
3681
3682 std::string old_transport_name = ch->transport_name();
3683 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003684 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3685 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003686 return true;
3687 }
3688
3689 cricket::DtlsTransportInternal* rtp_dtls_transport =
3690 transport_controller_->CreateDtlsTransport(
3691 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3692 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3693 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3694 if (need_rtcp) {
3695 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3696 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3697 }
3698
3699 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003700 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3701 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003702 transport_controller_->DestroyDtlsTransport(
3703 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3704 // If the channel needs rtcp, it means that the channel used to have a
3705 // rtcp transport which needs to be deleted now.
3706 if (need_rtcp) {
3707 transport_controller_->DestroyDtlsTransport(
3708 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3709 }
3710 return true;
3711 };
3712
3713 if (!maybe_set_transport(voice_channel()) ||
3714 !maybe_set_transport(video_channel()) ||
3715 !maybe_set_transport(rtp_data_channel())) {
3716 return false;
3717 }
3718 // For SCTP, transport creation/deletion happens here instead of in the
3719 // object itself.
3720 if (sctp_transport_) {
3721 RTC_DCHECK(sctp_transport_name_);
3722 RTC_DCHECK(sctp_content_name_);
3723 if (transport_name != *sctp_transport_name_ &&
3724 bundle.HasContentName(*sctp_content_name_)) {
3725 network_thread()->Invoke<void>(
3726 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3727 transport_name));
3728 }
3729 }
3730
3731 return true;
3732}
3733
Steve Anton75737c02017-11-06 10:37:17 -08003734cricket::IceConfig PeerConnection::ParseIceConfig(
3735 const PeerConnectionInterface::RTCConfiguration& config) const {
3736 cricket::ContinualGatheringPolicy gathering_policy;
3737 // TODO(honghaiz): Add the third continual gathering policy in
3738 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3739 switch (config.continual_gathering_policy) {
3740 case PeerConnectionInterface::GATHER_ONCE:
3741 gathering_policy = cricket::GATHER_ONCE;
3742 break;
3743 case PeerConnectionInterface::GATHER_CONTINUALLY:
3744 gathering_policy = cricket::GATHER_CONTINUALLY;
3745 break;
3746 default:
3747 RTC_NOTREACHED();
3748 gathering_policy = cricket::GATHER_ONCE;
3749 }
3750 cricket::IceConfig ice_config;
3751 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3752 ice_config.prioritize_most_likely_candidate_pairs =
3753 config.prioritize_most_likely_ice_candidate_pairs;
3754 ice_config.backup_connection_ping_interval =
3755 config.ice_backup_candidate_pair_ping_interval;
3756 ice_config.continual_gathering_policy = gathering_policy;
3757 ice_config.presume_writable_when_fully_relayed =
3758 config.presume_writable_when_fully_relayed;
3759 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3760 ice_config.regather_all_networks_interval_range =
3761 config.ice_regather_interval_range;
3762 return ice_config;
3763}
3764
Steve Anton75737c02017-11-06 10:37:17 -08003765bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3766 std::string* track_id) {
3767 if (!local_description()) {
3768 return false;
3769 }
3770 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3771 track_id);
3772}
3773
3774bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3775 std::string* track_id) {
3776 if (!remote_description()) {
3777 return false;
3778 }
3779 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3780 track_id);
3781}
3782
3783bool PeerConnection::SendData(const cricket::SendDataParams& params,
3784 const rtc::CopyOnWriteBuffer& payload,
3785 cricket::SendDataResult* result) {
3786 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003787 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3788 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003789 return false;
3790 }
3791 return rtp_data_channel_
3792 ? rtp_data_channel_->SendData(params, payload, result)
3793 : network_thread()->Invoke<bool>(
3794 RTC_FROM_HERE,
3795 Bind(&cricket::SctpTransportInternal::SendData,
3796 sctp_transport_.get(), params, payload, result));
3797}
3798
3799bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3800 if (!rtp_data_channel_ && !sctp_transport_) {
3801 // Don't log an error here, because DataChannels are expected to call
3802 // ConnectDataChannel in this state. It's the only way to initially tell
3803 // whether or not the underlying transport is ready.
3804 return false;
3805 }
3806 if (rtp_data_channel_) {
3807 rtp_data_channel_->SignalReadyToSendData.connect(
3808 webrtc_data_channel, &DataChannel::OnChannelReady);
3809 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3810 &DataChannel::OnDataReceived);
3811 } else {
3812 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3813 &DataChannel::OnChannelReady);
3814 SignalSctpDataReceived.connect(webrtc_data_channel,
3815 &DataChannel::OnDataReceived);
3816 SignalSctpStreamClosedRemotely.connect(
3817 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3818 }
3819 return true;
3820}
3821
3822void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3823 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003824 RTC_LOG(LS_ERROR)
3825 << "DisconnectDataChannel called when rtp_data_channel_ and "
3826 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003827 return;
3828 }
3829 if (rtp_data_channel_) {
3830 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3831 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3832 } else {
3833 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3834 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3835 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3836 }
3837}
3838
3839void PeerConnection::AddSctpDataStream(int sid) {
3840 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003841 RTC_LOG(LS_ERROR)
3842 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003843 return;
3844 }
3845 network_thread()->Invoke<void>(
3846 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3847 sctp_transport_.get(), sid));
3848}
3849
3850void PeerConnection::RemoveSctpDataStream(int sid) {
3851 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003852 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3853 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003854 return;
3855 }
3856 network_thread()->Invoke<void>(
3857 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3858 sctp_transport_.get(), sid));
3859}
3860
3861bool PeerConnection::ReadyToSendData() const {
3862 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3863 sctp_ready_to_send_data_;
3864}
3865
3866std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3867 RTC_DCHECK(signaling_thread()->IsCurrent());
3868 ChannelNamePairs channel_name_pairs;
3869 if (voice_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003870 channel_name_pairs.voice = ChannelNamePair(
3871 voice_channel()->content_name(), voice_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003872 }
3873 if (video_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003874 channel_name_pairs.video = ChannelNamePair(
3875 video_channel()->content_name(), video_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003876 }
3877 if (rtp_data_channel()) {
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003878 channel_name_pairs.data =
Steve Anton75737c02017-11-06 10:37:17 -08003879 ChannelNamePair(rtp_data_channel()->content_name(),
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003880 rtp_data_channel()->transport_name());
Steve Anton75737c02017-11-06 10:37:17 -08003881 }
3882 if (sctp_transport_) {
3883 RTC_DCHECK(sctp_content_name_);
3884 RTC_DCHECK(sctp_transport_name_);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01003885 channel_name_pairs.data =
3886 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_);
Steve Anton75737c02017-11-06 10:37:17 -08003887 }
3888 return GetSessionStats(channel_name_pairs);
3889}
3890
3891std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3892 const ChannelNamePairs& channel_name_pairs) {
3893 if (network_thread()->IsCurrent()) {
3894 return GetSessionStats_n(channel_name_pairs);
3895 }
3896 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3897 RTC_FROM_HERE,
3898 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3899}
3900
3901bool PeerConnection::GetLocalCertificate(
3902 const std::string& transport_name,
3903 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
3904 return transport_controller_->GetLocalCertificate(transport_name,
3905 certificate);
3906}
3907
3908std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
3909 const std::string& transport_name) {
3910 return transport_controller_->GetRemoteSSLCertificate(transport_name);
3911}
3912
3913cricket::DataChannelType PeerConnection::data_channel_type() const {
3914 return data_channel_type_;
3915}
3916
3917bool PeerConnection::IceRestartPending(const std::string& content_name) const {
3918 return pending_ice_restarts_.find(content_name) !=
3919 pending_ice_restarts_.end();
3920}
3921
Steve Anton75737c02017-11-06 10:37:17 -08003922bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
3923 return transport_controller_->NeedsIceRestart(content_name);
3924}
3925
3926void PeerConnection::OnCertificateReady(
3927 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
3928 transport_controller_->SetLocalCertificate(certificate);
3929}
3930
3931void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
Steve Antonf8470812017-12-04 10:46:21 -08003932 SetSessionError(SessionError::kTransport,
3933 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
Steve Anton75737c02017-11-06 10:37:17 -08003934}
3935
3936void PeerConnection::OnTransportControllerConnectionState(
3937 cricket::IceConnectionState state) {
3938 switch (state) {
3939 case cricket::kIceConnectionConnecting:
3940 // If the current state is Connected or Completed, then there were
3941 // writable channels but now there are not, so the next state must
3942 // be Disconnected.
3943 // kIceConnectionConnecting is currently used as the default,
3944 // un-connected state by the TransportController, so its only use is
3945 // detecting disconnections.
3946 if (ice_connection_state_ ==
3947 PeerConnectionInterface::kIceConnectionConnected ||
3948 ice_connection_state_ ==
3949 PeerConnectionInterface::kIceConnectionCompleted) {
3950 SetIceConnectionState(
3951 PeerConnectionInterface::kIceConnectionDisconnected);
3952 }
3953 break;
3954 case cricket::kIceConnectionFailed:
3955 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
3956 break;
3957 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003958 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
3959 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08003960 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3961 break;
3962 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003963 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
3964 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08003965 if (ice_connection_state_ !=
3966 PeerConnectionInterface::kIceConnectionConnected) {
3967 // If jumping directly from "checking" to "connected",
3968 // signal "connected" first.
3969 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3970 }
3971 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
3972 if (metrics_observer()) {
3973 ReportTransportStats();
3974 }
3975 break;
3976 default:
3977 RTC_NOTREACHED();
3978 }
3979}
3980
3981void PeerConnection::OnTransportControllerCandidatesGathered(
3982 const std::string& transport_name,
3983 const cricket::Candidates& candidates) {
3984 RTC_DCHECK(signaling_thread()->IsCurrent());
3985 int sdp_mline_index;
3986 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003987 RTC_LOG(LS_ERROR)
3988 << "OnTransportControllerCandidatesGathered: content name "
3989 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08003990 return;
3991 }
3992
3993 for (cricket::Candidates::const_iterator citer = candidates.begin();
3994 citer != candidates.end(); ++citer) {
3995 // Use transport_name as the candidate media id.
3996 std::unique_ptr<JsepIceCandidate> candidate(
3997 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
3998 if (local_description()) {
3999 mutable_local_description()->AddCandidate(candidate.get());
4000 }
4001 OnIceCandidate(std::move(candidate));
4002 }
4003}
4004
4005void PeerConnection::OnTransportControllerCandidatesRemoved(
4006 const std::vector<cricket::Candidate>& candidates) {
4007 RTC_DCHECK(signaling_thread()->IsCurrent());
4008 // Sanity check.
4009 for (const cricket::Candidate& candidate : candidates) {
4010 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004011 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
4012 << "empty content name in candidate "
4013 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08004014 return;
4015 }
4016 }
4017
4018 if (local_description()) {
4019 mutable_local_description()->RemoveCandidates(candidates);
4020 }
4021 OnIceCandidatesRemoved(candidates);
4022}
4023
4024void PeerConnection::OnTransportControllerDtlsHandshakeError(
4025 rtc::SSLHandshakeError error) {
4026 if (metrics_observer()) {
4027 metrics_observer()->IncrementEnumCounter(
4028 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
4029 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
4030 }
4031}
4032
4033// Enabling voice and video (and RTP data) channels.
4034void PeerConnection::EnableChannels() {
Steve Anton4171afb2017-11-20 10:20:22 -08004035 if (voice_channel() && !voice_channel()->enabled()) {
4036 voice_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004037 }
4038
Steve Anton4171afb2017-11-20 10:20:22 -08004039 if (video_channel() && !video_channel()->enabled()) {
4040 video_channel()->Enable(true);
Steve Anton75737c02017-11-06 10:37:17 -08004041 }
4042
Steve Anton4171afb2017-11-20 10:20:22 -08004043 if (rtp_data_channel_ && !rtp_data_channel_->enabled()) {
Steve Anton75737c02017-11-06 10:37:17 -08004044 rtp_data_channel_->Enable(true);
Steve Anton4171afb2017-11-20 10:20:22 -08004045 }
Steve Anton75737c02017-11-06 10:37:17 -08004046}
4047
4048// Returns the media index for a local ice candidate given the content name.
4049bool PeerConnection::GetLocalCandidateMediaIndex(
4050 const std::string& content_name,
4051 int* sdp_mline_index) {
4052 if (!local_description() || !sdp_mline_index) {
4053 return false;
4054 }
4055
4056 bool content_found = false;
4057 const ContentInfos& contents = local_description()->description()->contents();
4058 for (size_t index = 0; index < contents.size(); ++index) {
4059 if (contents[index].name == content_name) {
4060 *sdp_mline_index = static_cast<int>(index);
4061 content_found = true;
4062 break;
4063 }
4064 }
4065 return content_found;
4066}
4067
4068bool PeerConnection::UseCandidatesInSessionDescription(
4069 const SessionDescriptionInterface* remote_desc) {
4070 if (!remote_desc) {
4071 return true;
4072 }
4073 bool ret = true;
4074
4075 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
4076 const IceCandidateCollection* candidates = remote_desc->candidates(m);
4077 for (size_t n = 0; n < candidates->count(); ++n) {
4078 const IceCandidateInterface* candidate = candidates->at(n);
4079 bool valid = false;
4080 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
4081 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004082 RTC_LOG(LS_INFO)
4083 << "UseCandidatesInSessionDescription: Not ready to use "
4084 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08004085 }
4086 continue;
4087 }
4088 ret = UseCandidate(candidate);
4089 if (!ret) {
4090 break;
4091 }
4092 }
4093 }
4094 return ret;
4095}
4096
4097bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4098 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4099 size_t remote_content_size =
4100 remote_description()->description()->contents().size();
4101 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004102 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004103 return false;
4104 }
4105
4106 cricket::ContentInfo content =
4107 remote_description()->description()->contents()[mediacontent_index];
4108 std::vector<cricket::Candidate> candidates;
4109 candidates.push_back(candidate->candidate());
4110 // Invoking BaseSession method to handle remote candidates.
4111 std::string error;
4112 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4113 &error)) {
4114 // Candidates successfully submitted for checking.
4115 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4116 ice_connection_state_ ==
4117 PeerConnectionInterface::kIceConnectionDisconnected) {
4118 // If state is New, then the session has just gotten its first remote ICE
4119 // candidates, so go to Checking.
4120 // If state is Disconnected, the session is re-using old candidates or
4121 // receiving additional ones, so go to Checking.
4122 // If state is Connected, stay Connected.
4123 // TODO(bemasc): If state is Connected, and the new candidates are for a
4124 // newly added transport, then the state actually _should_ move to
4125 // checking. Add a way to distinguish that case.
4126 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4127 }
4128 // TODO(bemasc): If state is Completed, go back to Connected.
4129 } else {
4130 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004131 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004132 }
4133 }
4134 return true;
4135}
4136
4137void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
Steve Anton75737c02017-11-06 10:37:17 -08004138 // Destroy video channel first since it may have a pointer to the
4139 // voice channel.
4140 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
Steve Anton6fec8802017-12-04 10:37:29 -08004141 if (!video_info || video_info->rejected) {
4142 DestroyTransceiverChannel(GetVideoTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004143 }
4144
Steve Anton6fec8802017-12-04 10:37:29 -08004145 const cricket::ContentInfo* audio_info = cricket::GetFirstAudioContent(desc);
4146 if (!audio_info || audio_info->rejected) {
4147 DestroyTransceiverChannel(GetAudioTransceiver());
Steve Anton75737c02017-11-06 10:37:17 -08004148 }
4149
4150 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4151 if (!data_info || data_info->rejected) {
Steve Anton6fec8802017-12-04 10:37:29 -08004152 DestroyDataChannel();
Steve Anton75737c02017-11-06 10:37:17 -08004153 }
4154}
4155
Steve Antoneda6ccd2017-12-04 10:21:55 -08004156std::string PeerConnection::GetTransportNameForMediaSection(
4157 const std::string& mid,
4158 const cricket::ContentGroup* bundle_group) const {
4159 if (!bundle_group) {
4160 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004161 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004162 const std::string* first_content_name = bundle_group->FirstContentName();
Steve Anton75737c02017-11-06 10:37:17 -08004163 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004164 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Antoneda6ccd2017-12-04 10:21:55 -08004165 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004166 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004167 if (!bundle_group->HasContentName(mid)) {
4168 RTC_LOG(LS_WARNING) << mid << " is not part of any bundle group";
4169 return mid;
Steve Anton75737c02017-11-06 10:37:17 -08004170 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004171 RTC_LOG(LS_INFO) << "Bundling " << mid << " on " << *first_content_name;
4172 return *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004173}
4174
Steve Anton8a006912017-12-04 15:25:56 -08004175RTCError PeerConnection::CreateChannels(const SessionDescription* desc) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004176 RTC_DCHECK(desc);
4177
Steve Anton75737c02017-11-06 10:37:17 -08004178 const cricket::ContentGroup* bundle_group = nullptr;
4179 if (configuration_.bundle_policy ==
4180 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4181 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4182 if (!bundle_group) {
Steve Anton8a006912017-12-04 15:25:56 -08004183 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4184 "max-bundle configured but session description "
4185 "has no BUNDLE group");
Steve Anton75737c02017-11-06 10:37:17 -08004186 }
4187 }
4188
Steve Antoneda6ccd2017-12-04 10:21:55 -08004189 // Creating the media channels and transport proxies.
4190 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4191 if (voice && !voice->rejected &&
4192 !GetAudioTransceiver()->internal()->channel()) {
4193 cricket::VoiceChannel* voice_channel = CreateVoiceChannel(
4194 voice->name,
4195 GetTransportNameForMediaSection(voice->name, bundle_group));
4196 if (!voice_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004197 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4198 "Failed to create voice channel.");
Steve Antoneda6ccd2017-12-04 10:21:55 -08004199 }
4200 GetAudioTransceiver()->internal()->SetChannel(voice_channel);
4201 }
4202
Steve Anton75737c02017-11-06 10:37:17 -08004203 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
Steve Antoneda6ccd2017-12-04 10:21:55 -08004204 if (video && !video->rejected &&
4205 !GetVideoTransceiver()->internal()->channel()) {
4206 cricket::VideoChannel* video_channel = CreateVideoChannel(
4207 video->name,
4208 GetTransportNameForMediaSection(video->name, bundle_group));
4209 if (!video_channel) {
Steve Anton8a006912017-12-04 15:25:56 -08004210 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4211 "Failed to create video channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004212 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004213 GetVideoTransceiver()->internal()->SetChannel(video_channel);
Steve Anton75737c02017-11-06 10:37:17 -08004214 }
4215
4216 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4217 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4218 !rtp_data_channel_ && !sctp_transport_) {
Steve Antoneda6ccd2017-12-04 10:21:55 -08004219 if (!CreateDataChannel(data->name, GetTransportNameForMediaSection(
4220 data->name, bundle_group))) {
Steve Anton8a006912017-12-04 15:25:56 -08004221 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR,
4222 "Failed to create data channel.");
Steve Anton75737c02017-11-06 10:37:17 -08004223 }
4224 }
4225
Steve Anton8a006912017-12-04 15:25:56 -08004226 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004227}
4228
Steve Anton4171afb2017-11-20 10:20:22 -08004229// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004230cricket::VoiceChannel* PeerConnection::CreateVoiceChannel(
4231 const std::string& mid,
4232 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004233 cricket::DtlsTransportInternal* rtp_dtls_transport =
4234 transport_controller_->CreateDtlsTransport(
4235 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4236 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4237 if (configuration_.rtcp_mux_policy !=
4238 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4239 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4240 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4241 }
4242
4243 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4244 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004245 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4246 audio_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004247 if (!voice_channel) {
4248 transport_controller_->DestroyDtlsTransport(
4249 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4250 if (rtcp_dtls_transport) {
4251 transport_controller_->DestroyDtlsTransport(
4252 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4253 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004254 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004255 }
Steve Anton75737c02017-11-06 10:37:17 -08004256 voice_channel->SignalRtcpMuxFullyActive.connect(
4257 this, &PeerConnection::DestroyRtcpTransport_n);
4258 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4259 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004260 voice_channel->SignalSentPacket.connect(this,
4261 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004262
Steve Antoneda6ccd2017-12-04 10:21:55 -08004263 return voice_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004264}
4265
Steve Anton4171afb2017-11-20 10:20:22 -08004266// TODO(steveanton): Perhaps this should be managed by the RtpTransceiver.
Steve Antoneda6ccd2017-12-04 10:21:55 -08004267cricket::VideoChannel* PeerConnection::CreateVideoChannel(
4268 const std::string& mid,
4269 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004270 cricket::DtlsTransportInternal* rtp_dtls_transport =
4271 transport_controller_->CreateDtlsTransport(
4272 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4273 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4274 if (configuration_.rtcp_mux_policy !=
4275 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4276 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4277 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4278 }
4279
4280 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4281 call_.get(), configuration_.media_config, rtp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004282 rtcp_dtls_transport, signaling_thread(), mid, SrtpRequired(),
4283 video_options_);
Steve Anton75737c02017-11-06 10:37:17 -08004284
4285 if (!video_channel) {
4286 transport_controller_->DestroyDtlsTransport(
4287 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4288 if (rtcp_dtls_transport) {
4289 transport_controller_->DestroyDtlsTransport(
4290 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4291 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004292 return nullptr;
Steve Anton75737c02017-11-06 10:37:17 -08004293 }
Steve Anton75737c02017-11-06 10:37:17 -08004294 video_channel->SignalRtcpMuxFullyActive.connect(
4295 this, &PeerConnection::DestroyRtcpTransport_n);
4296 video_channel->SignalDtlsSrtpSetupFailure.connect(
4297 this, &PeerConnection::OnDtlsSrtpSetupFailure);
Steve Anton75737c02017-11-06 10:37:17 -08004298 video_channel->SignalSentPacket.connect(this,
4299 &PeerConnection::OnSentPacket_w);
Steve Anton4171afb2017-11-20 10:20:22 -08004300
Steve Antoneda6ccd2017-12-04 10:21:55 -08004301 return video_channel;
Steve Anton75737c02017-11-06 10:37:17 -08004302}
4303
Steve Antoneda6ccd2017-12-04 10:21:55 -08004304bool PeerConnection::CreateDataChannel(const std::string& mid,
4305 const std::string& transport_name) {
Steve Anton75737c02017-11-06 10:37:17 -08004306 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4307 if (sctp) {
4308 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004309 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004310 << "Trying to create SCTP transport, but didn't compile with "
4311 "SCTP support (HAVE_SCTP)";
4312 return false;
4313 }
4314 if (!network_thread()->Invoke<bool>(
4315 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004316 this, mid, transport_name))) {
Steve Anton75737c02017-11-06 10:37:17 -08004317 return false;
4318 }
Steve Antoneda6ccd2017-12-04 10:21:55 -08004319 for (const auto& channel : sctp_data_channels_) {
4320 channel->OnTransportChannelCreated();
4321 }
Steve Anton75737c02017-11-06 10:37:17 -08004322 } else {
Steve Anton75737c02017-11-06 10:37:17 -08004323 cricket::DtlsTransportInternal* rtp_dtls_transport =
4324 transport_controller_->CreateDtlsTransport(
4325 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4326 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4327 if (configuration_.rtcp_mux_policy !=
4328 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4329 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4330 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4331 }
4332
4333 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4334 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
Steve Antoneda6ccd2017-12-04 10:21:55 -08004335 signaling_thread(), mid, SrtpRequired());
Steve Anton75737c02017-11-06 10:37:17 -08004336
4337 if (!rtp_data_channel_) {
4338 transport_controller_->DestroyDtlsTransport(
4339 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4340 if (rtcp_dtls_transport) {
4341 transport_controller_->DestroyDtlsTransport(
4342 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4343 }
4344 return false;
4345 }
4346
4347 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4348 this, &PeerConnection::DestroyRtcpTransport_n);
4349 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4350 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4351 rtp_data_channel_->SignalSentPacket.connect(
4352 this, &PeerConnection::OnSentPacket_w);
4353 }
4354
Steve Anton75737c02017-11-06 10:37:17 -08004355 return true;
4356}
4357
4358Call::Stats PeerConnection::GetCallStats() {
4359 if (!worker_thread()->IsCurrent()) {
4360 return worker_thread()->Invoke<Call::Stats>(
4361 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4362 }
4363 if (call_) {
4364 return call_->GetStats();
4365 } else {
4366 return Call::Stats();
4367 }
4368}
4369
4370std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4371 const ChannelNamePairs& channel_name_pairs) {
4372 RTC_DCHECK(network_thread()->IsCurrent());
4373 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4374 for (const auto channel_name_pair :
4375 {&channel_name_pairs.voice, &channel_name_pairs.video,
4376 &channel_name_pairs.data}) {
4377 if (*channel_name_pair) {
4378 cricket::TransportStats transport_stats;
4379 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4380 &transport_stats)) {
4381 return nullptr;
4382 }
4383 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4384 (*channel_name_pair)->transport_name;
4385 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4386 std::move(transport_stats);
4387 }
4388 }
4389 return session_stats;
4390}
4391
4392bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4393 const std::string& transport_name) {
4394 RTC_DCHECK(network_thread()->IsCurrent());
4395 RTC_DCHECK(sctp_factory_);
4396 cricket::DtlsTransportInternal* tc =
4397 transport_controller_->CreateDtlsTransport_n(
4398 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4399 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4400 RTC_DCHECK(sctp_transport_);
4401 sctp_invoker_.reset(new rtc::AsyncInvoker());
4402 sctp_transport_->SignalReadyToSendData.connect(
4403 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4404 sctp_transport_->SignalDataReceived.connect(
4405 this, &PeerConnection::OnSctpTransportDataReceived_n);
4406 sctp_transport_->SignalStreamClosedRemotely.connect(
4407 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004408 sctp_transport_name_ = transport_name;
4409 sctp_content_name_ = content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004410 return true;
4411}
4412
4413void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4414 RTC_DCHECK(network_thread()->IsCurrent());
4415 RTC_DCHECK(sctp_transport_);
4416 RTC_DCHECK(sctp_transport_name_);
4417 std::string old_sctp_transport_name = *sctp_transport_name_;
Oskar Sundbom9b28a032017-11-16 10:53:30 +01004418 sctp_transport_name_ = transport_name;
Steve Anton75737c02017-11-06 10:37:17 -08004419 cricket::DtlsTransportInternal* tc =
4420 transport_controller_->CreateDtlsTransport_n(
4421 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4422 sctp_transport_->SetTransportChannel(tc);
4423 transport_controller_->DestroyDtlsTransport_n(
4424 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4425}
4426
4427void PeerConnection::DestroySctpTransport_n() {
4428 RTC_DCHECK(network_thread()->IsCurrent());
4429 sctp_transport_.reset(nullptr);
4430 sctp_content_name_.reset();
4431 sctp_transport_name_.reset();
4432 sctp_invoker_.reset(nullptr);
4433 sctp_ready_to_send_data_ = false;
4434}
4435
4436void PeerConnection::OnSctpTransportReadyToSendData_n() {
4437 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4438 RTC_DCHECK(network_thread()->IsCurrent());
4439 // Note: Cannot use rtc::Bind here because it will grab a reference to
4440 // PeerConnection and potentially cause PeerConnection to live longer than
4441 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4442 // be destroyed before PeerConnection is destroyed, and at that point all
4443 // pending tasks will be cleared.
4444 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4445 OnSctpTransportReadyToSendData_s(true);
4446 });
4447}
4448
4449void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4450 RTC_DCHECK(signaling_thread()->IsCurrent());
4451 sctp_ready_to_send_data_ = ready;
4452 SignalSctpReadyToSendData(ready);
4453}
4454
4455void PeerConnection::OnSctpTransportDataReceived_n(
4456 const cricket::ReceiveDataParams& params,
4457 const rtc::CopyOnWriteBuffer& payload) {
4458 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4459 RTC_DCHECK(network_thread()->IsCurrent());
4460 // Note: Cannot use rtc::Bind here because it will grab a reference to
4461 // PeerConnection and potentially cause PeerConnection to live longer than
4462 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4463 // be destroyed before PeerConnection is destroyed, and at that point all
4464 // pending tasks will be cleared.
4465 sctp_invoker_->AsyncInvoke<void>(
4466 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4467 OnSctpTransportDataReceived_s(params, payload);
4468 });
4469}
4470
4471void PeerConnection::OnSctpTransportDataReceived_s(
4472 const cricket::ReceiveDataParams& params,
4473 const rtc::CopyOnWriteBuffer& payload) {
4474 RTC_DCHECK(signaling_thread()->IsCurrent());
4475 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4476 // Received OPEN message; parse and signal that a new data channel should
4477 // be created.
4478 std::string label;
4479 InternalDataChannelInit config;
4480 config.id = params.ssrc;
4481 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004482 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4483 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004484 return;
4485 }
4486 config.open_handshake_role = InternalDataChannelInit::kAcker;
4487 OnDataChannelOpenMessage(label, config);
4488 } else {
4489 // Otherwise just forward the signal.
4490 SignalSctpDataReceived(params, payload);
4491 }
4492}
4493
4494void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4495 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4496 RTC_DCHECK(network_thread()->IsCurrent());
4497 sctp_invoker_->AsyncInvoke<void>(
4498 RTC_FROM_HERE, signaling_thread(),
4499 rtc::Bind(&sigslot::signal1<int>::operator(),
4500 &SignalSctpStreamClosedRemotely, sid));
4501}
4502
4503// Returns false if bundle is enabled and rtcp_mux is disabled.
4504bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4505 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4506 if (!bundle_enabled)
4507 return true;
4508
4509 const cricket::ContentGroup* bundle_group =
4510 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4511 RTC_DCHECK(bundle_group != NULL);
4512
4513 const cricket::ContentInfos& contents = desc->contents();
4514 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4515 citer != contents.end(); ++citer) {
4516 const cricket::ContentInfo* content = (&*citer);
4517 RTC_DCHECK(content != NULL);
4518 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4519 content->type == cricket::NS_JINGLE_RTP) {
4520 if (!HasRtcpMuxEnabled(content))
4521 return false;
4522 }
4523 }
4524 // RTCP-MUX is enabled in all the contents.
4525 return true;
4526}
4527
4528bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4529 const cricket::MediaContentDescription* description =
4530 static_cast<cricket::MediaContentDescription*>(content->description);
4531 return description->rtcp_mux();
4532}
4533
Steve Anton8a006912017-12-04 15:25:56 -08004534RTCError PeerConnection::ValidateSessionDescription(
Steve Anton75737c02017-11-06 10:37:17 -08004535 const SessionDescriptionInterface* sdesc,
Steve Anton8a006912017-12-04 15:25:56 -08004536 cricket::ContentSource source) {
Steve Antonf8470812017-12-04 10:46:21 -08004537 if (session_error() != SessionError::kNone) {
Steve Anton8a006912017-12-04 15:25:56 -08004538 LOG_AND_RETURN_ERROR(RTCErrorType::INTERNAL_ERROR, GetSessionErrorMsg());
Steve Anton75737c02017-11-06 10:37:17 -08004539 }
4540
4541 if (!sdesc || !sdesc->description()) {
Steve Anton8a006912017-12-04 15:25:56 -08004542 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER, kInvalidSdp);
Steve Anton75737c02017-11-06 10:37:17 -08004543 }
4544
Steve Anton75737c02017-11-06 10:37:17 -08004545 Action action = GetAction(sdesc->type());
Steve Anton8a006912017-12-04 15:25:56 -08004546 if ((source == cricket::CS_LOCAL && !ExpectSetLocalDescription(action)) ||
4547 (source == cricket::CS_REMOTE && !ExpectSetRemoteDescription(action))) {
4548 LOG_AND_RETURN_ERROR(
4549 RTCErrorType::INVALID_PARAMETER,
4550 "Called in wrong state: " + GetSignalingStateString(signaling_state()));
Steve Anton75737c02017-11-06 10:37:17 -08004551 }
4552
4553 // Verify crypto settings.
4554 std::string crypto_error;
Steve Anton8a006912017-12-04 15:25:56 -08004555 if (webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4556 dtls_enabled_) {
4557 RTCError crypto_error = VerifyCrypto(sdesc->description(), dtls_enabled_);
4558 if (!crypto_error.ok()) {
4559 return crypto_error;
4560 }
Steve Anton75737c02017-11-06 10:37:17 -08004561 }
4562
4563 // Verify ice-ufrag and ice-pwd.
4564 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004565 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4566 kSdpWithoutIceUfragPwd);
Steve Anton75737c02017-11-06 10:37:17 -08004567 }
4568
4569 if (!ValidateBundleSettings(sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004570 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4571 kBundleWithoutRtcpMux);
Steve Anton75737c02017-11-06 10:37:17 -08004572 }
4573
4574 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4575 // m-lines that do not rtcp-mux enabled.
4576
4577 // Verify m-lines in Answer when compared against Offer.
4578 if (action == kAnswer || action == kPrAnswer) {
4579 const cricket::SessionDescription* offer_desc =
4580 (source == cricket::CS_LOCAL) ? remote_description()->description()
4581 : local_description()->description();
4582 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4583 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004584 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4585 kMlineMismatchInAnswer);
Steve Anton75737c02017-11-06 10:37:17 -08004586 }
4587 } else {
4588 const cricket::SessionDescription* current_desc = nullptr;
4589 if (source == cricket::CS_LOCAL && local_description()) {
4590 current_desc = local_description()->description();
4591 } else if (source == cricket::CS_REMOTE && remote_description()) {
4592 current_desc = remote_description()->description();
4593 }
4594 // The re-offers should respect the order of m= sections in current
4595 // description. See RFC3264 Section 8 paragraph 4 for more details.
4596 if (current_desc &&
4597 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
Steve Anton8a006912017-12-04 15:25:56 -08004598 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
4599 kMlineMismatchInSubsequentOffer);
Steve Anton75737c02017-11-06 10:37:17 -08004600 }
4601 }
4602
Steve Anton8a006912017-12-04 15:25:56 -08004603 return RTCError::OK();
Steve Anton75737c02017-11-06 10:37:17 -08004604}
4605
4606bool PeerConnection::ExpectSetLocalDescription(Action action) {
4607 PeerConnectionInterface::SignalingState state = signaling_state();
4608 if (action == kOffer) {
4609 return (state == PeerConnectionInterface::kStable) ||
4610 (state == PeerConnectionInterface::kHaveLocalOffer);
4611 } else { // Answer or PrAnswer
4612 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4613 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4614 }
4615}
4616
4617bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4618 PeerConnectionInterface::SignalingState state = signaling_state();
4619 if (action == kOffer) {
4620 return (state == PeerConnectionInterface::kStable) ||
4621 (state == PeerConnectionInterface::kHaveRemoteOffer);
4622 } else { // Answer or PrAnswer.
4623 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4624 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4625 }
4626}
4627
Steve Antonf8470812017-12-04 10:46:21 -08004628const char* PeerConnection::SessionErrorToString(SessionError error) const {
4629 switch (error) {
4630 case SessionError::kNone:
4631 return "ERROR_NONE";
4632 case SessionError::kContent:
4633 return "ERROR_CONTENT";
4634 case SessionError::kTransport:
4635 return "ERROR_TRANSPORT";
4636 }
4637 RTC_NOTREACHED();
4638 return "";
4639}
4640
Steve Anton75737c02017-11-06 10:37:17 -08004641std::string PeerConnection::GetSessionErrorMsg() {
4642 std::ostringstream desc;
Steve Antonf8470812017-12-04 10:46:21 -08004643 desc << kSessionError << SessionErrorToString(session_error()) << ". ";
4644 desc << kSessionErrorDesc << session_error_desc() << ".";
Steve Anton75737c02017-11-06 10:37:17 -08004645 return desc.str();
4646}
4647
4648// We need to check the local/remote description for the Transport instead of
4649// the session, because a new Transport added during renegotiation may have
4650// them unset while the session has them set from the previous negotiation.
4651// Not doing so may trigger the auto generation of transport description and
4652// mess up DTLS identity information, ICE credential, etc.
4653bool PeerConnection::ReadyToUseRemoteCandidate(
4654 const IceCandidateInterface* candidate,
4655 const SessionDescriptionInterface* remote_desc,
4656 bool* valid) {
4657 *valid = true;
4658
4659 const SessionDescriptionInterface* current_remote_desc =
4660 remote_desc ? remote_desc : remote_description();
4661
4662 if (!current_remote_desc) {
4663 return false;
4664 }
4665
4666 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4667 size_t remote_content_size =
4668 current_remote_desc->description()->contents().size();
4669 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004670 RTC_LOG(LS_ERROR)
4671 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4672 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004673
4674 *valid = false;
4675 return false;
4676 }
4677
4678 cricket::ContentInfo content =
4679 current_remote_desc->description()->contents()[mediacontent_index];
4680
4681 const std::string transport_name = GetTransportName(content.name);
4682 if (transport_name.empty()) {
4683 return false;
4684 }
4685 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4686}
4687
4688bool PeerConnection::SrtpRequired() const {
4689 return dtls_enabled_ ||
4690 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4691}
4692
4693void PeerConnection::OnTransportControllerGatheringState(
4694 cricket::IceGatheringState state) {
4695 RTC_DCHECK(signaling_thread()->IsCurrent());
4696 if (state == cricket::kIceGatheringGathering) {
4697 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4698 } else if (state == cricket::kIceGatheringComplete) {
4699 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4700 }
4701}
4702
4703void PeerConnection::ReportTransportStats() {
4704 // Use a set so we don't report the same stats twice if two channels share
4705 // a transport.
4706 std::set<std::string> transport_names;
4707 if (voice_channel()) {
4708 transport_names.insert(voice_channel()->transport_name());
4709 }
4710 if (video_channel()) {
4711 transport_names.insert(video_channel()->transport_name());
4712 }
4713 if (rtp_data_channel()) {
4714 transport_names.insert(rtp_data_channel()->transport_name());
4715 }
4716 if (sctp_transport_name_) {
4717 transport_names.insert(*sctp_transport_name_);
4718 }
4719 for (const auto& name : transport_names) {
4720 cricket::TransportStats stats;
4721 if (transport_controller_->GetStats(name, &stats)) {
4722 ReportBestConnectionState(stats);
4723 ReportNegotiatedCiphers(stats);
4724 }
4725 }
4726}
4727// Walk through the ConnectionInfos to gather best connection usage
4728// for IPv4 and IPv6.
4729void PeerConnection::ReportBestConnectionState(
4730 const cricket::TransportStats& stats) {
4731 RTC_DCHECK(metrics_observer());
4732 for (cricket::TransportChannelStatsList::const_iterator it =
4733 stats.channel_stats.begin();
4734 it != stats.channel_stats.end(); ++it) {
4735 for (cricket::ConnectionInfos::const_iterator it_info =
4736 it->connection_infos.begin();
4737 it_info != it->connection_infos.end(); ++it_info) {
4738 if (!it_info->best_connection) {
4739 continue;
4740 }
4741
4742 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4743 const cricket::Candidate& local = it_info->local_candidate;
4744 const cricket::Candidate& remote = it_info->remote_candidate;
4745
4746 // Increment the counter for IceCandidatePairType.
4747 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4748 (local.type() == RELAY_PORT_TYPE &&
4749 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4750 type = kEnumCounterIceCandidatePairTypeTcp;
4751 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4752 type = kEnumCounterIceCandidatePairTypeUdp;
4753 } else {
4754 RTC_CHECK(0);
4755 }
4756 metrics_observer()->IncrementEnumCounter(
4757 type, GetIceCandidatePairCounter(local, remote),
4758 kIceCandidatePairMax);
4759
4760 // Increment the counter for IP type.
4761 if (local.address().family() == AF_INET) {
4762 metrics_observer()->IncrementEnumCounter(
4763 kEnumCounterAddressFamily, kBestConnections_IPv4,
4764 kPeerConnectionAddressFamilyCounter_Max);
4765
4766 } else if (local.address().family() == AF_INET6) {
4767 metrics_observer()->IncrementEnumCounter(
4768 kEnumCounterAddressFamily, kBestConnections_IPv6,
4769 kPeerConnectionAddressFamilyCounter_Max);
4770 } else {
4771 RTC_CHECK(0);
4772 }
4773
4774 return;
4775 }
4776 }
4777}
4778
4779void PeerConnection::ReportNegotiatedCiphers(
4780 const cricket::TransportStats& stats) {
4781 RTC_DCHECK(metrics_observer());
4782 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4783 return;
4784 }
4785
4786 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4787 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4788 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4789 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4790 return;
4791 }
4792
4793 PeerConnectionEnumCounterType srtp_counter_type;
4794 PeerConnectionEnumCounterType ssl_counter_type;
4795 if (stats.transport_name == cricket::CN_AUDIO) {
4796 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4797 ssl_counter_type = kEnumCounterAudioSslCipher;
4798 } else if (stats.transport_name == cricket::CN_VIDEO) {
4799 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4800 ssl_counter_type = kEnumCounterVideoSslCipher;
4801 } else if (stats.transport_name == cricket::CN_DATA) {
4802 srtp_counter_type = kEnumCounterDataSrtpCipher;
4803 ssl_counter_type = kEnumCounterDataSslCipher;
4804 } else {
4805 RTC_NOTREACHED();
4806 return;
4807 }
4808
4809 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4810 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4811 srtp_crypto_suite);
4812 }
4813 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4814 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4815 ssl_cipher_suite);
4816 }
4817}
4818
4819void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4820 RTC_DCHECK(worker_thread()->IsCurrent());
4821 RTC_DCHECK(call_);
4822 call_->OnSentPacket(sent_packet);
4823}
4824
4825const std::string PeerConnection::GetTransportName(
4826 const std::string& content_name) {
4827 cricket::BaseChannel* channel = GetChannel(content_name);
Steve Anton6fec8802017-12-04 10:37:29 -08004828 if (channel) {
4829 return channel->transport_name();
Steve Anton75737c02017-11-06 10:37:17 -08004830 }
Steve Anton6fec8802017-12-04 10:37:29 -08004831 if (sctp_transport_) {
4832 RTC_DCHECK(sctp_content_name_);
4833 RTC_DCHECK(sctp_transport_name_);
4834 if (content_name == *sctp_content_name_) {
4835 return *sctp_transport_name_;
4836 }
4837 }
4838 // Return an empty string if failed to retrieve the transport name.
4839 return "";
Steve Anton75737c02017-11-06 10:37:17 -08004840}
4841
4842void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4843 RTC_DCHECK(network_thread()->IsCurrent());
4844 transport_controller_->DestroyDtlsTransport_n(
4845 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4846}
4847
Steve Anton6fec8802017-12-04 10:37:29 -08004848void PeerConnection::DestroyTransceiverChannel(
4849 rtc::scoped_refptr<RtpTransceiverProxyWithInternal<RtpTransceiver>>
4850 transceiver) {
4851 RTC_DCHECK(transceiver);
Steve Anton75737c02017-11-06 10:37:17 -08004852
Steve Anton6fec8802017-12-04 10:37:29 -08004853 cricket::BaseChannel* channel = transceiver->internal()->channel();
4854 if (channel) {
4855 transceiver->internal()->SetChannel(nullptr);
4856 DestroyBaseChannel(channel);
Steve Anton75737c02017-11-06 10:37:17 -08004857 }
4858}
4859
4860void PeerConnection::DestroyDataChannel() {
Steve Anton6fec8802017-12-04 10:37:29 -08004861 if (rtp_data_channel_) {
4862 OnDataChannelDestroyed();
4863 DestroyBaseChannel(rtp_data_channel_);
4864 rtp_data_channel_ = nullptr;
4865 }
4866
4867 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
4868 // grab a reference to this PeerConnection. If this is called from the
4869 // PeerConnection destructor, the RefCountedObject vtable will have already
4870 // been destroyed (since it is a subclass of PeerConnection) and using
4871 // rtc::Bind will cause "Pure virtual function called" error to appear.
4872
4873 if (sctp_transport_) {
4874 OnDataChannelDestroyed();
4875 network_thread()->Invoke<void>(RTC_FROM_HERE,
4876 [this] { DestroySctpTransport_n(); });
4877 }
4878}
4879
4880void PeerConnection::DestroyBaseChannel(cricket::BaseChannel* channel) {
4881 RTC_DCHECK(channel);
4882 RTC_DCHECK(channel->rtp_dtls_transport());
4883
4884 // Need to cache these before destroying the base channel so that we do not
4885 // access uninitialized memory.
4886 const std::string transport_name =
4887 channel->rtp_dtls_transport()->transport_name();
4888 const bool need_to_delete_rtcp = (channel->rtcp_dtls_transport() != nullptr);
4889
4890 switch (channel->media_type()) {
4891 case cricket::MEDIA_TYPE_AUDIO:
4892 channel_manager()->DestroyVoiceChannel(
4893 static_cast<cricket::VoiceChannel*>(channel));
4894 break;
4895 case cricket::MEDIA_TYPE_VIDEO:
4896 channel_manager()->DestroyVideoChannel(
4897 static_cast<cricket::VideoChannel*>(channel));
4898 break;
4899 case cricket::MEDIA_TYPE_DATA:
4900 channel_manager()->DestroyRtpDataChannel(
4901 static_cast<cricket::RtpDataChannel*>(channel));
4902 break;
4903 default:
4904 RTC_NOTREACHED() << "Unknown media type: " << channel->media_type();
4905 break;
4906 }
4907
4908 // |channel| can no longer be used.
4909
Steve Anton75737c02017-11-06 10:37:17 -08004910 transport_controller_->DestroyDtlsTransport(
4911 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4912 if (need_to_delete_rtcp) {
4913 transport_controller_->DestroyDtlsTransport(
4914 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4915 }
4916}
4917
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004918} // namespace webrtc