blob: e8857a39df5859c4154b4dbf323965050e5f90ab [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"
34#include "pc/rtpreceiver.h"
35#include "pc/rtpsender.h"
Steve Anton75737c02017-11-06 10:37:17 -080036#include "pc/sctputils.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020037#include "pc/streamcollection.h"
38#include "pc/videocapturertracksource.h"
39#include "pc/videotrack.h"
40#include "rtc_base/bind.h"
41#include "rtc_base/checks.h"
42#include "rtc_base/logging.h"
Elad Alon83ccca12017-10-04 13:18:26 +020043#include "rtc_base/ptr_util.h"
44#include "rtc_base/safe_conversions.h"
Mirko Bonadei92ea95e2017-09-15 06:47:31 +020045#include "rtc_base/stringencode.h"
46#include "rtc_base/stringutils.h"
47#include "rtc_base/trace_event.h"
48#include "system_wrappers/include/clock.h"
49#include "system_wrappers/include/field_trial.h"
henrike@webrtc.org28e20752013-07-10 00:45:36 +000050
Steve Anton75737c02017-11-06 10:37:17 -080051using cricket::ContentInfo;
52using cricket::ContentInfos;
53using cricket::MediaContentDescription;
54using cricket::SessionDescription;
55using cricket::TransportInfo;
56
57using cricket::LOCAL_PORT_TYPE;
58using cricket::STUN_PORT_TYPE;
59using cricket::RELAY_PORT_TYPE;
60using cricket::PRFLX_PORT_TYPE;
61
Steve Antonba818672017-11-06 10:21:57 -080062namespace webrtc {
63
Steve Anton75737c02017-11-06 10:37:17 -080064// Error messages
65const char kBundleWithoutRtcpMux[] =
66 "rtcp-mux must be enabled when BUNDLE "
67 "is enabled.";
68const char kCreateChannelFailed[] = "Failed to create channels.";
69const 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.";
77const char kPushDownTDFailed[] = "Failed to push down transport description:";
78const char kSdpWithoutDtlsFingerprint[] =
79 "Called with SDP without DTLS fingerprint.";
80const char kSdpWithoutSdesCrypto[] = "Called with SDP without SDES crypto.";
81const char kSdpWithoutIceUfragPwd[] =
82 "Called with SDP without ice-ufrag and ice-pwd.";
83const char kSessionError[] = "Session error code: ";
84const char kSessionErrorDesc[] = "Session error description: ";
85const char kDtlsSrtpSetupFailureRtp[] =
86 "Couldn't set up DTLS-SRTP on RTP channel.";
87const char kDtlsSrtpSetupFailureRtcp[] =
88 "Couldn't set up DTLS-SRTP on RTCP channel.";
89const char kEnableBundleFailed[] = "Failed to enable BUNDLE.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +000090
Steve Anton75737c02017-11-06 10:37:17 -080091namespace {
henrike@webrtc.org28e20752013-07-10 00:45:36 +000092
deadbeefab9b2d12015-10-14 11:33:11 -070093static const char kDefaultStreamLabel[] = "default";
94static const char kDefaultAudioTrackLabel[] = "defaulta0";
95static const char kDefaultVideoTrackLabel[] = "defaultv0";
96
zhihuang8f65cdf2016-05-06 18:40:30 -070097// The length of RTCP CNAMEs.
98static const int kRtcpCnameLength = 16;
99
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000100enum {
wu@webrtc.org91053e72013-08-10 07:18:04 +0000101 MSG_SET_SESSIONDESCRIPTION_SUCCESS = 0,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000102 MSG_SET_SESSIONDESCRIPTION_FAILED,
deadbeefab9b2d12015-10-14 11:33:11 -0700103 MSG_CREATE_SESSIONDESCRIPTION_FAILED,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000104 MSG_GETSTATS,
deadbeefbd292462015-12-14 18:15:29 -0800105 MSG_FREE_DATACHANNELS,
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000106};
107
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000108struct SetSessionDescriptionMsg : public rtc::MessageData {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000109 explicit SetSessionDescriptionMsg(
110 webrtc::SetSessionDescriptionObserver* observer)
111 : observer(observer) {
112 }
113
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000114 rtc::scoped_refptr<webrtc::SetSessionDescriptionObserver> observer;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000115 std::string error;
116};
117
deadbeefab9b2d12015-10-14 11:33:11 -0700118struct CreateSessionDescriptionMsg : public rtc::MessageData {
119 explicit CreateSessionDescriptionMsg(
120 webrtc::CreateSessionDescriptionObserver* observer)
121 : observer(observer) {}
122
123 rtc::scoped_refptr<webrtc::CreateSessionDescriptionObserver> observer;
124 std::string error;
125};
126
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000127struct GetStatsMsg : public rtc::MessageData {
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000128 GetStatsMsg(webrtc::StatsObserver* observer,
129 webrtc::MediaStreamTrackInterface* track)
130 : observer(observer), track(track) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000131 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +0000132 rtc::scoped_refptr<webrtc::StatsObserver> observer;
tommi@webrtc.org5b06b062014-08-15 08:38:30 +0000133 rtc::scoped_refptr<webrtc::MediaStreamTrackInterface> track;
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000134};
135
deadbeefab9b2d12015-10-14 11:33:11 -0700136// Check if we can send |new_stream| on a PeerConnection.
137bool CanAddLocalMediaStream(webrtc::StreamCollectionInterface* current_streams,
138 webrtc::MediaStreamInterface* new_stream) {
139 if (!new_stream || !current_streams) {
140 return false;
141 }
142 if (current_streams->find(new_stream->label()) != nullptr) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100143 RTC_LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
144 << " is already added.";
deadbeefab9b2d12015-10-14 11:33:11 -0700145 return false;
146 }
147 return true;
148}
149
150bool MediaContentDirectionHasSend(cricket::MediaContentDirection dir) {
151 return dir == cricket::MD_SENDONLY || dir == cricket::MD_SENDRECV;
152}
153
deadbeef5e97fb52015-10-15 12:49:08 -0700154// If the direction is "recvonly" or "inactive", treat the description
155// as containing no streams.
156// See: https://code.google.com/p/webrtc/issues/detail?id=5054
157std::vector<cricket::StreamParams> GetActiveStreams(
158 const cricket::MediaContentDescription* desc) {
159 return MediaContentDirectionHasSend(desc->direction())
160 ? desc->streams()
161 : std::vector<cricket::StreamParams>();
162}
163
deadbeefab9b2d12015-10-14 11:33:11 -0700164bool IsValidOfferToReceiveMedia(int value) {
165 typedef PeerConnectionInterface::RTCOfferAnswerOptions Options;
166 return (value >= Options::kUndefined) &&
167 (value <= Options::kMaxOfferToReceiveMedia);
168}
169
zhihuang1c378ed2017-08-17 14:10:50 -0700170// Add options to |[audio/video]_media_description_options| from |senders|.
171void AddRtpSenderOptions(
deadbeefa601f5c2016-06-06 14:27:39 -0700172 const std::vector<rtc::scoped_refptr<
173 RtpSenderProxyWithInternal<RtpSenderInternal>>>& senders,
zhihuang1c378ed2017-08-17 14:10:50 -0700174 cricket::MediaDescriptionOptions* audio_media_description_options,
175 cricket::MediaDescriptionOptions* video_media_description_options) {
olka3c747662017-08-17 06:50:32 -0700176 for (const auto& sender : senders) {
zhihuang1c378ed2017-08-17 14:10:50 -0700177 if (sender->media_type() == cricket::MEDIA_TYPE_AUDIO) {
178 if (audio_media_description_options) {
179 audio_media_description_options->AddAudioSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700180 sender->id(), sender->internal()->stream_ids());
zhihuang1c378ed2017-08-17 14:10:50 -0700181 }
182 } else {
183 RTC_DCHECK(sender->media_type() == cricket::MEDIA_TYPE_VIDEO);
184 if (video_media_description_options) {
185 video_media_description_options->AddVideoSender(
Steve Anton8ffb9c32017-08-31 15:45:38 -0700186 sender->id(), sender->internal()->stream_ids(), 1);
zhihuang1c378ed2017-08-17 14:10:50 -0700187 }
188 }
zhihuanga77e6bb2017-08-14 18:17:48 -0700189 }
zhihuang1c378ed2017-08-17 14:10:50 -0700190}
olka3c747662017-08-17 06:50:32 -0700191
zhihuang1c378ed2017-08-17 14:10:50 -0700192// Add options to |session_options| from |rtp_data_channels|.
193void AddRtpDataChannelOptions(
194 const std::map<std::string, rtc::scoped_refptr<DataChannel>>&
195 rtp_data_channels,
196 cricket::MediaDescriptionOptions* data_media_description_options) {
197 if (!data_media_description_options) {
198 return;
199 }
deadbeefab9b2d12015-10-14 11:33:11 -0700200 // Check for data channels.
201 for (const auto& kv : rtp_data_channels) {
202 const DataChannel* channel = kv.second;
203 if (channel->state() == DataChannel::kConnecting ||
204 channel->state() == DataChannel::kOpen) {
zhihuang1c378ed2017-08-17 14:10:50 -0700205 // Legacy RTP data channels are signaled with the track/stream ID set to
206 // the data channel's label.
207 data_media_description_options->AddRtpDataChannel(channel->label(),
208 channel->label());
deadbeefab9b2d12015-10-14 11:33:11 -0700209 }
210 }
211}
212
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700213uint32_t ConvertIceTransportTypeToCandidateFilter(
214 PeerConnectionInterface::IceTransportsType type) {
215 switch (type) {
216 case PeerConnectionInterface::kNone:
217 return cricket::CF_NONE;
218 case PeerConnectionInterface::kRelay:
219 return cricket::CF_RELAY;
220 case PeerConnectionInterface::kNoHost:
221 return (cricket::CF_ALL & ~cricket::CF_HOST);
222 case PeerConnectionInterface::kAll:
223 return cricket::CF_ALL;
224 default:
nissec80e7412017-01-11 05:56:46 -0800225 RTC_NOTREACHED();
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700226 }
227 return cricket::CF_NONE;
228}
229
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700230// Helper method to set a voice/video channel on all applicable senders
Steve Anton75737c02017-11-06 10:37:17 -0800231// and receivers when one is created/destroyed by PeerConnection.
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700232//
233// Used by On(Voice|Video)Channel(Created|Destroyed)
234template <class SENDER,
235 class RECEIVER,
236 class CHANNEL,
237 class SENDERS,
238 class RECEIVERS>
239void SetChannelOnSendersAndReceivers(CHANNEL* channel,
Steve Anton36b29d12017-10-30 09:57:42 -0700240 const SENDERS& senders,
241 const RECEIVERS& receivers,
Taylor Brandstetterba29c6a2016-06-27 16:30:35 -0700242 cricket::MediaType media_type) {
243 for (auto& sender : senders) {
244 if (sender->media_type() == media_type) {
245 static_cast<SENDER*>(sender->internal())->SetChannel(channel);
246 }
247 }
248 for (auto& receiver : receivers) {
249 if (receiver->media_type() == media_type) {
250 if (!channel) {
251 receiver->internal()->Stop();
252 }
253 static_cast<RECEIVER*>(receiver->internal())->SetChannel(channel);
254 }
255 }
256}
257
deadbeef293e9262017-01-11 12:28:30 -0800258// Helper to set an error and return from a method.
259bool SafeSetError(webrtc::RTCErrorType type, webrtc::RTCError* error) {
260 if (error) {
261 error->set_type(type);
262 }
263 return type == webrtc::RTCErrorType::NONE;
264}
265
Steve Anton038834f2017-07-14 15:59:59 -0700266bool SafeSetError(webrtc::RTCError error, webrtc::RTCError* error_out) {
267 if (error_out) {
268 *error_out = std::move(error);
269 }
270 return error.ok();
271}
272
Steve Antonba818672017-11-06 10:21:57 -0800273std::string GetSignalingStateString(
274 PeerConnectionInterface::SignalingState state) {
275 switch (state) {
276 case PeerConnectionInterface::kStable:
277 return "kStable";
278 case PeerConnectionInterface::kHaveLocalOffer:
279 return "kHaveLocalOffer";
280 case PeerConnectionInterface::kHaveLocalPrAnswer:
281 return "kHavePrAnswer";
282 case PeerConnectionInterface::kHaveRemoteOffer:
283 return "kHaveRemoteOffer";
284 case PeerConnectionInterface::kHaveRemotePrAnswer:
285 return "kHaveRemotePrAnswer";
286 case PeerConnectionInterface::kClosed:
287 return "kClosed";
288 }
289 RTC_NOTREACHED();
290 return "";
291}
deadbeef0a6c4ca2015-10-06 11:38:28 -0700292
Steve Anton75737c02017-11-06 10:37:17 -0800293IceCandidatePairType GetIceCandidatePairCounter(
294 const cricket::Candidate& local,
295 const cricket::Candidate& remote) {
296 const auto& l = local.type();
297 const auto& r = remote.type();
298 const auto& host = LOCAL_PORT_TYPE;
299 const auto& srflx = STUN_PORT_TYPE;
300 const auto& relay = RELAY_PORT_TYPE;
301 const auto& prflx = PRFLX_PORT_TYPE;
302 if (l == host && r == host) {
303 bool local_private = IPIsPrivate(local.address().ipaddr());
304 bool remote_private = IPIsPrivate(remote.address().ipaddr());
305 if (local_private) {
306 if (remote_private) {
307 return kIceCandidatePairHostPrivateHostPrivate;
308 } else {
309 return kIceCandidatePairHostPrivateHostPublic;
310 }
311 } else {
312 if (remote_private) {
313 return kIceCandidatePairHostPublicHostPrivate;
314 } else {
315 return kIceCandidatePairHostPublicHostPublic;
316 }
317 }
318 }
319 if (l == host && r == srflx)
320 return kIceCandidatePairHostSrflx;
321 if (l == host && r == relay)
322 return kIceCandidatePairHostRelay;
323 if (l == host && r == prflx)
324 return kIceCandidatePairHostPrflx;
325 if (l == srflx && r == host)
326 return kIceCandidatePairSrflxHost;
327 if (l == srflx && r == srflx)
328 return kIceCandidatePairSrflxSrflx;
329 if (l == srflx && r == relay)
330 return kIceCandidatePairSrflxRelay;
331 if (l == srflx && r == prflx)
332 return kIceCandidatePairSrflxPrflx;
333 if (l == relay && r == host)
334 return kIceCandidatePairRelayHost;
335 if (l == relay && r == srflx)
336 return kIceCandidatePairRelaySrflx;
337 if (l == relay && r == relay)
338 return kIceCandidatePairRelayRelay;
339 if (l == relay && r == prflx)
340 return kIceCandidatePairRelayPrflx;
341 if (l == prflx && r == host)
342 return kIceCandidatePairPrflxHost;
343 if (l == prflx && r == srflx)
344 return kIceCandidatePairPrflxSrflx;
345 if (l == prflx && r == relay)
346 return kIceCandidatePairPrflxRelay;
347 return kIceCandidatePairMax;
348}
349
350// Verify that the order of media sections in |new_desc| matches
351// |existing_desc|. The number of m= sections in |new_desc| should be no less
352// than |existing_desc|.
353bool MediaSectionsInSameOrder(const SessionDescription* existing_desc,
354 const SessionDescription* new_desc) {
355 if (!existing_desc || !new_desc) {
356 return false;
357 }
358
359 if (existing_desc->contents().size() > new_desc->contents().size()) {
360 return false;
361 }
362
363 for (size_t i = 0; i < existing_desc->contents().size(); ++i) {
364 if (new_desc->contents()[i].name != existing_desc->contents()[i].name) {
365 return false;
366 }
367 const MediaContentDescription* new_desc_mdesc =
368 static_cast<const MediaContentDescription*>(
369 new_desc->contents()[i].description);
370 const MediaContentDescription* existing_desc_mdesc =
371 static_cast<const MediaContentDescription*>(
372 existing_desc->contents()[i].description);
373 if (new_desc_mdesc->type() != existing_desc_mdesc->type()) {
374 return false;
375 }
376 }
377 return true;
378}
379
380bool MediaSectionsHaveSameCount(const SessionDescription* desc1,
381 const SessionDescription* desc2) {
382 if (!desc1 || !desc2) {
383 return false;
384 }
385 return desc1->contents().size() == desc2->contents().size();
386}
387
388// Checks that each non-rejected content has SDES crypto keys or a DTLS
389// fingerprint, unless it's in a BUNDLE group, in which case only the
390// BUNDLE-tag section (first media section/description in the BUNDLE group)
391// needs a ufrag and pwd. Mismatches, such as replying with a DTLS fingerprint
392// to SDES keys, will be caught in JsepTransport negotiation, and backstopped
393// by Channel's |srtp_required| check.
394bool VerifyCrypto(const SessionDescription* desc,
395 bool dtls_enabled,
396 std::string* error) {
397 const cricket::ContentGroup* bundle =
398 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
399 const ContentInfos& contents = desc->contents();
400 for (size_t index = 0; index < contents.size(); ++index) {
401 const ContentInfo* cinfo = &contents[index];
402 if (cinfo->rejected) {
403 continue;
404 }
405 if (bundle && bundle->HasContentName(cinfo->name) &&
406 cinfo->name != *(bundle->FirstContentName())) {
407 // This isn't the first media section in the BUNDLE group, so it's not
408 // required to have crypto attributes, since only the crypto attributes
409 // from the first section actually get used.
410 continue;
411 }
412
413 // If the content isn't rejected or bundled into another m= section, crypto
414 // must be present.
415 const MediaContentDescription* media =
416 static_cast<const MediaContentDescription*>(cinfo->description);
417 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
418 if (!media || !tinfo) {
419 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100420 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800421 *error = kInvalidSdp;
422 return false;
423 }
424 if (dtls_enabled) {
425 if (!tinfo->description.identity_fingerprint) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100426 RTC_LOG(LS_WARNING)
427 << "Session description must have DTLS fingerprint if "
428 "DTLS enabled.";
Steve Anton75737c02017-11-06 10:37:17 -0800429 *error = kSdpWithoutDtlsFingerprint;
430 return false;
431 }
432 } else {
433 if (media->cryptos().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100434 RTC_LOG(LS_WARNING)
Steve Anton75737c02017-11-06 10:37:17 -0800435 << "Session description must have SDES when DTLS disabled.";
436 *error = kSdpWithoutSdesCrypto;
437 return false;
438 }
439 }
440 }
441
442 return true;
443}
444
445// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
446// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
447// media section/description in the BUNDLE group) needs a ufrag and pwd.
448bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
449 const cricket::ContentGroup* bundle =
450 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
451 const ContentInfos& contents = desc->contents();
452 for (size_t index = 0; index < contents.size(); ++index) {
453 const ContentInfo* cinfo = &contents[index];
454 if (cinfo->rejected) {
455 continue;
456 }
457 if (bundle && bundle->HasContentName(cinfo->name) &&
458 cinfo->name != *(bundle->FirstContentName())) {
459 // This isn't the first media section in the BUNDLE group, so it's not
460 // required to have ufrag/password, since only the ufrag/password from
461 // the first section actually get used.
462 continue;
463 }
464
465 // If the content isn't rejected or bundled into another m= section,
466 // ice-ufrag and ice-pwd must be present.
467 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
468 if (!tinfo) {
469 // Something is not right.
Mirko Bonadei675513b2017-11-09 11:09:25 +0100470 RTC_LOG(LS_ERROR) << kInvalidSdp;
Steve Anton75737c02017-11-06 10:37:17 -0800471 return false;
472 }
473 if (tinfo->description.ice_ufrag.empty() ||
474 tinfo->description.ice_pwd.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100475 RTC_LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
Steve Anton75737c02017-11-06 10:37:17 -0800476 return false;
477 }
478 }
479 return true;
480}
481
482bool GetTrackIdBySsrc(const SessionDescription* session_description,
483 uint32_t ssrc,
484 std::string* track_id) {
485 RTC_DCHECK(track_id != NULL);
486
487 const cricket::ContentInfo* audio_info =
488 cricket::GetFirstAudioContent(session_description);
489 if (audio_info) {
490 const cricket::MediaContentDescription* audio_content =
491 static_cast<const cricket::MediaContentDescription*>(
492 audio_info->description);
493
494 const auto* found =
495 cricket::GetStreamBySsrc(audio_content->streams(), ssrc);
496 if (found) {
497 *track_id = found->id;
498 return true;
499 }
500 }
501
502 const cricket::ContentInfo* video_info =
503 cricket::GetFirstVideoContent(session_description);
504 if (video_info) {
505 const cricket::MediaContentDescription* video_content =
506 static_cast<const cricket::MediaContentDescription*>(
507 video_info->description);
508
509 const auto* found =
510 cricket::GetStreamBySsrc(video_content->streams(), ssrc);
511 if (found) {
512 *track_id = found->id;
513 return true;
514 }
515 }
516 return false;
517}
518
519// Get the SCTP port out of a SessionDescription.
520// Return -1 if not found.
521int GetSctpPort(const SessionDescription* session_description) {
522 const ContentInfo* content_info = GetFirstDataContent(session_description);
523 RTC_DCHECK(content_info);
524 if (!content_info) {
525 return -1;
526 }
527 const cricket::DataContentDescription* data =
528 static_cast<const cricket::DataContentDescription*>(
529 (content_info->description));
530 std::string value;
531 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
532 cricket::kGoogleSctpDataCodecName);
533 for (const cricket::DataCodec& codec : data->codecs()) {
534 if (!codec.Matches(match_pattern)) {
535 continue;
536 }
537 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
538 return rtc::FromString<int>(value);
539 }
540 }
541 return -1;
542}
543
544bool BadSdp(const std::string& source,
545 const std::string& type,
546 const std::string& reason,
547 std::string* err_desc) {
548 std::ostringstream desc;
549 desc << "Failed to set " << source;
550 if (!type.empty()) {
551 desc << " " << type;
552 }
553 desc << " sdp: " << reason;
554
555 if (err_desc) {
556 *err_desc = desc.str();
557 }
Mirko Bonadei675513b2017-11-09 11:09:25 +0100558 RTC_LOG(LS_ERROR) << desc.str();
Steve Anton75737c02017-11-06 10:37:17 -0800559 return false;
560}
561
562bool BadSdp(cricket::ContentSource source,
563 const std::string& type,
564 const std::string& reason,
565 std::string* err_desc) {
566 if (source == cricket::CS_LOCAL) {
567 return BadSdp("local", type, reason, err_desc);
568 } else {
569 return BadSdp("remote", type, reason, err_desc);
570 }
571}
572
573bool BadLocalSdp(const std::string& type,
574 const std::string& reason,
575 std::string* err_desc) {
576 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
577}
578
579bool BadRemoteSdp(const std::string& type,
580 const std::string& reason,
581 std::string* err_desc) {
582 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
583}
584
585bool BadOfferSdp(cricket::ContentSource source,
586 const std::string& reason,
587 std::string* err_desc) {
588 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
589}
590
591bool BadPranswerSdp(cricket::ContentSource source,
592 const std::string& reason,
593 std::string* err_desc) {
594 return BadSdp(source, SessionDescriptionInterface::kPrAnswer, reason,
595 err_desc);
596}
597
598bool BadAnswerSdp(cricket::ContentSource source,
599 const std::string& reason,
600 std::string* err_desc) {
601 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
602}
603
604std::string BadStateErrMsg(PeerConnectionInterface::SignalingState state) {
605 std::ostringstream desc;
606 desc << "Called in wrong state: " << GetSignalingStateString(state);
607 return desc.str();
608}
609
610#define GET_STRING_OF_ERROR_CODE(err) \
611 case webrtc::PeerConnection::err: \
612 result = #err; \
613 break;
614
615std::string GetErrorCodeString(webrtc::PeerConnection::Error err) {
616 std::string result;
617 switch (err) {
618 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
619 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
620 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
621 default:
622 RTC_NOTREACHED();
623 break;
624 }
625 return result;
626}
627
628std::string MakeErrorString(const std::string& error, const std::string& desc) {
629 std::ostringstream ret;
630 ret << error << " " << desc;
631 return ret.str();
632}
633
634std::string MakeTdErrorString(const std::string& desc) {
635 return MakeErrorString(kPushDownTDFailed, desc);
636}
637
638// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
639bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
640 const SessionDescriptionInterface* new_desc,
641 const std::string& content_name) {
642 if (!old_desc) {
643 return false;
644 }
645 const SessionDescription* new_sd = new_desc->description();
646 const SessionDescription* old_sd = old_desc->description();
647 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
648 if (!cinfo || cinfo->rejected) {
649 return false;
650 }
651 // If the content isn't rejected, check if ufrag and password has changed.
652 const cricket::TransportDescription* new_transport_desc =
653 new_sd->GetTransportDescriptionByName(content_name);
654 const cricket::TransportDescription* old_transport_desc =
655 old_sd->GetTransportDescriptionByName(content_name);
656 if (!new_transport_desc || !old_transport_desc) {
657 // No transport description exists. This is not an ICE restart.
658 return false;
659 }
660 if (cricket::IceCredentialsChanged(
661 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
662 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100663 RTC_LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
664 << ".";
Steve Anton75737c02017-11-06 10:37:17 -0800665 return true;
666 }
667 return false;
668}
669
670} // namespace
671
deadbeef293e9262017-01-11 12:28:30 -0800672bool PeerConnectionInterface::RTCConfiguration::operator==(
673 const PeerConnectionInterface::RTCConfiguration& o) const {
674 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700675 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800676 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000677 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700678 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800679 BundlePolicy bundle_policy;
680 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700681 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
682 int ice_candidate_pool_size;
683 bool disable_ipv6;
684 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700685 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700686 bool enable_rtp_data_channel;
687 rtc::Optional<int> screencast_min_bitrate;
688 rtc::Optional<bool> combined_audio_video_bwe;
689 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800690 TcpCandidatePolicy tcp_candidate_policy;
691 CandidateNetworkPolicy candidate_network_policy;
692 int audio_jitter_buffer_max_packets;
693 bool audio_jitter_buffer_fast_accelerate;
694 int ice_connection_receiving_timeout;
695 int ice_backup_candidate_pair_ping_interval;
696 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800697 bool prioritize_most_likely_ice_candidate_pairs;
698 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800699 bool prune_turn_ports;
700 bool presume_writable_when_fully_relayed;
701 bool enable_ice_renomination;
702 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800703 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700704 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200705 webrtc::TurnCustomizer* turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800706 };
707 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
708 "Did you add something to RTCConfiguration and forget to "
709 "update operator==?");
710 return type == o.type && servers == o.servers &&
711 bundle_policy == o.bundle_policy &&
712 rtcp_mux_policy == o.rtcp_mux_policy &&
713 tcp_candidate_policy == o.tcp_candidate_policy &&
714 candidate_network_policy == o.candidate_network_policy &&
715 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
716 audio_jitter_buffer_fast_accelerate ==
717 o.audio_jitter_buffer_fast_accelerate &&
718 ice_connection_receiving_timeout ==
719 o.ice_connection_receiving_timeout &&
720 ice_backup_candidate_pair_ping_interval ==
721 o.ice_backup_candidate_pair_ping_interval &&
722 continual_gathering_policy == o.continual_gathering_policy &&
723 certificates == o.certificates &&
724 prioritize_most_likely_ice_candidate_pairs ==
725 o.prioritize_most_likely_ice_candidate_pairs &&
726 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800727 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700728 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800729 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800730 screencast_min_bitrate == o.screencast_min_bitrate &&
731 combined_audio_video_bwe == o.combined_audio_video_bwe &&
732 enable_dtls_srtp == o.enable_dtls_srtp &&
733 ice_candidate_pool_size == o.ice_candidate_pool_size &&
734 prune_turn_ports == o.prune_turn_ports &&
735 presume_writable_when_fully_relayed ==
736 o.presume_writable_when_fully_relayed &&
737 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800738 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700739 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200740 ice_regather_interval_range == o.ice_regather_interval_range &&
741 turn_customizer == o.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800742}
743
744bool PeerConnectionInterface::RTCConfiguration::operator!=(
745 const PeerConnectionInterface::RTCConfiguration& o) const {
746 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800747}
748
zhihuang8f65cdf2016-05-06 18:40:30 -0700749// Generate a RTCP CNAME when a PeerConnection is created.
750std::string GenerateRtcpCname() {
751 std::string cname;
752 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100753 RTC_LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800754 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700755 }
756 return cname;
757}
758
zhihuang1c378ed2017-08-17 14:10:50 -0700759bool ValidateOfferAnswerOptions(
760 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
761 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
762 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700763}
764
zhihuang1c378ed2017-08-17 14:10:50 -0700765// From |rtc_options|, fill parts of |session_options| shared by all generated
766// m= sections (in other words, nothing that involves a map/array).
767void ExtractSharedMediaSessionOptions(
768 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
769 cricket::MediaSessionOptions* session_options) {
770 session_options->vad_enabled = rtc_options.voice_activity_detection;
771 session_options->bundle_enabled = rtc_options.use_rtp_mux;
772}
zhihuanga77e6bb2017-08-14 18:17:48 -0700773
zhihuang1c378ed2017-08-17 14:10:50 -0700774bool ConvertConstraintsToOfferAnswerOptions(
775 const MediaConstraintsInterface* constraints,
776 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700777 if (!constraints) {
778 return true;
779 }
zhihuang1c378ed2017-08-17 14:10:50 -0700780
781 bool value = false;
782 size_t mandatory_constraints_satisfied = 0;
783
784 if (FindConstraint(constraints,
785 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
786 &mandatory_constraints_satisfied)) {
787 offer_answer_options->offer_to_receive_audio =
788 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
789 kOfferToReceiveMediaTrue
790 : 0;
791 }
792
793 if (FindConstraint(constraints,
794 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
795 &mandatory_constraints_satisfied)) {
796 offer_answer_options->offer_to_receive_video =
797 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
798 kOfferToReceiveMediaTrue
799 : 0;
800 }
801 if (FindConstraint(constraints,
802 MediaConstraintsInterface::kVoiceActivityDetection, &value,
803 &mandatory_constraints_satisfied)) {
804 offer_answer_options->voice_activity_detection = value;
805 }
806 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
807 &mandatory_constraints_satisfied)) {
808 offer_answer_options->use_rtp_mux = value;
809 }
810 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
811 &value, &mandatory_constraints_satisfied)) {
812 offer_answer_options->ice_restart = value;
813 }
814
deadbeefab9b2d12015-10-14 11:33:11 -0700815 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
816}
817
zhihuang38ede132017-06-15 12:52:32 -0700818PeerConnection::PeerConnection(PeerConnectionFactory* factory,
819 std::unique_ptr<RtcEventLog> event_log,
820 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000821 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700822 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700823 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700824 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700825 remote_streams_(StreamCollection::Create()),
826 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000827
828PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100829 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700830 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Anton75737c02017-11-06 10:37:17 -0800831 // Need to detach RTP senders/receivers from PeerConnection,
deadbeef70ab1a12015-09-28 16:53:55 -0700832 // since it's about to be destroyed.
833 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700834 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700835 }
836 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700837 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700838 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700839 // Destroy stats_ because it depends on session_.
840 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800841 if (stats_collector_) {
842 stats_collector_->WaitForPendingRequest();
843 stats_collector_ = nullptr;
844 }
Steve Anton75737c02017-11-06 10:37:17 -0800845
846 // Destroy video channels first since they may have a pointer to a voice
847 // channel.
848 for (auto* channel : video_channels_) {
849 DestroyVideoChannel(channel);
850 }
851 for (auto* channel : voice_channels_) {
852 DestroyVoiceChannel(channel);
853 }
854 if (rtp_data_channel_) {
855 DestroyDataChannel();
856 }
857
858 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
859 // grab a reference to this PeerConnection. The RefCountedObject vtable will
860 // have already been destroyed (since it is a subclass of PeerConnection) and
861 // using rtc::Bind will cause "Pure virtual function called" error to appear.
862
863 if (sctp_transport_) {
864 OnDataChannelDestroyed();
865 network_thread()->Invoke<void>(RTC_FROM_HERE,
866 [this] { DestroySctpTransport_n(); });
867 }
868
Mirko Bonadei675513b2017-11-09 11:09:25 +0100869 RTC_LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
Steve Anton75737c02017-11-06 10:37:17 -0800870
871 webrtc_session_desc_factory_.reset();
872 sctp_invoker_.reset();
873 sctp_factory_.reset();
874 transport_controller_.reset();
875
deadbeef91dd5672016-05-18 16:55:30 -0700876 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700877 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700878 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700879 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700880 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700881 call_.reset();
882 event_log_.reset();
883 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000884}
885
886bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000887 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700888 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200889 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800890 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100891 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700892
893 RTCError config_error = ValidateConfiguration(configuration);
894 if (!config_error.ok()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100895 RTC_LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
Steve Anton038834f2017-07-14 15:59:59 -0700896 return false;
897 }
898
deadbeef293e9262017-01-11 12:28:30 -0800899 if (!allocator) {
Mirko Bonadei675513b2017-11-09 11:09:25 +0100900 RTC_LOG(LS_ERROR)
901 << "PeerConnection initialized without a PortAllocator? "
902 << "This shouldn't happen if using PeerConnectionFactory.";
deadbeef293e9262017-01-11 12:28:30 -0800903 return false;
904 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200905
deadbeef653b8e02015-11-11 12:55:10 -0800906 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800907 // TODO(deadbeef): Why do we do this?
Mirko Bonadei675513b2017-11-09 11:09:25 +0100908 RTC_LOG(LS_ERROR) << "PeerConnection initialized without a "
909 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800910 return false;
911 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000912 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800913 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800914
deadbeef91dd5672016-05-18 16:55:30 -0700915 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700916 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700917 if (!network_thread()->Invoke<bool>(
918 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
919 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920 return false;
921 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000922
Steve Anton75737c02017-11-06 10:37:17 -0800923 // RFC 3264: The numeric value of the session id and version in the
924 // o line MUST be representable with a "64 bit signed integer".
925 // Due to this constraint session id |session_id_| is max limited to
926 // LLONG_MAX.
927 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
928 transport_controller_.reset(factory_->CreateTransportController(
929 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
930 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
931 transport_controller_->SignalConnectionState.connect(
932 this, &PeerConnection::OnTransportControllerConnectionState);
933 transport_controller_->SignalGatheringState.connect(
934 this, &PeerConnection::OnTransportControllerGatheringState);
935 transport_controller_->SignalCandidatesGathered.connect(
936 this, &PeerConnection::OnTransportControllerCandidatesGathered);
937 transport_controller_->SignalCandidatesRemoved.connect(
938 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
939 transport_controller_->SignalDtlsHandshakeError.connect(
940 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
941
942 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700943
deadbeefab9b2d12015-10-14 11:33:11 -0700944 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700945 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000946
Steve Antonba818672017-11-06 10:21:57 -0800947 configuration_ = configuration;
948
Steve Anton75737c02017-11-06 10:37:17 -0800949 const PeerConnectionFactoryInterface::Options& options = factory_->options();
950
951 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
952
953 // Obtain a certificate from RTCConfiguration if any were provided (optional).
954 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
955 if (!configuration.certificates.empty()) {
956 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
957 // just picking the first one. The decision should be made based on the DTLS
958 // handshake. The DTLS negotiations need to know about all certificates.
959 certificate = configuration.certificates[0];
960 }
961
Steve Antond25da372017-11-06 14:50:29 -0800962 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800963
964 if (options.disable_encryption) {
965 dtls_enabled_ = false;
966 } else {
967 // Enable DTLS by default if we have an identity store or a certificate.
968 dtls_enabled_ = (cert_generator || certificate);
969 // |configuration| can override the default |dtls_enabled_| value.
970 if (configuration.enable_dtls_srtp) {
971 dtls_enabled_ = *(configuration.enable_dtls_srtp);
972 }
973 }
974
975 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
976 // It takes precendence over the disable_sctp_data_channels
977 // PeerConnectionFactoryInterface::Options.
978 if (configuration.enable_rtp_data_channel) {
979 data_channel_type_ = cricket::DCT_RTP;
980 } else {
981 // DTLS has to be enabled to use SCTP.
982 if (!options.disable_sctp_data_channels && dtls_enabled_) {
983 data_channel_type_ = cricket::DCT_SCTP;
984 }
985 }
986
987 video_options_.screencast_min_bitrate_kbps =
988 configuration.screencast_min_bitrate;
989 audio_options_.combined_audio_video_bwe =
990 configuration.combined_audio_video_bwe;
991
992 audio_options_.audio_jitter_buffer_max_packets =
993 rtc::Optional<int>(configuration.audio_jitter_buffer_max_packets);
994
995 audio_options_.audio_jitter_buffer_fast_accelerate =
996 rtc::Optional<bool>(configuration.audio_jitter_buffer_fast_accelerate);
997
998 // Whether the certificate generator/certificate is null or not determines
999 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
1000 // the right instructions by clearing the variables if needed.
1001 if (!dtls_enabled_) {
1002 cert_generator.reset();
1003 certificate = nullptr;
1004 } else if (certificate) {
1005 // Favor generated certificate over the certificate generator.
1006 cert_generator.reset();
1007 }
1008
1009 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1010 signaling_thread(), channel_manager(), this, session_id(),
1011 std::move(cert_generator), certificate));
1012 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1013 this, &PeerConnection::OnCertificateReady);
1014
1015 if (options.disable_encryption) {
1016 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1017 }
1018
1019 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1020 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001021
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001022 return true;
1023}
1024
Steve Anton038834f2017-07-14 15:59:59 -07001025RTCError PeerConnection::ValidateConfiguration(
1026 const RTCConfiguration& config) const {
1027 if (config.ice_regather_interval_range &&
1028 config.continual_gathering_policy == GATHER_ONCE) {
1029 return RTCError(RTCErrorType::INVALID_PARAMETER,
1030 "ice_regather_interval_range specified but continual "
1031 "gathering policy is GATHER_ONCE");
1032 }
1033 return RTCError::OK();
1034}
1035
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001036rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001038 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001039}
1040
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001041rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001043 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001044}
1045
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001046bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001047 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001048 if (IsClosed()) {
1049 return false;
1050 }
deadbeefab9b2d12015-10-14 11:33:11 -07001051 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001052 return false;
1053 }
deadbeefab9b2d12015-10-14 11:33:11 -07001054
1055 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001056 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1057 observer->SignalAudioTrackAdded.connect(this,
1058 &PeerConnection::OnAudioTrackAdded);
1059 observer->SignalAudioTrackRemoved.connect(
1060 this, &PeerConnection::OnAudioTrackRemoved);
1061 observer->SignalVideoTrackAdded.connect(this,
1062 &PeerConnection::OnVideoTrackAdded);
1063 observer->SignalVideoTrackRemoved.connect(
1064 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001065 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001066
deadbeefab9b2d12015-10-14 11:33:11 -07001067 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001068 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001069 }
1070 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001071 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001072 }
1073
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001074 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001075 observer_->OnRenegotiationNeeded();
1076 return true;
1077}
1078
1079void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001080 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001081 if (!IsClosed()) {
1082 for (const auto& track : local_stream->GetAudioTracks()) {
1083 RemoveAudioTrack(track.get(), local_stream);
1084 }
1085 for (const auto& track : local_stream->GetVideoTracks()) {
1086 RemoveVideoTrack(track.get(), local_stream);
1087 }
deadbeefab9b2d12015-10-14 11:33:11 -07001088 }
deadbeefab9b2d12015-10-14 11:33:11 -07001089 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001090 stream_observers_.erase(
1091 std::remove_if(
1092 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001093 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001094 return observer->stream()->label().compare(local_stream->label()) ==
1095 0;
1096 }),
1097 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001098
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001099 if (IsClosed()) {
1100 return;
1101 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001102 observer_->OnRenegotiationNeeded();
1103}
1104
deadbeefe1f9d832016-01-14 15:35:42 -08001105rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1106 MediaStreamTrackInterface* track,
1107 std::vector<MediaStreamInterface*> streams) {
1108 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1109 if (IsClosed()) {
1110 return nullptr;
1111 }
1112 if (streams.size() >= 2) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001113 RTC_LOG(LS_ERROR)
deadbeefe1f9d832016-01-14 15:35:42 -08001114 << "Adding a track with two streams is not currently supported.";
1115 return nullptr;
1116 }
1117 // TODO(deadbeef): Support adding a track to two different senders.
1118 if (FindSenderForTrack(track) != senders_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001119 RTC_LOG(LS_ERROR) << "Sender for track " << track->id()
1120 << " already exists.";
deadbeefe1f9d832016-01-14 15:35:42 -08001121 return nullptr;
1122 }
1123
1124 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001125 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001126 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001127 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001128 signaling_thread(),
1129 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001130 voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -08001131 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001132 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001133 }
1134 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -07001135 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -08001136 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001137 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001138 }
1139 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001140 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001141 signaling_thread(),
1142 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001143 video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -08001144 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001145 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001146 }
1147 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -07001148 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -08001149 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001150 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001151 }
1152 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001153 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: "
1154 << track->kind();
deadbeefe1f9d832016-01-14 15:35:42 -08001155 return rtc::scoped_refptr<RtpSenderInterface>();
1156 }
1157
1158 senders_.push_back(new_sender);
1159 observer_->OnRenegotiationNeeded();
1160 return new_sender;
1161}
1162
1163bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1164 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1165 if (IsClosed()) {
1166 return false;
1167 }
1168
1169 auto it = std::find(senders_.begin(), senders_.end(), sender);
1170 if (it == senders_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001171 RTC_LOG(LS_ERROR) << "Couldn't find sender " << sender->id()
1172 << " to remove.";
deadbeefe1f9d832016-01-14 15:35:42 -08001173 return false;
1174 }
deadbeefa601f5c2016-06-06 14:27:39 -07001175 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -08001176 senders_.erase(it);
1177
1178 observer_->OnRenegotiationNeeded();
1179 return true;
1180}
1181
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001182rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001183 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001184 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001185 if (IsClosed()) {
1186 return nullptr;
1187 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001188 if (!track) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001189 RTC_LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001190 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 }
deadbeef20cb0c12017-02-01 20:27:00 -08001192 auto it = FindSenderForTrack(track);
1193 if (it == senders_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001194 RTC_LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
deadbeef20cb0c12017-02-01 20:27:00 -08001195 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001196 }
1197
deadbeef20cb0c12017-02-01 20:27:00 -08001198 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001199}
1200
deadbeeffac06552015-11-25 11:26:01 -08001201rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001202 const std::string& kind,
1203 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001204 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001205 if (IsClosed()) {
1206 return nullptr;
1207 }
deadbeefa601f5c2016-06-06 14:27:39 -07001208 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001209 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001210 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001211 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -08001212 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001213 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001214 signaling_thread(), new VideoRtpSender(video_channel()));
deadbeeffac06552015-11-25 11:26:01 -08001215 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001216 RTC_LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -08001217 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001218 }
deadbeefbd7d8f72015-12-18 16:58:44 -08001219 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001220 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001221 }
deadbeeffac06552015-11-25 11:26:01 -08001222 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001223 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001224}
1225
deadbeef70ab1a12015-09-28 16:53:55 -07001226std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1227 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001228 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
1229 for (const auto& sender : senders_) {
1230 ret.push_back(sender.get());
1231 }
1232 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001233}
1234
1235std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1236PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001237 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
1238 for (const auto& receiver : receivers_) {
1239 ret.push_back(receiver.get());
1240 }
1241 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001242}
1243
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001244bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001245 MediaStreamTrackInterface* track,
1246 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001247 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001248 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001249 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001250 RTC_LOG(LS_ERROR) << "GetStats - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001251 return false;
1252 }
1253
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001254 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001255 // The StatsCollector is used to tell if a track is valid because it may
1256 // remember tracks that the PeerConnection previously removed.
1257 if (track && !stats_->IsValidTrack(track->id())) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001258 RTC_LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1259 << track->id();
zhihuange9e94c32016-11-04 11:38:15 -07001260 return false;
1261 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001262 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001263 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001264 return true;
1265}
1266
hbos74e1a4f2016-09-15 23:33:01 -07001267void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1268 RTC_DCHECK(stats_collector_);
1269 stats_collector_->GetStatsReport(callback);
1270}
1271
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001272PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1273 return signaling_state_;
1274}
1275
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001276PeerConnectionInterface::IceConnectionState
1277PeerConnection::ice_connection_state() {
1278 return ice_connection_state_;
1279}
1280
1281PeerConnectionInterface::IceGatheringState
1282PeerConnection::ice_gathering_state() {
1283 return ice_gathering_state_;
1284}
1285
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001286rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001287PeerConnection::CreateDataChannel(
1288 const std::string& label,
1289 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001290 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001291
deadbeefab9b2d12015-10-14 11:33:11 -07001292 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001293
kwibergd1fe2812016-04-27 06:47:29 -07001294 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001295 if (config) {
1296 internal_config.reset(new InternalDataChannelInit(*config));
1297 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001298 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001299 InternalCreateDataChannel(label, internal_config.get()));
1300 if (!channel.get()) {
1301 return nullptr;
1302 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001303
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001304 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1305 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001306 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001307 observer_->OnRenegotiationNeeded();
1308 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001309
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001310 return DataChannelProxy::Create(signaling_thread(), channel.get());
1311}
1312
1313void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1314 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001315 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001316
zhihuang1c378ed2017-08-17 14:10:50 -07001317 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1318 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1319 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1320 // compares the mandatory fields parsed with the mandatory fields added in the
1321 // |constraints| and some downstream applications might create offers with
1322 // mandatory fields which would not be parsed in the helper method. For
1323 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1324 // |constraints| as a mandatory field but it is not parsed.
1325 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001326
zhihuang1c378ed2017-08-17 14:10:50 -07001327 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001328}
1329
1330void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1331 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001332 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001333
nisse7ce109a2017-01-31 00:57:56 -08001334 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001335 RTC_LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001336 return;
1337 }
deadbeefab9b2d12015-10-14 11:33:11 -07001338
Steve Anton8d3444d2017-10-20 15:30:51 -07001339 if (IsClosed()) {
1340 std::string error = "CreateOffer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001341 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001342 PostCreateSessionDescriptionFailure(observer, error);
1343 return;
1344 }
1345
zhihuang1c378ed2017-08-17 14:10:50 -07001346 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001347 std::string error = "CreateOffer called with invalid options.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001348 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001349 PostCreateSessionDescriptionFailure(observer, error);
1350 return;
1351 }
1352
zhihuang1c378ed2017-08-17 14:10:50 -07001353 cricket::MediaSessionOptions session_options;
1354 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001355 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001356}
1357
1358void PeerConnection::CreateAnswer(
1359 CreateSessionDescriptionObserver* observer,
1360 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001361 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001362
nisse7ce109a2017-01-31 00:57:56 -08001363 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001364 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001365 return;
1366 }
deadbeefab9b2d12015-10-14 11:33:11 -07001367
zhihuang1c378ed2017-08-17 14:10:50 -07001368 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1369 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1370 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001371 std::string error = "CreateAnswer called with invalid constraints.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001372 RTC_LOG(LS_ERROR) << error;
deadbeefab9b2d12015-10-14 11:33:11 -07001373 PostCreateSessionDescriptionFailure(observer, error);
1374 return;
1375 }
1376
Steve Anton8d3444d2017-10-20 15:30:51 -07001377 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001378}
1379
1380void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1381 const RTCOfferAnswerOptions& options) {
1382 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001383 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001384 RTC_LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
htaa2a49d92016-03-04 02:51:39 -08001385 return;
1386 }
1387
Steve Anton8d3444d2017-10-20 15:30:51 -07001388 if (IsClosed()) {
1389 std::string error = "CreateAnswer called when PeerConnection is closed.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001390 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001391 PostCreateSessionDescriptionFailure(observer, error);
1392 return;
1393 }
1394
Steve Anton75737c02017-11-06 10:37:17 -08001395 if (remote_description() &&
1396 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001397 std::string error = "CreateAnswer called without remote offer.";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001398 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001399 PostCreateSessionDescriptionFailure(observer, error);
1400 return;
1401 }
1402
htaa2a49d92016-03-04 02:51:39 -08001403 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001404 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001405
Steve Antond25da372017-11-06 14:50:29 -08001406 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001407}
1408
1409void PeerConnection::SetLocalDescription(
1410 SetSessionDescriptionObserver* observer,
1411 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001412 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -08001413 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001414 RTC_LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001415 return;
1416 }
1417 if (!desc) {
1418 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1419 return;
1420 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001421
1422 // Takes the ownership of |desc| regardless of the result.
1423 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1424
1425 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001426 std::string error = "Failed to set local " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001427 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001428 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001429 PostSetSessionDescriptionFailure(observer, error);
1430 return;
1431 }
1432
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001433 // Update stats here so that we have the most recent stats for tracks and
1434 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001435 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001436 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001437 // Takes the ownership of |desc_temp|. On success, local_description() is
1438 // updated to reflect the description that was passed in.
Steve Anton75737c02017-11-06 10:37:17 -08001439 if (!SetLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001440 PostSetSessionDescriptionFailure(observer, error);
1441 return;
1442 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001443 RTC_DCHECK(local_description());
deadbeefab9b2d12015-10-14 11:33:11 -07001444
1445 // If setting the description decided our SSL role, allocate any necessary
1446 // SCTP sids.
1447 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001448 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001449 AllocateSctpSids(role);
1450 }
1451
1452 // Update state and SSRC of local MediaStreams and DataChannels based on the
1453 // local session description.
1454 const cricket::ContentInfo* audio_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001455 GetFirstAudioContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001456 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001457 if (audio_content->rejected) {
1458 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1459 } else {
1460 const cricket::AudioContentDescription* audio_desc =
1461 static_cast<const cricket::AudioContentDescription*>(
1462 audio_content->description);
1463 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1464 }
deadbeefab9b2d12015-10-14 11:33:11 -07001465 }
1466
1467 const cricket::ContentInfo* video_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001468 GetFirstVideoContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001469 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001470 if (video_content->rejected) {
1471 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1472 } else {
1473 const cricket::VideoContentDescription* video_desc =
1474 static_cast<const cricket::VideoContentDescription*>(
1475 video_content->description);
1476 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1477 }
deadbeefab9b2d12015-10-14 11:33:11 -07001478 }
1479
1480 const cricket::ContentInfo* data_content =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001481 GetFirstDataContent(local_description()->description());
deadbeefab9b2d12015-10-14 11:33:11 -07001482 if (data_content) {
1483 const cricket::DataContentDescription* data_desc =
1484 static_cast<const cricket::DataContentDescription*>(
1485 data_content->description);
1486 if (rtc::starts_with(data_desc->protocol().data(),
1487 cricket::kMediaProtocolRtpPrefix)) {
1488 UpdateLocalRtpDataChannels(data_desc->streams());
1489 }
1490 }
1491
1492 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001493 signaling_thread()->Post(RTC_FROM_HERE, this,
1494 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001495
deadbeef42a42632017-03-10 15:18:00 -08001496 // According to JSEP, after setLocalDescription, changing the candidate pool
1497 // size is not allowed, and changing the set of ICE servers will not result
1498 // in new candidates being gathered.
1499 port_allocator_->FreezeCandidatePool();
1500
deadbeefcbecd352015-09-23 11:50:27 -07001501 // MaybeStartGathering needs to be called after posting
1502 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1503 // before signaling that SetLocalDescription completed.
Steve Antond25da372017-11-06 14:50:29 -08001504 transport_controller_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001505
Henrik Boströmfdb92012017-11-09 19:55:44 +01001506 if (local_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001507 // TODO(deadbeef): We already had to hop to the network thread for
1508 // MaybeStartGathering...
1509 network_thread()->Invoke<void>(
1510 RTC_FROM_HERE,
1511 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1512 port_allocator_.get()));
1513 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001514}
1515
1516void PeerConnection::SetRemoteDescription(
1517 SetSessionDescriptionObserver* observer,
1518 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001519 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001520 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001521 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001522 return;
1523 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001524 if (!desc) {
1525 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1526 return;
1527 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001528
1529 // Takes the ownership of |desc| regardless of the result.
1530 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1531
1532 if (IsClosed()) {
Henrik Boströmfdb92012017-11-09 19:55:44 +01001533 std::string error = "Failed to set remote " + desc_temp->type() +
Steve Anton8d3444d2017-10-20 15:30:51 -07001534 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001535 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001536 PostSetSessionDescriptionFailure(observer, error);
1537 return;
1538 }
1539
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001540 // Update stats here so that we have the most recent stats for tracks and
1541 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001542 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001543 std::string error;
Henrik Boströmfdb92012017-11-09 19:55:44 +01001544 // Takes the ownership of |desc_temp|. On success, remote_description() is
1545 // updated to reflect the description that was passed in.
Steve Anton75737c02017-11-06 10:37:17 -08001546 if (!SetRemoteDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001547 PostSetSessionDescriptionFailure(observer, error);
1548 return;
1549 }
Henrik Boströmfdb92012017-11-09 19:55:44 +01001550 RTC_DCHECK(remote_description());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001551
deadbeefab9b2d12015-10-14 11:33:11 -07001552 // If setting the description decided our SSL role, allocate any necessary
1553 // SCTP sids.
1554 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001555 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001556 AllocateSctpSids(role);
1557 }
1558
Henrik Boströmfdb92012017-11-09 19:55:44 +01001559 const cricket::ContentInfo* audio_content =
1560 GetFirstAudioContent(remote_description()->description());
1561 const cricket::ContentInfo* video_content =
1562 GetFirstVideoContent(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001563 const cricket::AudioContentDescription* audio_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001564 GetFirstAudioContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001565 const cricket::VideoContentDescription* video_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001566 GetFirstVideoContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001567 const cricket::DataContentDescription* data_desc =
Henrik Boströmfdb92012017-11-09 19:55:44 +01001568 GetFirstDataContentDescription(remote_description()->description());
deadbeefbda7e0b2015-12-08 17:13:40 -08001569
1570 // Check if the descriptions include streams, just in case the peer supports
1571 // MSID, but doesn't indicate so with "a=msid-semantic".
Henrik Boströmfdb92012017-11-09 19:55:44 +01001572 if (remote_description()->description()->msid_supported() ||
deadbeefbda7e0b2015-12-08 17:13:40 -08001573 (audio_desc && !audio_desc->streams().empty()) ||
1574 (video_desc && !video_desc->streams().empty())) {
1575 remote_peer_supports_msid_ = true;
1576 }
deadbeefab9b2d12015-10-14 11:33:11 -07001577
1578 // We wait to signal new streams until we finish processing the description,
1579 // since only at that point will new streams have all their tracks.
1580 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1581
Steve Anton8d3444d2017-10-20 15:30:51 -07001582 // TODO(steveanton): When removing RTP senders/receivers in response to a
1583 // rejected media section, there is some cleanup logic that expects the voice/
1584 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001585 // would have been destroyed by the SetRemoteDescription caller above so the
1586 // cleanup that relies on them fails to run. The RemoveTracks calls should be
1587 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001588
deadbeefab9b2d12015-10-14 11:33:11 -07001589 // Find all audio rtp streams and create corresponding remote AudioTracks
1590 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001591 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001592 if (audio_content->rejected) {
1593 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1594 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001595 bool default_audio_track_needed =
1596 !remote_peer_supports_msid_ &&
1597 MediaContentDirectionHasSend(audio_desc->direction());
1598 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1599 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001600 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001601 }
deadbeefab9b2d12015-10-14 11:33:11 -07001602 }
1603
1604 // Find all video rtp streams and create corresponding remote VideoTracks
1605 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001606 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001607 if (video_content->rejected) {
1608 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1609 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001610 bool default_video_track_needed =
1611 !remote_peer_supports_msid_ &&
1612 MediaContentDirectionHasSend(video_desc->direction());
1613 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1614 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001615 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001616 }
deadbeefab9b2d12015-10-14 11:33:11 -07001617 }
1618
1619 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001620 if (data_desc) {
1621 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001622 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001623 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001624 }
1625 }
1626
1627 // Iterate new_streams and notify the observer about new MediaStreams.
1628 for (size_t i = 0; i < new_streams->count(); ++i) {
1629 MediaStreamInterface* new_stream = new_streams->at(i);
1630 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001631 observer_->OnAddStream(
1632 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001633 }
1634
deadbeefbda7e0b2015-12-08 17:13:40 -08001635 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001636
1637 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001638 signaling_thread()->Post(RTC_FROM_HERE, this,
1639 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001640
Henrik Boströmfdb92012017-11-09 19:55:44 +01001641 if (remote_description()->type() == SessionDescriptionInterface::kAnswer) {
deadbeef42a42632017-03-10 15:18:00 -08001642 // TODO(deadbeef): We already had to hop to the network thread for
1643 // MaybeStartGathering...
1644 network_thread()->Invoke<void>(
1645 RTC_FROM_HERE,
1646 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1647 port_allocator_.get()));
1648 }
deadbeeffc648b62015-10-13 16:42:33 -07001649}
1650
deadbeef46c73892016-11-16 19:42:04 -08001651PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1652 return configuration_;
1653}
1654
deadbeef293e9262017-01-11 12:28:30 -08001655bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1656 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001657 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001658
Steve Anton75737c02017-11-06 10:37:17 -08001659 if (local_description() && configuration.ice_candidate_pool_size !=
1660 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001661 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1662 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001663 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001664 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001665
deadbeef293e9262017-01-11 12:28:30 -08001666 // The simplest (and most future-compatible) way to tell if the config was
1667 // modified in an invalid way is to copy each property we do support
1668 // modifying, then use operator==. There are far more properties we don't
1669 // support modifying than those we do, and more could be added.
1670 RTCConfiguration modified_config = configuration_;
1671 modified_config.servers = configuration.servers;
1672 modified_config.type = configuration.type;
1673 modified_config.ice_candidate_pool_size =
1674 configuration.ice_candidate_pool_size;
1675 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001676 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001677 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001678 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001679 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001680 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1681 }
1682
Steve Anton038834f2017-07-14 15:59:59 -07001683 // Validate the modified configuration.
1684 RTCError validate_error = ValidateConfiguration(modified_config);
1685 if (!validate_error.ok()) {
1686 return SafeSetError(std::move(validate_error), error);
1687 }
1688
deadbeef293e9262017-01-11 12:28:30 -08001689 // Note that this isn't possible through chromium, since it's an unsigned
1690 // short in WebIDL.
1691 if (configuration.ice_candidate_pool_size < 0 ||
1692 configuration.ice_candidate_pool_size > UINT16_MAX) {
1693 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1694 }
1695
1696 // Parse ICE servers before hopping to network thread.
1697 cricket::ServerAddresses stun_servers;
1698 std::vector<cricket::RelayServerConfig> turn_servers;
1699 RTCErrorType parse_error =
1700 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1701 if (parse_error != RTCErrorType::NONE) {
1702 return SafeSetError(parse_error, error);
1703 }
1704
1705 // In theory this shouldn't fail.
1706 if (!network_thread()->Invoke<bool>(
1707 RTC_FROM_HERE,
1708 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1709 stun_servers, turn_servers, modified_config.type,
1710 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001711 modified_config.prune_turn_ports,
1712 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001713 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001714 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1715 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001716
deadbeefd1a38b52016-12-10 13:15:33 -08001717 // As described in JSEP, calling setConfiguration with new ICE servers or
1718 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1719 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001720 if (modified_config.servers != configuration_.servers ||
1721 modified_config.type != configuration_.type ||
1722 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001723 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001724 }
skvladd1f5fda2017-02-03 16:54:05 -08001725
1726 if (modified_config.ice_check_min_interval !=
1727 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001728 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001729 }
1730
deadbeef293e9262017-01-11 12:28:30 -08001731 configuration_ = modified_config;
1732 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001733}
1734
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001735bool PeerConnection::AddIceCandidate(
1736 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001737 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001738 if (IsClosed()) {
1739 return false;
1740 }
Steve Antond25da372017-11-06 14:50:29 -08001741
1742 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001743 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1744 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001745 return false;
1746 }
1747
1748 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001749 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001750 return false;
1751 }
1752
1753 bool valid = false;
1754 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1755 if (!valid) {
1756 return false;
1757 }
1758
1759 // Add this candidate to the remote session description.
1760 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001761 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001762 return false;
1763 }
1764
1765 if (ready) {
1766 return UseCandidate(ice_candidate);
1767 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001768 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001769 return true;
1770 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001771}
1772
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001773bool PeerConnection::RemoveIceCandidates(
1774 const std::vector<cricket::Candidate>& candidates) {
1775 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001776 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001777 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1778 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001779 return false;
1780 }
1781
1782 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001783 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08001784 return false;
1785 }
1786
1787 size_t number_removed =
1788 mutable_remote_description()->RemoveCandidates(candidates);
1789 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001790 RTC_LOG(LS_ERROR)
1791 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
1792 << "Requested " << candidates.size() << " but only " << number_removed
1793 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08001794 }
1795
1796 // Remove the candidates from the transport controller.
1797 std::string error;
1798 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
1799 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001800 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08001801 }
1802 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001803}
1804
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001805void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001806 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001807 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001808
Steve Anton75737c02017-11-06 10:37:17 -08001809 if (transport_controller()) {
1810 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001811 }
1812
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001813 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001814 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001815 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001816 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001817 uma_observer_->IncrementEnumCounter(
1818 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1819 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001820 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001821 uma_observer_->IncrementEnumCounter(
1822 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1823 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001824 }
1825 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001826}
1827
zstein4b979802017-06-02 14:37:37 -07001828RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001829 if (!worker_thread()->IsCurrent()) {
1830 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001831 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1832 }
1833
1834 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1835 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1836 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1837 if (has_min && *bitrate.min_bitrate_bps < 0) {
1838 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1839 "min_bitrate_bps <= 0");
1840 }
1841 if (has_current) {
1842 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1843 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1844 "current_bitrate_bps < min_bitrate_bps");
1845 } else if (*bitrate.current_bitrate_bps < 0) {
1846 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1847 "curent_bitrate_bps < 0");
1848 }
1849 }
1850 if (has_max) {
1851 if (has_current &&
1852 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1853 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1854 "max_bitrate_bps < current_bitrate_bps");
1855 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1856 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1857 "max_bitrate_bps < min_bitrate_bps");
1858 } else if (*bitrate.max_bitrate_bps < 0) {
1859 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1860 "max_bitrate_bps < 0");
1861 }
1862 }
1863
1864 Call::Config::BitrateConfigMask mask;
1865 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1866 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1867 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1868
1869 RTC_DCHECK(call_.get());
1870 call_->SetBitrateConfigMask(mask);
1871
1872 return RTCError::OK();
1873}
1874
Alex Narest78609d52017-10-20 10:37:47 +02001875void PeerConnection::SetBitrateAllocationStrategy(
1876 std::unique_ptr<rtc::BitrateAllocationStrategy>
1877 bitrate_allocation_strategy) {
1878 rtc::Thread* worker_thread = factory_->worker_thread();
1879 if (!worker_thread->IsCurrent()) {
1880 rtc::BitrateAllocationStrategy* strategy_raw =
1881 bitrate_allocation_strategy.release();
1882 auto functor = [this, strategy_raw]() {
1883 call_->SetBitrateAllocationStrategy(
1884 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
1885 };
1886 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
1887 return;
1888 }
1889 RTC_DCHECK(call_.get());
1890 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
1891}
1892
henrika5f6bf242017-11-01 11:06:56 +01001893void PeerConnection::SetAudioPlayout(bool playout) {
1894 if (!worker_thread()->IsCurrent()) {
1895 worker_thread()->Invoke<void>(
1896 RTC_FROM_HERE,
1897 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
1898 return;
1899 }
1900 auto audio_state =
1901 factory_->channel_manager()->media_engine()->GetAudioState();
1902 audio_state->SetPlayout(playout);
1903}
1904
1905void PeerConnection::SetAudioRecording(bool recording) {
1906 if (!worker_thread()->IsCurrent()) {
1907 worker_thread()->Invoke<void>(
1908 RTC_FROM_HERE,
1909 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
1910 return;
1911 }
1912 auto audio_state =
1913 factory_->channel_manager()->media_engine()->GetAudioState();
1914 audio_state->SetRecording(recording);
1915}
1916
Steve Anton8c0f7a72017-10-03 10:03:10 -07001917std::unique_ptr<rtc::SSLCertificate>
1918PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08001919 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07001920 return nullptr;
1921 }
Steve Anton75737c02017-11-06 10:37:17 -08001922 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001923}
1924
ivoc14d5dbe2016-07-04 07:06:55 -07001925bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1926 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02001927 // TODO(eladalon): It would be better to not allow negative values into PC.
1928 const size_t max_size = (max_size_bytes < 0)
1929 ? RtcEventLog::kUnlimitedOutput
1930 : rtc::saturated_cast<size_t>(max_size_bytes);
1931 return StartRtcEventLog(
1932 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size));
1933}
1934
1935bool PeerConnection::StartRtcEventLog(
1936 std::unique_ptr<RtcEventLogOutput> output) {
Karl Wibergd6b48192017-10-16 23:01:06 +02001937 // TODO(eladalon): In C++14, this can be done with a lambda.
1938 struct Functor {
1939 bool operator()() { return pc->StartRtcEventLog_w(std::move(output)); }
1940 PeerConnection* const pc;
1941 std::unique_ptr<RtcEventLogOutput> output;
Elad Alon99c3fe52017-10-13 16:29:40 +02001942 };
Karl Wibergd6b48192017-10-16 23:01:06 +02001943 return worker_thread()->Invoke<bool>(RTC_FROM_HERE,
1944 Functor{this, std::move(output)});
ivoc14d5dbe2016-07-04 07:06:55 -07001945}
1946
1947void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001948 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001949 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1950}
1951
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001952const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08001953 return pending_local_description_ ? pending_local_description_.get()
1954 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001955}
1956
1957const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08001958 return pending_remote_description_ ? pending_remote_description_.get()
1959 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001960}
1961
deadbeeffe4a8a42016-12-20 17:56:17 -08001962const SessionDescriptionInterface* PeerConnection::current_local_description()
1963 const {
Steve Anton75737c02017-11-06 10:37:17 -08001964 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001965}
1966
1967const SessionDescriptionInterface* PeerConnection::current_remote_description()
1968 const {
Steve Anton75737c02017-11-06 10:37:17 -08001969 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001970}
1971
1972const SessionDescriptionInterface* PeerConnection::pending_local_description()
1973 const {
Steve Anton75737c02017-11-06 10:37:17 -08001974 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001975}
1976
1977const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1978 const {
Steve Anton75737c02017-11-06 10:37:17 -08001979 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001980}
1981
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001982void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001983 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001984 // Update stats here so that we have the most recent stats for tracks and
1985 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001986 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001987
Steve Anton75737c02017-11-06 10:37:17 -08001988 ChangeSignalingState(PeerConnectionInterface::kClosed);
1989 RemoveUnusedChannels(nullptr);
1990 RTC_DCHECK(voice_channels_.empty());
1991 RTC_DCHECK(video_channels_.empty());
1992 RTC_DCHECK(!rtp_data_channel_);
1993 RTC_DCHECK(!sctp_transport_);
1994
deadbeef42a42632017-03-10 15:18:00 -08001995 network_thread()->Invoke<void>(
1996 RTC_FROM_HERE,
1997 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1998 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001999
Steve Anton978b8762017-09-29 12:15:02 -07002000 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07002001 call_.reset();
2002 // The event log must outlive call (and any other object that uses it).
2003 event_log_.reset();
2004 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002005}
2006
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002007void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002008 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002009 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2010 SetSessionDescriptionMsg* param =
2011 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2012 param->observer->OnSuccess();
2013 delete param;
2014 break;
2015 }
2016 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2017 SetSessionDescriptionMsg* param =
2018 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2019 param->observer->OnFailure(param->error);
2020 delete param;
2021 break;
2022 }
deadbeefab9b2d12015-10-14 11:33:11 -07002023 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2024 CreateSessionDescriptionMsg* param =
2025 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2026 param->observer->OnFailure(param->error);
2027 delete param;
2028 break;
2029 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002030 case MSG_GETSTATS: {
2031 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002032 StatsReports reports;
2033 stats_->GetStats(param->track, &reports);
2034 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002035 delete param;
2036 break;
2037 }
deadbeefbd292462015-12-14 18:15:29 -08002038 case MSG_FREE_DATACHANNELS: {
2039 sctp_data_channels_to_free_.clear();
2040 break;
2041 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002042 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002043 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002044 break;
2045 }
2046}
2047
deadbeefab9b2d12015-10-14 11:33:11 -07002048void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07002049 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07002050 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08002051 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2052 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002053 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002054 new AudioRtpReceiver(track_id, ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002055 stream->AddTrack(
2056 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08002057 receivers_.push_back(receiver);
2058 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2059 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
2060 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002061}
2062
deadbeefab9b2d12015-10-14 11:33:11 -07002063void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01002064 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07002065 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08002066 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2067 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002068 signaling_thread(), new VideoRtpReceiver(track_id, worker_thread(),
2069 ssrc, video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002070 stream->AddTrack(
2071 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08002072 receivers_.push_back(receiver);
2073 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2074 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
2075 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002076}
2077
deadbeef70ab1a12015-09-28 16:53:55 -07002078// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2079// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002080rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
2081 const std::string& track_id) {
perkjd61bf802016-03-24 03:16:19 -07002082 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07002083 if (it == receivers_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002084 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
2085 << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002086 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002087 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002088 (*it)->internal()->Stop();
2089 rtc::scoped_refptr<RtpReceiverInterface> receiver = *it;
2090 receivers_.erase(it);
2091 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002092}
2093
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002094void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2095 MediaStreamInterface* stream) {
2096 RTC_DCHECK(!IsClosed());
2097 auto sender = FindSenderForTrack(track);
2098 if (sender != senders_.end()) {
2099 // We already have a sender for this track, so just change the stream_id
2100 // so that it's correct in the next call to CreateOffer.
2101 (*sender)->internal()->set_stream_id(stream->label());
2102 return;
2103 }
2104
2105 // Normal case; we've never seen this track before.
2106 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2107 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2108 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002109 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2110 stats_.get()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002111 senders_.push_back(new_sender);
2112 // If the sender has already been configured in SDP, we call SetSsrc,
2113 // which will connect the sender to the underlying transport. This can
2114 // occur if a local session description that contains the ID of the sender
2115 // is set before AddStream is called. It can also occur if the local
2116 // session description is not changed and RemoveStream is called, and
2117 // later AddStream is called again with the same stream.
2118 const TrackInfo* track_info =
2119 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
2120 if (track_info) {
2121 new_sender->internal()->SetSsrc(track_info->ssrc);
2122 }
2123}
2124
2125// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2126// indefinitely, when we have unified plan SDP.
2127void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2128 MediaStreamInterface* stream) {
2129 RTC_DCHECK(!IsClosed());
2130 auto sender = FindSenderForTrack(track);
2131 if (sender == senders_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002132 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2133 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002134 return;
2135 }
2136 (*sender)->internal()->Stop();
2137 senders_.erase(sender);
2138}
2139
2140void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2141 MediaStreamInterface* stream) {
2142 RTC_DCHECK(!IsClosed());
2143 auto sender = FindSenderForTrack(track);
2144 if (sender != senders_.end()) {
2145 // We already have a sender for this track, so just change the stream_id
2146 // so that it's correct in the next call to CreateOffer.
2147 (*sender)->internal()->set_stream_id(stream->label());
2148 return;
2149 }
2150
2151 // Normal case; we've never seen this track before.
2152 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2153 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002154 signaling_thread(),
2155 new VideoRtpSender(track, {stream->label()}, video_channel()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002156 senders_.push_back(new_sender);
2157 const TrackInfo* track_info =
2158 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
2159 if (track_info) {
2160 new_sender->internal()->SetSsrc(track_info->ssrc);
2161 }
2162}
2163
2164void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2165 MediaStreamInterface* stream) {
2166 RTC_DCHECK(!IsClosed());
2167 auto sender = FindSenderForTrack(track);
2168 if (sender == senders_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002169 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2170 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002171 return;
2172 }
2173 (*sender)->internal()->Stop();
2174 senders_.erase(sender);
2175}
2176
Steve Antonba818672017-11-06 10:21:57 -08002177void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002178 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002179 if (ice_connection_state_ == new_state) {
2180 return;
2181 }
2182
deadbeefcbecd352015-09-23 11:50:27 -07002183 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002184 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002185 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002186 return;
2187 }
Steve Antonba818672017-11-06 10:21:57 -08002188
Mirko Bonadei675513b2017-11-09 11:09:25 +01002189 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2190 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002191 RTC_DCHECK(ice_connection_state_ !=
2192 PeerConnectionInterface::kIceConnectionClosed);
2193
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002194 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002195 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002196}
2197
2198void PeerConnection::OnIceGatheringChange(
2199 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002200 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002201 if (IsClosed()) {
2202 return;
2203 }
2204 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002205 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002206}
2207
jbauch81bf7b02017-03-25 08:31:12 -07002208void PeerConnection::OnIceCandidate(
2209 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002210 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002211 if (IsClosed()) {
2212 return;
2213 }
jbauch81bf7b02017-03-25 08:31:12 -07002214 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002215}
2216
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002217void PeerConnection::OnIceCandidatesRemoved(
2218 const std::vector<cricket::Candidate>& candidates) {
2219 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002220 if (IsClosed()) {
2221 return;
2222 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002223 observer_->OnIceCandidatesRemoved(candidates);
2224}
2225
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002226void PeerConnection::ChangeSignalingState(
2227 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002228 RTC_DCHECK(signaling_thread()->IsCurrent());
2229 if (signaling_state_ == signaling_state) {
2230 return;
2231 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002232 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2233 << GetSignalingStateString(signaling_state_)
2234 << " New state: "
2235 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002236 signaling_state_ = signaling_state;
2237 if (signaling_state == kClosed) {
2238 ice_connection_state_ = kIceConnectionClosed;
2239 observer_->OnIceConnectionChange(ice_connection_state_);
2240 if (ice_gathering_state_ != kIceGatheringComplete) {
2241 ice_gathering_state_ = kIceGatheringComplete;
2242 observer_->OnIceGatheringChange(ice_gathering_state_);
2243 }
2244 }
2245 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002246}
2247
deadbeefeb459812015-12-15 19:24:43 -08002248void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2249 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002250 if (IsClosed()) {
2251 return;
2252 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002253 AddAudioTrack(track, stream);
2254 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002255}
2256
deadbeefeb459812015-12-15 19:24:43 -08002257void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2258 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002259 if (IsClosed()) {
2260 return;
2261 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002262 RemoveAudioTrack(track, stream);
2263 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002264}
2265
2266void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2267 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002268 if (IsClosed()) {
2269 return;
2270 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002271 AddVideoTrack(track, stream);
2272 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002273}
2274
2275void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2276 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002277 if (IsClosed()) {
2278 return;
2279 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002280 RemoveVideoTrack(track, stream);
2281 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002282}
2283
deadbeefab9b2d12015-10-14 11:33:11 -07002284void PeerConnection::PostSetSessionDescriptionFailure(
2285 SetSessionDescriptionObserver* observer,
2286 const std::string& error) {
2287 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2288 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002289 signaling_thread()->Post(RTC_FROM_HERE, this,
2290 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002291}
2292
2293void PeerConnection::PostCreateSessionDescriptionFailure(
2294 CreateSessionDescriptionObserver* observer,
2295 const std::string& error) {
2296 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2297 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002298 signaling_thread()->Post(RTC_FROM_HERE, this,
2299 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002300}
2301
zhihuang1c378ed2017-08-17 14:10:50 -07002302void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002303 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2304 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002305 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2306
2307 // Figure out transceiver directional preferences.
2308 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2309 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2310
2311 // By default, generate sendrecv/recvonly m= sections.
2312 bool recv_audio = true;
2313 bool recv_video = true;
2314
2315 // By default, only offer a new m= section if we have media to send with it.
2316 bool offer_new_audio_description = send_audio;
2317 bool offer_new_video_description = send_video;
2318 bool offer_new_data_description = HasDataChannels();
2319
2320 // The "offer_to_receive_X" options allow those defaults to be overridden.
2321 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2322 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2323 offer_new_audio_description =
2324 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2325 }
2326 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2327 recv_video = (rtc_options.offer_to_receive_video > 0);
2328 offer_new_video_description =
2329 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2330 }
2331
2332 rtc::Optional<size_t> audio_index;
2333 rtc::Optional<size_t> video_index;
2334 rtc::Optional<size_t> data_index;
2335 // If a current description exists, generate m= sections in the same order,
2336 // using the first audio/video/data section that appears and rejecting
2337 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002338 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002339 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002340 local_description(),
zhihuang1c378ed2017-08-17 14:10:50 -07002341 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2342 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2343 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002344 }
2345
zhihuang1c378ed2017-08-17 14:10:50 -07002346 // Add audio/video/data m= sections to the end if needed.
2347 if (!audio_index && offer_new_audio_description) {
2348 session_options->media_description_options.push_back(
2349 cricket::MediaDescriptionOptions(
2350 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
2351 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
2352 audio_index = rtc::Optional<size_t>(
2353 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07002354 }
zhihuang1c378ed2017-08-17 14:10:50 -07002355 if (!video_index && offer_new_video_description) {
2356 session_options->media_description_options.push_back(
2357 cricket::MediaDescriptionOptions(
2358 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
2359 cricket::RtpTransceiverDirection(send_video, recv_video), false));
2360 video_index = rtc::Optional<size_t>(
2361 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07002362 }
zhihuang1c378ed2017-08-17 14:10:50 -07002363 if (!data_index && offer_new_data_description) {
2364 session_options->media_description_options.push_back(
2365 cricket::MediaDescriptionOptions(
2366 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
2367 cricket::RtpTransceiverDirection(true, true), false));
2368 data_index = rtc::Optional<size_t>(
2369 session_options->media_description_options.size() - 1);
2370 }
2371
2372 cricket::MediaDescriptionOptions* audio_media_description_options =
2373 !audio_index ? nullptr
2374 : &session_options->media_description_options[*audio_index];
2375 cricket::MediaDescriptionOptions* video_media_description_options =
2376 !video_index ? nullptr
2377 : &session_options->media_description_options[*video_index];
2378 cricket::MediaDescriptionOptions* data_media_description_options =
2379 !data_index ? nullptr
2380 : &session_options->media_description_options[*data_index];
2381
2382 // Apply ICE restart flag and renomination flag.
2383 for (auto& options : session_options->media_description_options) {
2384 options.transport_options.ice_restart = rtc_options.ice_restart;
2385 options.transport_options.enable_ice_renomination =
2386 configuration_.enable_ice_renomination;
2387 }
2388
2389 AddRtpSenderOptions(senders_, audio_media_description_options,
2390 video_media_description_options);
2391 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002392
zhihuang9763d562016-08-05 11:14:50 -07002393 // Intentionally unset the data channel type for RTP data channel with the
2394 // second condition. Otherwise the RTP data channels would be successfully
2395 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2396 // when building with chromium. We want to leave RTP data channels broken, so
2397 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002398 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2399 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002400 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002401
2402 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002403 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002404}
2405
zhihuang1c378ed2017-08-17 14:10:50 -07002406void PeerConnection::GetOptionsForAnswer(
2407 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002408 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002409 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002410
zhihuang1c378ed2017-08-17 14:10:50 -07002411 // Figure out transceiver directional preferences.
2412 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2413 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2414
2415 // By default, generate sendrecv/recvonly m= sections. The direction is also
2416 // restricted by the direction in the offer.
2417 bool recv_audio = true;
2418 bool recv_video = true;
2419
2420 // The "offer_to_receive_X" options allow those defaults to be overridden.
2421 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2422 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002423 }
zhihuang1c378ed2017-08-17 14:10:50 -07002424 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2425 recv_video = (rtc_options.offer_to_receive_video > 0);
2426 }
2427
2428 rtc::Optional<size_t> audio_index;
2429 rtc::Optional<size_t> video_index;
2430 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002431 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002432 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002433 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002434 SessionDescriptionInterface::kOffer);
2435 // Generate m= sections that match those in the offer.
2436 // Note that mediasession.cc will handle intersection our preferred
2437 // direction with the offered direction.
2438 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002439 remote_description(),
zhihuang141aacb2017-08-29 13:23:53 -07002440 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2441 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2442 &video_index, &data_index, session_options);
2443 }
zhihuang1c378ed2017-08-17 14:10:50 -07002444
2445 cricket::MediaDescriptionOptions* audio_media_description_options =
2446 !audio_index ? nullptr
2447 : &session_options->media_description_options[*audio_index];
2448 cricket::MediaDescriptionOptions* video_media_description_options =
2449 !video_index ? nullptr
2450 : &session_options->media_description_options[*video_index];
2451 cricket::MediaDescriptionOptions* data_media_description_options =
2452 !data_index ? nullptr
2453 : &session_options->media_description_options[*data_index];
2454
2455 // Apply ICE renomination flag.
2456 for (auto& options : session_options->media_description_options) {
2457 options.transport_options.enable_ice_renomination =
2458 configuration_.enable_ice_renomination;
2459 }
2460
2461 AddRtpSenderOptions(senders_, audio_media_description_options,
2462 video_media_description_options);
2463 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2464
zhihuang9763d562016-08-05 11:14:50 -07002465 // Intentionally unset the data channel type for RTP data channel. Otherwise
2466 // the RTP data channels would be successfully negotiated by default and the
2467 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2468 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002469 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2470 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002471 }
zhihuangaf388472016-11-02 16:49:48 -07002472
zhihuang1c378ed2017-08-17 14:10:50 -07002473 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002474 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002475}
2476
zhihuang1c378ed2017-08-17 14:10:50 -07002477void PeerConnection::GenerateMediaDescriptionOptions(
2478 const SessionDescriptionInterface* session_desc,
2479 cricket::RtpTransceiverDirection audio_direction,
2480 cricket::RtpTransceiverDirection video_direction,
2481 rtc::Optional<size_t>* audio_index,
2482 rtc::Optional<size_t>* video_index,
2483 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002484 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002485 for (const cricket::ContentInfo& content :
2486 session_desc->description()->contents()) {
2487 if (IsAudioContent(&content)) {
2488 // If we already have an audio m= section, reject this extra one.
2489 if (*audio_index) {
2490 session_options->media_description_options.push_back(
2491 cricket::MediaDescriptionOptions(
2492 cricket::MEDIA_TYPE_AUDIO, content.name,
2493 cricket::RtpTransceiverDirection(false, false), true));
2494 } else {
2495 session_options->media_description_options.push_back(
2496 cricket::MediaDescriptionOptions(
2497 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
2498 !audio_direction.send && !audio_direction.recv));
2499 *audio_index = rtc::Optional<size_t>(
2500 session_options->media_description_options.size() - 1);
2501 }
2502 } else if (IsVideoContent(&content)) {
2503 // If we already have an video m= section, reject this extra one.
2504 if (*video_index) {
2505 session_options->media_description_options.push_back(
2506 cricket::MediaDescriptionOptions(
2507 cricket::MEDIA_TYPE_VIDEO, content.name,
2508 cricket::RtpTransceiverDirection(false, false), true));
2509 } else {
2510 session_options->media_description_options.push_back(
2511 cricket::MediaDescriptionOptions(
2512 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
2513 !video_direction.send && !video_direction.recv));
2514 *video_index = rtc::Optional<size_t>(
2515 session_options->media_description_options.size() - 1);
2516 }
2517 } else {
2518 RTC_DCHECK(IsDataContent(&content));
2519 // If we already have an data m= section, reject this extra one.
2520 if (*data_index) {
2521 session_options->media_description_options.push_back(
2522 cricket::MediaDescriptionOptions(
2523 cricket::MEDIA_TYPE_DATA, content.name,
2524 cricket::RtpTransceiverDirection(false, false), true));
2525 } else {
2526 session_options->media_description_options.push_back(
2527 cricket::MediaDescriptionOptions(
2528 cricket::MEDIA_TYPE_DATA, content.name,
2529 // Direction for data sections is meaningless, but legacy
2530 // endpoints might expect sendrecv.
2531 cricket::RtpTransceiverDirection(true, true), false));
2532 *data_index = rtc::Optional<size_t>(
2533 session_options->media_description_options.size() - 1);
2534 }
2535 }
htaa2a49d92016-03-04 02:51:39 -08002536 }
deadbeefab9b2d12015-10-14 11:33:11 -07002537}
2538
deadbeeffaac4972015-11-12 15:33:07 -08002539void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
2540 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002541 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
2542 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002543}
2544
deadbeefab9b2d12015-10-14 11:33:11 -07002545void PeerConnection::UpdateRemoteStreamsList(
2546 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08002547 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002548 cricket::MediaType media_type,
2549 StreamCollection* new_streams) {
2550 TrackInfos* current_tracks = GetRemoteTracks(media_type);
2551
2552 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002553 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07002554 auto track_it = current_tracks->begin();
2555 while (track_it != current_tracks->end()) {
2556 const TrackInfo& info = *track_it;
2557 const cricket::StreamParams* params =
2558 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08002559 bool track_exists = params && params->id == info.track_id;
2560 // If this is a default track, and we still need it, don't remove it.
2561 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
2562 track_exists) {
2563 ++track_it;
2564 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07002565 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
2566 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002567 }
2568 }
2569
2570 // Find new and active tracks.
2571 for (const cricket::StreamParams& params : streams) {
2572 // The sync_label is the MediaStream label and the |stream.id| is the
2573 // track id.
2574 const std::string& stream_label = params.sync_label;
2575 const std::string& track_id = params.id;
2576 uint32_t ssrc = params.first_ssrc();
2577
2578 rtc::scoped_refptr<MediaStreamInterface> stream =
2579 remote_streams_->find(stream_label);
2580 if (!stream) {
2581 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002582 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2583 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002584 remote_streams_->AddStream(stream);
2585 new_streams->AddStream(stream);
2586 }
2587
2588 const TrackInfo* track_info =
2589 FindTrackInfo(*current_tracks, stream_label, track_id);
2590 if (!track_info) {
2591 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2592 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2593 }
2594 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002595
2596 // Add default track if necessary.
2597 if (default_track_needed) {
2598 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2599 remote_streams_->find(kDefaultStreamLabel);
2600 if (!default_stream) {
2601 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002602 default_stream = MediaStreamProxy::Create(
2603 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002604 remote_streams_->AddStream(default_stream);
2605 new_streams->AddStream(default_stream);
2606 }
2607 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2608 ? kDefaultAudioTrackLabel
2609 : kDefaultVideoTrackLabel;
2610 const TrackInfo* default_track_info =
2611 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2612 if (!default_track_info) {
2613 current_tracks->push_back(
2614 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2615 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2616 }
2617 }
deadbeefab9b2d12015-10-14 11:33:11 -07002618}
2619
2620void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2621 const std::string& track_id,
2622 uint32_t ssrc,
2623 cricket::MediaType media_type) {
2624 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2625
2626 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002627 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002628 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002629 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002630 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002631 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002632 }
2633}
2634
2635void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2636 const std::string& track_id,
2637 cricket::MediaType media_type) {
2638 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2639
Henrik Boström933d8b02017-10-10 10:05:16 -07002640 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002641 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002642 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2643 // will be notified which will end the AudioRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002644 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002645 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2646 stream->FindAudioTrack(track_id);
2647 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002648 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002649 }
2650 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002651 // Stopping or destroying a VideoRtpReceiver will end the
2652 // VideoRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002653 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002654 rtc::scoped_refptr<VideoTrackInterface> video_track =
2655 stream->FindVideoTrack(track_id);
2656 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002657 // There's no guarantee the track is still available, e.g. the track may
2658 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002659 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002660 }
2661 } else {
nisseede5da42017-01-12 05:15:36 -08002662 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002663 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002664 if (receiver) {
2665 observer_->OnRemoveTrack(receiver);
2666 }
deadbeefab9b2d12015-10-14 11:33:11 -07002667}
2668
2669void PeerConnection::UpdateEndedRemoteMediaStreams() {
2670 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2671 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2672 MediaStreamInterface* stream = remote_streams_->at(i);
2673 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2674 streams_to_remove.push_back(stream);
2675 }
2676 }
2677
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002678 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002679 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002680 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002681 }
2682}
2683
deadbeefab9b2d12015-10-14 11:33:11 -07002684void PeerConnection::UpdateLocalTracks(
2685 const std::vector<cricket::StreamParams>& streams,
2686 cricket::MediaType media_type) {
2687 TrackInfos* current_tracks = GetLocalTracks(media_type);
2688
2689 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2690 // don't match the new StreamParam.
2691 TrackInfos::iterator track_it = current_tracks->begin();
2692 while (track_it != current_tracks->end()) {
2693 const TrackInfo& info = *track_it;
2694 const cricket::StreamParams* params =
2695 cricket::GetStreamBySsrc(streams, info.ssrc);
2696 if (!params || params->id != info.track_id ||
2697 params->sync_label != info.stream_label) {
2698 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2699 media_type);
2700 track_it = current_tracks->erase(track_it);
2701 } else {
2702 ++track_it;
2703 }
2704 }
2705
2706 // Find new and active tracks.
2707 for (const cricket::StreamParams& params : streams) {
2708 // The sync_label is the MediaStream label and the |stream.id| is the
2709 // track id.
2710 const std::string& stream_label = params.sync_label;
2711 const std::string& track_id = params.id;
2712 uint32_t ssrc = params.first_ssrc();
2713 const TrackInfo* track_info =
2714 FindTrackInfo(*current_tracks, stream_label, track_id);
2715 if (!track_info) {
2716 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2717 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2718 }
2719 }
2720}
2721
2722void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2723 const std::string& track_id,
2724 uint32_t ssrc,
2725 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002726 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002727 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002728 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2729 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002730 return;
2731 }
2732
deadbeeffac06552015-11-25 11:26:01 -08002733 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002734 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2735 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002736 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002737 }
deadbeeffac06552015-11-25 11:26:01 -08002738
2739 sender->set_stream_id(stream_label);
2740 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002741}
2742
2743void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2744 const std::string& track_id,
2745 uint32_t ssrc,
2746 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002747 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002748 if (!sender) {
2749 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002750 // SessionDescriptions has been renegotiated.
2751 return;
2752 }
deadbeeffac06552015-11-25 11:26:01 -08002753
2754 // A sender has been removed from the SessionDescription but it's still
2755 // associated with the PeerConnection. This only occurs if the SDP doesn't
2756 // match with the calls to CreateSender, AddStream and RemoveStream.
2757 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002758 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2759 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002760 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002761 }
deadbeeffac06552015-11-25 11:26:01 -08002762
2763 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002764}
2765
2766void PeerConnection::UpdateLocalRtpDataChannels(
2767 const cricket::StreamParamsVec& streams) {
2768 std::vector<std::string> existing_channels;
2769
2770 // Find new and active data channels.
2771 for (const cricket::StreamParams& params : streams) {
2772 // |it->sync_label| is actually the data channel label. The reason is that
2773 // we use the same naming of data channels as we do for
2774 // MediaStreams and Tracks.
2775 // For MediaStreams, the sync_label is the MediaStream label and the
2776 // track label is the same as |streamid|.
2777 const std::string& channel_label = params.sync_label;
2778 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002779 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002780 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002781 continue;
2782 }
2783 // Set the SSRC the data channel should use for sending.
2784 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2785 existing_channels.push_back(data_channel_it->first);
2786 }
2787
2788 UpdateClosingRtpDataChannels(existing_channels, true);
2789}
2790
2791void PeerConnection::UpdateRemoteRtpDataChannels(
2792 const cricket::StreamParamsVec& streams) {
2793 std::vector<std::string> existing_channels;
2794
2795 // Find new and active data channels.
2796 for (const cricket::StreamParams& params : streams) {
2797 // The data channel label is either the mslabel or the SSRC if the mslabel
2798 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2799 std::string label = params.sync_label.empty()
2800 ? rtc::ToString(params.first_ssrc())
2801 : params.sync_label;
2802 auto data_channel_it = rtp_data_channels_.find(label);
2803 if (data_channel_it == rtp_data_channels_.end()) {
2804 // This is a new data channel.
2805 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2806 } else {
2807 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2808 }
2809 existing_channels.push_back(label);
2810 }
2811
2812 UpdateClosingRtpDataChannels(existing_channels, false);
2813}
2814
2815void PeerConnection::UpdateClosingRtpDataChannels(
2816 const std::vector<std::string>& active_channels,
2817 bool is_local_update) {
2818 auto it = rtp_data_channels_.begin();
2819 while (it != rtp_data_channels_.end()) {
2820 DataChannel* data_channel = it->second;
2821 if (std::find(active_channels.begin(), active_channels.end(),
2822 data_channel->label()) != active_channels.end()) {
2823 ++it;
2824 continue;
2825 }
2826
2827 if (is_local_update) {
2828 data_channel->SetSendSsrc(0);
2829 } else {
2830 data_channel->RemotePeerRequestClose();
2831 }
2832
2833 if (data_channel->state() == DataChannel::kClosed) {
2834 rtp_data_channels_.erase(it);
2835 it = rtp_data_channels_.begin();
2836 } else {
2837 ++it;
2838 }
2839 }
2840}
2841
2842void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2843 uint32_t remote_ssrc) {
2844 rtc::scoped_refptr<DataChannel> channel(
2845 InternalCreateDataChannel(label, nullptr));
2846 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002847 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2848 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07002849 return;
2850 }
2851 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002852 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2853 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002854 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002855}
2856
2857rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2858 const std::string& label,
2859 const InternalDataChannelInit* config) {
2860 if (IsClosed()) {
2861 return nullptr;
2862 }
Steve Anton75737c02017-11-06 10:37:17 -08002863 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002864 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07002865 << "InternalCreateDataChannel: Data is not supported in this call.";
2866 return nullptr;
2867 }
2868 InternalDataChannelInit new_config =
2869 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08002870 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07002871 if (new_config.id < 0) {
2872 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002873 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002874 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002875 RTC_LOG(LS_ERROR)
2876 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07002877 return nullptr;
2878 }
2879 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002880 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2881 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07002882 return nullptr;
2883 }
2884 }
2885
Steve Anton75737c02017-11-06 10:37:17 -08002886 rtc::scoped_refptr<DataChannel> channel(
2887 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002888 if (!channel) {
2889 sid_allocator_.ReleaseSid(new_config.id);
2890 return nullptr;
2891 }
2892
2893 if (channel->data_channel_type() == cricket::DCT_RTP) {
2894 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002895 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2896 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07002897 return nullptr;
2898 }
2899 rtp_data_channels_[channel->label()] = channel;
2900 } else {
2901 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2902 sctp_data_channels_.push_back(channel);
2903 channel->SignalClosed.connect(this,
2904 &PeerConnection::OnSctpDataChannelClosed);
2905 }
2906
hbos82ebe022016-11-14 01:41:09 -08002907 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002908 return channel;
2909}
2910
2911bool PeerConnection::HasDataChannels() const {
2912 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
2913}
2914
2915void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2916 for (const auto& channel : sctp_data_channels_) {
2917 if (channel->id() < 0) {
2918 int sid;
2919 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002920 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07002921 continue;
2922 }
2923 channel->SetSctpSid(sid);
2924 }
2925 }
2926}
2927
2928void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002929 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002930 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2931 ++it) {
2932 if (it->get() == channel) {
2933 if (channel->id() >= 0) {
2934 sid_allocator_.ReleaseSid(channel->id());
2935 }
deadbeefbd292462015-12-14 18:15:29 -08002936 // Since this method is triggered by a signal from the DataChannel,
2937 // we can't free it directly here; we need to free it asynchronously.
2938 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002939 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002940 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2941 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002942 return;
2943 }
2944 }
2945}
2946
deadbeefab9b2d12015-10-14 11:33:11 -07002947void PeerConnection::OnDataChannelDestroyed() {
2948 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2949 // DataChannel may callback to us and try to modify the list.
2950 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2951 temp_rtp_dcs.swap(rtp_data_channels_);
2952 for (const auto& kv : temp_rtp_dcs) {
2953 kv.second->OnTransportChannelDestroyed();
2954 }
2955
2956 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2957 temp_sctp_dcs.swap(sctp_data_channels_);
2958 for (const auto& channel : temp_sctp_dcs) {
2959 channel->OnTransportChannelDestroyed();
2960 }
2961}
2962
2963void PeerConnection::OnDataChannelOpenMessage(
2964 const std::string& label,
2965 const InternalDataChannelInit& config) {
2966 rtc::scoped_refptr<DataChannel> channel(
2967 InternalCreateDataChannel(label, &config));
2968 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002969 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07002970 return;
2971 }
2972
deadbeefa601f5c2016-06-06 14:27:39 -07002973 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2974 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002975 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002976}
2977
zhihuang1c378ed2017-08-17 14:10:50 -07002978bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2979 return std::find_if(
2980 senders_.begin(), senders_.end(),
2981 [type](const rtc::scoped_refptr<
2982 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2983 return sender->media_type() == type;
2984 }) != senders_.end();
2985}
2986
deadbeefa601f5c2016-06-06 14:27:39 -07002987RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2988 auto it = std::find_if(
2989 senders_.begin(), senders_.end(),
2990 [id](const rtc::scoped_refptr<
2991 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2992 return sender->id() == id;
2993 });
2994 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002995}
2996
deadbeefa601f5c2016-06-06 14:27:39 -07002997std::vector<
2998 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002999PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
3000 return std::find_if(
3001 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07003002 [track](const rtc::scoped_refptr<
3003 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07003004 return sender->track() == track;
3005 });
3006}
3007
deadbeefa601f5c2016-06-06 14:27:39 -07003008std::vector<rtc::scoped_refptr<
3009 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07003010PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07003011 return std::find_if(
3012 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07003013 [track_id](const rtc::scoped_refptr<
3014 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07003015 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07003016 });
3017}
3018
deadbeefab9b2d12015-10-14 11:33:11 -07003019PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
3020 cricket::MediaType media_type) {
3021 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3022 media_type == cricket::MEDIA_TYPE_VIDEO);
3023 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
3024 : &remote_video_tracks_;
3025}
3026
3027PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
3028 cricket::MediaType media_type) {
3029 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3030 media_type == cricket::MEDIA_TYPE_VIDEO);
3031 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
3032 : &local_video_tracks_;
3033}
3034
3035const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
3036 const PeerConnection::TrackInfos& infos,
3037 const std::string& stream_label,
3038 const std::string track_id) const {
3039 for (const TrackInfo& track_info : infos) {
3040 if (track_info.stream_label == stream_label &&
3041 track_info.track_id == track_id) {
3042 return &track_info;
3043 }
3044 }
3045 return nullptr;
3046}
3047
3048DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3049 for (const auto& channel : sctp_data_channels_) {
3050 if (channel->id() == sid) {
3051 return channel;
3052 }
3053 }
3054 return nullptr;
3055}
3056
deadbeef91dd5672016-05-18 16:55:30 -07003057bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003058 const RTCConfiguration& configuration) {
3059 cricket::ServerAddresses stun_servers;
3060 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003061 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3062 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003063 return false;
3064 }
3065
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003066 port_allocator_->Initialize();
3067
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003068 // To handle both internal and externally created port allocator, we will
3069 // enable BUNDLE here.
3070 int portallocator_flags = port_allocator_->flags();
3071 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003072 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3073 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003074 // If the disable-IPv6 flag was specified, we'll not override it
3075 // by experiment.
3076 if (configuration.disable_ipv6) {
3077 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003078 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3079 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003080 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3081 }
3082
zhihuangb09b3f92017-03-07 14:40:51 -08003083 if (configuration.disable_ipv6_on_wifi) {
3084 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003085 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003086 }
3087
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003088 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3089 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003090 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003091 }
3092
honghaiz60347052016-05-31 18:29:12 -07003093 if (configuration.candidate_network_policy ==
3094 kCandidateNetworkPolicyLowCost) {
3095 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003096 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003097 }
3098
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003099 port_allocator_->set_flags(portallocator_flags);
3100 // No step delay is used while allocating ports.
3101 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3102 port_allocator_->set_candidate_filter(
3103 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003104 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003105
3106 // Call this last since it may create pooled allocator sessions using the
3107 // properties set above.
3108 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003109 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003110 configuration.prune_turn_ports,
3111 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003112 return true;
3113}
3114
deadbeef91dd5672016-05-18 16:55:30 -07003115bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003116 const cricket::ServerAddresses& stun_servers,
3117 const std::vector<cricket::RelayServerConfig>& turn_servers,
3118 IceTransportsType type,
3119 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003120 bool prune_turn_ports,
3121 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003122 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003123 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003124 // Call this last since it may create pooled allocator sessions using the
3125 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003126 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003127 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3128 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003129}
3130
Steve Antonba818672017-11-06 10:21:57 -08003131cricket::ChannelManager* PeerConnection::channel_manager() const {
3132 return factory_->channel_manager();
3133}
3134
3135MetricsObserverInterface* PeerConnection::metrics_observer() const {
3136 return uma_observer_;
3137}
3138
Elad Alon99c3fe52017-10-13 16:29:40 +02003139bool PeerConnection::StartRtcEventLog_w(
3140 std::unique_ptr<RtcEventLogOutput> output) {
zhihuang77985012017-02-07 15:45:16 -08003141 if (!event_log_) {
3142 return false;
3143 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003144 return event_log_->StartLogging(std::move(output));
ivoc14d5dbe2016-07-04 07:06:55 -07003145}
3146
3147void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003148 if (event_log_) {
3149 event_log_->StopLogging();
3150 }
ivoc14d5dbe2016-07-04 07:06:55 -07003151}
nisseeaabdf62017-05-05 02:23:02 -07003152
Steve Anton75737c02017-11-06 10:37:17 -08003153cricket::BaseChannel* PeerConnection::GetChannel(
3154 const std::string& content_name) {
3155 if (voice_channel() && voice_channel()->content_name() == content_name) {
3156 return voice_channel();
3157 }
3158 if (video_channel() && video_channel()->content_name() == content_name) {
3159 return video_channel();
3160 }
3161 if (rtp_data_channel() &&
3162 rtp_data_channel()->content_name() == content_name) {
3163 return rtp_data_channel();
3164 }
3165 return nullptr;
3166}
3167
3168bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3169 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003170 RTC_LOG(LS_INFO)
3171 << "Local and Remote descriptions must be applied to get the "
3172 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003173 return false;
3174 }
3175 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003176 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3177 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003178 return false;
3179 }
3180
3181 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3182}
3183
3184bool PeerConnection::GetSslRole(const std::string& content_name,
3185 rtc::SSLRole* role) {
3186 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003187 RTC_LOG(LS_INFO)
3188 << "Local and Remote descriptions must be applied to get the "
3189 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003190 return false;
3191 }
3192
3193 return transport_controller_->GetSslRole(GetTransportName(content_name),
3194 role);
3195}
3196
Steve Anton75737c02017-11-06 10:37:17 -08003197bool PeerConnection::SetLocalDescription(
3198 std::unique_ptr<SessionDescriptionInterface> desc,
3199 std::string* err_desc) {
3200 RTC_DCHECK(signaling_thread()->IsCurrent());
3201
3202 // Validate SDP.
3203 if (!ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, err_desc)) {
3204 return false;
3205 }
3206
3207 // Update the initial_offerer flag if this session is the initial_offerer.
3208 Action action = GetAction(desc->type());
3209 if (!initial_offerer_.has_value()) {
3210 initial_offerer_.emplace(action == kOffer);
3211 if (*initial_offerer_) {
3212 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3213 } else {
3214 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3215 }
3216 }
3217
3218 if (action == kAnswer) {
3219 current_local_description_ = std::move(desc);
3220 pending_local_description_ = nullptr;
3221 current_remote_description_ = std::move(pending_remote_description_);
3222 } else {
3223 pending_local_description_ = std::move(desc);
3224 }
3225
3226 // Transport and Media channels will be created only when offer is set.
3227 if (action == kOffer && !CreateChannels(local_description()->description())) {
3228 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3229 // is applied. Restore back to old description.
3230 return BadLocalSdp(local_description()->type(), kCreateChannelFailed,
3231 err_desc);
3232 }
3233
3234 // Remove unused channels if MediaContentDescription is rejected.
3235 RemoveUnusedChannels(local_description()->description());
3236
3237 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
3238 return false;
3239 }
3240 if (remote_description()) {
3241 // Now that we have a local description, we can push down remote candidates.
3242 UseCandidatesInSessionDescription(remote_description());
3243 }
3244
3245 pending_ice_restarts_.clear();
3246 if (error() != ERROR_NONE) {
3247 return BadLocalSdp(local_description()->type(), GetSessionErrorMsg(),
3248 err_desc);
3249 }
3250 return true;
3251}
3252
3253bool PeerConnection::SetRemoteDescription(
3254 std::unique_ptr<SessionDescriptionInterface> desc,
3255 std::string* err_desc) {
3256 RTC_DCHECK(signaling_thread()->IsCurrent());
3257
3258 // Validate SDP.
3259 if (!ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, err_desc)) {
3260 return false;
3261 }
3262
3263 // Hold this pointer so candidates can be copied to it later in the method.
3264 SessionDescriptionInterface* desc_ptr = desc.get();
3265
3266 const SessionDescriptionInterface* old_remote_description =
3267 remote_description();
3268 // Grab ownership of the description being replaced for the remainder of this
3269 // method, since it's used below as |old_remote_description|.
3270 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
3271 Action action = GetAction(desc->type());
3272 if (action == kAnswer) {
3273 replaced_remote_description = pending_remote_description_
3274 ? std::move(pending_remote_description_)
3275 : std::move(current_remote_description_);
3276 current_remote_description_ = std::move(desc);
3277 pending_remote_description_ = nullptr;
3278 current_local_description_ = std::move(pending_local_description_);
3279 } else {
3280 replaced_remote_description = std::move(pending_remote_description_);
3281 pending_remote_description_ = std::move(desc);
3282 }
3283
3284 // Transport and Media channels will be created only when offer is set.
3285 if (action == kOffer &&
3286 !CreateChannels(remote_description()->description())) {
3287 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3288 // is applied. Restore back to old description.
3289 return BadRemoteSdp(remote_description()->type(), kCreateChannelFailed,
3290 err_desc);
3291 }
3292
3293 // Remove unused channels if MediaContentDescription is rejected.
3294 RemoveUnusedChannels(remote_description()->description());
3295
3296 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
3297 // is called.
3298 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
3299 return false;
3300 }
3301
3302 if (local_description() &&
3303 !UseCandidatesInSessionDescription(remote_description())) {
3304 return BadRemoteSdp(remote_description()->type(), kInvalidCandidates,
3305 err_desc);
3306 }
3307
3308 if (old_remote_description) {
3309 for (const cricket::ContentInfo& content :
3310 old_remote_description->description()->contents()) {
3311 // Check if this new SessionDescription contains new ICE ufrag and
3312 // password that indicates the remote peer requests an ICE restart.
3313 // TODO(deadbeef): When we start storing both the current and pending
3314 // remote description, this should reset pending_ice_restarts and compare
3315 // against the current description.
3316 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3317 content.name)) {
3318 if (action == kOffer) {
3319 pending_ice_restarts_.insert(content.name);
3320 }
3321 } else {
3322 // We retain all received candidates only if ICE is not restarted.
3323 // When ICE is restarted, all previous candidates belong to an old
3324 // generation and should not be kept.
3325 // TODO(deadbeef): This goes against the W3C spec which says the remote
3326 // description should only contain candidates from the last set remote
3327 // description plus any candidates added since then. We should remove
3328 // this once we're sure it won't break anything.
3329 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3330 old_remote_description, content.name, desc_ptr);
3331 }
3332 }
3333 }
3334
3335 if (error() != ERROR_NONE) {
3336 return BadRemoteSdp(remote_description()->type(), GetSessionErrorMsg(),
3337 err_desc);
3338 }
3339
3340 // Set the the ICE connection state to connecting since the connection may
3341 // become writable with peer reflexive candidates before any remote candidate
3342 // is signaled.
3343 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3344 // is to have a new signal the indicates a change in checking state from the
3345 // transport and expose a new checking() member from transport that can be
3346 // read to determine the current checking state. The existing SignalConnecting
3347 // actually means "gathering candidates", so cannot be be used here.
3348 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
3349 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3350 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3351 }
3352 return true;
3353}
3354
3355// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3356// vector of BaseChannel pointers instead of separate voice and video channel
3357// vectors. At that point, this will become a simple getter.
3358std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3359 std::vector<cricket::BaseChannel*> channels;
3360 channels.insert(channels.end(), voice_channels_.begin(),
3361 voice_channels_.end());
3362 channels.insert(channels.end(), video_channels_.begin(),
3363 video_channels_.end());
3364 if (rtp_data_channel_) {
3365 channels.push_back(rtp_data_channel_);
3366 }
3367 return channels;
3368}
3369
3370void PeerConnection::SetError(Error error, const std::string& error_desc) {
3371 RTC_DCHECK(signaling_thread()->IsCurrent());
3372 if (error != error_) {
3373 error_ = error;
3374 error_desc_ = error_desc;
3375 }
3376}
3377
3378bool PeerConnection::UpdateSessionState(Action action,
3379 cricket::ContentSource source,
3380 std::string* err_desc) {
3381 RTC_DCHECK(signaling_thread()->IsCurrent());
3382
3383 // If there's already a pending error then no state transition should happen.
3384 // But all call-sites should be verifying this before calling us!
3385 RTC_DCHECK(error() == ERROR_NONE);
3386 std::string td_err;
3387 if (action == kOffer) {
3388 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
3389 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
3390 }
3391 ChangeSignalingState(source == cricket::CS_LOCAL
3392 ? PeerConnectionInterface::kHaveLocalOffer
3393 : PeerConnectionInterface::kHaveRemoteOffer);
3394 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
3395 SetError(ERROR_CONTENT, *err_desc);
3396 }
3397 if (error() != ERROR_NONE) {
3398 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
3399 }
3400 } else if (action == kPrAnswer) {
3401 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
3402 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
3403 }
3404 EnableChannels();
3405 ChangeSignalingState(source == cricket::CS_LOCAL
3406 ? PeerConnectionInterface::kHaveLocalPrAnswer
3407 : PeerConnectionInterface::kHaveRemotePrAnswer);
3408 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
3409 SetError(ERROR_CONTENT, *err_desc);
3410 }
3411 if (error() != ERROR_NONE) {
3412 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
3413 }
3414 } else if (action == kAnswer) {
3415 const cricket::ContentGroup* local_bundle =
3416 local_description()->description()->GetGroupByName(
3417 cricket::GROUP_TYPE_BUNDLE);
3418 const cricket::ContentGroup* remote_bundle =
3419 remote_description()->description()->GetGroupByName(
3420 cricket::GROUP_TYPE_BUNDLE);
3421 if (local_bundle && remote_bundle) {
3422 // The answerer decides the transport to bundle on.
3423 const cricket::ContentGroup* answer_bundle =
3424 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3425 if (!EnableBundle(*answer_bundle)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003426 RTC_LOG(LS_WARNING) << "Failed to enable BUNDLE.";
Steve Anton75737c02017-11-06 10:37:17 -08003427 return BadAnswerSdp(source, kEnableBundleFailed, err_desc);
3428 }
3429 }
3430 // Only push down the transport description after enabling BUNDLE; we don't
3431 // want to push down a description on a transport about to be destroyed.
3432 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
3433 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
3434 }
3435 EnableChannels();
3436 ChangeSignalingState(PeerConnectionInterface::kStable);
3437 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
3438 SetError(ERROR_CONTENT, *err_desc);
3439 }
3440 if (error() != ERROR_NONE) {
3441 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
3442 }
3443 }
3444 return true;
3445}
3446
3447PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3448 if (type == SessionDescriptionInterface::kOffer) {
3449 return PeerConnection::kOffer;
3450 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3451 return PeerConnection::kPrAnswer;
3452 } else if (type == SessionDescriptionInterface::kAnswer) {
3453 return PeerConnection::kAnswer;
3454 }
3455 RTC_NOTREACHED() << "unknown action type";
3456 return PeerConnection::kOffer;
3457}
3458
3459bool PeerConnection::PushdownMediaDescription(cricket::ContentAction action,
3460 cricket::ContentSource source,
3461 std::string* err) {
3462 const SessionDescription* sdesc =
3463 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3464 ->description();
3465 RTC_DCHECK(sdesc);
3466 bool all_success = true;
3467 for (auto* channel : Channels()) {
3468 // TODO(steveanton): Add support for multiple channels of the same type.
3469 const ContentInfo* content_info =
3470 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3471 if (!content_info) {
3472 continue;
3473 }
3474 const MediaContentDescription* content_desc =
3475 static_cast<const MediaContentDescription*>(content_info->description);
3476 if (content_desc && !content_info->rejected) {
3477 bool success = (source == cricket::CS_LOCAL)
3478 ? channel->SetLocalContent(content_desc, action, err)
3479 : channel->SetRemoteContent(content_desc, action, err);
3480 if (!success) {
3481 all_success = false;
3482 break;
3483 }
3484 }
3485 }
3486 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3487 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3488 if (sctp_transport_ && local_description() && remote_description() &&
3489 cricket::GetFirstDataContent(local_description()->description()) &&
3490 cricket::GetFirstDataContent(remote_description()->description())) {
3491 all_success &= network_thread()->Invoke<bool>(
3492 RTC_FROM_HERE,
3493 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
3494 }
3495 return all_success;
3496}
3497
3498bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3499 RTC_DCHECK(network_thread()->IsCurrent());
3500 RTC_DCHECK(local_description());
3501 RTC_DCHECK(remote_description());
3502 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3503 // When we support "max-message-size", that would also be pushed down here.
3504 return sctp_transport_->Start(
3505 GetSctpPort(local_description()->description()),
3506 GetSctpPort(remote_description()->description()));
3507}
3508
3509bool PeerConnection::PushdownTransportDescription(cricket::ContentSource source,
3510 cricket::ContentAction action,
3511 std::string* error_desc) {
3512 RTC_DCHECK(signaling_thread()->IsCurrent());
3513
3514 if (source == cricket::CS_LOCAL) {
3515 return PushdownLocalTransportDescription(local_description()->description(),
3516 action, error_desc);
3517 }
3518 return PushdownRemoteTransportDescription(remote_description()->description(),
3519 action, error_desc);
3520}
3521
3522bool PeerConnection::PushdownLocalTransportDescription(
3523 const SessionDescription* sdesc,
3524 cricket::ContentAction action,
3525 std::string* err) {
3526 RTC_DCHECK(signaling_thread()->IsCurrent());
3527
3528 if (!sdesc) {
3529 return false;
3530 }
3531
3532 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3533 if (!transport_controller_->SetLocalTransportDescription(
3534 tinfo.content_name, tinfo.description, action, err)) {
3535 return false;
3536 }
3537 }
3538
3539 return true;
3540}
3541
3542bool PeerConnection::PushdownRemoteTransportDescription(
3543 const SessionDescription* sdesc,
3544 cricket::ContentAction action,
3545 std::string* err) {
3546 RTC_DCHECK(signaling_thread()->IsCurrent());
3547
3548 if (!sdesc) {
3549 return false;
3550 }
3551
3552 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3553 if (!transport_controller_->SetRemoteTransportDescription(
3554 tinfo.content_name, tinfo.description, action, err)) {
3555 return false;
3556 }
3557 }
3558
3559 return true;
3560}
3561
3562bool PeerConnection::GetTransportDescription(
3563 const SessionDescription* description,
3564 const std::string& content_name,
3565 cricket::TransportDescription* tdesc) {
3566 if (!description || !tdesc) {
3567 return false;
3568 }
3569 const TransportInfo* transport_info =
3570 description->GetTransportInfoByName(content_name);
3571 if (!transport_info) {
3572 return false;
3573 }
3574 *tdesc = transport_info->description;
3575 return true;
3576}
3577
3578bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3579 const std::string* first_content_name = bundle.FirstContentName();
3580 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003581 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003582 return false;
3583 }
3584 const std::string& transport_name = *first_content_name;
3585
3586 auto maybe_set_transport = [this, bundle,
3587 transport_name](cricket::BaseChannel* ch) {
3588 if (!ch || !bundle.HasContentName(ch->content_name())) {
3589 return true;
3590 }
3591
3592 std::string old_transport_name = ch->transport_name();
3593 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003594 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3595 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003596 return true;
3597 }
3598
3599 cricket::DtlsTransportInternal* rtp_dtls_transport =
3600 transport_controller_->CreateDtlsTransport(
3601 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3602 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3603 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3604 if (need_rtcp) {
3605 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3606 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3607 }
3608
3609 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003610 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3611 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003612 transport_controller_->DestroyDtlsTransport(
3613 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3614 // If the channel needs rtcp, it means that the channel used to have a
3615 // rtcp transport which needs to be deleted now.
3616 if (need_rtcp) {
3617 transport_controller_->DestroyDtlsTransport(
3618 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3619 }
3620 return true;
3621 };
3622
3623 if (!maybe_set_transport(voice_channel()) ||
3624 !maybe_set_transport(video_channel()) ||
3625 !maybe_set_transport(rtp_data_channel())) {
3626 return false;
3627 }
3628 // For SCTP, transport creation/deletion happens here instead of in the
3629 // object itself.
3630 if (sctp_transport_) {
3631 RTC_DCHECK(sctp_transport_name_);
3632 RTC_DCHECK(sctp_content_name_);
3633 if (transport_name != *sctp_transport_name_ &&
3634 bundle.HasContentName(*sctp_content_name_)) {
3635 network_thread()->Invoke<void>(
3636 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3637 transport_name));
3638 }
3639 }
3640
3641 return true;
3642}
3643
Steve Anton75737c02017-11-06 10:37:17 -08003644cricket::IceConfig PeerConnection::ParseIceConfig(
3645 const PeerConnectionInterface::RTCConfiguration& config) const {
3646 cricket::ContinualGatheringPolicy gathering_policy;
3647 // TODO(honghaiz): Add the third continual gathering policy in
3648 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3649 switch (config.continual_gathering_policy) {
3650 case PeerConnectionInterface::GATHER_ONCE:
3651 gathering_policy = cricket::GATHER_ONCE;
3652 break;
3653 case PeerConnectionInterface::GATHER_CONTINUALLY:
3654 gathering_policy = cricket::GATHER_CONTINUALLY;
3655 break;
3656 default:
3657 RTC_NOTREACHED();
3658 gathering_policy = cricket::GATHER_ONCE;
3659 }
3660 cricket::IceConfig ice_config;
3661 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3662 ice_config.prioritize_most_likely_candidate_pairs =
3663 config.prioritize_most_likely_ice_candidate_pairs;
3664 ice_config.backup_connection_ping_interval =
3665 config.ice_backup_candidate_pair_ping_interval;
3666 ice_config.continual_gathering_policy = gathering_policy;
3667 ice_config.presume_writable_when_fully_relayed =
3668 config.presume_writable_when_fully_relayed;
3669 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3670 ice_config.regather_all_networks_interval_range =
3671 config.ice_regather_interval_range;
3672 return ice_config;
3673}
3674
Steve Anton75737c02017-11-06 10:37:17 -08003675bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3676 std::string* track_id) {
3677 if (!local_description()) {
3678 return false;
3679 }
3680 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3681 track_id);
3682}
3683
3684bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3685 std::string* track_id) {
3686 if (!remote_description()) {
3687 return false;
3688 }
3689 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3690 track_id);
3691}
3692
3693bool PeerConnection::SendData(const cricket::SendDataParams& params,
3694 const rtc::CopyOnWriteBuffer& payload,
3695 cricket::SendDataResult* result) {
3696 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003697 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3698 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003699 return false;
3700 }
3701 return rtp_data_channel_
3702 ? rtp_data_channel_->SendData(params, payload, result)
3703 : network_thread()->Invoke<bool>(
3704 RTC_FROM_HERE,
3705 Bind(&cricket::SctpTransportInternal::SendData,
3706 sctp_transport_.get(), params, payload, result));
3707}
3708
3709bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3710 if (!rtp_data_channel_ && !sctp_transport_) {
3711 // Don't log an error here, because DataChannels are expected to call
3712 // ConnectDataChannel in this state. It's the only way to initially tell
3713 // whether or not the underlying transport is ready.
3714 return false;
3715 }
3716 if (rtp_data_channel_) {
3717 rtp_data_channel_->SignalReadyToSendData.connect(
3718 webrtc_data_channel, &DataChannel::OnChannelReady);
3719 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3720 &DataChannel::OnDataReceived);
3721 } else {
3722 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3723 &DataChannel::OnChannelReady);
3724 SignalSctpDataReceived.connect(webrtc_data_channel,
3725 &DataChannel::OnDataReceived);
3726 SignalSctpStreamClosedRemotely.connect(
3727 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3728 }
3729 return true;
3730}
3731
3732void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3733 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003734 RTC_LOG(LS_ERROR)
3735 << "DisconnectDataChannel called when rtp_data_channel_ and "
3736 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003737 return;
3738 }
3739 if (rtp_data_channel_) {
3740 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3741 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3742 } else {
3743 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3744 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3745 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3746 }
3747}
3748
3749void PeerConnection::AddSctpDataStream(int sid) {
3750 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003751 RTC_LOG(LS_ERROR)
3752 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003753 return;
3754 }
3755 network_thread()->Invoke<void>(
3756 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3757 sctp_transport_.get(), sid));
3758}
3759
3760void PeerConnection::RemoveSctpDataStream(int sid) {
3761 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003762 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3763 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003764 return;
3765 }
3766 network_thread()->Invoke<void>(
3767 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3768 sctp_transport_.get(), sid));
3769}
3770
3771bool PeerConnection::ReadyToSendData() const {
3772 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3773 sctp_ready_to_send_data_;
3774}
3775
3776std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3777 RTC_DCHECK(signaling_thread()->IsCurrent());
3778 ChannelNamePairs channel_name_pairs;
3779 if (voice_channel()) {
3780 channel_name_pairs.voice = rtc::Optional<ChannelNamePair>(ChannelNamePair(
3781 voice_channel()->content_name(), voice_channel()->transport_name()));
3782 }
3783 if (video_channel()) {
3784 channel_name_pairs.video = rtc::Optional<ChannelNamePair>(ChannelNamePair(
3785 video_channel()->content_name(), video_channel()->transport_name()));
3786 }
3787 if (rtp_data_channel()) {
3788 channel_name_pairs.data = rtc::Optional<ChannelNamePair>(
3789 ChannelNamePair(rtp_data_channel()->content_name(),
3790 rtp_data_channel()->transport_name()));
3791 }
3792 if (sctp_transport_) {
3793 RTC_DCHECK(sctp_content_name_);
3794 RTC_DCHECK(sctp_transport_name_);
3795 channel_name_pairs.data = rtc::Optional<ChannelNamePair>(
3796 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_));
3797 }
3798 return GetSessionStats(channel_name_pairs);
3799}
3800
3801std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3802 const ChannelNamePairs& channel_name_pairs) {
3803 if (network_thread()->IsCurrent()) {
3804 return GetSessionStats_n(channel_name_pairs);
3805 }
3806 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3807 RTC_FROM_HERE,
3808 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3809}
3810
3811bool PeerConnection::GetLocalCertificate(
3812 const std::string& transport_name,
3813 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
3814 return transport_controller_->GetLocalCertificate(transport_name,
3815 certificate);
3816}
3817
3818std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
3819 const std::string& transport_name) {
3820 return transport_controller_->GetRemoteSSLCertificate(transport_name);
3821}
3822
3823cricket::DataChannelType PeerConnection::data_channel_type() const {
3824 return data_channel_type_;
3825}
3826
3827bool PeerConnection::IceRestartPending(const std::string& content_name) const {
3828 return pending_ice_restarts_.find(content_name) !=
3829 pending_ice_restarts_.end();
3830}
3831
Steve Anton75737c02017-11-06 10:37:17 -08003832bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
3833 return transport_controller_->NeedsIceRestart(content_name);
3834}
3835
3836void PeerConnection::OnCertificateReady(
3837 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
3838 transport_controller_->SetLocalCertificate(certificate);
3839}
3840
3841void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
3842 SetError(ERROR_TRANSPORT,
3843 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
3844}
3845
3846void PeerConnection::OnTransportControllerConnectionState(
3847 cricket::IceConnectionState state) {
3848 switch (state) {
3849 case cricket::kIceConnectionConnecting:
3850 // If the current state is Connected or Completed, then there were
3851 // writable channels but now there are not, so the next state must
3852 // be Disconnected.
3853 // kIceConnectionConnecting is currently used as the default,
3854 // un-connected state by the TransportController, so its only use is
3855 // detecting disconnections.
3856 if (ice_connection_state_ ==
3857 PeerConnectionInterface::kIceConnectionConnected ||
3858 ice_connection_state_ ==
3859 PeerConnectionInterface::kIceConnectionCompleted) {
3860 SetIceConnectionState(
3861 PeerConnectionInterface::kIceConnectionDisconnected);
3862 }
3863 break;
3864 case cricket::kIceConnectionFailed:
3865 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
3866 break;
3867 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003868 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
3869 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08003870 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3871 break;
3872 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003873 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
3874 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08003875 if (ice_connection_state_ !=
3876 PeerConnectionInterface::kIceConnectionConnected) {
3877 // If jumping directly from "checking" to "connected",
3878 // signal "connected" first.
3879 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3880 }
3881 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
3882 if (metrics_observer()) {
3883 ReportTransportStats();
3884 }
3885 break;
3886 default:
3887 RTC_NOTREACHED();
3888 }
3889}
3890
3891void PeerConnection::OnTransportControllerCandidatesGathered(
3892 const std::string& transport_name,
3893 const cricket::Candidates& candidates) {
3894 RTC_DCHECK(signaling_thread()->IsCurrent());
3895 int sdp_mline_index;
3896 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003897 RTC_LOG(LS_ERROR)
3898 << "OnTransportControllerCandidatesGathered: content name "
3899 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08003900 return;
3901 }
3902
3903 for (cricket::Candidates::const_iterator citer = candidates.begin();
3904 citer != candidates.end(); ++citer) {
3905 // Use transport_name as the candidate media id.
3906 std::unique_ptr<JsepIceCandidate> candidate(
3907 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
3908 if (local_description()) {
3909 mutable_local_description()->AddCandidate(candidate.get());
3910 }
3911 OnIceCandidate(std::move(candidate));
3912 }
3913}
3914
3915void PeerConnection::OnTransportControllerCandidatesRemoved(
3916 const std::vector<cricket::Candidate>& candidates) {
3917 RTC_DCHECK(signaling_thread()->IsCurrent());
3918 // Sanity check.
3919 for (const cricket::Candidate& candidate : candidates) {
3920 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003921 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
3922 << "empty content name in candidate "
3923 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08003924 return;
3925 }
3926 }
3927
3928 if (local_description()) {
3929 mutable_local_description()->RemoveCandidates(candidates);
3930 }
3931 OnIceCandidatesRemoved(candidates);
3932}
3933
3934void PeerConnection::OnTransportControllerDtlsHandshakeError(
3935 rtc::SSLHandshakeError error) {
3936 if (metrics_observer()) {
3937 metrics_observer()->IncrementEnumCounter(
3938 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
3939 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
3940 }
3941}
3942
3943// Enabling voice and video (and RTP data) channels.
3944void PeerConnection::EnableChannels() {
3945 for (cricket::VoiceChannel* voice_channel : voice_channels_) {
3946 if (!voice_channel->enabled()) {
3947 voice_channel->Enable(true);
3948 }
3949 }
3950
3951 for (cricket::VideoChannel* video_channel : video_channels_) {
3952 if (!video_channel->enabled()) {
3953 video_channel->Enable(true);
3954 }
3955 }
3956
3957 if (rtp_data_channel_ && !rtp_data_channel_->enabled())
3958 rtp_data_channel_->Enable(true);
3959}
3960
3961// Returns the media index for a local ice candidate given the content name.
3962bool PeerConnection::GetLocalCandidateMediaIndex(
3963 const std::string& content_name,
3964 int* sdp_mline_index) {
3965 if (!local_description() || !sdp_mline_index) {
3966 return false;
3967 }
3968
3969 bool content_found = false;
3970 const ContentInfos& contents = local_description()->description()->contents();
3971 for (size_t index = 0; index < contents.size(); ++index) {
3972 if (contents[index].name == content_name) {
3973 *sdp_mline_index = static_cast<int>(index);
3974 content_found = true;
3975 break;
3976 }
3977 }
3978 return content_found;
3979}
3980
3981bool PeerConnection::UseCandidatesInSessionDescription(
3982 const SessionDescriptionInterface* remote_desc) {
3983 if (!remote_desc) {
3984 return true;
3985 }
3986 bool ret = true;
3987
3988 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
3989 const IceCandidateCollection* candidates = remote_desc->candidates(m);
3990 for (size_t n = 0; n < candidates->count(); ++n) {
3991 const IceCandidateInterface* candidate = candidates->at(n);
3992 bool valid = false;
3993 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
3994 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003995 RTC_LOG(LS_INFO)
3996 << "UseCandidatesInSessionDescription: Not ready to use "
3997 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08003998 }
3999 continue;
4000 }
4001 ret = UseCandidate(candidate);
4002 if (!ret) {
4003 break;
4004 }
4005 }
4006 }
4007 return ret;
4008}
4009
4010bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4011 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4012 size_t remote_content_size =
4013 remote_description()->description()->contents().size();
4014 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004015 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004016 return false;
4017 }
4018
4019 cricket::ContentInfo content =
4020 remote_description()->description()->contents()[mediacontent_index];
4021 std::vector<cricket::Candidate> candidates;
4022 candidates.push_back(candidate->candidate());
4023 // Invoking BaseSession method to handle remote candidates.
4024 std::string error;
4025 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4026 &error)) {
4027 // Candidates successfully submitted for checking.
4028 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4029 ice_connection_state_ ==
4030 PeerConnectionInterface::kIceConnectionDisconnected) {
4031 // If state is New, then the session has just gotten its first remote ICE
4032 // candidates, so go to Checking.
4033 // If state is Disconnected, the session is re-using old candidates or
4034 // receiving additional ones, so go to Checking.
4035 // If state is Connected, stay Connected.
4036 // TODO(bemasc): If state is Connected, and the new candidates are for a
4037 // newly added transport, then the state actually _should_ move to
4038 // checking. Add a way to distinguish that case.
4039 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4040 }
4041 // TODO(bemasc): If state is Completed, go back to Connected.
4042 } else {
4043 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004044 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004045 }
4046 }
4047 return true;
4048}
4049
4050void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
4051 // TODO(steveanton): Add support for multiple audio/video channels.
4052 // Destroy video channel first since it may have a pointer to the
4053 // voice channel.
4054 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
4055 if ((!video_info || video_info->rejected) && video_channel()) {
4056 RemoveAndDestroyVideoChannel(video_channel());
4057 }
4058
4059 const cricket::ContentInfo* voice_info = cricket::GetFirstAudioContent(desc);
4060 if ((!voice_info || voice_info->rejected) && voice_channel()) {
4061 RemoveAndDestroyVoiceChannel(voice_channel());
4062 }
4063
4064 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4065 if (!data_info || data_info->rejected) {
4066 if (rtp_data_channel_) {
4067 DestroyDataChannel();
4068 }
4069 if (sctp_transport_) {
4070 OnDataChannelDestroyed();
4071 network_thread()->Invoke<void>(
4072 RTC_FROM_HERE,
4073 rtc::Bind(&PeerConnection::DestroySctpTransport_n, this));
4074 }
4075 }
4076}
4077
4078// Returns the name of the transport channel when BUNDLE is enabled, or nullptr
4079// if the channel is not part of any bundle.
4080const std::string* PeerConnection::GetBundleTransportName(
4081 const cricket::ContentInfo* content,
4082 const cricket::ContentGroup* bundle) {
4083 if (!bundle) {
4084 return nullptr;
4085 }
4086 const std::string* first_content_name = bundle->FirstContentName();
4087 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004088 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004089 return nullptr;
4090 }
4091 if (!bundle->HasContentName(content->name)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004092 RTC_LOG(LS_WARNING) << content->name << " is not part of any bundle group";
Steve Anton75737c02017-11-06 10:37:17 -08004093 return nullptr;
4094 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004095 RTC_LOG(LS_INFO) << "Bundling " << content->name << " on "
4096 << *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004097 return first_content_name;
4098}
4099
4100bool PeerConnection::CreateChannels(const SessionDescription* desc) {
4101 // TODO(steveanton): Add support for multiple audio/video channels.
4102 const cricket::ContentGroup* bundle_group = nullptr;
4103 if (configuration_.bundle_policy ==
4104 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4105 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4106 if (!bundle_group) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004107 RTC_LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
Steve Anton75737c02017-11-06 10:37:17 -08004108 return false;
4109 }
4110 }
4111 // Creating the media channels and transport proxies.
4112 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4113 if (voice && !voice->rejected && !voice_channel()) {
4114 if (!CreateVoiceChannel(voice,
4115 GetBundleTransportName(voice, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004116 RTC_LOG(LS_ERROR) << "Failed to create voice channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004117 return false;
4118 }
4119 }
4120
4121 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
4122 if (video && !video->rejected && !video_channel()) {
4123 if (!CreateVideoChannel(video,
4124 GetBundleTransportName(video, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004125 RTC_LOG(LS_ERROR) << "Failed to create video channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004126 return false;
4127 }
4128 }
4129
4130 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4131 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4132 !rtp_data_channel_ && !sctp_transport_) {
4133 if (!CreateDataChannel(data, GetBundleTransportName(data, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004134 RTC_LOG(LS_ERROR) << "Failed to create data channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004135 return false;
4136 }
4137 }
4138
4139 return true;
4140}
4141
4142bool PeerConnection::CreateVoiceChannel(const cricket::ContentInfo* content,
4143 const std::string* bundle_transport) {
4144 // TODO(steveanton): Check to see if it's safe to create multiple voice
4145 // channels.
4146 RTC_DCHECK(voice_channels_.empty());
4147
4148 std::string transport_name =
4149 bundle_transport ? *bundle_transport : content->name;
4150
4151 cricket::DtlsTransportInternal* rtp_dtls_transport =
4152 transport_controller_->CreateDtlsTransport(
4153 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4154 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4155 if (configuration_.rtcp_mux_policy !=
4156 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4157 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4158 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4159 }
4160
4161 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4162 call_.get(), configuration_.media_config, rtp_dtls_transport,
4163 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4164 content->name, SrtpRequired(), audio_options_);
4165 if (!voice_channel) {
4166 transport_controller_->DestroyDtlsTransport(
4167 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4168 if (rtcp_dtls_transport) {
4169 transport_controller_->DestroyDtlsTransport(
4170 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4171 }
4172 return false;
4173 }
4174
4175 voice_channels_.push_back(voice_channel);
4176
4177 voice_channel->SignalRtcpMuxFullyActive.connect(
4178 this, &PeerConnection::DestroyRtcpTransport_n);
4179 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4180 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4181
Steve Antond25da372017-11-06 14:50:29 -08004182 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
4183 voice_channel, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
Steve Anton75737c02017-11-06 10:37:17 -08004184 voice_channel->SignalSentPacket.connect(this,
4185 &PeerConnection::OnSentPacket_w);
4186 return true;
4187}
4188
4189bool PeerConnection::CreateVideoChannel(const cricket::ContentInfo* content,
4190 const std::string* bundle_transport) {
4191 // TODO(steveanton): Check to see if it's safe to create multiple video
4192 // channels.
4193 RTC_DCHECK(video_channels_.empty());
4194
4195 std::string transport_name =
4196 bundle_transport ? *bundle_transport : content->name;
4197
4198 cricket::DtlsTransportInternal* rtp_dtls_transport =
4199 transport_controller_->CreateDtlsTransport(
4200 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4201 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4202 if (configuration_.rtcp_mux_policy !=
4203 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4204 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4205 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4206 }
4207
4208 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4209 call_.get(), configuration_.media_config, rtp_dtls_transport,
4210 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4211 content->name, SrtpRequired(), video_options_);
4212
4213 if (!video_channel) {
4214 transport_controller_->DestroyDtlsTransport(
4215 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4216 if (rtcp_dtls_transport) {
4217 transport_controller_->DestroyDtlsTransport(
4218 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4219 }
4220 return false;
4221 }
4222
4223 video_channels_.push_back(video_channel);
4224
4225 video_channel->SignalRtcpMuxFullyActive.connect(
4226 this, &PeerConnection::DestroyRtcpTransport_n);
4227 video_channel->SignalDtlsSrtpSetupFailure.connect(
4228 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4229
Steve Antond25da372017-11-06 14:50:29 -08004230 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
4231 video_channel, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
Steve Anton75737c02017-11-06 10:37:17 -08004232 video_channel->SignalSentPacket.connect(this,
4233 &PeerConnection::OnSentPacket_w);
4234 return true;
4235}
4236
4237bool PeerConnection::CreateDataChannel(const cricket::ContentInfo* content,
4238 const std::string* bundle_transport) {
4239 const std::string transport_name =
4240 bundle_transport ? *bundle_transport : content->name;
4241 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4242 if (sctp) {
4243 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004244 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004245 << "Trying to create SCTP transport, but didn't compile with "
4246 "SCTP support (HAVE_SCTP)";
4247 return false;
4248 }
4249 if (!network_thread()->Invoke<bool>(
4250 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
4251 this, content->name, transport_name))) {
4252 return false;
4253 }
4254 } else {
4255 std::string transport_name =
4256 bundle_transport ? *bundle_transport : content->name;
4257 cricket::DtlsTransportInternal* rtp_dtls_transport =
4258 transport_controller_->CreateDtlsTransport(
4259 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4260 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4261 if (configuration_.rtcp_mux_policy !=
4262 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4263 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4264 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4265 }
4266
4267 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4268 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
4269 transport_controller_->signaling_thread(), content->name,
4270 SrtpRequired());
4271
4272 if (!rtp_data_channel_) {
4273 transport_controller_->DestroyDtlsTransport(
4274 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4275 if (rtcp_dtls_transport) {
4276 transport_controller_->DestroyDtlsTransport(
4277 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4278 }
4279 return false;
4280 }
4281
4282 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4283 this, &PeerConnection::DestroyRtcpTransport_n);
4284 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4285 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4286 rtp_data_channel_->SignalSentPacket.connect(
4287 this, &PeerConnection::OnSentPacket_w);
4288 }
4289
Steve Antond25da372017-11-06 14:50:29 -08004290 for (const auto& channel : sctp_data_channels_) {
4291 channel->OnTransportChannelCreated();
4292 }
Steve Anton75737c02017-11-06 10:37:17 -08004293
4294 return true;
4295}
4296
4297Call::Stats PeerConnection::GetCallStats() {
4298 if (!worker_thread()->IsCurrent()) {
4299 return worker_thread()->Invoke<Call::Stats>(
4300 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4301 }
4302 if (call_) {
4303 return call_->GetStats();
4304 } else {
4305 return Call::Stats();
4306 }
4307}
4308
4309std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4310 const ChannelNamePairs& channel_name_pairs) {
4311 RTC_DCHECK(network_thread()->IsCurrent());
4312 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4313 for (const auto channel_name_pair :
4314 {&channel_name_pairs.voice, &channel_name_pairs.video,
4315 &channel_name_pairs.data}) {
4316 if (*channel_name_pair) {
4317 cricket::TransportStats transport_stats;
4318 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4319 &transport_stats)) {
4320 return nullptr;
4321 }
4322 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4323 (*channel_name_pair)->transport_name;
4324 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4325 std::move(transport_stats);
4326 }
4327 }
4328 return session_stats;
4329}
4330
4331bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4332 const std::string& transport_name) {
4333 RTC_DCHECK(network_thread()->IsCurrent());
4334 RTC_DCHECK(sctp_factory_);
4335 cricket::DtlsTransportInternal* tc =
4336 transport_controller_->CreateDtlsTransport_n(
4337 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4338 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4339 RTC_DCHECK(sctp_transport_);
4340 sctp_invoker_.reset(new rtc::AsyncInvoker());
4341 sctp_transport_->SignalReadyToSendData.connect(
4342 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4343 sctp_transport_->SignalDataReceived.connect(
4344 this, &PeerConnection::OnSctpTransportDataReceived_n);
4345 sctp_transport_->SignalStreamClosedRemotely.connect(
4346 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
4347 sctp_transport_name_ = rtc::Optional<std::string>(transport_name);
4348 sctp_content_name_ = rtc::Optional<std::string>(content_name);
4349 return true;
4350}
4351
4352void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4353 RTC_DCHECK(network_thread()->IsCurrent());
4354 RTC_DCHECK(sctp_transport_);
4355 RTC_DCHECK(sctp_transport_name_);
4356 std::string old_sctp_transport_name = *sctp_transport_name_;
4357 sctp_transport_name_ = rtc::Optional<std::string>(transport_name);
4358 cricket::DtlsTransportInternal* tc =
4359 transport_controller_->CreateDtlsTransport_n(
4360 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4361 sctp_transport_->SetTransportChannel(tc);
4362 transport_controller_->DestroyDtlsTransport_n(
4363 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4364}
4365
4366void PeerConnection::DestroySctpTransport_n() {
4367 RTC_DCHECK(network_thread()->IsCurrent());
4368 sctp_transport_.reset(nullptr);
4369 sctp_content_name_.reset();
4370 sctp_transport_name_.reset();
4371 sctp_invoker_.reset(nullptr);
4372 sctp_ready_to_send_data_ = false;
4373}
4374
4375void PeerConnection::OnSctpTransportReadyToSendData_n() {
4376 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4377 RTC_DCHECK(network_thread()->IsCurrent());
4378 // Note: Cannot use rtc::Bind here because it will grab a reference to
4379 // PeerConnection and potentially cause PeerConnection to live longer than
4380 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4381 // be destroyed before PeerConnection is destroyed, and at that point all
4382 // pending tasks will be cleared.
4383 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4384 OnSctpTransportReadyToSendData_s(true);
4385 });
4386}
4387
4388void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4389 RTC_DCHECK(signaling_thread()->IsCurrent());
4390 sctp_ready_to_send_data_ = ready;
4391 SignalSctpReadyToSendData(ready);
4392}
4393
4394void PeerConnection::OnSctpTransportDataReceived_n(
4395 const cricket::ReceiveDataParams& params,
4396 const rtc::CopyOnWriteBuffer& payload) {
4397 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4398 RTC_DCHECK(network_thread()->IsCurrent());
4399 // Note: Cannot use rtc::Bind here because it will grab a reference to
4400 // PeerConnection and potentially cause PeerConnection to live longer than
4401 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4402 // be destroyed before PeerConnection is destroyed, and at that point all
4403 // pending tasks will be cleared.
4404 sctp_invoker_->AsyncInvoke<void>(
4405 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4406 OnSctpTransportDataReceived_s(params, payload);
4407 });
4408}
4409
4410void PeerConnection::OnSctpTransportDataReceived_s(
4411 const cricket::ReceiveDataParams& params,
4412 const rtc::CopyOnWriteBuffer& payload) {
4413 RTC_DCHECK(signaling_thread()->IsCurrent());
4414 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4415 // Received OPEN message; parse and signal that a new data channel should
4416 // be created.
4417 std::string label;
4418 InternalDataChannelInit config;
4419 config.id = params.ssrc;
4420 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004421 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4422 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004423 return;
4424 }
4425 config.open_handshake_role = InternalDataChannelInit::kAcker;
4426 OnDataChannelOpenMessage(label, config);
4427 } else {
4428 // Otherwise just forward the signal.
4429 SignalSctpDataReceived(params, payload);
4430 }
4431}
4432
4433void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4434 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4435 RTC_DCHECK(network_thread()->IsCurrent());
4436 sctp_invoker_->AsyncInvoke<void>(
4437 RTC_FROM_HERE, signaling_thread(),
4438 rtc::Bind(&sigslot::signal1<int>::operator(),
4439 &SignalSctpStreamClosedRemotely, sid));
4440}
4441
4442// Returns false if bundle is enabled and rtcp_mux is disabled.
4443bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4444 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4445 if (!bundle_enabled)
4446 return true;
4447
4448 const cricket::ContentGroup* bundle_group =
4449 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4450 RTC_DCHECK(bundle_group != NULL);
4451
4452 const cricket::ContentInfos& contents = desc->contents();
4453 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4454 citer != contents.end(); ++citer) {
4455 const cricket::ContentInfo* content = (&*citer);
4456 RTC_DCHECK(content != NULL);
4457 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4458 content->type == cricket::NS_JINGLE_RTP) {
4459 if (!HasRtcpMuxEnabled(content))
4460 return false;
4461 }
4462 }
4463 // RTCP-MUX is enabled in all the contents.
4464 return true;
4465}
4466
4467bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4468 const cricket::MediaContentDescription* description =
4469 static_cast<cricket::MediaContentDescription*>(content->description);
4470 return description->rtcp_mux();
4471}
4472
4473bool PeerConnection::ValidateSessionDescription(
4474 const SessionDescriptionInterface* sdesc,
4475 cricket::ContentSource source,
4476 std::string* err_desc) {
4477 std::string type;
4478 if (error() != ERROR_NONE) {
4479 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
4480 }
4481
4482 if (!sdesc || !sdesc->description()) {
4483 return BadSdp(source, type, kInvalidSdp, err_desc);
4484 }
4485
4486 type = sdesc->type();
4487 Action action = GetAction(sdesc->type());
4488 if (source == cricket::CS_LOCAL) {
4489 if (!ExpectSetLocalDescription(action))
4490 return BadLocalSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4491 } else {
4492 if (!ExpectSetRemoteDescription(action))
4493 return BadRemoteSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4494 }
4495
4496 // Verify crypto settings.
4497 std::string crypto_error;
4498 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4499 dtls_enabled_) &&
4500 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
4501 return BadSdp(source, type, crypto_error, err_desc);
4502 }
4503
4504 // Verify ice-ufrag and ice-pwd.
4505 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
4506 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
4507 }
4508
4509 if (!ValidateBundleSettings(sdesc->description())) {
4510 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
4511 }
4512
4513 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4514 // m-lines that do not rtcp-mux enabled.
4515
4516 // Verify m-lines in Answer when compared against Offer.
4517 if (action == kAnswer || action == kPrAnswer) {
4518 const cricket::SessionDescription* offer_desc =
4519 (source == cricket::CS_LOCAL) ? remote_description()->description()
4520 : local_description()->description();
4521 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4522 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
4523 return BadAnswerSdp(source, kMlineMismatchInAnswer, err_desc);
4524 }
4525 } else {
4526 const cricket::SessionDescription* current_desc = nullptr;
4527 if (source == cricket::CS_LOCAL && local_description()) {
4528 current_desc = local_description()->description();
4529 } else if (source == cricket::CS_REMOTE && remote_description()) {
4530 current_desc = remote_description()->description();
4531 }
4532 // The re-offers should respect the order of m= sections in current
4533 // description. See RFC3264 Section 8 paragraph 4 for more details.
4534 if (current_desc &&
4535 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
4536 return BadOfferSdp(source, kMlineMismatchInSubsequentOffer, err_desc);
4537 }
4538 }
4539
4540 return true;
4541}
4542
4543bool PeerConnection::ExpectSetLocalDescription(Action action) {
4544 PeerConnectionInterface::SignalingState state = signaling_state();
4545 if (action == kOffer) {
4546 return (state == PeerConnectionInterface::kStable) ||
4547 (state == PeerConnectionInterface::kHaveLocalOffer);
4548 } else { // Answer or PrAnswer
4549 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4550 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4551 }
4552}
4553
4554bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4555 PeerConnectionInterface::SignalingState state = signaling_state();
4556 if (action == kOffer) {
4557 return (state == PeerConnectionInterface::kStable) ||
4558 (state == PeerConnectionInterface::kHaveRemoteOffer);
4559 } else { // Answer or PrAnswer.
4560 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4561 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4562 }
4563}
4564
4565std::string PeerConnection::GetSessionErrorMsg() {
4566 std::ostringstream desc;
4567 desc << kSessionError << GetErrorCodeString(error()) << ". ";
4568 desc << kSessionErrorDesc << error_desc() << ".";
4569 return desc.str();
4570}
4571
4572// We need to check the local/remote description for the Transport instead of
4573// the session, because a new Transport added during renegotiation may have
4574// them unset while the session has them set from the previous negotiation.
4575// Not doing so may trigger the auto generation of transport description and
4576// mess up DTLS identity information, ICE credential, etc.
4577bool PeerConnection::ReadyToUseRemoteCandidate(
4578 const IceCandidateInterface* candidate,
4579 const SessionDescriptionInterface* remote_desc,
4580 bool* valid) {
4581 *valid = true;
4582
4583 const SessionDescriptionInterface* current_remote_desc =
4584 remote_desc ? remote_desc : remote_description();
4585
4586 if (!current_remote_desc) {
4587 return false;
4588 }
4589
4590 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4591 size_t remote_content_size =
4592 current_remote_desc->description()->contents().size();
4593 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004594 RTC_LOG(LS_ERROR)
4595 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4596 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004597
4598 *valid = false;
4599 return false;
4600 }
4601
4602 cricket::ContentInfo content =
4603 current_remote_desc->description()->contents()[mediacontent_index];
4604
4605 const std::string transport_name = GetTransportName(content.name);
4606 if (transport_name.empty()) {
4607 return false;
4608 }
4609 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4610}
4611
4612bool PeerConnection::SrtpRequired() const {
4613 return dtls_enabled_ ||
4614 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4615}
4616
4617void PeerConnection::OnTransportControllerGatheringState(
4618 cricket::IceGatheringState state) {
4619 RTC_DCHECK(signaling_thread()->IsCurrent());
4620 if (state == cricket::kIceGatheringGathering) {
4621 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4622 } else if (state == cricket::kIceGatheringComplete) {
4623 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4624 }
4625}
4626
4627void PeerConnection::ReportTransportStats() {
4628 // Use a set so we don't report the same stats twice if two channels share
4629 // a transport.
4630 std::set<std::string> transport_names;
4631 if (voice_channel()) {
4632 transport_names.insert(voice_channel()->transport_name());
4633 }
4634 if (video_channel()) {
4635 transport_names.insert(video_channel()->transport_name());
4636 }
4637 if (rtp_data_channel()) {
4638 transport_names.insert(rtp_data_channel()->transport_name());
4639 }
4640 if (sctp_transport_name_) {
4641 transport_names.insert(*sctp_transport_name_);
4642 }
4643 for (const auto& name : transport_names) {
4644 cricket::TransportStats stats;
4645 if (transport_controller_->GetStats(name, &stats)) {
4646 ReportBestConnectionState(stats);
4647 ReportNegotiatedCiphers(stats);
4648 }
4649 }
4650}
4651// Walk through the ConnectionInfos to gather best connection usage
4652// for IPv4 and IPv6.
4653void PeerConnection::ReportBestConnectionState(
4654 const cricket::TransportStats& stats) {
4655 RTC_DCHECK(metrics_observer());
4656 for (cricket::TransportChannelStatsList::const_iterator it =
4657 stats.channel_stats.begin();
4658 it != stats.channel_stats.end(); ++it) {
4659 for (cricket::ConnectionInfos::const_iterator it_info =
4660 it->connection_infos.begin();
4661 it_info != it->connection_infos.end(); ++it_info) {
4662 if (!it_info->best_connection) {
4663 continue;
4664 }
4665
4666 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4667 const cricket::Candidate& local = it_info->local_candidate;
4668 const cricket::Candidate& remote = it_info->remote_candidate;
4669
4670 // Increment the counter for IceCandidatePairType.
4671 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4672 (local.type() == RELAY_PORT_TYPE &&
4673 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4674 type = kEnumCounterIceCandidatePairTypeTcp;
4675 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4676 type = kEnumCounterIceCandidatePairTypeUdp;
4677 } else {
4678 RTC_CHECK(0);
4679 }
4680 metrics_observer()->IncrementEnumCounter(
4681 type, GetIceCandidatePairCounter(local, remote),
4682 kIceCandidatePairMax);
4683
4684 // Increment the counter for IP type.
4685 if (local.address().family() == AF_INET) {
4686 metrics_observer()->IncrementEnumCounter(
4687 kEnumCounterAddressFamily, kBestConnections_IPv4,
4688 kPeerConnectionAddressFamilyCounter_Max);
4689
4690 } else if (local.address().family() == AF_INET6) {
4691 metrics_observer()->IncrementEnumCounter(
4692 kEnumCounterAddressFamily, kBestConnections_IPv6,
4693 kPeerConnectionAddressFamilyCounter_Max);
4694 } else {
4695 RTC_CHECK(0);
4696 }
4697
4698 return;
4699 }
4700 }
4701}
4702
4703void PeerConnection::ReportNegotiatedCiphers(
4704 const cricket::TransportStats& stats) {
4705 RTC_DCHECK(metrics_observer());
4706 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4707 return;
4708 }
4709
4710 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4711 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4712 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4713 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4714 return;
4715 }
4716
4717 PeerConnectionEnumCounterType srtp_counter_type;
4718 PeerConnectionEnumCounterType ssl_counter_type;
4719 if (stats.transport_name == cricket::CN_AUDIO) {
4720 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4721 ssl_counter_type = kEnumCounterAudioSslCipher;
4722 } else if (stats.transport_name == cricket::CN_VIDEO) {
4723 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4724 ssl_counter_type = kEnumCounterVideoSslCipher;
4725 } else if (stats.transport_name == cricket::CN_DATA) {
4726 srtp_counter_type = kEnumCounterDataSrtpCipher;
4727 ssl_counter_type = kEnumCounterDataSslCipher;
4728 } else {
4729 RTC_NOTREACHED();
4730 return;
4731 }
4732
4733 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4734 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4735 srtp_crypto_suite);
4736 }
4737 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4738 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4739 ssl_cipher_suite);
4740 }
4741}
4742
4743void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4744 RTC_DCHECK(worker_thread()->IsCurrent());
4745 RTC_DCHECK(call_);
4746 call_->OnSentPacket(sent_packet);
4747}
4748
4749const std::string PeerConnection::GetTransportName(
4750 const std::string& content_name) {
4751 cricket::BaseChannel* channel = GetChannel(content_name);
4752 if (!channel) {
4753 if (sctp_transport_) {
4754 RTC_DCHECK(sctp_content_name_);
4755 RTC_DCHECK(sctp_transport_name_);
4756 if (content_name == *sctp_content_name_) {
4757 return *sctp_transport_name_;
4758 }
4759 }
4760 // Return an empty string if failed to retrieve the transport name.
4761 return "";
4762 }
4763 return channel->transport_name();
4764}
4765
4766void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4767 RTC_DCHECK(network_thread()->IsCurrent());
4768 transport_controller_->DestroyDtlsTransport_n(
4769 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4770}
4771
4772void PeerConnection::RemoveAndDestroyVideoChannel(
4773 cricket::VideoChannel* video_channel) {
4774 auto it =
4775 std::find(video_channels_.begin(), video_channels_.end(), video_channel);
4776 RTC_DCHECK(it != video_channels_.end());
4777 if (it == video_channels_.end()) {
4778 return;
4779 }
4780 video_channels_.erase(it);
4781 DestroyVideoChannel(video_channel);
4782}
4783
4784void PeerConnection::DestroyVideoChannel(cricket::VideoChannel* video_channel) {
Steve Antond25da372017-11-06 14:50:29 -08004785 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
4786 cricket::VideoChannel>(
4787 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
Steve Anton75737c02017-11-06 10:37:17 -08004788 RTC_DCHECK(video_channel->rtp_dtls_transport());
4789 const std::string transport_name =
4790 video_channel->rtp_dtls_transport()->transport_name();
4791 const bool need_to_delete_rtcp =
4792 (video_channel->rtcp_dtls_transport() != nullptr);
4793 // The above need to be cached before destroying the video channel so that we
4794 // do not access uninitialized memory.
4795 channel_manager()->DestroyVideoChannel(video_channel);
4796 transport_controller_->DestroyDtlsTransport(
4797 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4798 if (need_to_delete_rtcp) {
4799 transport_controller_->DestroyDtlsTransport(
4800 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4801 }
4802}
4803
4804void PeerConnection::RemoveAndDestroyVoiceChannel(
4805 cricket::VoiceChannel* voice_channel) {
4806 auto it =
4807 std::find(voice_channels_.begin(), voice_channels_.end(), voice_channel);
4808 RTC_DCHECK(it != voice_channels_.end());
4809 if (it == voice_channels_.end()) {
4810 return;
4811 }
4812 voice_channels_.erase(it);
4813 DestroyVoiceChannel(voice_channel);
4814}
4815
4816void PeerConnection::DestroyVoiceChannel(cricket::VoiceChannel* voice_channel) {
Steve Antond25da372017-11-06 14:50:29 -08004817 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
4818 cricket::VoiceChannel>(
4819 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
Steve Anton75737c02017-11-06 10:37:17 -08004820 RTC_DCHECK(voice_channel->rtp_dtls_transport());
4821 const std::string transport_name =
4822 voice_channel->rtp_dtls_transport()->transport_name();
4823 const bool need_to_delete_rtcp =
4824 (voice_channel->rtcp_dtls_transport() != nullptr);
4825 // The above need to be cached before destroying the video channel so that we
4826 // do not access uninitialized memory.
4827 channel_manager()->DestroyVoiceChannel(voice_channel);
4828 transport_controller_->DestroyDtlsTransport(
4829 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4830 if (need_to_delete_rtcp) {
4831 transport_controller_->DestroyDtlsTransport(
4832 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4833 }
4834}
4835
4836void PeerConnection::DestroyDataChannel() {
4837 OnDataChannelDestroyed();
4838 RTC_DCHECK(rtp_data_channel_->rtp_dtls_transport());
4839 std::string transport_name;
4840 transport_name = rtp_data_channel_->rtp_dtls_transport()->transport_name();
4841 bool need_to_delete_rtcp =
4842 (rtp_data_channel_->rtcp_dtls_transport() != nullptr);
4843 channel_manager()->DestroyRtpDataChannel(rtp_data_channel_);
4844 rtp_data_channel_ = nullptr;
4845 transport_controller_->DestroyDtlsTransport(
4846 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4847 if (need_to_delete_rtcp) {
4848 transport_controller_->DestroyDtlsTransport(
4849 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4850 }
4851}
4852
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004853} // namespace webrtc