blob: 3ea4a3f3d8e2eaf5dbdd3719218cf8a963c41375 [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()) {
1426 std::string error = "Failed to set local " + desc->type() +
1427 " 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;
Steve Anton75737c02017-11-06 10:37:17 -08001437 if (!SetLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001438 PostSetSessionDescriptionFailure(observer, error);
1439 return;
1440 }
deadbeefab9b2d12015-10-14 11:33:11 -07001441
1442 // If setting the description decided our SSL role, allocate any necessary
1443 // SCTP sids.
1444 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001445 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001446 AllocateSctpSids(role);
1447 }
1448
1449 // Update state and SSRC of local MediaStreams and DataChannels based on the
1450 // local session description.
1451 const cricket::ContentInfo* audio_content =
1452 GetFirstAudioContent(desc->description());
1453 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001454 if (audio_content->rejected) {
1455 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1456 } else {
1457 const cricket::AudioContentDescription* audio_desc =
1458 static_cast<const cricket::AudioContentDescription*>(
1459 audio_content->description);
1460 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1461 }
deadbeefab9b2d12015-10-14 11:33:11 -07001462 }
1463
1464 const cricket::ContentInfo* video_content =
1465 GetFirstVideoContent(desc->description());
1466 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001467 if (video_content->rejected) {
1468 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1469 } else {
1470 const cricket::VideoContentDescription* video_desc =
1471 static_cast<const cricket::VideoContentDescription*>(
1472 video_content->description);
1473 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1474 }
deadbeefab9b2d12015-10-14 11:33:11 -07001475 }
1476
1477 const cricket::ContentInfo* data_content =
1478 GetFirstDataContent(desc->description());
1479 if (data_content) {
1480 const cricket::DataContentDescription* data_desc =
1481 static_cast<const cricket::DataContentDescription*>(
1482 data_content->description);
1483 if (rtc::starts_with(data_desc->protocol().data(),
1484 cricket::kMediaProtocolRtpPrefix)) {
1485 UpdateLocalRtpDataChannels(data_desc->streams());
1486 }
1487 }
1488
1489 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001490 signaling_thread()->Post(RTC_FROM_HERE, this,
1491 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001492
deadbeef42a42632017-03-10 15:18:00 -08001493 // According to JSEP, after setLocalDescription, changing the candidate pool
1494 // size is not allowed, and changing the set of ICE servers will not result
1495 // in new candidates being gathered.
1496 port_allocator_->FreezeCandidatePool();
1497
deadbeefcbecd352015-09-23 11:50:27 -07001498 // MaybeStartGathering needs to be called after posting
1499 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1500 // before signaling that SetLocalDescription completed.
Steve Antond25da372017-11-06 14:50:29 -08001501 transport_controller_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001502
1503 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1504 // TODO(deadbeef): We already had to hop to the network thread for
1505 // MaybeStartGathering...
1506 network_thread()->Invoke<void>(
1507 RTC_FROM_HERE,
1508 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1509 port_allocator_.get()));
1510 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001511}
1512
1513void PeerConnection::SetRemoteDescription(
1514 SetSessionDescriptionObserver* observer,
1515 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001516 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001517 if (!observer) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001518 RTC_LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001519 return;
1520 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001521 if (!desc) {
1522 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1523 return;
1524 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001525
1526 // Takes the ownership of |desc| regardless of the result.
1527 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1528
1529 if (IsClosed()) {
1530 std::string error = "Failed to set remote " + desc->type() +
1531 " sdp: Called in wrong state: STATE_CLOSED";
Mirko Bonadei675513b2017-11-09 11:09:25 +01001532 RTC_LOG(LS_ERROR) << error;
Steve Anton8d3444d2017-10-20 15:30:51 -07001533 PostSetSessionDescriptionFailure(observer, error);
1534 return;
1535 }
1536
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001537 // Update stats here so that we have the most recent stats for tracks and
1538 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001539 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001540 std::string error;
Steve Anton75737c02017-11-06 10:37:17 -08001541 if (!SetRemoteDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001542 PostSetSessionDescriptionFailure(observer, error);
1543 return;
1544 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001545
deadbeefab9b2d12015-10-14 11:33:11 -07001546 // If setting the description decided our SSL role, allocate any necessary
1547 // SCTP sids.
1548 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001549 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001550 AllocateSctpSids(role);
1551 }
1552
1553 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001554 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1555 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1556 const cricket::AudioContentDescription* audio_desc =
1557 GetFirstAudioContentDescription(remote_desc);
1558 const cricket::VideoContentDescription* video_desc =
1559 GetFirstVideoContentDescription(remote_desc);
1560 const cricket::DataContentDescription* data_desc =
1561 GetFirstDataContentDescription(remote_desc);
1562
1563 // Check if the descriptions include streams, just in case the peer supports
1564 // MSID, but doesn't indicate so with "a=msid-semantic".
1565 if (remote_desc->msid_supported() ||
1566 (audio_desc && !audio_desc->streams().empty()) ||
1567 (video_desc && !video_desc->streams().empty())) {
1568 remote_peer_supports_msid_ = true;
1569 }
deadbeefab9b2d12015-10-14 11:33:11 -07001570
1571 // We wait to signal new streams until we finish processing the description,
1572 // since only at that point will new streams have all their tracks.
1573 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1574
Steve Anton8d3444d2017-10-20 15:30:51 -07001575 // TODO(steveanton): When removing RTP senders/receivers in response to a
1576 // rejected media section, there is some cleanup logic that expects the voice/
1577 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001578 // would have been destroyed by the SetRemoteDescription caller above so the
1579 // cleanup that relies on them fails to run. The RemoveTracks calls should be
1580 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001581
deadbeefab9b2d12015-10-14 11:33:11 -07001582 // Find all audio rtp streams and create corresponding remote AudioTracks
1583 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001584 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001585 if (audio_content->rejected) {
1586 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1587 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001588 bool default_audio_track_needed =
1589 !remote_peer_supports_msid_ &&
1590 MediaContentDirectionHasSend(audio_desc->direction());
1591 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1592 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001593 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001594 }
deadbeefab9b2d12015-10-14 11:33:11 -07001595 }
1596
1597 // Find all video rtp streams and create corresponding remote VideoTracks
1598 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001599 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001600 if (video_content->rejected) {
1601 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1602 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001603 bool default_video_track_needed =
1604 !remote_peer_supports_msid_ &&
1605 MediaContentDirectionHasSend(video_desc->direction());
1606 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1607 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001608 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001609 }
deadbeefab9b2d12015-10-14 11:33:11 -07001610 }
1611
1612 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001613 if (data_desc) {
1614 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001615 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001616 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001617 }
1618 }
1619
1620 // Iterate new_streams and notify the observer about new MediaStreams.
1621 for (size_t i = 0; i < new_streams->count(); ++i) {
1622 MediaStreamInterface* new_stream = new_streams->at(i);
1623 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001624 observer_->OnAddStream(
1625 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001626 }
1627
deadbeefbda7e0b2015-12-08 17:13:40 -08001628 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001629
1630 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001631 signaling_thread()->Post(RTC_FROM_HERE, this,
1632 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001633
1634 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1635 // TODO(deadbeef): We already had to hop to the network thread for
1636 // MaybeStartGathering...
1637 network_thread()->Invoke<void>(
1638 RTC_FROM_HERE,
1639 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1640 port_allocator_.get()));
1641 }
deadbeeffc648b62015-10-13 16:42:33 -07001642}
1643
deadbeef46c73892016-11-16 19:42:04 -08001644PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1645 return configuration_;
1646}
1647
deadbeef293e9262017-01-11 12:28:30 -08001648bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1649 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001650 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001651
Steve Anton75737c02017-11-06 10:37:17 -08001652 if (local_description() && configuration.ice_candidate_pool_size !=
1653 configuration_.ice_candidate_pool_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001654 RTC_LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1655 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001656 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001657 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001658
deadbeef293e9262017-01-11 12:28:30 -08001659 // The simplest (and most future-compatible) way to tell if the config was
1660 // modified in an invalid way is to copy each property we do support
1661 // modifying, then use operator==. There are far more properties we don't
1662 // support modifying than those we do, and more could be added.
1663 RTCConfiguration modified_config = configuration_;
1664 modified_config.servers = configuration.servers;
1665 modified_config.type = configuration.type;
1666 modified_config.ice_candidate_pool_size =
1667 configuration.ice_candidate_pool_size;
1668 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001669 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001670 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001671 if (configuration != modified_config) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001672 RTC_LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
deadbeef293e9262017-01-11 12:28:30 -08001673 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1674 }
1675
Steve Anton038834f2017-07-14 15:59:59 -07001676 // Validate the modified configuration.
1677 RTCError validate_error = ValidateConfiguration(modified_config);
1678 if (!validate_error.ok()) {
1679 return SafeSetError(std::move(validate_error), error);
1680 }
1681
deadbeef293e9262017-01-11 12:28:30 -08001682 // Note that this isn't possible through chromium, since it's an unsigned
1683 // short in WebIDL.
1684 if (configuration.ice_candidate_pool_size < 0 ||
1685 configuration.ice_candidate_pool_size > UINT16_MAX) {
1686 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1687 }
1688
1689 // Parse ICE servers before hopping to network thread.
1690 cricket::ServerAddresses stun_servers;
1691 std::vector<cricket::RelayServerConfig> turn_servers;
1692 RTCErrorType parse_error =
1693 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1694 if (parse_error != RTCErrorType::NONE) {
1695 return SafeSetError(parse_error, error);
1696 }
1697
1698 // In theory this shouldn't fail.
1699 if (!network_thread()->Invoke<bool>(
1700 RTC_FROM_HERE,
1701 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1702 stun_servers, turn_servers, modified_config.type,
1703 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001704 modified_config.prune_turn_ports,
1705 modified_config.turn_customizer))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001706 RTC_LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
deadbeef293e9262017-01-11 12:28:30 -08001707 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1708 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001709
deadbeefd1a38b52016-12-10 13:15:33 -08001710 // As described in JSEP, calling setConfiguration with new ICE servers or
1711 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1712 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001713 if (modified_config.servers != configuration_.servers ||
1714 modified_config.type != configuration_.type ||
1715 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001716 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001717 }
skvladd1f5fda2017-02-03 16:54:05 -08001718
1719 if (modified_config.ice_check_min_interval !=
1720 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001721 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001722 }
1723
deadbeef293e9262017-01-11 12:28:30 -08001724 configuration_ = modified_config;
1725 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001726}
1727
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001728bool PeerConnection::AddIceCandidate(
1729 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001730 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001731 if (IsClosed()) {
1732 return false;
1733 }
Steve Antond25da372017-11-06 14:50:29 -08001734
1735 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001736 RTC_LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1737 << "without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001738 return false;
1739 }
1740
1741 if (!ice_candidate) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001742 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
Steve Antond25da372017-11-06 14:50:29 -08001743 return false;
1744 }
1745
1746 bool valid = false;
1747 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1748 if (!valid) {
1749 return false;
1750 }
1751
1752 // Add this candidate to the remote session description.
1753 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001754 RTC_LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
Steve Antond25da372017-11-06 14:50:29 -08001755 return false;
1756 }
1757
1758 if (ready) {
1759 return UseCandidate(ice_candidate);
1760 } else {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001761 RTC_LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
Steve Antond25da372017-11-06 14:50:29 -08001762 return true;
1763 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001764}
1765
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001766bool PeerConnection::RemoveIceCandidates(
1767 const std::vector<cricket::Candidate>& candidates) {
1768 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001769 if (!remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001770 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1771 << "removed without any remote session description.";
Steve Antond25da372017-11-06 14:50:29 -08001772 return false;
1773 }
1774
1775 if (candidates.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001776 RTC_LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
Steve Antond25da372017-11-06 14:50:29 -08001777 return false;
1778 }
1779
1780 size_t number_removed =
1781 mutable_remote_description()->RemoveCandidates(candidates);
1782 if (number_removed != candidates.size()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001783 RTC_LOG(LS_ERROR)
1784 << "RemoveRemoteIceCandidates: Failed to remove candidates. "
1785 << "Requested " << candidates.size() << " but only " << number_removed
1786 << " are removed.";
Steve Antond25da372017-11-06 14:50:29 -08001787 }
1788
1789 // Remove the candidates from the transport controller.
1790 std::string error;
1791 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
1792 if (!res && !error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01001793 RTC_LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
Steve Antond25da372017-11-06 14:50:29 -08001794 }
1795 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001796}
1797
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001798void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001799 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001800 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001801
Steve Anton75737c02017-11-06 10:37:17 -08001802 if (transport_controller()) {
1803 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001804 }
1805
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001806 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001807 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001808 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001809 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001810 uma_observer_->IncrementEnumCounter(
1811 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1812 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001813 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001814 uma_observer_->IncrementEnumCounter(
1815 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1816 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001817 }
1818 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001819}
1820
zstein4b979802017-06-02 14:37:37 -07001821RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001822 if (!worker_thread()->IsCurrent()) {
1823 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001824 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1825 }
1826
1827 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1828 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1829 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1830 if (has_min && *bitrate.min_bitrate_bps < 0) {
1831 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1832 "min_bitrate_bps <= 0");
1833 }
1834 if (has_current) {
1835 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1836 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1837 "current_bitrate_bps < min_bitrate_bps");
1838 } else if (*bitrate.current_bitrate_bps < 0) {
1839 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1840 "curent_bitrate_bps < 0");
1841 }
1842 }
1843 if (has_max) {
1844 if (has_current &&
1845 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1846 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1847 "max_bitrate_bps < current_bitrate_bps");
1848 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1849 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1850 "max_bitrate_bps < min_bitrate_bps");
1851 } else if (*bitrate.max_bitrate_bps < 0) {
1852 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1853 "max_bitrate_bps < 0");
1854 }
1855 }
1856
1857 Call::Config::BitrateConfigMask mask;
1858 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1859 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1860 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1861
1862 RTC_DCHECK(call_.get());
1863 call_->SetBitrateConfigMask(mask);
1864
1865 return RTCError::OK();
1866}
1867
Alex Narest78609d52017-10-20 10:37:47 +02001868void PeerConnection::SetBitrateAllocationStrategy(
1869 std::unique_ptr<rtc::BitrateAllocationStrategy>
1870 bitrate_allocation_strategy) {
1871 rtc::Thread* worker_thread = factory_->worker_thread();
1872 if (!worker_thread->IsCurrent()) {
1873 rtc::BitrateAllocationStrategy* strategy_raw =
1874 bitrate_allocation_strategy.release();
1875 auto functor = [this, strategy_raw]() {
1876 call_->SetBitrateAllocationStrategy(
1877 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
1878 };
1879 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
1880 return;
1881 }
1882 RTC_DCHECK(call_.get());
1883 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
1884}
1885
henrika5f6bf242017-11-01 11:06:56 +01001886void PeerConnection::SetAudioPlayout(bool playout) {
1887 if (!worker_thread()->IsCurrent()) {
1888 worker_thread()->Invoke<void>(
1889 RTC_FROM_HERE,
1890 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
1891 return;
1892 }
1893 auto audio_state =
1894 factory_->channel_manager()->media_engine()->GetAudioState();
1895 audio_state->SetPlayout(playout);
1896}
1897
1898void PeerConnection::SetAudioRecording(bool recording) {
1899 if (!worker_thread()->IsCurrent()) {
1900 worker_thread()->Invoke<void>(
1901 RTC_FROM_HERE,
1902 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
1903 return;
1904 }
1905 auto audio_state =
1906 factory_->channel_manager()->media_engine()->GetAudioState();
1907 audio_state->SetRecording(recording);
1908}
1909
Steve Anton8c0f7a72017-10-03 10:03:10 -07001910std::unique_ptr<rtc::SSLCertificate>
1911PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08001912 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07001913 return nullptr;
1914 }
Steve Anton75737c02017-11-06 10:37:17 -08001915 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001916}
1917
ivoc14d5dbe2016-07-04 07:06:55 -07001918bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1919 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02001920 // TODO(eladalon): It would be better to not allow negative values into PC.
1921 const size_t max_size = (max_size_bytes < 0)
1922 ? RtcEventLog::kUnlimitedOutput
1923 : rtc::saturated_cast<size_t>(max_size_bytes);
1924 return StartRtcEventLog(
1925 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size));
1926}
1927
1928bool PeerConnection::StartRtcEventLog(
1929 std::unique_ptr<RtcEventLogOutput> output) {
Karl Wibergd6b48192017-10-16 23:01:06 +02001930 // TODO(eladalon): In C++14, this can be done with a lambda.
1931 struct Functor {
1932 bool operator()() { return pc->StartRtcEventLog_w(std::move(output)); }
1933 PeerConnection* const pc;
1934 std::unique_ptr<RtcEventLogOutput> output;
Elad Alon99c3fe52017-10-13 16:29:40 +02001935 };
Karl Wibergd6b48192017-10-16 23:01:06 +02001936 return worker_thread()->Invoke<bool>(RTC_FROM_HERE,
1937 Functor{this, std::move(output)});
ivoc14d5dbe2016-07-04 07:06:55 -07001938}
1939
1940void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001941 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001942 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1943}
1944
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001945const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08001946 return pending_local_description_ ? pending_local_description_.get()
1947 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001948}
1949
1950const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08001951 return pending_remote_description_ ? pending_remote_description_.get()
1952 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001953}
1954
deadbeeffe4a8a42016-12-20 17:56:17 -08001955const SessionDescriptionInterface* PeerConnection::current_local_description()
1956 const {
Steve Anton75737c02017-11-06 10:37:17 -08001957 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001958}
1959
1960const SessionDescriptionInterface* PeerConnection::current_remote_description()
1961 const {
Steve Anton75737c02017-11-06 10:37:17 -08001962 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001963}
1964
1965const SessionDescriptionInterface* PeerConnection::pending_local_description()
1966 const {
Steve Anton75737c02017-11-06 10:37:17 -08001967 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001968}
1969
1970const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1971 const {
Steve Anton75737c02017-11-06 10:37:17 -08001972 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001973}
1974
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001975void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001976 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001977 // Update stats here so that we have the most recent stats for tracks and
1978 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001979 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001980
Steve Anton75737c02017-11-06 10:37:17 -08001981 ChangeSignalingState(PeerConnectionInterface::kClosed);
1982 RemoveUnusedChannels(nullptr);
1983 RTC_DCHECK(voice_channels_.empty());
1984 RTC_DCHECK(video_channels_.empty());
1985 RTC_DCHECK(!rtp_data_channel_);
1986 RTC_DCHECK(!sctp_transport_);
1987
deadbeef42a42632017-03-10 15:18:00 -08001988 network_thread()->Invoke<void>(
1989 RTC_FROM_HERE,
1990 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1991 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001992
Steve Anton978b8762017-09-29 12:15:02 -07001993 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07001994 call_.reset();
1995 // The event log must outlive call (and any other object that uses it).
1996 event_log_.reset();
1997 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001998}
1999
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00002000void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002001 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002002 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
2003 SetSessionDescriptionMsg* param =
2004 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2005 param->observer->OnSuccess();
2006 delete param;
2007 break;
2008 }
2009 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2010 SetSessionDescriptionMsg* param =
2011 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2012 param->observer->OnFailure(param->error);
2013 delete param;
2014 break;
2015 }
deadbeefab9b2d12015-10-14 11:33:11 -07002016 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2017 CreateSessionDescriptionMsg* param =
2018 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2019 param->observer->OnFailure(param->error);
2020 delete param;
2021 break;
2022 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002023 case MSG_GETSTATS: {
2024 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002025 StatsReports reports;
2026 stats_->GetStats(param->track, &reports);
2027 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002028 delete param;
2029 break;
2030 }
deadbeefbd292462015-12-14 18:15:29 -08002031 case MSG_FREE_DATACHANNELS: {
2032 sctp_data_channels_to_free_.clear();
2033 break;
2034 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002035 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002036 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002037 break;
2038 }
2039}
2040
deadbeefab9b2d12015-10-14 11:33:11 -07002041void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07002042 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07002043 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08002044 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2045 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002046 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002047 new AudioRtpReceiver(track_id, ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002048 stream->AddTrack(
2049 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08002050 receivers_.push_back(receiver);
2051 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2052 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
2053 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002054}
2055
deadbeefab9b2d12015-10-14 11:33:11 -07002056void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01002057 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07002058 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08002059 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2060 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002061 signaling_thread(), new VideoRtpReceiver(track_id, worker_thread(),
2062 ssrc, video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002063 stream->AddTrack(
2064 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08002065 receivers_.push_back(receiver);
2066 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2067 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
2068 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002069}
2070
deadbeef70ab1a12015-09-28 16:53:55 -07002071// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2072// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002073rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
2074 const std::string& track_id) {
perkjd61bf802016-03-24 03:16:19 -07002075 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07002076 if (it == receivers_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002077 RTC_LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
2078 << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002079 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002080 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002081 (*it)->internal()->Stop();
2082 rtc::scoped_refptr<RtpReceiverInterface> receiver = *it;
2083 receivers_.erase(it);
2084 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002085}
2086
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002087void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2088 MediaStreamInterface* stream) {
2089 RTC_DCHECK(!IsClosed());
2090 auto sender = FindSenderForTrack(track);
2091 if (sender != senders_.end()) {
2092 // We already have a sender for this track, so just change the stream_id
2093 // so that it's correct in the next call to CreateOffer.
2094 (*sender)->internal()->set_stream_id(stream->label());
2095 return;
2096 }
2097
2098 // Normal case; we've never seen this track before.
2099 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2100 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2101 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002102 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2103 stats_.get()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002104 senders_.push_back(new_sender);
2105 // If the sender has already been configured in SDP, we call SetSsrc,
2106 // which will connect the sender to the underlying transport. This can
2107 // occur if a local session description that contains the ID of the sender
2108 // is set before AddStream is called. It can also occur if the local
2109 // session description is not changed and RemoveStream is called, and
2110 // later AddStream is called again with the same stream.
2111 const TrackInfo* track_info =
2112 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
2113 if (track_info) {
2114 new_sender->internal()->SetSsrc(track_info->ssrc);
2115 }
2116}
2117
2118// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2119// indefinitely, when we have unified plan SDP.
2120void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2121 MediaStreamInterface* stream) {
2122 RTC_DCHECK(!IsClosed());
2123 auto sender = FindSenderForTrack(track);
2124 if (sender == senders_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002125 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2126 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002127 return;
2128 }
2129 (*sender)->internal()->Stop();
2130 senders_.erase(sender);
2131}
2132
2133void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2134 MediaStreamInterface* stream) {
2135 RTC_DCHECK(!IsClosed());
2136 auto sender = FindSenderForTrack(track);
2137 if (sender != senders_.end()) {
2138 // We already have a sender for this track, so just change the stream_id
2139 // so that it's correct in the next call to CreateOffer.
2140 (*sender)->internal()->set_stream_id(stream->label());
2141 return;
2142 }
2143
2144 // Normal case; we've never seen this track before.
2145 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2146 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002147 signaling_thread(),
2148 new VideoRtpSender(track, {stream->label()}, video_channel()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002149 senders_.push_back(new_sender);
2150 const TrackInfo* track_info =
2151 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
2152 if (track_info) {
2153 new_sender->internal()->SetSsrc(track_info->ssrc);
2154 }
2155}
2156
2157void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2158 MediaStreamInterface* stream) {
2159 RTC_DCHECK(!IsClosed());
2160 auto sender = FindSenderForTrack(track);
2161 if (sender == senders_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002162 RTC_LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2163 << " doesn't exist.";
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002164 return;
2165 }
2166 (*sender)->internal()->Stop();
2167 senders_.erase(sender);
2168}
2169
Steve Antonba818672017-11-06 10:21:57 -08002170void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002171 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002172 if (ice_connection_state_ == new_state) {
2173 return;
2174 }
2175
deadbeefcbecd352015-09-23 11:50:27 -07002176 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002177 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002178 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002179 return;
2180 }
Steve Antonba818672017-11-06 10:21:57 -08002181
Mirko Bonadei675513b2017-11-09 11:09:25 +01002182 RTC_LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2183 << " => " << new_state;
Steve Antonba818672017-11-06 10:21:57 -08002184 RTC_DCHECK(ice_connection_state_ !=
2185 PeerConnectionInterface::kIceConnectionClosed);
2186
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002187 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002188 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002189}
2190
2191void PeerConnection::OnIceGatheringChange(
2192 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002193 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002194 if (IsClosed()) {
2195 return;
2196 }
2197 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002198 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002199}
2200
jbauch81bf7b02017-03-25 08:31:12 -07002201void PeerConnection::OnIceCandidate(
2202 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002203 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002204 if (IsClosed()) {
2205 return;
2206 }
jbauch81bf7b02017-03-25 08:31:12 -07002207 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002208}
2209
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002210void PeerConnection::OnIceCandidatesRemoved(
2211 const std::vector<cricket::Candidate>& candidates) {
2212 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002213 if (IsClosed()) {
2214 return;
2215 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002216 observer_->OnIceCandidatesRemoved(candidates);
2217}
2218
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002219void PeerConnection::ChangeSignalingState(
2220 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002221 RTC_DCHECK(signaling_thread()->IsCurrent());
2222 if (signaling_state_ == signaling_state) {
2223 return;
2224 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01002225 RTC_LOG(LS_INFO) << "Session: " << session_id() << " Old state: "
2226 << GetSignalingStateString(signaling_state_)
2227 << " New state: "
2228 << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002229 signaling_state_ = signaling_state;
2230 if (signaling_state == kClosed) {
2231 ice_connection_state_ = kIceConnectionClosed;
2232 observer_->OnIceConnectionChange(ice_connection_state_);
2233 if (ice_gathering_state_ != kIceGatheringComplete) {
2234 ice_gathering_state_ = kIceGatheringComplete;
2235 observer_->OnIceGatheringChange(ice_gathering_state_);
2236 }
2237 }
2238 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002239}
2240
deadbeefeb459812015-12-15 19:24:43 -08002241void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2242 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002243 if (IsClosed()) {
2244 return;
2245 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002246 AddAudioTrack(track, stream);
2247 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002248}
2249
deadbeefeb459812015-12-15 19:24:43 -08002250void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2251 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002252 if (IsClosed()) {
2253 return;
2254 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002255 RemoveAudioTrack(track, stream);
2256 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002257}
2258
2259void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2260 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002261 if (IsClosed()) {
2262 return;
2263 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002264 AddVideoTrack(track, stream);
2265 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002266}
2267
2268void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2269 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002270 if (IsClosed()) {
2271 return;
2272 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002273 RemoveVideoTrack(track, stream);
2274 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002275}
2276
deadbeefab9b2d12015-10-14 11:33:11 -07002277void PeerConnection::PostSetSessionDescriptionFailure(
2278 SetSessionDescriptionObserver* observer,
2279 const std::string& error) {
2280 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2281 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002282 signaling_thread()->Post(RTC_FROM_HERE, this,
2283 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002284}
2285
2286void PeerConnection::PostCreateSessionDescriptionFailure(
2287 CreateSessionDescriptionObserver* observer,
2288 const std::string& error) {
2289 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2290 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002291 signaling_thread()->Post(RTC_FROM_HERE, this,
2292 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002293}
2294
zhihuang1c378ed2017-08-17 14:10:50 -07002295void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002296 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2297 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002298 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2299
2300 // Figure out transceiver directional preferences.
2301 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2302 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2303
2304 // By default, generate sendrecv/recvonly m= sections.
2305 bool recv_audio = true;
2306 bool recv_video = true;
2307
2308 // By default, only offer a new m= section if we have media to send with it.
2309 bool offer_new_audio_description = send_audio;
2310 bool offer_new_video_description = send_video;
2311 bool offer_new_data_description = HasDataChannels();
2312
2313 // The "offer_to_receive_X" options allow those defaults to be overridden.
2314 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2315 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2316 offer_new_audio_description =
2317 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2318 }
2319 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2320 recv_video = (rtc_options.offer_to_receive_video > 0);
2321 offer_new_video_description =
2322 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2323 }
2324
2325 rtc::Optional<size_t> audio_index;
2326 rtc::Optional<size_t> video_index;
2327 rtc::Optional<size_t> data_index;
2328 // If a current description exists, generate m= sections in the same order,
2329 // using the first audio/video/data section that appears and rejecting
2330 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002331 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002332 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002333 local_description(),
zhihuang1c378ed2017-08-17 14:10:50 -07002334 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2335 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2336 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002337 }
2338
zhihuang1c378ed2017-08-17 14:10:50 -07002339 // Add audio/video/data m= sections to the end if needed.
2340 if (!audio_index && offer_new_audio_description) {
2341 session_options->media_description_options.push_back(
2342 cricket::MediaDescriptionOptions(
2343 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
2344 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
2345 audio_index = rtc::Optional<size_t>(
2346 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07002347 }
zhihuang1c378ed2017-08-17 14:10:50 -07002348 if (!video_index && offer_new_video_description) {
2349 session_options->media_description_options.push_back(
2350 cricket::MediaDescriptionOptions(
2351 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
2352 cricket::RtpTransceiverDirection(send_video, recv_video), false));
2353 video_index = rtc::Optional<size_t>(
2354 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07002355 }
zhihuang1c378ed2017-08-17 14:10:50 -07002356 if (!data_index && offer_new_data_description) {
2357 session_options->media_description_options.push_back(
2358 cricket::MediaDescriptionOptions(
2359 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
2360 cricket::RtpTransceiverDirection(true, true), false));
2361 data_index = rtc::Optional<size_t>(
2362 session_options->media_description_options.size() - 1);
2363 }
2364
2365 cricket::MediaDescriptionOptions* audio_media_description_options =
2366 !audio_index ? nullptr
2367 : &session_options->media_description_options[*audio_index];
2368 cricket::MediaDescriptionOptions* video_media_description_options =
2369 !video_index ? nullptr
2370 : &session_options->media_description_options[*video_index];
2371 cricket::MediaDescriptionOptions* data_media_description_options =
2372 !data_index ? nullptr
2373 : &session_options->media_description_options[*data_index];
2374
2375 // Apply ICE restart flag and renomination flag.
2376 for (auto& options : session_options->media_description_options) {
2377 options.transport_options.ice_restart = rtc_options.ice_restart;
2378 options.transport_options.enable_ice_renomination =
2379 configuration_.enable_ice_renomination;
2380 }
2381
2382 AddRtpSenderOptions(senders_, audio_media_description_options,
2383 video_media_description_options);
2384 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002385
zhihuang9763d562016-08-05 11:14:50 -07002386 // Intentionally unset the data channel type for RTP data channel with the
2387 // second condition. Otherwise the RTP data channels would be successfully
2388 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2389 // when building with chromium. We want to leave RTP data channels broken, so
2390 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002391 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2392 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002393 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002394
2395 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002396 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002397}
2398
zhihuang1c378ed2017-08-17 14:10:50 -07002399void PeerConnection::GetOptionsForAnswer(
2400 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002401 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002402 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002403
zhihuang1c378ed2017-08-17 14:10:50 -07002404 // Figure out transceiver directional preferences.
2405 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2406 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2407
2408 // By default, generate sendrecv/recvonly m= sections. The direction is also
2409 // restricted by the direction in the offer.
2410 bool recv_audio = true;
2411 bool recv_video = true;
2412
2413 // The "offer_to_receive_X" options allow those defaults to be overridden.
2414 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2415 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002416 }
zhihuang1c378ed2017-08-17 14:10:50 -07002417 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2418 recv_video = (rtc_options.offer_to_receive_video > 0);
2419 }
2420
2421 rtc::Optional<size_t> audio_index;
2422 rtc::Optional<size_t> video_index;
2423 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002424 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002425 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002426 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002427 SessionDescriptionInterface::kOffer);
2428 // Generate m= sections that match those in the offer.
2429 // Note that mediasession.cc will handle intersection our preferred
2430 // direction with the offered direction.
2431 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002432 remote_description(),
zhihuang141aacb2017-08-29 13:23:53 -07002433 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2434 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2435 &video_index, &data_index, session_options);
2436 }
zhihuang1c378ed2017-08-17 14:10:50 -07002437
2438 cricket::MediaDescriptionOptions* audio_media_description_options =
2439 !audio_index ? nullptr
2440 : &session_options->media_description_options[*audio_index];
2441 cricket::MediaDescriptionOptions* video_media_description_options =
2442 !video_index ? nullptr
2443 : &session_options->media_description_options[*video_index];
2444 cricket::MediaDescriptionOptions* data_media_description_options =
2445 !data_index ? nullptr
2446 : &session_options->media_description_options[*data_index];
2447
2448 // Apply ICE renomination flag.
2449 for (auto& options : session_options->media_description_options) {
2450 options.transport_options.enable_ice_renomination =
2451 configuration_.enable_ice_renomination;
2452 }
2453
2454 AddRtpSenderOptions(senders_, audio_media_description_options,
2455 video_media_description_options);
2456 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2457
zhihuang9763d562016-08-05 11:14:50 -07002458 // Intentionally unset the data channel type for RTP data channel. Otherwise
2459 // the RTP data channels would be successfully negotiated by default and the
2460 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2461 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002462 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2463 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002464 }
zhihuangaf388472016-11-02 16:49:48 -07002465
zhihuang1c378ed2017-08-17 14:10:50 -07002466 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002467 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002468}
2469
zhihuang1c378ed2017-08-17 14:10:50 -07002470void PeerConnection::GenerateMediaDescriptionOptions(
2471 const SessionDescriptionInterface* session_desc,
2472 cricket::RtpTransceiverDirection audio_direction,
2473 cricket::RtpTransceiverDirection video_direction,
2474 rtc::Optional<size_t>* audio_index,
2475 rtc::Optional<size_t>* video_index,
2476 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002477 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002478 for (const cricket::ContentInfo& content :
2479 session_desc->description()->contents()) {
2480 if (IsAudioContent(&content)) {
2481 // If we already have an audio m= section, reject this extra one.
2482 if (*audio_index) {
2483 session_options->media_description_options.push_back(
2484 cricket::MediaDescriptionOptions(
2485 cricket::MEDIA_TYPE_AUDIO, content.name,
2486 cricket::RtpTransceiverDirection(false, false), true));
2487 } else {
2488 session_options->media_description_options.push_back(
2489 cricket::MediaDescriptionOptions(
2490 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
2491 !audio_direction.send && !audio_direction.recv));
2492 *audio_index = rtc::Optional<size_t>(
2493 session_options->media_description_options.size() - 1);
2494 }
2495 } else if (IsVideoContent(&content)) {
2496 // If we already have an video m= section, reject this extra one.
2497 if (*video_index) {
2498 session_options->media_description_options.push_back(
2499 cricket::MediaDescriptionOptions(
2500 cricket::MEDIA_TYPE_VIDEO, content.name,
2501 cricket::RtpTransceiverDirection(false, false), true));
2502 } else {
2503 session_options->media_description_options.push_back(
2504 cricket::MediaDescriptionOptions(
2505 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
2506 !video_direction.send && !video_direction.recv));
2507 *video_index = rtc::Optional<size_t>(
2508 session_options->media_description_options.size() - 1);
2509 }
2510 } else {
2511 RTC_DCHECK(IsDataContent(&content));
2512 // If we already have an data m= section, reject this extra one.
2513 if (*data_index) {
2514 session_options->media_description_options.push_back(
2515 cricket::MediaDescriptionOptions(
2516 cricket::MEDIA_TYPE_DATA, content.name,
2517 cricket::RtpTransceiverDirection(false, false), true));
2518 } else {
2519 session_options->media_description_options.push_back(
2520 cricket::MediaDescriptionOptions(
2521 cricket::MEDIA_TYPE_DATA, content.name,
2522 // Direction for data sections is meaningless, but legacy
2523 // endpoints might expect sendrecv.
2524 cricket::RtpTransceiverDirection(true, true), false));
2525 *data_index = rtc::Optional<size_t>(
2526 session_options->media_description_options.size() - 1);
2527 }
2528 }
htaa2a49d92016-03-04 02:51:39 -08002529 }
deadbeefab9b2d12015-10-14 11:33:11 -07002530}
2531
deadbeeffaac4972015-11-12 15:33:07 -08002532void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
2533 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002534 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
2535 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002536}
2537
deadbeefab9b2d12015-10-14 11:33:11 -07002538void PeerConnection::UpdateRemoteStreamsList(
2539 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08002540 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002541 cricket::MediaType media_type,
2542 StreamCollection* new_streams) {
2543 TrackInfos* current_tracks = GetRemoteTracks(media_type);
2544
2545 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002546 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07002547 auto track_it = current_tracks->begin();
2548 while (track_it != current_tracks->end()) {
2549 const TrackInfo& info = *track_it;
2550 const cricket::StreamParams* params =
2551 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08002552 bool track_exists = params && params->id == info.track_id;
2553 // If this is a default track, and we still need it, don't remove it.
2554 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
2555 track_exists) {
2556 ++track_it;
2557 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07002558 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
2559 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002560 }
2561 }
2562
2563 // Find new and active tracks.
2564 for (const cricket::StreamParams& params : streams) {
2565 // The sync_label is the MediaStream label and the |stream.id| is the
2566 // track id.
2567 const std::string& stream_label = params.sync_label;
2568 const std::string& track_id = params.id;
2569 uint32_t ssrc = params.first_ssrc();
2570
2571 rtc::scoped_refptr<MediaStreamInterface> stream =
2572 remote_streams_->find(stream_label);
2573 if (!stream) {
2574 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002575 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2576 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002577 remote_streams_->AddStream(stream);
2578 new_streams->AddStream(stream);
2579 }
2580
2581 const TrackInfo* track_info =
2582 FindTrackInfo(*current_tracks, stream_label, track_id);
2583 if (!track_info) {
2584 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2585 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2586 }
2587 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002588
2589 // Add default track if necessary.
2590 if (default_track_needed) {
2591 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2592 remote_streams_->find(kDefaultStreamLabel);
2593 if (!default_stream) {
2594 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002595 default_stream = MediaStreamProxy::Create(
2596 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002597 remote_streams_->AddStream(default_stream);
2598 new_streams->AddStream(default_stream);
2599 }
2600 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2601 ? kDefaultAudioTrackLabel
2602 : kDefaultVideoTrackLabel;
2603 const TrackInfo* default_track_info =
2604 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2605 if (!default_track_info) {
2606 current_tracks->push_back(
2607 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2608 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2609 }
2610 }
deadbeefab9b2d12015-10-14 11:33:11 -07002611}
2612
2613void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2614 const std::string& track_id,
2615 uint32_t ssrc,
2616 cricket::MediaType media_type) {
2617 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2618
2619 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002620 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002621 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002622 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002623 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002624 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002625 }
2626}
2627
2628void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2629 const std::string& track_id,
2630 cricket::MediaType media_type) {
2631 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2632
Henrik Boström933d8b02017-10-10 10:05:16 -07002633 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002634 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002635 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2636 // will be notified which will end the AudioRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002637 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002638 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2639 stream->FindAudioTrack(track_id);
2640 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002641 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002642 }
2643 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002644 // Stopping or destroying a VideoRtpReceiver will end the
2645 // VideoRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002646 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002647 rtc::scoped_refptr<VideoTrackInterface> video_track =
2648 stream->FindVideoTrack(track_id);
2649 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002650 // There's no guarantee the track is still available, e.g. the track may
2651 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002652 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002653 }
2654 } else {
nisseede5da42017-01-12 05:15:36 -08002655 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002656 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002657 if (receiver) {
2658 observer_->OnRemoveTrack(receiver);
2659 }
deadbeefab9b2d12015-10-14 11:33:11 -07002660}
2661
2662void PeerConnection::UpdateEndedRemoteMediaStreams() {
2663 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2664 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2665 MediaStreamInterface* stream = remote_streams_->at(i);
2666 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2667 streams_to_remove.push_back(stream);
2668 }
2669 }
2670
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002671 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002672 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002673 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002674 }
2675}
2676
deadbeefab9b2d12015-10-14 11:33:11 -07002677void PeerConnection::UpdateLocalTracks(
2678 const std::vector<cricket::StreamParams>& streams,
2679 cricket::MediaType media_type) {
2680 TrackInfos* current_tracks = GetLocalTracks(media_type);
2681
2682 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2683 // don't match the new StreamParam.
2684 TrackInfos::iterator track_it = current_tracks->begin();
2685 while (track_it != current_tracks->end()) {
2686 const TrackInfo& info = *track_it;
2687 const cricket::StreamParams* params =
2688 cricket::GetStreamBySsrc(streams, info.ssrc);
2689 if (!params || params->id != info.track_id ||
2690 params->sync_label != info.stream_label) {
2691 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2692 media_type);
2693 track_it = current_tracks->erase(track_it);
2694 } else {
2695 ++track_it;
2696 }
2697 }
2698
2699 // Find new and active tracks.
2700 for (const cricket::StreamParams& params : streams) {
2701 // The sync_label is the MediaStream label and the |stream.id| is the
2702 // track id.
2703 const std::string& stream_label = params.sync_label;
2704 const std::string& track_id = params.id;
2705 uint32_t ssrc = params.first_ssrc();
2706 const TrackInfo* track_info =
2707 FindTrackInfo(*current_tracks, stream_label, track_id);
2708 if (!track_info) {
2709 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2710 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2711 }
2712 }
2713}
2714
2715void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2716 const std::string& track_id,
2717 uint32_t ssrc,
2718 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002719 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002720 if (!sender) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002721 RTC_LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2722 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002723 return;
2724 }
2725
deadbeeffac06552015-11-25 11:26:01 -08002726 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002727 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2728 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002729 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002730 }
deadbeeffac06552015-11-25 11:26:01 -08002731
2732 sender->set_stream_id(stream_label);
2733 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002734}
2735
2736void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2737 const std::string& track_id,
2738 uint32_t ssrc,
2739 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002740 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002741 if (!sender) {
2742 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002743 // SessionDescriptions has been renegotiated.
2744 return;
2745 }
deadbeeffac06552015-11-25 11:26:01 -08002746
2747 // A sender has been removed from the SessionDescription but it's still
2748 // associated with the PeerConnection. This only occurs if the SDP doesn't
2749 // match with the calls to CreateSender, AddStream and RemoveStream.
2750 if (sender->media_type() != media_type) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002751 RTC_LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2752 << " description with an unexpected media type.";
deadbeeffac06552015-11-25 11:26:01 -08002753 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002754 }
deadbeeffac06552015-11-25 11:26:01 -08002755
2756 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002757}
2758
2759void PeerConnection::UpdateLocalRtpDataChannels(
2760 const cricket::StreamParamsVec& streams) {
2761 std::vector<std::string> existing_channels;
2762
2763 // Find new and active data channels.
2764 for (const cricket::StreamParams& params : streams) {
2765 // |it->sync_label| is actually the data channel label. The reason is that
2766 // we use the same naming of data channels as we do for
2767 // MediaStreams and Tracks.
2768 // For MediaStreams, the sync_label is the MediaStream label and the
2769 // track label is the same as |streamid|.
2770 const std::string& channel_label = params.sync_label;
2771 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002772 if (data_channel_it == rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002773 RTC_LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002774 continue;
2775 }
2776 // Set the SSRC the data channel should use for sending.
2777 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2778 existing_channels.push_back(data_channel_it->first);
2779 }
2780
2781 UpdateClosingRtpDataChannels(existing_channels, true);
2782}
2783
2784void PeerConnection::UpdateRemoteRtpDataChannels(
2785 const cricket::StreamParamsVec& streams) {
2786 std::vector<std::string> existing_channels;
2787
2788 // Find new and active data channels.
2789 for (const cricket::StreamParams& params : streams) {
2790 // The data channel label is either the mslabel or the SSRC if the mslabel
2791 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2792 std::string label = params.sync_label.empty()
2793 ? rtc::ToString(params.first_ssrc())
2794 : params.sync_label;
2795 auto data_channel_it = rtp_data_channels_.find(label);
2796 if (data_channel_it == rtp_data_channels_.end()) {
2797 // This is a new data channel.
2798 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2799 } else {
2800 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2801 }
2802 existing_channels.push_back(label);
2803 }
2804
2805 UpdateClosingRtpDataChannels(existing_channels, false);
2806}
2807
2808void PeerConnection::UpdateClosingRtpDataChannels(
2809 const std::vector<std::string>& active_channels,
2810 bool is_local_update) {
2811 auto it = rtp_data_channels_.begin();
2812 while (it != rtp_data_channels_.end()) {
2813 DataChannel* data_channel = it->second;
2814 if (std::find(active_channels.begin(), active_channels.end(),
2815 data_channel->label()) != active_channels.end()) {
2816 ++it;
2817 continue;
2818 }
2819
2820 if (is_local_update) {
2821 data_channel->SetSendSsrc(0);
2822 } else {
2823 data_channel->RemotePeerRequestClose();
2824 }
2825
2826 if (data_channel->state() == DataChannel::kClosed) {
2827 rtp_data_channels_.erase(it);
2828 it = rtp_data_channels_.begin();
2829 } else {
2830 ++it;
2831 }
2832 }
2833}
2834
2835void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2836 uint32_t remote_ssrc) {
2837 rtc::scoped_refptr<DataChannel> channel(
2838 InternalCreateDataChannel(label, nullptr));
2839 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002840 RTC_LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2841 << "CreateDataChannel failed.";
deadbeefab9b2d12015-10-14 11:33:11 -07002842 return;
2843 }
2844 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002845 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2846 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002847 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002848}
2849
2850rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2851 const std::string& label,
2852 const InternalDataChannelInit* config) {
2853 if (IsClosed()) {
2854 return nullptr;
2855 }
Steve Anton75737c02017-11-06 10:37:17 -08002856 if (data_channel_type() == cricket::DCT_NONE) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002857 RTC_LOG(LS_ERROR)
deadbeefab9b2d12015-10-14 11:33:11 -07002858 << "InternalCreateDataChannel: Data is not supported in this call.";
2859 return nullptr;
2860 }
2861 InternalDataChannelInit new_config =
2862 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08002863 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07002864 if (new_config.id < 0) {
2865 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002866 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002867 !sid_allocator_.AllocateSid(role, &new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002868 RTC_LOG(LS_ERROR)
2869 << "No id can be allocated for the SCTP data channel.";
deadbeefab9b2d12015-10-14 11:33:11 -07002870 return nullptr;
2871 }
2872 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002873 RTC_LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2874 << "because the id is already in use or out of range.";
deadbeefab9b2d12015-10-14 11:33:11 -07002875 return nullptr;
2876 }
2877 }
2878
Steve Anton75737c02017-11-06 10:37:17 -08002879 rtc::scoped_refptr<DataChannel> channel(
2880 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002881 if (!channel) {
2882 sid_allocator_.ReleaseSid(new_config.id);
2883 return nullptr;
2884 }
2885
2886 if (channel->data_channel_type() == cricket::DCT_RTP) {
2887 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002888 RTC_LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2889 << " already exists.";
deadbeefab9b2d12015-10-14 11:33:11 -07002890 return nullptr;
2891 }
2892 rtp_data_channels_[channel->label()] = channel;
2893 } else {
2894 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2895 sctp_data_channels_.push_back(channel);
2896 channel->SignalClosed.connect(this,
2897 &PeerConnection::OnSctpDataChannelClosed);
2898 }
2899
hbos82ebe022016-11-14 01:41:09 -08002900 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002901 return channel;
2902}
2903
2904bool PeerConnection::HasDataChannels() const {
2905 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
2906}
2907
2908void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2909 for (const auto& channel : sctp_data_channels_) {
2910 if (channel->id() < 0) {
2911 int sid;
2912 if (!sid_allocator_.AllocateSid(role, &sid)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002913 RTC_LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
deadbeefab9b2d12015-10-14 11:33:11 -07002914 continue;
2915 }
2916 channel->SetSctpSid(sid);
2917 }
2918 }
2919}
2920
2921void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002922 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002923 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2924 ++it) {
2925 if (it->get() == channel) {
2926 if (channel->id() >= 0) {
2927 sid_allocator_.ReleaseSid(channel->id());
2928 }
deadbeefbd292462015-12-14 18:15:29 -08002929 // Since this method is triggered by a signal from the DataChannel,
2930 // we can't free it directly here; we need to free it asynchronously.
2931 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002932 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002933 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2934 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002935 return;
2936 }
2937 }
2938}
2939
deadbeefab9b2d12015-10-14 11:33:11 -07002940void PeerConnection::OnDataChannelDestroyed() {
2941 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2942 // DataChannel may callback to us and try to modify the list.
2943 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2944 temp_rtp_dcs.swap(rtp_data_channels_);
2945 for (const auto& kv : temp_rtp_dcs) {
2946 kv.second->OnTransportChannelDestroyed();
2947 }
2948
2949 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2950 temp_sctp_dcs.swap(sctp_data_channels_);
2951 for (const auto& channel : temp_sctp_dcs) {
2952 channel->OnTransportChannelDestroyed();
2953 }
2954}
2955
2956void PeerConnection::OnDataChannelOpenMessage(
2957 const std::string& label,
2958 const InternalDataChannelInit& config) {
2959 rtc::scoped_refptr<DataChannel> channel(
2960 InternalCreateDataChannel(label, &config));
2961 if (!channel.get()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01002962 RTC_LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
deadbeefab9b2d12015-10-14 11:33:11 -07002963 return;
2964 }
2965
deadbeefa601f5c2016-06-06 14:27:39 -07002966 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2967 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002968 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002969}
2970
zhihuang1c378ed2017-08-17 14:10:50 -07002971bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2972 return std::find_if(
2973 senders_.begin(), senders_.end(),
2974 [type](const rtc::scoped_refptr<
2975 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2976 return sender->media_type() == type;
2977 }) != senders_.end();
2978}
2979
deadbeefa601f5c2016-06-06 14:27:39 -07002980RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2981 auto it = std::find_if(
2982 senders_.begin(), senders_.end(),
2983 [id](const rtc::scoped_refptr<
2984 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2985 return sender->id() == id;
2986 });
2987 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002988}
2989
deadbeefa601f5c2016-06-06 14:27:39 -07002990std::vector<
2991 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002992PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2993 return std::find_if(
2994 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002995 [track](const rtc::scoped_refptr<
2996 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002997 return sender->track() == track;
2998 });
2999}
3000
deadbeefa601f5c2016-06-06 14:27:39 -07003001std::vector<rtc::scoped_refptr<
3002 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07003003PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07003004 return std::find_if(
3005 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07003006 [track_id](const rtc::scoped_refptr<
3007 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07003008 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07003009 });
3010}
3011
deadbeefab9b2d12015-10-14 11:33:11 -07003012PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
3013 cricket::MediaType media_type) {
3014 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3015 media_type == cricket::MEDIA_TYPE_VIDEO);
3016 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
3017 : &remote_video_tracks_;
3018}
3019
3020PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
3021 cricket::MediaType media_type) {
3022 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3023 media_type == cricket::MEDIA_TYPE_VIDEO);
3024 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &local_audio_tracks_
3025 : &local_video_tracks_;
3026}
3027
3028const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
3029 const PeerConnection::TrackInfos& infos,
3030 const std::string& stream_label,
3031 const std::string track_id) const {
3032 for (const TrackInfo& track_info : infos) {
3033 if (track_info.stream_label == stream_label &&
3034 track_info.track_id == track_id) {
3035 return &track_info;
3036 }
3037 }
3038 return nullptr;
3039}
3040
3041DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3042 for (const auto& channel : sctp_data_channels_) {
3043 if (channel->id() == sid) {
3044 return channel;
3045 }
3046 }
3047 return nullptr;
3048}
3049
deadbeef91dd5672016-05-18 16:55:30 -07003050bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003051 const RTCConfiguration& configuration) {
3052 cricket::ServerAddresses stun_servers;
3053 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003054 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3055 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003056 return false;
3057 }
3058
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003059 port_allocator_->Initialize();
3060
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003061 // To handle both internal and externally created port allocator, we will
3062 // enable BUNDLE here.
3063 int portallocator_flags = port_allocator_->flags();
3064 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003065 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3066 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003067 // If the disable-IPv6 flag was specified, we'll not override it
3068 // by experiment.
3069 if (configuration.disable_ipv6) {
3070 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003071 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3072 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003073 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3074 }
3075
zhihuangb09b3f92017-03-07 14:40:51 -08003076 if (configuration.disable_ipv6_on_wifi) {
3077 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003078 RTC_LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
zhihuangb09b3f92017-03-07 14:40:51 -08003079 }
3080
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003081 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3082 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003083 RTC_LOG(LS_INFO) << "TCP candidates are disabled.";
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003084 }
3085
honghaiz60347052016-05-31 18:29:12 -07003086 if (configuration.candidate_network_policy ==
3087 kCandidateNetworkPolicyLowCost) {
3088 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
Mirko Bonadei675513b2017-11-09 11:09:25 +01003089 RTC_LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
honghaiz60347052016-05-31 18:29:12 -07003090 }
3091
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003092 port_allocator_->set_flags(portallocator_flags);
3093 // No step delay is used while allocating ports.
3094 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3095 port_allocator_->set_candidate_filter(
3096 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003097 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003098
3099 // Call this last since it may create pooled allocator sessions using the
3100 // properties set above.
3101 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003102 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003103 configuration.prune_turn_ports,
3104 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003105 return true;
3106}
3107
deadbeef91dd5672016-05-18 16:55:30 -07003108bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003109 const cricket::ServerAddresses& stun_servers,
3110 const std::vector<cricket::RelayServerConfig>& turn_servers,
3111 IceTransportsType type,
3112 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003113 bool prune_turn_ports,
3114 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003115 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003116 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003117 // Call this last since it may create pooled allocator sessions using the
3118 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003119 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003120 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3121 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003122}
3123
Steve Antonba818672017-11-06 10:21:57 -08003124cricket::ChannelManager* PeerConnection::channel_manager() const {
3125 return factory_->channel_manager();
3126}
3127
3128MetricsObserverInterface* PeerConnection::metrics_observer() const {
3129 return uma_observer_;
3130}
3131
Elad Alon99c3fe52017-10-13 16:29:40 +02003132bool PeerConnection::StartRtcEventLog_w(
3133 std::unique_ptr<RtcEventLogOutput> output) {
zhihuang77985012017-02-07 15:45:16 -08003134 if (!event_log_) {
3135 return false;
3136 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003137 return event_log_->StartLogging(std::move(output));
ivoc14d5dbe2016-07-04 07:06:55 -07003138}
3139
3140void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003141 if (event_log_) {
3142 event_log_->StopLogging();
3143 }
ivoc14d5dbe2016-07-04 07:06:55 -07003144}
nisseeaabdf62017-05-05 02:23:02 -07003145
Steve Anton75737c02017-11-06 10:37:17 -08003146cricket::BaseChannel* PeerConnection::GetChannel(
3147 const std::string& content_name) {
3148 if (voice_channel() && voice_channel()->content_name() == content_name) {
3149 return voice_channel();
3150 }
3151 if (video_channel() && video_channel()->content_name() == content_name) {
3152 return video_channel();
3153 }
3154 if (rtp_data_channel() &&
3155 rtp_data_channel()->content_name() == content_name) {
3156 return rtp_data_channel();
3157 }
3158 return nullptr;
3159}
3160
3161bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3162 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003163 RTC_LOG(LS_INFO)
3164 << "Local and Remote descriptions must be applied to get the "
3165 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003166 return false;
3167 }
3168 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003169 RTC_LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3170 << "SSL Role of the SCTP transport.";
Steve Anton75737c02017-11-06 10:37:17 -08003171 return false;
3172 }
3173
3174 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3175}
3176
3177bool PeerConnection::GetSslRole(const std::string& content_name,
3178 rtc::SSLRole* role) {
3179 if (!local_description() || !remote_description()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003180 RTC_LOG(LS_INFO)
3181 << "Local and Remote descriptions must be applied to get the "
3182 << "SSL Role of the session.";
Steve Anton75737c02017-11-06 10:37:17 -08003183 return false;
3184 }
3185
3186 return transport_controller_->GetSslRole(GetTransportName(content_name),
3187 role);
3188}
3189
Steve Anton75737c02017-11-06 10:37:17 -08003190bool PeerConnection::SetLocalDescription(
3191 std::unique_ptr<SessionDescriptionInterface> desc,
3192 std::string* err_desc) {
3193 RTC_DCHECK(signaling_thread()->IsCurrent());
3194
3195 // Validate SDP.
3196 if (!ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, err_desc)) {
3197 return false;
3198 }
3199
3200 // Update the initial_offerer flag if this session is the initial_offerer.
3201 Action action = GetAction(desc->type());
3202 if (!initial_offerer_.has_value()) {
3203 initial_offerer_.emplace(action == kOffer);
3204 if (*initial_offerer_) {
3205 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3206 } else {
3207 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3208 }
3209 }
3210
3211 if (action == kAnswer) {
3212 current_local_description_ = std::move(desc);
3213 pending_local_description_ = nullptr;
3214 current_remote_description_ = std::move(pending_remote_description_);
3215 } else {
3216 pending_local_description_ = std::move(desc);
3217 }
3218
3219 // Transport and Media channels will be created only when offer is set.
3220 if (action == kOffer && !CreateChannels(local_description()->description())) {
3221 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3222 // is applied. Restore back to old description.
3223 return BadLocalSdp(local_description()->type(), kCreateChannelFailed,
3224 err_desc);
3225 }
3226
3227 // Remove unused channels if MediaContentDescription is rejected.
3228 RemoveUnusedChannels(local_description()->description());
3229
3230 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
3231 return false;
3232 }
3233 if (remote_description()) {
3234 // Now that we have a local description, we can push down remote candidates.
3235 UseCandidatesInSessionDescription(remote_description());
3236 }
3237
3238 pending_ice_restarts_.clear();
3239 if (error() != ERROR_NONE) {
3240 return BadLocalSdp(local_description()->type(), GetSessionErrorMsg(),
3241 err_desc);
3242 }
3243 return true;
3244}
3245
3246bool PeerConnection::SetRemoteDescription(
3247 std::unique_ptr<SessionDescriptionInterface> desc,
3248 std::string* err_desc) {
3249 RTC_DCHECK(signaling_thread()->IsCurrent());
3250
3251 // Validate SDP.
3252 if (!ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, err_desc)) {
3253 return false;
3254 }
3255
3256 // Hold this pointer so candidates can be copied to it later in the method.
3257 SessionDescriptionInterface* desc_ptr = desc.get();
3258
3259 const SessionDescriptionInterface* old_remote_description =
3260 remote_description();
3261 // Grab ownership of the description being replaced for the remainder of this
3262 // method, since it's used below as |old_remote_description|.
3263 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
3264 Action action = GetAction(desc->type());
3265 if (action == kAnswer) {
3266 replaced_remote_description = pending_remote_description_
3267 ? std::move(pending_remote_description_)
3268 : std::move(current_remote_description_);
3269 current_remote_description_ = std::move(desc);
3270 pending_remote_description_ = nullptr;
3271 current_local_description_ = std::move(pending_local_description_);
3272 } else {
3273 replaced_remote_description = std::move(pending_remote_description_);
3274 pending_remote_description_ = std::move(desc);
3275 }
3276
3277 // Transport and Media channels will be created only when offer is set.
3278 if (action == kOffer &&
3279 !CreateChannels(remote_description()->description())) {
3280 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3281 // is applied. Restore back to old description.
3282 return BadRemoteSdp(remote_description()->type(), kCreateChannelFailed,
3283 err_desc);
3284 }
3285
3286 // Remove unused channels if MediaContentDescription is rejected.
3287 RemoveUnusedChannels(remote_description()->description());
3288
3289 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
3290 // is called.
3291 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
3292 return false;
3293 }
3294
3295 if (local_description() &&
3296 !UseCandidatesInSessionDescription(remote_description())) {
3297 return BadRemoteSdp(remote_description()->type(), kInvalidCandidates,
3298 err_desc);
3299 }
3300
3301 if (old_remote_description) {
3302 for (const cricket::ContentInfo& content :
3303 old_remote_description->description()->contents()) {
3304 // Check if this new SessionDescription contains new ICE ufrag and
3305 // password that indicates the remote peer requests an ICE restart.
3306 // TODO(deadbeef): When we start storing both the current and pending
3307 // remote description, this should reset pending_ice_restarts and compare
3308 // against the current description.
3309 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3310 content.name)) {
3311 if (action == kOffer) {
3312 pending_ice_restarts_.insert(content.name);
3313 }
3314 } else {
3315 // We retain all received candidates only if ICE is not restarted.
3316 // When ICE is restarted, all previous candidates belong to an old
3317 // generation and should not be kept.
3318 // TODO(deadbeef): This goes against the W3C spec which says the remote
3319 // description should only contain candidates from the last set remote
3320 // description plus any candidates added since then. We should remove
3321 // this once we're sure it won't break anything.
3322 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3323 old_remote_description, content.name, desc_ptr);
3324 }
3325 }
3326 }
3327
3328 if (error() != ERROR_NONE) {
3329 return BadRemoteSdp(remote_description()->type(), GetSessionErrorMsg(),
3330 err_desc);
3331 }
3332
3333 // Set the the ICE connection state to connecting since the connection may
3334 // become writable with peer reflexive candidates before any remote candidate
3335 // is signaled.
3336 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3337 // is to have a new signal the indicates a change in checking state from the
3338 // transport and expose a new checking() member from transport that can be
3339 // read to determine the current checking state. The existing SignalConnecting
3340 // actually means "gathering candidates", so cannot be be used here.
3341 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
3342 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3343 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3344 }
3345 return true;
3346}
3347
3348// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3349// vector of BaseChannel pointers instead of separate voice and video channel
3350// vectors. At that point, this will become a simple getter.
3351std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3352 std::vector<cricket::BaseChannel*> channels;
3353 channels.insert(channels.end(), voice_channels_.begin(),
3354 voice_channels_.end());
3355 channels.insert(channels.end(), video_channels_.begin(),
3356 video_channels_.end());
3357 if (rtp_data_channel_) {
3358 channels.push_back(rtp_data_channel_);
3359 }
3360 return channels;
3361}
3362
3363void PeerConnection::SetError(Error error, const std::string& error_desc) {
3364 RTC_DCHECK(signaling_thread()->IsCurrent());
3365 if (error != error_) {
3366 error_ = error;
3367 error_desc_ = error_desc;
3368 }
3369}
3370
3371bool PeerConnection::UpdateSessionState(Action action,
3372 cricket::ContentSource source,
3373 std::string* err_desc) {
3374 RTC_DCHECK(signaling_thread()->IsCurrent());
3375
3376 // If there's already a pending error then no state transition should happen.
3377 // But all call-sites should be verifying this before calling us!
3378 RTC_DCHECK(error() == ERROR_NONE);
3379 std::string td_err;
3380 if (action == kOffer) {
3381 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
3382 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
3383 }
3384 ChangeSignalingState(source == cricket::CS_LOCAL
3385 ? PeerConnectionInterface::kHaveLocalOffer
3386 : PeerConnectionInterface::kHaveRemoteOffer);
3387 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
3388 SetError(ERROR_CONTENT, *err_desc);
3389 }
3390 if (error() != ERROR_NONE) {
3391 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
3392 }
3393 } else if (action == kPrAnswer) {
3394 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
3395 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
3396 }
3397 EnableChannels();
3398 ChangeSignalingState(source == cricket::CS_LOCAL
3399 ? PeerConnectionInterface::kHaveLocalPrAnswer
3400 : PeerConnectionInterface::kHaveRemotePrAnswer);
3401 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
3402 SetError(ERROR_CONTENT, *err_desc);
3403 }
3404 if (error() != ERROR_NONE) {
3405 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
3406 }
3407 } else if (action == kAnswer) {
3408 const cricket::ContentGroup* local_bundle =
3409 local_description()->description()->GetGroupByName(
3410 cricket::GROUP_TYPE_BUNDLE);
3411 const cricket::ContentGroup* remote_bundle =
3412 remote_description()->description()->GetGroupByName(
3413 cricket::GROUP_TYPE_BUNDLE);
3414 if (local_bundle && remote_bundle) {
3415 // The answerer decides the transport to bundle on.
3416 const cricket::ContentGroup* answer_bundle =
3417 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3418 if (!EnableBundle(*answer_bundle)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003419 RTC_LOG(LS_WARNING) << "Failed to enable BUNDLE.";
Steve Anton75737c02017-11-06 10:37:17 -08003420 return BadAnswerSdp(source, kEnableBundleFailed, err_desc);
3421 }
3422 }
3423 // Only push down the transport description after enabling BUNDLE; we don't
3424 // want to push down a description on a transport about to be destroyed.
3425 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
3426 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
3427 }
3428 EnableChannels();
3429 ChangeSignalingState(PeerConnectionInterface::kStable);
3430 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
3431 SetError(ERROR_CONTENT, *err_desc);
3432 }
3433 if (error() != ERROR_NONE) {
3434 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
3435 }
3436 }
3437 return true;
3438}
3439
3440PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3441 if (type == SessionDescriptionInterface::kOffer) {
3442 return PeerConnection::kOffer;
3443 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3444 return PeerConnection::kPrAnswer;
3445 } else if (type == SessionDescriptionInterface::kAnswer) {
3446 return PeerConnection::kAnswer;
3447 }
3448 RTC_NOTREACHED() << "unknown action type";
3449 return PeerConnection::kOffer;
3450}
3451
3452bool PeerConnection::PushdownMediaDescription(cricket::ContentAction action,
3453 cricket::ContentSource source,
3454 std::string* err) {
3455 const SessionDescription* sdesc =
3456 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3457 ->description();
3458 RTC_DCHECK(sdesc);
3459 bool all_success = true;
3460 for (auto* channel : Channels()) {
3461 // TODO(steveanton): Add support for multiple channels of the same type.
3462 const ContentInfo* content_info =
3463 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3464 if (!content_info) {
3465 continue;
3466 }
3467 const MediaContentDescription* content_desc =
3468 static_cast<const MediaContentDescription*>(content_info->description);
3469 if (content_desc && !content_info->rejected) {
3470 bool success = (source == cricket::CS_LOCAL)
3471 ? channel->SetLocalContent(content_desc, action, err)
3472 : channel->SetRemoteContent(content_desc, action, err);
3473 if (!success) {
3474 all_success = false;
3475 break;
3476 }
3477 }
3478 }
3479 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3480 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3481 if (sctp_transport_ && local_description() && remote_description() &&
3482 cricket::GetFirstDataContent(local_description()->description()) &&
3483 cricket::GetFirstDataContent(remote_description()->description())) {
3484 all_success &= network_thread()->Invoke<bool>(
3485 RTC_FROM_HERE,
3486 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
3487 }
3488 return all_success;
3489}
3490
3491bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3492 RTC_DCHECK(network_thread()->IsCurrent());
3493 RTC_DCHECK(local_description());
3494 RTC_DCHECK(remote_description());
3495 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3496 // When we support "max-message-size", that would also be pushed down here.
3497 return sctp_transport_->Start(
3498 GetSctpPort(local_description()->description()),
3499 GetSctpPort(remote_description()->description()));
3500}
3501
3502bool PeerConnection::PushdownTransportDescription(cricket::ContentSource source,
3503 cricket::ContentAction action,
3504 std::string* error_desc) {
3505 RTC_DCHECK(signaling_thread()->IsCurrent());
3506
3507 if (source == cricket::CS_LOCAL) {
3508 return PushdownLocalTransportDescription(local_description()->description(),
3509 action, error_desc);
3510 }
3511 return PushdownRemoteTransportDescription(remote_description()->description(),
3512 action, error_desc);
3513}
3514
3515bool PeerConnection::PushdownLocalTransportDescription(
3516 const SessionDescription* sdesc,
3517 cricket::ContentAction action,
3518 std::string* err) {
3519 RTC_DCHECK(signaling_thread()->IsCurrent());
3520
3521 if (!sdesc) {
3522 return false;
3523 }
3524
3525 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3526 if (!transport_controller_->SetLocalTransportDescription(
3527 tinfo.content_name, tinfo.description, action, err)) {
3528 return false;
3529 }
3530 }
3531
3532 return true;
3533}
3534
3535bool PeerConnection::PushdownRemoteTransportDescription(
3536 const SessionDescription* sdesc,
3537 cricket::ContentAction action,
3538 std::string* err) {
3539 RTC_DCHECK(signaling_thread()->IsCurrent());
3540
3541 if (!sdesc) {
3542 return false;
3543 }
3544
3545 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3546 if (!transport_controller_->SetRemoteTransportDescription(
3547 tinfo.content_name, tinfo.description, action, err)) {
3548 return false;
3549 }
3550 }
3551
3552 return true;
3553}
3554
3555bool PeerConnection::GetTransportDescription(
3556 const SessionDescription* description,
3557 const std::string& content_name,
3558 cricket::TransportDescription* tdesc) {
3559 if (!description || !tdesc) {
3560 return false;
3561 }
3562 const TransportInfo* transport_info =
3563 description->GetTransportInfoByName(content_name);
3564 if (!transport_info) {
3565 return false;
3566 }
3567 *tdesc = transport_info->description;
3568 return true;
3569}
3570
3571bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3572 const std::string* first_content_name = bundle.FirstContentName();
3573 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003574 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08003575 return false;
3576 }
3577 const std::string& transport_name = *first_content_name;
3578
3579 auto maybe_set_transport = [this, bundle,
3580 transport_name](cricket::BaseChannel* ch) {
3581 if (!ch || !bundle.HasContentName(ch->content_name())) {
3582 return true;
3583 }
3584
3585 std::string old_transport_name = ch->transport_name();
3586 if (old_transport_name == transport_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003587 RTC_LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3588 << " on " << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003589 return true;
3590 }
3591
3592 cricket::DtlsTransportInternal* rtp_dtls_transport =
3593 transport_controller_->CreateDtlsTransport(
3594 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3595 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3596 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3597 if (need_rtcp) {
3598 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3599 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3600 }
3601
3602 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
Mirko Bonadei675513b2017-11-09 11:09:25 +01003603 RTC_LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3604 << transport_name << ".";
Steve Anton75737c02017-11-06 10:37:17 -08003605 transport_controller_->DestroyDtlsTransport(
3606 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3607 // If the channel needs rtcp, it means that the channel used to have a
3608 // rtcp transport which needs to be deleted now.
3609 if (need_rtcp) {
3610 transport_controller_->DestroyDtlsTransport(
3611 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3612 }
3613 return true;
3614 };
3615
3616 if (!maybe_set_transport(voice_channel()) ||
3617 !maybe_set_transport(video_channel()) ||
3618 !maybe_set_transport(rtp_data_channel())) {
3619 return false;
3620 }
3621 // For SCTP, transport creation/deletion happens here instead of in the
3622 // object itself.
3623 if (sctp_transport_) {
3624 RTC_DCHECK(sctp_transport_name_);
3625 RTC_DCHECK(sctp_content_name_);
3626 if (transport_name != *sctp_transport_name_ &&
3627 bundle.HasContentName(*sctp_content_name_)) {
3628 network_thread()->Invoke<void>(
3629 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3630 transport_name));
3631 }
3632 }
3633
3634 return true;
3635}
3636
Steve Anton75737c02017-11-06 10:37:17 -08003637cricket::IceConfig PeerConnection::ParseIceConfig(
3638 const PeerConnectionInterface::RTCConfiguration& config) const {
3639 cricket::ContinualGatheringPolicy gathering_policy;
3640 // TODO(honghaiz): Add the third continual gathering policy in
3641 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3642 switch (config.continual_gathering_policy) {
3643 case PeerConnectionInterface::GATHER_ONCE:
3644 gathering_policy = cricket::GATHER_ONCE;
3645 break;
3646 case PeerConnectionInterface::GATHER_CONTINUALLY:
3647 gathering_policy = cricket::GATHER_CONTINUALLY;
3648 break;
3649 default:
3650 RTC_NOTREACHED();
3651 gathering_policy = cricket::GATHER_ONCE;
3652 }
3653 cricket::IceConfig ice_config;
3654 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3655 ice_config.prioritize_most_likely_candidate_pairs =
3656 config.prioritize_most_likely_ice_candidate_pairs;
3657 ice_config.backup_connection_ping_interval =
3658 config.ice_backup_candidate_pair_ping_interval;
3659 ice_config.continual_gathering_policy = gathering_policy;
3660 ice_config.presume_writable_when_fully_relayed =
3661 config.presume_writable_when_fully_relayed;
3662 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3663 ice_config.regather_all_networks_interval_range =
3664 config.ice_regather_interval_range;
3665 return ice_config;
3666}
3667
Steve Anton75737c02017-11-06 10:37:17 -08003668bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3669 std::string* track_id) {
3670 if (!local_description()) {
3671 return false;
3672 }
3673 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3674 track_id);
3675}
3676
3677bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3678 std::string* track_id) {
3679 if (!remote_description()) {
3680 return false;
3681 }
3682 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3683 track_id);
3684}
3685
3686bool PeerConnection::SendData(const cricket::SendDataParams& params,
3687 const rtc::CopyOnWriteBuffer& payload,
3688 cricket::SendDataResult* result) {
3689 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003690 RTC_LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3691 << "and sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003692 return false;
3693 }
3694 return rtp_data_channel_
3695 ? rtp_data_channel_->SendData(params, payload, result)
3696 : network_thread()->Invoke<bool>(
3697 RTC_FROM_HERE,
3698 Bind(&cricket::SctpTransportInternal::SendData,
3699 sctp_transport_.get(), params, payload, result));
3700}
3701
3702bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3703 if (!rtp_data_channel_ && !sctp_transport_) {
3704 // Don't log an error here, because DataChannels are expected to call
3705 // ConnectDataChannel in this state. It's the only way to initially tell
3706 // whether or not the underlying transport is ready.
3707 return false;
3708 }
3709 if (rtp_data_channel_) {
3710 rtp_data_channel_->SignalReadyToSendData.connect(
3711 webrtc_data_channel, &DataChannel::OnChannelReady);
3712 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3713 &DataChannel::OnDataReceived);
3714 } else {
3715 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3716 &DataChannel::OnChannelReady);
3717 SignalSctpDataReceived.connect(webrtc_data_channel,
3718 &DataChannel::OnDataReceived);
3719 SignalSctpStreamClosedRemotely.connect(
3720 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3721 }
3722 return true;
3723}
3724
3725void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3726 if (!rtp_data_channel_ && !sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003727 RTC_LOG(LS_ERROR)
3728 << "DisconnectDataChannel called when rtp_data_channel_ and "
3729 "sctp_transport_ are NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003730 return;
3731 }
3732 if (rtp_data_channel_) {
3733 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3734 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3735 } else {
3736 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3737 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3738 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3739 }
3740}
3741
3742void PeerConnection::AddSctpDataStream(int sid) {
3743 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003744 RTC_LOG(LS_ERROR)
3745 << "AddSctpDataStream called when sctp_transport_ is NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003746 return;
3747 }
3748 network_thread()->Invoke<void>(
3749 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3750 sctp_transport_.get(), sid));
3751}
3752
3753void PeerConnection::RemoveSctpDataStream(int sid) {
3754 if (!sctp_transport_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003755 RTC_LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3756 << "NULL.";
Steve Anton75737c02017-11-06 10:37:17 -08003757 return;
3758 }
3759 network_thread()->Invoke<void>(
3760 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3761 sctp_transport_.get(), sid));
3762}
3763
3764bool PeerConnection::ReadyToSendData() const {
3765 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3766 sctp_ready_to_send_data_;
3767}
3768
3769std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3770 RTC_DCHECK(signaling_thread()->IsCurrent());
3771 ChannelNamePairs channel_name_pairs;
3772 if (voice_channel()) {
3773 channel_name_pairs.voice = rtc::Optional<ChannelNamePair>(ChannelNamePair(
3774 voice_channel()->content_name(), voice_channel()->transport_name()));
3775 }
3776 if (video_channel()) {
3777 channel_name_pairs.video = rtc::Optional<ChannelNamePair>(ChannelNamePair(
3778 video_channel()->content_name(), video_channel()->transport_name()));
3779 }
3780 if (rtp_data_channel()) {
3781 channel_name_pairs.data = rtc::Optional<ChannelNamePair>(
3782 ChannelNamePair(rtp_data_channel()->content_name(),
3783 rtp_data_channel()->transport_name()));
3784 }
3785 if (sctp_transport_) {
3786 RTC_DCHECK(sctp_content_name_);
3787 RTC_DCHECK(sctp_transport_name_);
3788 channel_name_pairs.data = rtc::Optional<ChannelNamePair>(
3789 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_));
3790 }
3791 return GetSessionStats(channel_name_pairs);
3792}
3793
3794std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3795 const ChannelNamePairs& channel_name_pairs) {
3796 if (network_thread()->IsCurrent()) {
3797 return GetSessionStats_n(channel_name_pairs);
3798 }
3799 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3800 RTC_FROM_HERE,
3801 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3802}
3803
3804bool PeerConnection::GetLocalCertificate(
3805 const std::string& transport_name,
3806 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
3807 return transport_controller_->GetLocalCertificate(transport_name,
3808 certificate);
3809}
3810
3811std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
3812 const std::string& transport_name) {
3813 return transport_controller_->GetRemoteSSLCertificate(transport_name);
3814}
3815
3816cricket::DataChannelType PeerConnection::data_channel_type() const {
3817 return data_channel_type_;
3818}
3819
3820bool PeerConnection::IceRestartPending(const std::string& content_name) const {
3821 return pending_ice_restarts_.find(content_name) !=
3822 pending_ice_restarts_.end();
3823}
3824
Steve Anton75737c02017-11-06 10:37:17 -08003825bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
3826 return transport_controller_->NeedsIceRestart(content_name);
3827}
3828
3829void PeerConnection::OnCertificateReady(
3830 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
3831 transport_controller_->SetLocalCertificate(certificate);
3832}
3833
3834void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
3835 SetError(ERROR_TRANSPORT,
3836 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
3837}
3838
3839void PeerConnection::OnTransportControllerConnectionState(
3840 cricket::IceConnectionState state) {
3841 switch (state) {
3842 case cricket::kIceConnectionConnecting:
3843 // If the current state is Connected or Completed, then there were
3844 // writable channels but now there are not, so the next state must
3845 // be Disconnected.
3846 // kIceConnectionConnecting is currently used as the default,
3847 // un-connected state by the TransportController, so its only use is
3848 // detecting disconnections.
3849 if (ice_connection_state_ ==
3850 PeerConnectionInterface::kIceConnectionConnected ||
3851 ice_connection_state_ ==
3852 PeerConnectionInterface::kIceConnectionCompleted) {
3853 SetIceConnectionState(
3854 PeerConnectionInterface::kIceConnectionDisconnected);
3855 }
3856 break;
3857 case cricket::kIceConnectionFailed:
3858 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
3859 break;
3860 case cricket::kIceConnectionConnected:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003861 RTC_LOG(LS_INFO) << "Changing to ICE connected state because "
3862 << "all transports are writable.";
Steve Anton75737c02017-11-06 10:37:17 -08003863 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3864 break;
3865 case cricket::kIceConnectionCompleted:
Mirko Bonadei675513b2017-11-09 11:09:25 +01003866 RTC_LOG(LS_INFO) << "Changing to ICE completed state because "
3867 << "all transports are complete.";
Steve Anton75737c02017-11-06 10:37:17 -08003868 if (ice_connection_state_ !=
3869 PeerConnectionInterface::kIceConnectionConnected) {
3870 // If jumping directly from "checking" to "connected",
3871 // signal "connected" first.
3872 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3873 }
3874 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
3875 if (metrics_observer()) {
3876 ReportTransportStats();
3877 }
3878 break;
3879 default:
3880 RTC_NOTREACHED();
3881 }
3882}
3883
3884void PeerConnection::OnTransportControllerCandidatesGathered(
3885 const std::string& transport_name,
3886 const cricket::Candidates& candidates) {
3887 RTC_DCHECK(signaling_thread()->IsCurrent());
3888 int sdp_mline_index;
3889 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003890 RTC_LOG(LS_ERROR)
3891 << "OnTransportControllerCandidatesGathered: content name "
3892 << transport_name << " not found";
Steve Anton75737c02017-11-06 10:37:17 -08003893 return;
3894 }
3895
3896 for (cricket::Candidates::const_iterator citer = candidates.begin();
3897 citer != candidates.end(); ++citer) {
3898 // Use transport_name as the candidate media id.
3899 std::unique_ptr<JsepIceCandidate> candidate(
3900 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
3901 if (local_description()) {
3902 mutable_local_description()->AddCandidate(candidate.get());
3903 }
3904 OnIceCandidate(std::move(candidate));
3905 }
3906}
3907
3908void PeerConnection::OnTransportControllerCandidatesRemoved(
3909 const std::vector<cricket::Candidate>& candidates) {
3910 RTC_DCHECK(signaling_thread()->IsCurrent());
3911 // Sanity check.
3912 for (const cricket::Candidate& candidate : candidates) {
3913 if (candidate.transport_name().empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003914 RTC_LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
3915 << "empty content name in candidate "
3916 << candidate.ToString();
Steve Anton75737c02017-11-06 10:37:17 -08003917 return;
3918 }
3919 }
3920
3921 if (local_description()) {
3922 mutable_local_description()->RemoveCandidates(candidates);
3923 }
3924 OnIceCandidatesRemoved(candidates);
3925}
3926
3927void PeerConnection::OnTransportControllerDtlsHandshakeError(
3928 rtc::SSLHandshakeError error) {
3929 if (metrics_observer()) {
3930 metrics_observer()->IncrementEnumCounter(
3931 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
3932 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
3933 }
3934}
3935
3936// Enabling voice and video (and RTP data) channels.
3937void PeerConnection::EnableChannels() {
3938 for (cricket::VoiceChannel* voice_channel : voice_channels_) {
3939 if (!voice_channel->enabled()) {
3940 voice_channel->Enable(true);
3941 }
3942 }
3943
3944 for (cricket::VideoChannel* video_channel : video_channels_) {
3945 if (!video_channel->enabled()) {
3946 video_channel->Enable(true);
3947 }
3948 }
3949
3950 if (rtp_data_channel_ && !rtp_data_channel_->enabled())
3951 rtp_data_channel_->Enable(true);
3952}
3953
3954// Returns the media index for a local ice candidate given the content name.
3955bool PeerConnection::GetLocalCandidateMediaIndex(
3956 const std::string& content_name,
3957 int* sdp_mline_index) {
3958 if (!local_description() || !sdp_mline_index) {
3959 return false;
3960 }
3961
3962 bool content_found = false;
3963 const ContentInfos& contents = local_description()->description()->contents();
3964 for (size_t index = 0; index < contents.size(); ++index) {
3965 if (contents[index].name == content_name) {
3966 *sdp_mline_index = static_cast<int>(index);
3967 content_found = true;
3968 break;
3969 }
3970 }
3971 return content_found;
3972}
3973
3974bool PeerConnection::UseCandidatesInSessionDescription(
3975 const SessionDescriptionInterface* remote_desc) {
3976 if (!remote_desc) {
3977 return true;
3978 }
3979 bool ret = true;
3980
3981 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
3982 const IceCandidateCollection* candidates = remote_desc->candidates(m);
3983 for (size_t n = 0; n < candidates->count(); ++n) {
3984 const IceCandidateInterface* candidate = candidates->at(n);
3985 bool valid = false;
3986 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
3987 if (valid) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01003988 RTC_LOG(LS_INFO)
3989 << "UseCandidatesInSessionDescription: Not ready to use "
3990 << "candidate.";
Steve Anton75737c02017-11-06 10:37:17 -08003991 }
3992 continue;
3993 }
3994 ret = UseCandidate(candidate);
3995 if (!ret) {
3996 break;
3997 }
3998 }
3999 }
4000 return ret;
4001}
4002
4003bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
4004 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4005 size_t remote_content_size =
4006 remote_description()->description()->contents().size();
4007 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004008 RTC_LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
Steve Anton75737c02017-11-06 10:37:17 -08004009 return false;
4010 }
4011
4012 cricket::ContentInfo content =
4013 remote_description()->description()->contents()[mediacontent_index];
4014 std::vector<cricket::Candidate> candidates;
4015 candidates.push_back(candidate->candidate());
4016 // Invoking BaseSession method to handle remote candidates.
4017 std::string error;
4018 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4019 &error)) {
4020 // Candidates successfully submitted for checking.
4021 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4022 ice_connection_state_ ==
4023 PeerConnectionInterface::kIceConnectionDisconnected) {
4024 // If state is New, then the session has just gotten its first remote ICE
4025 // candidates, so go to Checking.
4026 // If state is Disconnected, the session is re-using old candidates or
4027 // receiving additional ones, so go to Checking.
4028 // If state is Connected, stay Connected.
4029 // TODO(bemasc): If state is Connected, and the new candidates are for a
4030 // newly added transport, then the state actually _should_ move to
4031 // checking. Add a way to distinguish that case.
4032 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4033 }
4034 // TODO(bemasc): If state is Completed, go back to Connected.
4035 } else {
4036 if (!error.empty()) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004037 RTC_LOG(LS_WARNING) << error;
Steve Anton75737c02017-11-06 10:37:17 -08004038 }
4039 }
4040 return true;
4041}
4042
4043void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
4044 // TODO(steveanton): Add support for multiple audio/video channels.
4045 // Destroy video channel first since it may have a pointer to the
4046 // voice channel.
4047 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
4048 if ((!video_info || video_info->rejected) && video_channel()) {
4049 RemoveAndDestroyVideoChannel(video_channel());
4050 }
4051
4052 const cricket::ContentInfo* voice_info = cricket::GetFirstAudioContent(desc);
4053 if ((!voice_info || voice_info->rejected) && voice_channel()) {
4054 RemoveAndDestroyVoiceChannel(voice_channel());
4055 }
4056
4057 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4058 if (!data_info || data_info->rejected) {
4059 if (rtp_data_channel_) {
4060 DestroyDataChannel();
4061 }
4062 if (sctp_transport_) {
4063 OnDataChannelDestroyed();
4064 network_thread()->Invoke<void>(
4065 RTC_FROM_HERE,
4066 rtc::Bind(&PeerConnection::DestroySctpTransport_n, this));
4067 }
4068 }
4069}
4070
4071// Returns the name of the transport channel when BUNDLE is enabled, or nullptr
4072// if the channel is not part of any bundle.
4073const std::string* PeerConnection::GetBundleTransportName(
4074 const cricket::ContentInfo* content,
4075 const cricket::ContentGroup* bundle) {
4076 if (!bundle) {
4077 return nullptr;
4078 }
4079 const std::string* first_content_name = bundle->FirstContentName();
4080 if (!first_content_name) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004081 RTC_LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
Steve Anton75737c02017-11-06 10:37:17 -08004082 return nullptr;
4083 }
4084 if (!bundle->HasContentName(content->name)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004085 RTC_LOG(LS_WARNING) << content->name << " is not part of any bundle group";
Steve Anton75737c02017-11-06 10:37:17 -08004086 return nullptr;
4087 }
Mirko Bonadei675513b2017-11-09 11:09:25 +01004088 RTC_LOG(LS_INFO) << "Bundling " << content->name << " on "
4089 << *first_content_name;
Steve Anton75737c02017-11-06 10:37:17 -08004090 return first_content_name;
4091}
4092
4093bool PeerConnection::CreateChannels(const SessionDescription* desc) {
4094 // TODO(steveanton): Add support for multiple audio/video channels.
4095 const cricket::ContentGroup* bundle_group = nullptr;
4096 if (configuration_.bundle_policy ==
4097 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4098 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4099 if (!bundle_group) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004100 RTC_LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
Steve Anton75737c02017-11-06 10:37:17 -08004101 return false;
4102 }
4103 }
4104 // Creating the media channels and transport proxies.
4105 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4106 if (voice && !voice->rejected && !voice_channel()) {
4107 if (!CreateVoiceChannel(voice,
4108 GetBundleTransportName(voice, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004109 RTC_LOG(LS_ERROR) << "Failed to create voice channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004110 return false;
4111 }
4112 }
4113
4114 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
4115 if (video && !video->rejected && !video_channel()) {
4116 if (!CreateVideoChannel(video,
4117 GetBundleTransportName(video, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004118 RTC_LOG(LS_ERROR) << "Failed to create video channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004119 return false;
4120 }
4121 }
4122
4123 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4124 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4125 !rtp_data_channel_ && !sctp_transport_) {
4126 if (!CreateDataChannel(data, GetBundleTransportName(data, bundle_group))) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004127 RTC_LOG(LS_ERROR) << "Failed to create data channel.";
Steve Anton75737c02017-11-06 10:37:17 -08004128 return false;
4129 }
4130 }
4131
4132 return true;
4133}
4134
4135bool PeerConnection::CreateVoiceChannel(const cricket::ContentInfo* content,
4136 const std::string* bundle_transport) {
4137 // TODO(steveanton): Check to see if it's safe to create multiple voice
4138 // channels.
4139 RTC_DCHECK(voice_channels_.empty());
4140
4141 std::string transport_name =
4142 bundle_transport ? *bundle_transport : content->name;
4143
4144 cricket::DtlsTransportInternal* rtp_dtls_transport =
4145 transport_controller_->CreateDtlsTransport(
4146 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4147 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4148 if (configuration_.rtcp_mux_policy !=
4149 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4150 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4151 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4152 }
4153
4154 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4155 call_.get(), configuration_.media_config, rtp_dtls_transport,
4156 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4157 content->name, SrtpRequired(), audio_options_);
4158 if (!voice_channel) {
4159 transport_controller_->DestroyDtlsTransport(
4160 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4161 if (rtcp_dtls_transport) {
4162 transport_controller_->DestroyDtlsTransport(
4163 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4164 }
4165 return false;
4166 }
4167
4168 voice_channels_.push_back(voice_channel);
4169
4170 voice_channel->SignalRtcpMuxFullyActive.connect(
4171 this, &PeerConnection::DestroyRtcpTransport_n);
4172 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4173 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4174
Steve Antond25da372017-11-06 14:50:29 -08004175 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
4176 voice_channel, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
Steve Anton75737c02017-11-06 10:37:17 -08004177 voice_channel->SignalSentPacket.connect(this,
4178 &PeerConnection::OnSentPacket_w);
4179 return true;
4180}
4181
4182bool PeerConnection::CreateVideoChannel(const cricket::ContentInfo* content,
4183 const std::string* bundle_transport) {
4184 // TODO(steveanton): Check to see if it's safe to create multiple video
4185 // channels.
4186 RTC_DCHECK(video_channels_.empty());
4187
4188 std::string transport_name =
4189 bundle_transport ? *bundle_transport : content->name;
4190
4191 cricket::DtlsTransportInternal* rtp_dtls_transport =
4192 transport_controller_->CreateDtlsTransport(
4193 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4194 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4195 if (configuration_.rtcp_mux_policy !=
4196 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4197 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4198 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4199 }
4200
4201 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4202 call_.get(), configuration_.media_config, rtp_dtls_transport,
4203 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4204 content->name, SrtpRequired(), video_options_);
4205
4206 if (!video_channel) {
4207 transport_controller_->DestroyDtlsTransport(
4208 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4209 if (rtcp_dtls_transport) {
4210 transport_controller_->DestroyDtlsTransport(
4211 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4212 }
4213 return false;
4214 }
4215
4216 video_channels_.push_back(video_channel);
4217
4218 video_channel->SignalRtcpMuxFullyActive.connect(
4219 this, &PeerConnection::DestroyRtcpTransport_n);
4220 video_channel->SignalDtlsSrtpSetupFailure.connect(
4221 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4222
Steve Antond25da372017-11-06 14:50:29 -08004223 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
4224 video_channel, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
Steve Anton75737c02017-11-06 10:37:17 -08004225 video_channel->SignalSentPacket.connect(this,
4226 &PeerConnection::OnSentPacket_w);
4227 return true;
4228}
4229
4230bool PeerConnection::CreateDataChannel(const cricket::ContentInfo* content,
4231 const std::string* bundle_transport) {
4232 const std::string transport_name =
4233 bundle_transport ? *bundle_transport : content->name;
4234 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4235 if (sctp) {
4236 if (!sctp_factory_) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004237 RTC_LOG(LS_ERROR)
Steve Anton75737c02017-11-06 10:37:17 -08004238 << "Trying to create SCTP transport, but didn't compile with "
4239 "SCTP support (HAVE_SCTP)";
4240 return false;
4241 }
4242 if (!network_thread()->Invoke<bool>(
4243 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
4244 this, content->name, transport_name))) {
4245 return false;
4246 }
4247 } else {
4248 std::string transport_name =
4249 bundle_transport ? *bundle_transport : content->name;
4250 cricket::DtlsTransportInternal* rtp_dtls_transport =
4251 transport_controller_->CreateDtlsTransport(
4252 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4253 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4254 if (configuration_.rtcp_mux_policy !=
4255 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4256 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4257 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4258 }
4259
4260 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4261 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
4262 transport_controller_->signaling_thread(), content->name,
4263 SrtpRequired());
4264
4265 if (!rtp_data_channel_) {
4266 transport_controller_->DestroyDtlsTransport(
4267 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4268 if (rtcp_dtls_transport) {
4269 transport_controller_->DestroyDtlsTransport(
4270 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4271 }
4272 return false;
4273 }
4274
4275 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4276 this, &PeerConnection::DestroyRtcpTransport_n);
4277 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4278 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4279 rtp_data_channel_->SignalSentPacket.connect(
4280 this, &PeerConnection::OnSentPacket_w);
4281 }
4282
Steve Antond25da372017-11-06 14:50:29 -08004283 for (const auto& channel : sctp_data_channels_) {
4284 channel->OnTransportChannelCreated();
4285 }
Steve Anton75737c02017-11-06 10:37:17 -08004286
4287 return true;
4288}
4289
4290Call::Stats PeerConnection::GetCallStats() {
4291 if (!worker_thread()->IsCurrent()) {
4292 return worker_thread()->Invoke<Call::Stats>(
4293 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4294 }
4295 if (call_) {
4296 return call_->GetStats();
4297 } else {
4298 return Call::Stats();
4299 }
4300}
4301
4302std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4303 const ChannelNamePairs& channel_name_pairs) {
4304 RTC_DCHECK(network_thread()->IsCurrent());
4305 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4306 for (const auto channel_name_pair :
4307 {&channel_name_pairs.voice, &channel_name_pairs.video,
4308 &channel_name_pairs.data}) {
4309 if (*channel_name_pair) {
4310 cricket::TransportStats transport_stats;
4311 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4312 &transport_stats)) {
4313 return nullptr;
4314 }
4315 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4316 (*channel_name_pair)->transport_name;
4317 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4318 std::move(transport_stats);
4319 }
4320 }
4321 return session_stats;
4322}
4323
4324bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4325 const std::string& transport_name) {
4326 RTC_DCHECK(network_thread()->IsCurrent());
4327 RTC_DCHECK(sctp_factory_);
4328 cricket::DtlsTransportInternal* tc =
4329 transport_controller_->CreateDtlsTransport_n(
4330 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4331 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4332 RTC_DCHECK(sctp_transport_);
4333 sctp_invoker_.reset(new rtc::AsyncInvoker());
4334 sctp_transport_->SignalReadyToSendData.connect(
4335 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4336 sctp_transport_->SignalDataReceived.connect(
4337 this, &PeerConnection::OnSctpTransportDataReceived_n);
4338 sctp_transport_->SignalStreamClosedRemotely.connect(
4339 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
4340 sctp_transport_name_ = rtc::Optional<std::string>(transport_name);
4341 sctp_content_name_ = rtc::Optional<std::string>(content_name);
4342 return true;
4343}
4344
4345void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4346 RTC_DCHECK(network_thread()->IsCurrent());
4347 RTC_DCHECK(sctp_transport_);
4348 RTC_DCHECK(sctp_transport_name_);
4349 std::string old_sctp_transport_name = *sctp_transport_name_;
4350 sctp_transport_name_ = rtc::Optional<std::string>(transport_name);
4351 cricket::DtlsTransportInternal* tc =
4352 transport_controller_->CreateDtlsTransport_n(
4353 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4354 sctp_transport_->SetTransportChannel(tc);
4355 transport_controller_->DestroyDtlsTransport_n(
4356 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4357}
4358
4359void PeerConnection::DestroySctpTransport_n() {
4360 RTC_DCHECK(network_thread()->IsCurrent());
4361 sctp_transport_.reset(nullptr);
4362 sctp_content_name_.reset();
4363 sctp_transport_name_.reset();
4364 sctp_invoker_.reset(nullptr);
4365 sctp_ready_to_send_data_ = false;
4366}
4367
4368void PeerConnection::OnSctpTransportReadyToSendData_n() {
4369 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4370 RTC_DCHECK(network_thread()->IsCurrent());
4371 // Note: Cannot use rtc::Bind here because it will grab a reference to
4372 // PeerConnection and potentially cause PeerConnection to live longer than
4373 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4374 // be destroyed before PeerConnection is destroyed, and at that point all
4375 // pending tasks will be cleared.
4376 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4377 OnSctpTransportReadyToSendData_s(true);
4378 });
4379}
4380
4381void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4382 RTC_DCHECK(signaling_thread()->IsCurrent());
4383 sctp_ready_to_send_data_ = ready;
4384 SignalSctpReadyToSendData(ready);
4385}
4386
4387void PeerConnection::OnSctpTransportDataReceived_n(
4388 const cricket::ReceiveDataParams& params,
4389 const rtc::CopyOnWriteBuffer& payload) {
4390 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4391 RTC_DCHECK(network_thread()->IsCurrent());
4392 // Note: Cannot use rtc::Bind here because it will grab a reference to
4393 // PeerConnection and potentially cause PeerConnection to live longer than
4394 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4395 // be destroyed before PeerConnection is destroyed, and at that point all
4396 // pending tasks will be cleared.
4397 sctp_invoker_->AsyncInvoke<void>(
4398 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4399 OnSctpTransportDataReceived_s(params, payload);
4400 });
4401}
4402
4403void PeerConnection::OnSctpTransportDataReceived_s(
4404 const cricket::ReceiveDataParams& params,
4405 const rtc::CopyOnWriteBuffer& payload) {
4406 RTC_DCHECK(signaling_thread()->IsCurrent());
4407 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4408 // Received OPEN message; parse and signal that a new data channel should
4409 // be created.
4410 std::string label;
4411 InternalDataChannelInit config;
4412 config.id = params.ssrc;
4413 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004414 RTC_LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4415 << params.ssrc;
Steve Anton75737c02017-11-06 10:37:17 -08004416 return;
4417 }
4418 config.open_handshake_role = InternalDataChannelInit::kAcker;
4419 OnDataChannelOpenMessage(label, config);
4420 } else {
4421 // Otherwise just forward the signal.
4422 SignalSctpDataReceived(params, payload);
4423 }
4424}
4425
4426void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4427 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4428 RTC_DCHECK(network_thread()->IsCurrent());
4429 sctp_invoker_->AsyncInvoke<void>(
4430 RTC_FROM_HERE, signaling_thread(),
4431 rtc::Bind(&sigslot::signal1<int>::operator(),
4432 &SignalSctpStreamClosedRemotely, sid));
4433}
4434
4435// Returns false if bundle is enabled and rtcp_mux is disabled.
4436bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4437 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4438 if (!bundle_enabled)
4439 return true;
4440
4441 const cricket::ContentGroup* bundle_group =
4442 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4443 RTC_DCHECK(bundle_group != NULL);
4444
4445 const cricket::ContentInfos& contents = desc->contents();
4446 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4447 citer != contents.end(); ++citer) {
4448 const cricket::ContentInfo* content = (&*citer);
4449 RTC_DCHECK(content != NULL);
4450 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4451 content->type == cricket::NS_JINGLE_RTP) {
4452 if (!HasRtcpMuxEnabled(content))
4453 return false;
4454 }
4455 }
4456 // RTCP-MUX is enabled in all the contents.
4457 return true;
4458}
4459
4460bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4461 const cricket::MediaContentDescription* description =
4462 static_cast<cricket::MediaContentDescription*>(content->description);
4463 return description->rtcp_mux();
4464}
4465
4466bool PeerConnection::ValidateSessionDescription(
4467 const SessionDescriptionInterface* sdesc,
4468 cricket::ContentSource source,
4469 std::string* err_desc) {
4470 std::string type;
4471 if (error() != ERROR_NONE) {
4472 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
4473 }
4474
4475 if (!sdesc || !sdesc->description()) {
4476 return BadSdp(source, type, kInvalidSdp, err_desc);
4477 }
4478
4479 type = sdesc->type();
4480 Action action = GetAction(sdesc->type());
4481 if (source == cricket::CS_LOCAL) {
4482 if (!ExpectSetLocalDescription(action))
4483 return BadLocalSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4484 } else {
4485 if (!ExpectSetRemoteDescription(action))
4486 return BadRemoteSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4487 }
4488
4489 // Verify crypto settings.
4490 std::string crypto_error;
4491 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4492 dtls_enabled_) &&
4493 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
4494 return BadSdp(source, type, crypto_error, err_desc);
4495 }
4496
4497 // Verify ice-ufrag and ice-pwd.
4498 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
4499 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
4500 }
4501
4502 if (!ValidateBundleSettings(sdesc->description())) {
4503 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
4504 }
4505
4506 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4507 // m-lines that do not rtcp-mux enabled.
4508
4509 // Verify m-lines in Answer when compared against Offer.
4510 if (action == kAnswer || action == kPrAnswer) {
4511 const cricket::SessionDescription* offer_desc =
4512 (source == cricket::CS_LOCAL) ? remote_description()->description()
4513 : local_description()->description();
4514 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4515 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
4516 return BadAnswerSdp(source, kMlineMismatchInAnswer, err_desc);
4517 }
4518 } else {
4519 const cricket::SessionDescription* current_desc = nullptr;
4520 if (source == cricket::CS_LOCAL && local_description()) {
4521 current_desc = local_description()->description();
4522 } else if (source == cricket::CS_REMOTE && remote_description()) {
4523 current_desc = remote_description()->description();
4524 }
4525 // The re-offers should respect the order of m= sections in current
4526 // description. See RFC3264 Section 8 paragraph 4 for more details.
4527 if (current_desc &&
4528 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
4529 return BadOfferSdp(source, kMlineMismatchInSubsequentOffer, err_desc);
4530 }
4531 }
4532
4533 return true;
4534}
4535
4536bool PeerConnection::ExpectSetLocalDescription(Action action) {
4537 PeerConnectionInterface::SignalingState state = signaling_state();
4538 if (action == kOffer) {
4539 return (state == PeerConnectionInterface::kStable) ||
4540 (state == PeerConnectionInterface::kHaveLocalOffer);
4541 } else { // Answer or PrAnswer
4542 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4543 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4544 }
4545}
4546
4547bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4548 PeerConnectionInterface::SignalingState state = signaling_state();
4549 if (action == kOffer) {
4550 return (state == PeerConnectionInterface::kStable) ||
4551 (state == PeerConnectionInterface::kHaveRemoteOffer);
4552 } else { // Answer or PrAnswer.
4553 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4554 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4555 }
4556}
4557
4558std::string PeerConnection::GetSessionErrorMsg() {
4559 std::ostringstream desc;
4560 desc << kSessionError << GetErrorCodeString(error()) << ". ";
4561 desc << kSessionErrorDesc << error_desc() << ".";
4562 return desc.str();
4563}
4564
4565// We need to check the local/remote description for the Transport instead of
4566// the session, because a new Transport added during renegotiation may have
4567// them unset while the session has them set from the previous negotiation.
4568// Not doing so may trigger the auto generation of transport description and
4569// mess up DTLS identity information, ICE credential, etc.
4570bool PeerConnection::ReadyToUseRemoteCandidate(
4571 const IceCandidateInterface* candidate,
4572 const SessionDescriptionInterface* remote_desc,
4573 bool* valid) {
4574 *valid = true;
4575
4576 const SessionDescriptionInterface* current_remote_desc =
4577 remote_desc ? remote_desc : remote_description();
4578
4579 if (!current_remote_desc) {
4580 return false;
4581 }
4582
4583 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4584 size_t remote_content_size =
4585 current_remote_desc->description()->contents().size();
4586 if (mediacontent_index >= remote_content_size) {
Mirko Bonadei675513b2017-11-09 11:09:25 +01004587 RTC_LOG(LS_ERROR)
4588 << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4589 << mediacontent_index;
Steve Anton75737c02017-11-06 10:37:17 -08004590
4591 *valid = false;
4592 return false;
4593 }
4594
4595 cricket::ContentInfo content =
4596 current_remote_desc->description()->contents()[mediacontent_index];
4597
4598 const std::string transport_name = GetTransportName(content.name);
4599 if (transport_name.empty()) {
4600 return false;
4601 }
4602 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4603}
4604
4605bool PeerConnection::SrtpRequired() const {
4606 return dtls_enabled_ ||
4607 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4608}
4609
4610void PeerConnection::OnTransportControllerGatheringState(
4611 cricket::IceGatheringState state) {
4612 RTC_DCHECK(signaling_thread()->IsCurrent());
4613 if (state == cricket::kIceGatheringGathering) {
4614 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4615 } else if (state == cricket::kIceGatheringComplete) {
4616 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4617 }
4618}
4619
4620void PeerConnection::ReportTransportStats() {
4621 // Use a set so we don't report the same stats twice if two channels share
4622 // a transport.
4623 std::set<std::string> transport_names;
4624 if (voice_channel()) {
4625 transport_names.insert(voice_channel()->transport_name());
4626 }
4627 if (video_channel()) {
4628 transport_names.insert(video_channel()->transport_name());
4629 }
4630 if (rtp_data_channel()) {
4631 transport_names.insert(rtp_data_channel()->transport_name());
4632 }
4633 if (sctp_transport_name_) {
4634 transport_names.insert(*sctp_transport_name_);
4635 }
4636 for (const auto& name : transport_names) {
4637 cricket::TransportStats stats;
4638 if (transport_controller_->GetStats(name, &stats)) {
4639 ReportBestConnectionState(stats);
4640 ReportNegotiatedCiphers(stats);
4641 }
4642 }
4643}
4644// Walk through the ConnectionInfos to gather best connection usage
4645// for IPv4 and IPv6.
4646void PeerConnection::ReportBestConnectionState(
4647 const cricket::TransportStats& stats) {
4648 RTC_DCHECK(metrics_observer());
4649 for (cricket::TransportChannelStatsList::const_iterator it =
4650 stats.channel_stats.begin();
4651 it != stats.channel_stats.end(); ++it) {
4652 for (cricket::ConnectionInfos::const_iterator it_info =
4653 it->connection_infos.begin();
4654 it_info != it->connection_infos.end(); ++it_info) {
4655 if (!it_info->best_connection) {
4656 continue;
4657 }
4658
4659 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4660 const cricket::Candidate& local = it_info->local_candidate;
4661 const cricket::Candidate& remote = it_info->remote_candidate;
4662
4663 // Increment the counter for IceCandidatePairType.
4664 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4665 (local.type() == RELAY_PORT_TYPE &&
4666 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4667 type = kEnumCounterIceCandidatePairTypeTcp;
4668 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4669 type = kEnumCounterIceCandidatePairTypeUdp;
4670 } else {
4671 RTC_CHECK(0);
4672 }
4673 metrics_observer()->IncrementEnumCounter(
4674 type, GetIceCandidatePairCounter(local, remote),
4675 kIceCandidatePairMax);
4676
4677 // Increment the counter for IP type.
4678 if (local.address().family() == AF_INET) {
4679 metrics_observer()->IncrementEnumCounter(
4680 kEnumCounterAddressFamily, kBestConnections_IPv4,
4681 kPeerConnectionAddressFamilyCounter_Max);
4682
4683 } else if (local.address().family() == AF_INET6) {
4684 metrics_observer()->IncrementEnumCounter(
4685 kEnumCounterAddressFamily, kBestConnections_IPv6,
4686 kPeerConnectionAddressFamilyCounter_Max);
4687 } else {
4688 RTC_CHECK(0);
4689 }
4690
4691 return;
4692 }
4693 }
4694}
4695
4696void PeerConnection::ReportNegotiatedCiphers(
4697 const cricket::TransportStats& stats) {
4698 RTC_DCHECK(metrics_observer());
4699 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4700 return;
4701 }
4702
4703 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4704 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4705 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4706 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4707 return;
4708 }
4709
4710 PeerConnectionEnumCounterType srtp_counter_type;
4711 PeerConnectionEnumCounterType ssl_counter_type;
4712 if (stats.transport_name == cricket::CN_AUDIO) {
4713 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4714 ssl_counter_type = kEnumCounterAudioSslCipher;
4715 } else if (stats.transport_name == cricket::CN_VIDEO) {
4716 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4717 ssl_counter_type = kEnumCounterVideoSslCipher;
4718 } else if (stats.transport_name == cricket::CN_DATA) {
4719 srtp_counter_type = kEnumCounterDataSrtpCipher;
4720 ssl_counter_type = kEnumCounterDataSslCipher;
4721 } else {
4722 RTC_NOTREACHED();
4723 return;
4724 }
4725
4726 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4727 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4728 srtp_crypto_suite);
4729 }
4730 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4731 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4732 ssl_cipher_suite);
4733 }
4734}
4735
4736void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4737 RTC_DCHECK(worker_thread()->IsCurrent());
4738 RTC_DCHECK(call_);
4739 call_->OnSentPacket(sent_packet);
4740}
4741
4742const std::string PeerConnection::GetTransportName(
4743 const std::string& content_name) {
4744 cricket::BaseChannel* channel = GetChannel(content_name);
4745 if (!channel) {
4746 if (sctp_transport_) {
4747 RTC_DCHECK(sctp_content_name_);
4748 RTC_DCHECK(sctp_transport_name_);
4749 if (content_name == *sctp_content_name_) {
4750 return *sctp_transport_name_;
4751 }
4752 }
4753 // Return an empty string if failed to retrieve the transport name.
4754 return "";
4755 }
4756 return channel->transport_name();
4757}
4758
4759void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4760 RTC_DCHECK(network_thread()->IsCurrent());
4761 transport_controller_->DestroyDtlsTransport_n(
4762 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4763}
4764
4765void PeerConnection::RemoveAndDestroyVideoChannel(
4766 cricket::VideoChannel* video_channel) {
4767 auto it =
4768 std::find(video_channels_.begin(), video_channels_.end(), video_channel);
4769 RTC_DCHECK(it != video_channels_.end());
4770 if (it == video_channels_.end()) {
4771 return;
4772 }
4773 video_channels_.erase(it);
4774 DestroyVideoChannel(video_channel);
4775}
4776
4777void PeerConnection::DestroyVideoChannel(cricket::VideoChannel* video_channel) {
Steve Antond25da372017-11-06 14:50:29 -08004778 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
4779 cricket::VideoChannel>(
4780 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
Steve Anton75737c02017-11-06 10:37:17 -08004781 RTC_DCHECK(video_channel->rtp_dtls_transport());
4782 const std::string transport_name =
4783 video_channel->rtp_dtls_transport()->transport_name();
4784 const bool need_to_delete_rtcp =
4785 (video_channel->rtcp_dtls_transport() != nullptr);
4786 // The above need to be cached before destroying the video channel so that we
4787 // do not access uninitialized memory.
4788 channel_manager()->DestroyVideoChannel(video_channel);
4789 transport_controller_->DestroyDtlsTransport(
4790 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4791 if (need_to_delete_rtcp) {
4792 transport_controller_->DestroyDtlsTransport(
4793 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4794 }
4795}
4796
4797void PeerConnection::RemoveAndDestroyVoiceChannel(
4798 cricket::VoiceChannel* voice_channel) {
4799 auto it =
4800 std::find(voice_channels_.begin(), voice_channels_.end(), voice_channel);
4801 RTC_DCHECK(it != voice_channels_.end());
4802 if (it == voice_channels_.end()) {
4803 return;
4804 }
4805 voice_channels_.erase(it);
4806 DestroyVoiceChannel(voice_channel);
4807}
4808
4809void PeerConnection::DestroyVoiceChannel(cricket::VoiceChannel* voice_channel) {
Steve Antond25da372017-11-06 14:50:29 -08004810 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
4811 cricket::VoiceChannel>(
4812 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
Steve Anton75737c02017-11-06 10:37:17 -08004813 RTC_DCHECK(voice_channel->rtp_dtls_transport());
4814 const std::string transport_name =
4815 voice_channel->rtp_dtls_transport()->transport_name();
4816 const bool need_to_delete_rtcp =
4817 (voice_channel->rtcp_dtls_transport() != nullptr);
4818 // The above need to be cached before destroying the video channel so that we
4819 // do not access uninitialized memory.
4820 channel_manager()->DestroyVoiceChannel(voice_channel);
4821 transport_controller_->DestroyDtlsTransport(
4822 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4823 if (need_to_delete_rtcp) {
4824 transport_controller_->DestroyDtlsTransport(
4825 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4826 }
4827}
4828
4829void PeerConnection::DestroyDataChannel() {
4830 OnDataChannelDestroyed();
4831 RTC_DCHECK(rtp_data_channel_->rtp_dtls_transport());
4832 std::string transport_name;
4833 transport_name = rtp_data_channel_->rtp_dtls_transport()->transport_name();
4834 bool need_to_delete_rtcp =
4835 (rtp_data_channel_->rtcp_dtls_transport() != nullptr);
4836 channel_manager()->DestroyRtpDataChannel(rtp_data_channel_);
4837 rtp_data_channel_ = nullptr;
4838 transport_controller_->DestroyDtlsTransport(
4839 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4840 if (need_to_delete_rtcp) {
4841 transport_controller_->DestroyDtlsTransport(
4842 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4843 }
4844}
4845
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004846} // namespace webrtc