blob: bf2c4c34eba167d1e04481dd51e28b88125f01f6 [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) {
143 LOG(LS_ERROR) << "MediaStream with label " << new_stream->label()
144 << " is already added.";
145 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.
420 LOG(LS_ERROR) << kInvalidSdp;
421 *error = kInvalidSdp;
422 return false;
423 }
424 if (dtls_enabled) {
425 if (!tinfo->description.identity_fingerprint) {
426 LOG(LS_WARNING) << "Session description must have DTLS fingerprint if "
427 "DTLS enabled.";
428 *error = kSdpWithoutDtlsFingerprint;
429 return false;
430 }
431 } else {
432 if (media->cryptos().empty()) {
433 LOG(LS_WARNING)
434 << "Session description must have SDES when DTLS disabled.";
435 *error = kSdpWithoutSdesCrypto;
436 return false;
437 }
438 }
439 }
440
441 return true;
442}
443
444// Checks that each non-rejected content has ice-ufrag and ice-pwd set, unless
445// it's in a BUNDLE group, in which case only the BUNDLE-tag section (first
446// media section/description in the BUNDLE group) needs a ufrag and pwd.
447bool VerifyIceUfragPwdPresent(const SessionDescription* desc) {
448 const cricket::ContentGroup* bundle =
449 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
450 const ContentInfos& contents = desc->contents();
451 for (size_t index = 0; index < contents.size(); ++index) {
452 const ContentInfo* cinfo = &contents[index];
453 if (cinfo->rejected) {
454 continue;
455 }
456 if (bundle && bundle->HasContentName(cinfo->name) &&
457 cinfo->name != *(bundle->FirstContentName())) {
458 // This isn't the first media section in the BUNDLE group, so it's not
459 // required to have ufrag/password, since only the ufrag/password from
460 // the first section actually get used.
461 continue;
462 }
463
464 // If the content isn't rejected or bundled into another m= section,
465 // ice-ufrag and ice-pwd must be present.
466 const TransportInfo* tinfo = desc->GetTransportInfoByName(cinfo->name);
467 if (!tinfo) {
468 // Something is not right.
469 LOG(LS_ERROR) << kInvalidSdp;
470 return false;
471 }
472 if (tinfo->description.ice_ufrag.empty() ||
473 tinfo->description.ice_pwd.empty()) {
474 LOG(LS_ERROR) << "Session description must have ice ufrag and pwd.";
475 return false;
476 }
477 }
478 return true;
479}
480
481bool GetTrackIdBySsrc(const SessionDescription* session_description,
482 uint32_t ssrc,
483 std::string* track_id) {
484 RTC_DCHECK(track_id != NULL);
485
486 const cricket::ContentInfo* audio_info =
487 cricket::GetFirstAudioContent(session_description);
488 if (audio_info) {
489 const cricket::MediaContentDescription* audio_content =
490 static_cast<const cricket::MediaContentDescription*>(
491 audio_info->description);
492
493 const auto* found =
494 cricket::GetStreamBySsrc(audio_content->streams(), ssrc);
495 if (found) {
496 *track_id = found->id;
497 return true;
498 }
499 }
500
501 const cricket::ContentInfo* video_info =
502 cricket::GetFirstVideoContent(session_description);
503 if (video_info) {
504 const cricket::MediaContentDescription* video_content =
505 static_cast<const cricket::MediaContentDescription*>(
506 video_info->description);
507
508 const auto* found =
509 cricket::GetStreamBySsrc(video_content->streams(), ssrc);
510 if (found) {
511 *track_id = found->id;
512 return true;
513 }
514 }
515 return false;
516}
517
518// Get the SCTP port out of a SessionDescription.
519// Return -1 if not found.
520int GetSctpPort(const SessionDescription* session_description) {
521 const ContentInfo* content_info = GetFirstDataContent(session_description);
522 RTC_DCHECK(content_info);
523 if (!content_info) {
524 return -1;
525 }
526 const cricket::DataContentDescription* data =
527 static_cast<const cricket::DataContentDescription*>(
528 (content_info->description));
529 std::string value;
530 cricket::DataCodec match_pattern(cricket::kGoogleSctpDataCodecPlType,
531 cricket::kGoogleSctpDataCodecName);
532 for (const cricket::DataCodec& codec : data->codecs()) {
533 if (!codec.Matches(match_pattern)) {
534 continue;
535 }
536 if (codec.GetParam(cricket::kCodecParamPort, &value)) {
537 return rtc::FromString<int>(value);
538 }
539 }
540 return -1;
541}
542
543bool BadSdp(const std::string& source,
544 const std::string& type,
545 const std::string& reason,
546 std::string* err_desc) {
547 std::ostringstream desc;
548 desc << "Failed to set " << source;
549 if (!type.empty()) {
550 desc << " " << type;
551 }
552 desc << " sdp: " << reason;
553
554 if (err_desc) {
555 *err_desc = desc.str();
556 }
557 LOG(LS_ERROR) << desc.str();
558 return false;
559}
560
561bool BadSdp(cricket::ContentSource source,
562 const std::string& type,
563 const std::string& reason,
564 std::string* err_desc) {
565 if (source == cricket::CS_LOCAL) {
566 return BadSdp("local", type, reason, err_desc);
567 } else {
568 return BadSdp("remote", type, reason, err_desc);
569 }
570}
571
572bool BadLocalSdp(const std::string& type,
573 const std::string& reason,
574 std::string* err_desc) {
575 return BadSdp(cricket::CS_LOCAL, type, reason, err_desc);
576}
577
578bool BadRemoteSdp(const std::string& type,
579 const std::string& reason,
580 std::string* err_desc) {
581 return BadSdp(cricket::CS_REMOTE, type, reason, err_desc);
582}
583
584bool BadOfferSdp(cricket::ContentSource source,
585 const std::string& reason,
586 std::string* err_desc) {
587 return BadSdp(source, SessionDescriptionInterface::kOffer, reason, err_desc);
588}
589
590bool BadPranswerSdp(cricket::ContentSource source,
591 const std::string& reason,
592 std::string* err_desc) {
593 return BadSdp(source, SessionDescriptionInterface::kPrAnswer, reason,
594 err_desc);
595}
596
597bool BadAnswerSdp(cricket::ContentSource source,
598 const std::string& reason,
599 std::string* err_desc) {
600 return BadSdp(source, SessionDescriptionInterface::kAnswer, reason, err_desc);
601}
602
603std::string BadStateErrMsg(PeerConnectionInterface::SignalingState state) {
604 std::ostringstream desc;
605 desc << "Called in wrong state: " << GetSignalingStateString(state);
606 return desc.str();
607}
608
609#define GET_STRING_OF_ERROR_CODE(err) \
610 case webrtc::PeerConnection::err: \
611 result = #err; \
612 break;
613
614std::string GetErrorCodeString(webrtc::PeerConnection::Error err) {
615 std::string result;
616 switch (err) {
617 GET_STRING_OF_ERROR_CODE(ERROR_NONE)
618 GET_STRING_OF_ERROR_CODE(ERROR_CONTENT)
619 GET_STRING_OF_ERROR_CODE(ERROR_TRANSPORT)
620 default:
621 RTC_NOTREACHED();
622 break;
623 }
624 return result;
625}
626
627std::string MakeErrorString(const std::string& error, const std::string& desc) {
628 std::ostringstream ret;
629 ret << error << " " << desc;
630 return ret.str();
631}
632
633std::string MakeTdErrorString(const std::string& desc) {
634 return MakeErrorString(kPushDownTDFailed, desc);
635}
636
637// Returns true if |new_desc| requests an ICE restart (i.e., new ufrag/pwd).
638bool CheckForRemoteIceRestart(const SessionDescriptionInterface* old_desc,
639 const SessionDescriptionInterface* new_desc,
640 const std::string& content_name) {
641 if (!old_desc) {
642 return false;
643 }
644 const SessionDescription* new_sd = new_desc->description();
645 const SessionDescription* old_sd = old_desc->description();
646 const ContentInfo* cinfo = new_sd->GetContentByName(content_name);
647 if (!cinfo || cinfo->rejected) {
648 return false;
649 }
650 // If the content isn't rejected, check if ufrag and password has changed.
651 const cricket::TransportDescription* new_transport_desc =
652 new_sd->GetTransportDescriptionByName(content_name);
653 const cricket::TransportDescription* old_transport_desc =
654 old_sd->GetTransportDescriptionByName(content_name);
655 if (!new_transport_desc || !old_transport_desc) {
656 // No transport description exists. This is not an ICE restart.
657 return false;
658 }
659 if (cricket::IceCredentialsChanged(
660 old_transport_desc->ice_ufrag, old_transport_desc->ice_pwd,
661 new_transport_desc->ice_ufrag, new_transport_desc->ice_pwd)) {
662 LOG(LS_INFO) << "Remote peer requests ICE restart for " << content_name
663 << ".";
664 return true;
665 }
666 return false;
667}
668
669} // namespace
670
deadbeef293e9262017-01-11 12:28:30 -0800671bool PeerConnectionInterface::RTCConfiguration::operator==(
672 const PeerConnectionInterface::RTCConfiguration& o) const {
673 // This static_assert prevents us from accidentally breaking operator==.
Steve Anton300bf8e2017-07-14 10:13:10 -0700674 // Note: Order matters! Fields must be ordered the same as RTCConfiguration.
deadbeef293e9262017-01-11 12:28:30 -0800675 struct stuff_being_tested_for_equality {
Magnus Jedvert3beb2072017-07-14 14:23:56 +0000676 IceServers servers;
Steve Anton300bf8e2017-07-14 10:13:10 -0700677 IceTransportsType type;
deadbeef293e9262017-01-11 12:28:30 -0800678 BundlePolicy bundle_policy;
679 RtcpMuxPolicy rtcp_mux_policy;
Steve Anton300bf8e2017-07-14 10:13:10 -0700680 std::vector<rtc::scoped_refptr<rtc::RTCCertificate>> certificates;
681 int ice_candidate_pool_size;
682 bool disable_ipv6;
683 bool disable_ipv6_on_wifi;
deadbeefd21eab32017-07-26 16:50:11 -0700684 int max_ipv6_networks;
Steve Anton300bf8e2017-07-14 10:13:10 -0700685 bool enable_rtp_data_channel;
686 rtc::Optional<int> screencast_min_bitrate;
687 rtc::Optional<bool> combined_audio_video_bwe;
688 rtc::Optional<bool> enable_dtls_srtp;
deadbeef293e9262017-01-11 12:28:30 -0800689 TcpCandidatePolicy tcp_candidate_policy;
690 CandidateNetworkPolicy candidate_network_policy;
691 int audio_jitter_buffer_max_packets;
692 bool audio_jitter_buffer_fast_accelerate;
693 int ice_connection_receiving_timeout;
694 int ice_backup_candidate_pair_ping_interval;
695 ContinualGatheringPolicy continual_gathering_policy;
deadbeef293e9262017-01-11 12:28:30 -0800696 bool prioritize_most_likely_ice_candidate_pairs;
697 struct cricket::MediaConfig media_config;
deadbeef293e9262017-01-11 12:28:30 -0800698 bool prune_turn_ports;
699 bool presume_writable_when_fully_relayed;
700 bool enable_ice_renomination;
701 bool redetermine_role_on_ice_restart;
skvlad51072462017-02-02 11:50:14 -0800702 rtc::Optional<int> ice_check_min_interval;
Steve Anton300bf8e2017-07-14 10:13:10 -0700703 rtc::Optional<rtc::IntervalRange> ice_regather_interval_range;
Jonas Orelandbdcee282017-10-10 14:01:40 +0200704 webrtc::TurnCustomizer* turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800705 };
706 static_assert(sizeof(stuff_being_tested_for_equality) == sizeof(*this),
707 "Did you add something to RTCConfiguration and forget to "
708 "update operator==?");
709 return type == o.type && servers == o.servers &&
710 bundle_policy == o.bundle_policy &&
711 rtcp_mux_policy == o.rtcp_mux_policy &&
712 tcp_candidate_policy == o.tcp_candidate_policy &&
713 candidate_network_policy == o.candidate_network_policy &&
714 audio_jitter_buffer_max_packets == o.audio_jitter_buffer_max_packets &&
715 audio_jitter_buffer_fast_accelerate ==
716 o.audio_jitter_buffer_fast_accelerate &&
717 ice_connection_receiving_timeout ==
718 o.ice_connection_receiving_timeout &&
719 ice_backup_candidate_pair_ping_interval ==
720 o.ice_backup_candidate_pair_ping_interval &&
721 continual_gathering_policy == o.continual_gathering_policy &&
722 certificates == o.certificates &&
723 prioritize_most_likely_ice_candidate_pairs ==
724 o.prioritize_most_likely_ice_candidate_pairs &&
725 media_config == o.media_config && disable_ipv6 == o.disable_ipv6 &&
zhihuangb09b3f92017-03-07 14:40:51 -0800726 disable_ipv6_on_wifi == o.disable_ipv6_on_wifi &&
deadbeefd21eab32017-07-26 16:50:11 -0700727 max_ipv6_networks == o.max_ipv6_networks &&
deadbeef293e9262017-01-11 12:28:30 -0800728 enable_rtp_data_channel == o.enable_rtp_data_channel &&
deadbeef293e9262017-01-11 12:28:30 -0800729 screencast_min_bitrate == o.screencast_min_bitrate &&
730 combined_audio_video_bwe == o.combined_audio_video_bwe &&
731 enable_dtls_srtp == o.enable_dtls_srtp &&
732 ice_candidate_pool_size == o.ice_candidate_pool_size &&
733 prune_turn_ports == o.prune_turn_ports &&
734 presume_writable_when_fully_relayed ==
735 o.presume_writable_when_fully_relayed &&
736 enable_ice_renomination == o.enable_ice_renomination &&
skvlad51072462017-02-02 11:50:14 -0800737 redetermine_role_on_ice_restart == o.redetermine_role_on_ice_restart &&
Steve Anton300bf8e2017-07-14 10:13:10 -0700738 ice_check_min_interval == o.ice_check_min_interval &&
Jonas Orelandbdcee282017-10-10 14:01:40 +0200739 ice_regather_interval_range == o.ice_regather_interval_range &&
740 turn_customizer == o.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -0800741}
742
743bool PeerConnectionInterface::RTCConfiguration::operator!=(
744 const PeerConnectionInterface::RTCConfiguration& o) const {
745 return !(*this == o);
deadbeef3edec7c2016-12-10 11:44:26 -0800746}
747
zhihuang8f65cdf2016-05-06 18:40:30 -0700748// Generate a RTCP CNAME when a PeerConnection is created.
749std::string GenerateRtcpCname() {
750 std::string cname;
751 if (!rtc::CreateRandomString(kRtcpCnameLength, &cname)) {
752 LOG(LS_ERROR) << "Failed to generate CNAME.";
nisseeb4ca4e2017-01-12 02:24:27 -0800753 RTC_NOTREACHED();
zhihuang8f65cdf2016-05-06 18:40:30 -0700754 }
755 return cname;
756}
757
zhihuang1c378ed2017-08-17 14:10:50 -0700758bool ValidateOfferAnswerOptions(
759 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options) {
760 return IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_audio) &&
761 IsValidOfferToReceiveMedia(rtc_options.offer_to_receive_video);
olka3c747662017-08-17 06:50:32 -0700762}
763
zhihuang1c378ed2017-08-17 14:10:50 -0700764// From |rtc_options|, fill parts of |session_options| shared by all generated
765// m= sections (in other words, nothing that involves a map/array).
766void ExtractSharedMediaSessionOptions(
767 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
768 cricket::MediaSessionOptions* session_options) {
769 session_options->vad_enabled = rtc_options.voice_activity_detection;
770 session_options->bundle_enabled = rtc_options.use_rtp_mux;
771}
zhihuanga77e6bb2017-08-14 18:17:48 -0700772
zhihuang1c378ed2017-08-17 14:10:50 -0700773bool ConvertConstraintsToOfferAnswerOptions(
774 const MediaConstraintsInterface* constraints,
775 PeerConnectionInterface::RTCOfferAnswerOptions* offer_answer_options) {
olka3c747662017-08-17 06:50:32 -0700776 if (!constraints) {
777 return true;
778 }
zhihuang1c378ed2017-08-17 14:10:50 -0700779
780 bool value = false;
781 size_t mandatory_constraints_satisfied = 0;
782
783 if (FindConstraint(constraints,
784 MediaConstraintsInterface::kOfferToReceiveAudio, &value,
785 &mandatory_constraints_satisfied)) {
786 offer_answer_options->offer_to_receive_audio =
787 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
788 kOfferToReceiveMediaTrue
789 : 0;
790 }
791
792 if (FindConstraint(constraints,
793 MediaConstraintsInterface::kOfferToReceiveVideo, &value,
794 &mandatory_constraints_satisfied)) {
795 offer_answer_options->offer_to_receive_video =
796 value ? PeerConnectionInterface::RTCOfferAnswerOptions::
797 kOfferToReceiveMediaTrue
798 : 0;
799 }
800 if (FindConstraint(constraints,
801 MediaConstraintsInterface::kVoiceActivityDetection, &value,
802 &mandatory_constraints_satisfied)) {
803 offer_answer_options->voice_activity_detection = value;
804 }
805 if (FindConstraint(constraints, MediaConstraintsInterface::kUseRtpMux, &value,
806 &mandatory_constraints_satisfied)) {
807 offer_answer_options->use_rtp_mux = value;
808 }
809 if (FindConstraint(constraints, MediaConstraintsInterface::kIceRestart,
810 &value, &mandatory_constraints_satisfied)) {
811 offer_answer_options->ice_restart = value;
812 }
813
deadbeefab9b2d12015-10-14 11:33:11 -0700814 return mandatory_constraints_satisfied == constraints->GetMandatory().size();
815}
816
zhihuang38ede132017-06-15 12:52:32 -0700817PeerConnection::PeerConnection(PeerConnectionFactory* factory,
818 std::unique_ptr<RtcEventLog> event_log,
819 std::unique_ptr<Call> call)
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000820 : factory_(factory),
zhihuang38ede132017-06-15 12:52:32 -0700821 event_log_(std::move(event_log)),
zhihuang8f65cdf2016-05-06 18:40:30 -0700822 rtcp_cname_(GenerateRtcpCname()),
deadbeefab9b2d12015-10-14 11:33:11 -0700823 local_streams_(StreamCollection::Create()),
zhihuang38ede132017-06-15 12:52:32 -0700824 remote_streams_(StreamCollection::Create()),
825 call_(std::move(call)) {}
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000826
827PeerConnection::~PeerConnection() {
Peter Boström1a9d6152015-12-08 22:15:17 +0100828 TRACE_EVENT0("webrtc", "PeerConnection::~PeerConnection");
deadbeef0a6c4ca2015-10-06 11:38:28 -0700829 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Anton75737c02017-11-06 10:37:17 -0800830 // Need to detach RTP senders/receivers from PeerConnection,
deadbeef70ab1a12015-09-28 16:53:55 -0700831 // since it's about to be destroyed.
832 for (const auto& sender : senders_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700833 sender->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700834 }
835 for (const auto& receiver : receivers_) {
deadbeefa601f5c2016-06-06 14:27:39 -0700836 receiver->internal()->Stop();
deadbeef70ab1a12015-09-28 16:53:55 -0700837 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700838 // Destroy stats_ because it depends on session_.
839 stats_.reset(nullptr);
hbosb78306a2016-12-19 05:06:57 -0800840 if (stats_collector_) {
841 stats_collector_->WaitForPendingRequest();
842 stats_collector_ = nullptr;
843 }
Steve Anton75737c02017-11-06 10:37:17 -0800844
845 // Destroy video channels first since they may have a pointer to a voice
846 // channel.
847 for (auto* channel : video_channels_) {
848 DestroyVideoChannel(channel);
849 }
850 for (auto* channel : voice_channels_) {
851 DestroyVoiceChannel(channel);
852 }
853 if (rtp_data_channel_) {
854 DestroyDataChannel();
855 }
856
857 // Note: Cannot use rtc::Bind to create a functor to invoke because it will
858 // grab a reference to this PeerConnection. The RefCountedObject vtable will
859 // have already been destroyed (since it is a subclass of PeerConnection) and
860 // using rtc::Bind will cause "Pure virtual function called" error to appear.
861
862 if (sctp_transport_) {
863 OnDataChannelDestroyed();
864 network_thread()->Invoke<void>(RTC_FROM_HERE,
865 [this] { DestroySctpTransport_n(); });
866 }
867
868 LOG(LS_INFO) << "Session: " << session_id() << " is destroyed.";
869
870 webrtc_session_desc_factory_.reset();
871 sctp_invoker_.reset();
872 sctp_factory_.reset();
873 transport_controller_.reset();
874
deadbeef91dd5672016-05-18 16:55:30 -0700875 // port_allocator_ lives on the network thread and should be destroyed there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700876 network_thread()->Invoke<void>(RTC_FROM_HERE,
nisseeaabdf62017-05-05 02:23:02 -0700877 [this] { port_allocator_.reset(); });
eladalon248fd4f2017-09-06 05:18:15 -0700878 // call_ and event_log_ must be destroyed on the worker thread.
Steve Anton978b8762017-09-29 12:15:02 -0700879 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -0700880 call_.reset();
881 event_log_.reset();
882 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000883}
884
885bool PeerConnection::Initialize(
buildbot@webrtc.org41451d42014-05-03 05:39:45 +0000886 const PeerConnectionInterface::RTCConfiguration& configuration,
kwibergd1fe2812016-04-27 06:47:29 -0700887 std::unique_ptr<cricket::PortAllocator> allocator,
Henrik Boströmd03c23b2016-06-01 11:44:18 +0200888 std::unique_ptr<rtc::RTCCertificateGeneratorInterface> cert_generator,
deadbeef653b8e02015-11-11 12:55:10 -0800889 PeerConnectionObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +0100890 TRACE_EVENT0("webrtc", "PeerConnection::Initialize");
Steve Anton038834f2017-07-14 15:59:59 -0700891
892 RTCError config_error = ValidateConfiguration(configuration);
893 if (!config_error.ok()) {
894 LOG(LS_ERROR) << "Invalid configuration: " << config_error.message();
895 return false;
896 }
897
deadbeef293e9262017-01-11 12:28:30 -0800898 if (!allocator) {
899 LOG(LS_ERROR) << "PeerConnection initialized without a PortAllocator? "
900 << "This shouldn't happen if using PeerConnectionFactory.";
901 return false;
902 }
Jonas Orelandbdcee282017-10-10 14:01:40 +0200903
deadbeef653b8e02015-11-11 12:55:10 -0800904 if (!observer) {
deadbeef293e9262017-01-11 12:28:30 -0800905 // TODO(deadbeef): Why do we do this?
906 LOG(LS_ERROR) << "PeerConnection initialized without a "
907 << "PeerConnectionObserver";
deadbeef653b8e02015-11-11 12:55:10 -0800908 return false;
909 }
pthatcher@webrtc.org877ac762015-02-04 22:03:09 +0000910 observer_ = observer;
kwiberg0eb15ed2015-12-17 03:04:15 -0800911 port_allocator_ = std::move(allocator);
deadbeef653b8e02015-11-11 12:55:10 -0800912
deadbeef91dd5672016-05-18 16:55:30 -0700913 // The port allocator lives on the network thread and should be initialized
Taylor Brandstettera1c30352016-05-13 08:15:11 -0700914 // there.
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -0700915 if (!network_thread()->Invoke<bool>(
916 RTC_FROM_HERE, rtc::Bind(&PeerConnection::InitializePortAllocator_n,
917 this, configuration))) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000918 return false;
919 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000920
Steve Anton75737c02017-11-06 10:37:17 -0800921 // RFC 3264: The numeric value of the session id and version in the
922 // o line MUST be representable with a "64 bit signed integer".
923 // Due to this constraint session id |session_id_| is max limited to
924 // LLONG_MAX.
925 session_id_ = rtc::ToString(rtc::CreateRandomId64() & LLONG_MAX);
926 transport_controller_.reset(factory_->CreateTransportController(
927 port_allocator_.get(), configuration.redetermine_role_on_ice_restart));
928 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
929 transport_controller_->SignalConnectionState.connect(
930 this, &PeerConnection::OnTransportControllerConnectionState);
931 transport_controller_->SignalGatheringState.connect(
932 this, &PeerConnection::OnTransportControllerGatheringState);
933 transport_controller_->SignalCandidatesGathered.connect(
934 this, &PeerConnection::OnTransportControllerCandidatesGathered);
935 transport_controller_->SignalCandidatesRemoved.connect(
936 this, &PeerConnection::OnTransportControllerCandidatesRemoved);
937 transport_controller_->SignalDtlsHandshakeError.connect(
938 this, &PeerConnection::OnTransportControllerDtlsHandshakeError);
939
940 sctp_factory_ = factory_->CreateSctpTransportInternalFactory();
zhihuang29ff8442016-07-27 11:07:25 -0700941
deadbeefab9b2d12015-10-14 11:33:11 -0700942 stats_.reset(new StatsCollector(this));
hbos74e1a4f2016-09-15 23:33:01 -0700943 stats_collector_ = RTCStatsCollector::Create(this);
henrike@webrtc.org28e20752013-07-10 00:45:36 +0000944
Steve Antonba818672017-11-06 10:21:57 -0800945 configuration_ = configuration;
946
Steve Anton75737c02017-11-06 10:37:17 -0800947 const PeerConnectionFactoryInterface::Options& options = factory_->options();
948
949 transport_controller_->SetSslMaxProtocolVersion(options.ssl_max_version);
950
951 // Obtain a certificate from RTCConfiguration if any were provided (optional).
952 rtc::scoped_refptr<rtc::RTCCertificate> certificate;
953 if (!configuration.certificates.empty()) {
954 // TODO(hbos,torbjorng): Decide on certificate-selection strategy instead of
955 // just picking the first one. The decision should be made based on the DTLS
956 // handshake. The DTLS negotiations need to know about all certificates.
957 certificate = configuration.certificates[0];
958 }
959
Steve Antond25da372017-11-06 14:50:29 -0800960 transport_controller_->SetIceConfig(ParseIceConfig(configuration));
Steve Anton75737c02017-11-06 10:37:17 -0800961
962 if (options.disable_encryption) {
963 dtls_enabled_ = false;
964 } else {
965 // Enable DTLS by default if we have an identity store or a certificate.
966 dtls_enabled_ = (cert_generator || certificate);
967 // |configuration| can override the default |dtls_enabled_| value.
968 if (configuration.enable_dtls_srtp) {
969 dtls_enabled_ = *(configuration.enable_dtls_srtp);
970 }
971 }
972
973 // Enable creation of RTP data channels if the kEnableRtpDataChannels is set.
974 // It takes precendence over the disable_sctp_data_channels
975 // PeerConnectionFactoryInterface::Options.
976 if (configuration.enable_rtp_data_channel) {
977 data_channel_type_ = cricket::DCT_RTP;
978 } else {
979 // DTLS has to be enabled to use SCTP.
980 if (!options.disable_sctp_data_channels && dtls_enabled_) {
981 data_channel_type_ = cricket::DCT_SCTP;
982 }
983 }
984
985 video_options_.screencast_min_bitrate_kbps =
986 configuration.screencast_min_bitrate;
987 audio_options_.combined_audio_video_bwe =
988 configuration.combined_audio_video_bwe;
989
990 audio_options_.audio_jitter_buffer_max_packets =
991 rtc::Optional<int>(configuration.audio_jitter_buffer_max_packets);
992
993 audio_options_.audio_jitter_buffer_fast_accelerate =
994 rtc::Optional<bool>(configuration.audio_jitter_buffer_fast_accelerate);
995
996 // Whether the certificate generator/certificate is null or not determines
997 // what PeerConnectionDescriptionFactory will do, so make sure that we give it
998 // the right instructions by clearing the variables if needed.
999 if (!dtls_enabled_) {
1000 cert_generator.reset();
1001 certificate = nullptr;
1002 } else if (certificate) {
1003 // Favor generated certificate over the certificate generator.
1004 cert_generator.reset();
1005 }
1006
1007 webrtc_session_desc_factory_.reset(new WebRtcSessionDescriptionFactory(
1008 signaling_thread(), channel_manager(), this, session_id(),
1009 std::move(cert_generator), certificate));
1010 webrtc_session_desc_factory_->SignalCertificateReady.connect(
1011 this, &PeerConnection::OnCertificateReady);
1012
1013 if (options.disable_encryption) {
1014 webrtc_session_desc_factory_->SetSdesPolicy(cricket::SEC_DISABLED);
1015 }
1016
1017 webrtc_session_desc_factory_->set_enable_encrypted_rtp_header_extensions(
1018 options.crypto_options.enable_encrypted_rtp_header_extensions);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001019
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001020 return true;
1021}
1022
Steve Anton038834f2017-07-14 15:59:59 -07001023RTCError PeerConnection::ValidateConfiguration(
1024 const RTCConfiguration& config) const {
1025 if (config.ice_regather_interval_range &&
1026 config.continual_gathering_policy == GATHER_ONCE) {
1027 return RTCError(RTCErrorType::INVALID_PARAMETER,
1028 "ice_regather_interval_range specified but continual "
1029 "gathering policy is GATHER_ONCE");
1030 }
1031 return RTCError::OK();
1032}
1033
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001034rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001035PeerConnection::local_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001036 return local_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001037}
1038
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001039rtc::scoped_refptr<StreamCollectionInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001040PeerConnection::remote_streams() {
deadbeefab9b2d12015-10-14 11:33:11 -07001041 return remote_streams_;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001042}
1043
perkj@webrtc.orgc2dd5ee2014-11-04 11:31:29 +00001044bool PeerConnection::AddStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001045 TRACE_EVENT0("webrtc", "PeerConnection::AddStream");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001046 if (IsClosed()) {
1047 return false;
1048 }
deadbeefab9b2d12015-10-14 11:33:11 -07001049 if (!CanAddLocalMediaStream(local_streams_, local_stream)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001050 return false;
1051 }
deadbeefab9b2d12015-10-14 11:33:11 -07001052
1053 local_streams_->AddStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001054 MediaStreamObserver* observer = new MediaStreamObserver(local_stream);
1055 observer->SignalAudioTrackAdded.connect(this,
1056 &PeerConnection::OnAudioTrackAdded);
1057 observer->SignalAudioTrackRemoved.connect(
1058 this, &PeerConnection::OnAudioTrackRemoved);
1059 observer->SignalVideoTrackAdded.connect(this,
1060 &PeerConnection::OnVideoTrackAdded);
1061 observer->SignalVideoTrackRemoved.connect(
1062 this, &PeerConnection::OnVideoTrackRemoved);
kwibergd1fe2812016-04-27 06:47:29 -07001063 stream_observers_.push_back(std::unique_ptr<MediaStreamObserver>(observer));
deadbeefab9b2d12015-10-14 11:33:11 -07001064
deadbeefab9b2d12015-10-14 11:33:11 -07001065 for (const auto& track : local_stream->GetAudioTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001066 AddAudioTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001067 }
1068 for (const auto& track : local_stream->GetVideoTracks()) {
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001069 AddVideoTrack(track.get(), local_stream);
deadbeefab9b2d12015-10-14 11:33:11 -07001070 }
1071
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001072 stats_->AddStream(local_stream);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001073 observer_->OnRenegotiationNeeded();
1074 return true;
1075}
1076
1077void PeerConnection::RemoveStream(MediaStreamInterface* local_stream) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001078 TRACE_EVENT0("webrtc", "PeerConnection::RemoveStream");
korniltsev.anatolyec390b52017-07-24 17:00:25 -07001079 if (!IsClosed()) {
1080 for (const auto& track : local_stream->GetAudioTracks()) {
1081 RemoveAudioTrack(track.get(), local_stream);
1082 }
1083 for (const auto& track : local_stream->GetVideoTracks()) {
1084 RemoveVideoTrack(track.get(), local_stream);
1085 }
deadbeefab9b2d12015-10-14 11:33:11 -07001086 }
deadbeefab9b2d12015-10-14 11:33:11 -07001087 local_streams_->RemoveStream(local_stream);
deadbeefeb459812015-12-15 19:24:43 -08001088 stream_observers_.erase(
1089 std::remove_if(
1090 stream_observers_.begin(), stream_observers_.end(),
kwibergd1fe2812016-04-27 06:47:29 -07001091 [local_stream](const std::unique_ptr<MediaStreamObserver>& observer) {
deadbeefeb459812015-12-15 19:24:43 -08001092 return observer->stream()->label().compare(local_stream->label()) ==
1093 0;
1094 }),
1095 stream_observers_.end());
deadbeefab9b2d12015-10-14 11:33:11 -07001096
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001097 if (IsClosed()) {
1098 return;
1099 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001100 observer_->OnRenegotiationNeeded();
1101}
1102
deadbeefe1f9d832016-01-14 15:35:42 -08001103rtc::scoped_refptr<RtpSenderInterface> PeerConnection::AddTrack(
1104 MediaStreamTrackInterface* track,
1105 std::vector<MediaStreamInterface*> streams) {
1106 TRACE_EVENT0("webrtc", "PeerConnection::AddTrack");
1107 if (IsClosed()) {
1108 return nullptr;
1109 }
1110 if (streams.size() >= 2) {
1111 LOG(LS_ERROR)
1112 << "Adding a track with two streams is not currently supported.";
1113 return nullptr;
1114 }
1115 // TODO(deadbeef): Support adding a track to two different senders.
1116 if (FindSenderForTrack(track) != senders_.end()) {
1117 LOG(LS_ERROR) << "Sender for track " << track->id() << " already exists.";
1118 return nullptr;
1119 }
1120
1121 // TODO(deadbeef): Support adding a track to multiple streams.
deadbeefa601f5c2016-06-06 14:27:39 -07001122 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeefe1f9d832016-01-14 15:35:42 -08001123 if (track->kind() == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001124 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001125 signaling_thread(),
1126 new AudioRtpSender(static_cast<AudioTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001127 voice_channel(), stats_.get()));
deadbeefe1f9d832016-01-14 15:35:42 -08001128 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001129 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001130 }
1131 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -07001132 local_audio_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -08001133 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001134 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001135 }
1136 } else if (track->kind() == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001137 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
deadbeefe1f9d832016-01-14 15:35:42 -08001138 signaling_thread(),
1139 new VideoRtpSender(static_cast<VideoTrackInterface*>(track),
Steve Anton75737c02017-11-06 10:37:17 -08001140 video_channel()));
deadbeefe1f9d832016-01-14 15:35:42 -08001141 if (!streams.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001142 new_sender->internal()->set_stream_id(streams[0]->label());
deadbeefe1f9d832016-01-14 15:35:42 -08001143 }
1144 const TrackInfo* track_info = FindTrackInfo(
deadbeefa601f5c2016-06-06 14:27:39 -07001145 local_video_tracks_, new_sender->internal()->stream_id(), track->id());
deadbeefe1f9d832016-01-14 15:35:42 -08001146 if (track_info) {
deadbeefa601f5c2016-06-06 14:27:39 -07001147 new_sender->internal()->SetSsrc(track_info->ssrc);
deadbeefe1f9d832016-01-14 15:35:42 -08001148 }
1149 } else {
1150 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << track->kind();
1151 return rtc::scoped_refptr<RtpSenderInterface>();
1152 }
1153
1154 senders_.push_back(new_sender);
1155 observer_->OnRenegotiationNeeded();
1156 return new_sender;
1157}
1158
1159bool PeerConnection::RemoveTrack(RtpSenderInterface* sender) {
1160 TRACE_EVENT0("webrtc", "PeerConnection::RemoveTrack");
1161 if (IsClosed()) {
1162 return false;
1163 }
1164
1165 auto it = std::find(senders_.begin(), senders_.end(), sender);
1166 if (it == senders_.end()) {
1167 LOG(LS_ERROR) << "Couldn't find sender " << sender->id() << " to remove.";
1168 return false;
1169 }
deadbeefa601f5c2016-06-06 14:27:39 -07001170 (*it)->internal()->Stop();
deadbeefe1f9d832016-01-14 15:35:42 -08001171 senders_.erase(it);
1172
1173 observer_->OnRenegotiationNeeded();
1174 return true;
1175}
1176
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001177rtc::scoped_refptr<DtmfSenderInterface> PeerConnection::CreateDtmfSender(
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001178 AudioTrackInterface* track) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001179 TRACE_EVENT0("webrtc", "PeerConnection::CreateDtmfSender");
zhihuang29ff8442016-07-27 11:07:25 -07001180 if (IsClosed()) {
1181 return nullptr;
1182 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001183 if (!track) {
1184 LOG(LS_ERROR) << "CreateDtmfSender - track is NULL.";
deadbeef20cb0c12017-02-01 20:27:00 -08001185 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001186 }
deadbeef20cb0c12017-02-01 20:27:00 -08001187 auto it = FindSenderForTrack(track);
1188 if (it == senders_.end()) {
1189 LOG(LS_ERROR) << "CreateDtmfSender called with a non-added track.";
1190 return nullptr;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001191 }
1192
deadbeef20cb0c12017-02-01 20:27:00 -08001193 return (*it)->GetDtmfSender();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001194}
1195
deadbeeffac06552015-11-25 11:26:01 -08001196rtc::scoped_refptr<RtpSenderInterface> PeerConnection::CreateSender(
deadbeefbd7d8f72015-12-18 16:58:44 -08001197 const std::string& kind,
1198 const std::string& stream_id) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001199 TRACE_EVENT0("webrtc", "PeerConnection::CreateSender");
zhihuang29ff8442016-07-27 11:07:25 -07001200 if (IsClosed()) {
1201 return nullptr;
1202 }
deadbeefa601f5c2016-06-06 14:27:39 -07001203 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001204 if (kind == MediaStreamTrackInterface::kAudioKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001205 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001206 signaling_thread(), new AudioRtpSender(voice_channel(), stats_.get()));
deadbeeffac06552015-11-25 11:26:01 -08001207 } else if (kind == MediaStreamTrackInterface::kVideoKind) {
deadbeefa601f5c2016-06-06 14:27:39 -07001208 new_sender = RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08001209 signaling_thread(), new VideoRtpSender(video_channel()));
deadbeeffac06552015-11-25 11:26:01 -08001210 } else {
1211 LOG(LS_ERROR) << "CreateSender called with invalid kind: " << kind;
deadbeefe1f9d832016-01-14 15:35:42 -08001212 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001213 }
deadbeefbd7d8f72015-12-18 16:58:44 -08001214 if (!stream_id.empty()) {
deadbeefa601f5c2016-06-06 14:27:39 -07001215 new_sender->internal()->set_stream_id(stream_id);
deadbeefbd7d8f72015-12-18 16:58:44 -08001216 }
deadbeeffac06552015-11-25 11:26:01 -08001217 senders_.push_back(new_sender);
deadbeefe1f9d832016-01-14 15:35:42 -08001218 return new_sender;
deadbeeffac06552015-11-25 11:26:01 -08001219}
1220
deadbeef70ab1a12015-09-28 16:53:55 -07001221std::vector<rtc::scoped_refptr<RtpSenderInterface>> PeerConnection::GetSenders()
1222 const {
deadbeefa601f5c2016-06-06 14:27:39 -07001223 std::vector<rtc::scoped_refptr<RtpSenderInterface>> ret;
1224 for (const auto& sender : senders_) {
1225 ret.push_back(sender.get());
1226 }
1227 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001228}
1229
1230std::vector<rtc::scoped_refptr<RtpReceiverInterface>>
1231PeerConnection::GetReceivers() const {
deadbeefa601f5c2016-06-06 14:27:39 -07001232 std::vector<rtc::scoped_refptr<RtpReceiverInterface>> ret;
1233 for (const auto& receiver : receivers_) {
1234 ret.push_back(receiver.get());
1235 }
1236 return ret;
deadbeef70ab1a12015-09-28 16:53:55 -07001237}
1238
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001239bool PeerConnection::GetStats(StatsObserver* observer,
wu@webrtc.orgb9a088b2014-02-13 23:18:49 +00001240 MediaStreamTrackInterface* track,
1241 StatsOutputLevel level) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001242 TRACE_EVENT0("webrtc", "PeerConnection::GetStats");
deadbeef0a6c4ca2015-10-06 11:38:28 -07001243 RTC_DCHECK(signaling_thread()->IsCurrent());
nisse7ce109a2017-01-31 00:57:56 -08001244 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001245 LOG(LS_ERROR) << "GetStats - observer is NULL.";
1246 return false;
1247 }
1248
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001249 stats_->UpdateStats(level);
zhihuange9e94c32016-11-04 11:38:15 -07001250 // The StatsCollector is used to tell if a track is valid because it may
1251 // remember tracks that the PeerConnection previously removed.
1252 if (track && !stats_->IsValidTrack(track->id())) {
1253 LOG(LS_WARNING) << "GetStats is called with an invalid track: "
1254 << track->id();
1255 return false;
1256 }
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001257 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_GETSTATS,
tommi@webrtc.org5b06b062014-08-15 08:38:30 +00001258 new GetStatsMsg(observer, track));
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001259 return true;
1260}
1261
hbos74e1a4f2016-09-15 23:33:01 -07001262void PeerConnection::GetStats(RTCStatsCollectorCallback* callback) {
1263 RTC_DCHECK(stats_collector_);
1264 stats_collector_->GetStatsReport(callback);
1265}
1266
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001267PeerConnectionInterface::SignalingState PeerConnection::signaling_state() {
1268 return signaling_state_;
1269}
1270
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001271PeerConnectionInterface::IceConnectionState
1272PeerConnection::ice_connection_state() {
1273 return ice_connection_state_;
1274}
1275
1276PeerConnectionInterface::IceGatheringState
1277PeerConnection::ice_gathering_state() {
1278 return ice_gathering_state_;
1279}
1280
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001281rtc::scoped_refptr<DataChannelInterface>
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001282PeerConnection::CreateDataChannel(
1283 const std::string& label,
1284 const DataChannelInit* config) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001285 TRACE_EVENT0("webrtc", "PeerConnection::CreateDataChannel");
zhihuang9763d562016-08-05 11:14:50 -07001286
deadbeefab9b2d12015-10-14 11:33:11 -07001287 bool first_datachannel = !HasDataChannels();
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001288
kwibergd1fe2812016-04-27 06:47:29 -07001289 std::unique_ptr<InternalDataChannelInit> internal_config;
henrika@webrtc.orgaebb1ad2014-01-14 10:00:58 +00001290 if (config) {
1291 internal_config.reset(new InternalDataChannelInit(*config));
1292 }
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001293 rtc::scoped_refptr<DataChannelInterface> channel(
deadbeefab9b2d12015-10-14 11:33:11 -07001294 InternalCreateDataChannel(label, internal_config.get()));
1295 if (!channel.get()) {
1296 return nullptr;
1297 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001298
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001299 // Trigger the onRenegotiationNeeded event for every new RTP DataChannel, or
1300 // the first SCTP DataChannel.
Steve Anton75737c02017-11-06 10:37:17 -08001301 if (data_channel_type() == cricket::DCT_RTP || first_datachannel) {
jiayl@webrtc.org001fd2d2014-05-29 15:31:11 +00001302 observer_->OnRenegotiationNeeded();
1303 }
wu@webrtc.org91053e72013-08-10 07:18:04 +00001304
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001305 return DataChannelProxy::Create(signaling_thread(), channel.get());
1306}
1307
1308void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1309 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001310 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001311
zhihuang1c378ed2017-08-17 14:10:50 -07001312 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1313 // Always create an offer even if |ConvertConstraintsToOfferAnswerOptions|
1314 // returns false for now. Because |ConvertConstraintsToOfferAnswerOptions|
1315 // compares the mandatory fields parsed with the mandatory fields added in the
1316 // |constraints| and some downstream applications might create offers with
1317 // mandatory fields which would not be parsed in the helper method. For
1318 // example, in Chromium/remoting, |kEnableDtlsSrtp| is added to the
1319 // |constraints| as a mandatory field but it is not parsed.
1320 ConvertConstraintsToOfferAnswerOptions(constraints, &offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001321
zhihuang1c378ed2017-08-17 14:10:50 -07001322 CreateOffer(observer, offer_answer_options);
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001323}
1324
1325void PeerConnection::CreateOffer(CreateSessionDescriptionObserver* observer,
1326 const RTCOfferAnswerOptions& options) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001327 TRACE_EVENT0("webrtc", "PeerConnection::CreateOffer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001328
nisse7ce109a2017-01-31 00:57:56 -08001329 if (!observer) {
jiayl@webrtc.orgb18bf5e2014-08-04 18:34:16 +00001330 LOG(LS_ERROR) << "CreateOffer - observer is NULL.";
1331 return;
1332 }
deadbeefab9b2d12015-10-14 11:33:11 -07001333
Steve Anton8d3444d2017-10-20 15:30:51 -07001334 if (IsClosed()) {
1335 std::string error = "CreateOffer called when PeerConnection is closed.";
1336 LOG(LS_ERROR) << error;
1337 PostCreateSessionDescriptionFailure(observer, error);
1338 return;
1339 }
1340
zhihuang1c378ed2017-08-17 14:10:50 -07001341 if (!ValidateOfferAnswerOptions(options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001342 std::string error = "CreateOffer called with invalid options.";
1343 LOG(LS_ERROR) << error;
1344 PostCreateSessionDescriptionFailure(observer, error);
1345 return;
1346 }
1347
zhihuang1c378ed2017-08-17 14:10:50 -07001348 cricket::MediaSessionOptions session_options;
1349 GetOptionsForOffer(options, &session_options);
Steve Antond25da372017-11-06 14:50:29 -08001350 webrtc_session_desc_factory_->CreateOffer(observer, options, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001351}
1352
1353void PeerConnection::CreateAnswer(
1354 CreateSessionDescriptionObserver* observer,
1355 const MediaConstraintsInterface* constraints) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001356 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
Steve Anton8d3444d2017-10-20 15:30:51 -07001357
nisse7ce109a2017-01-31 00:57:56 -08001358 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001359 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1360 return;
1361 }
deadbeefab9b2d12015-10-14 11:33:11 -07001362
zhihuang1c378ed2017-08-17 14:10:50 -07001363 PeerConnectionInterface::RTCOfferAnswerOptions offer_answer_options;
1364 if (!ConvertConstraintsToOfferAnswerOptions(constraints,
1365 &offer_answer_options)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001366 std::string error = "CreateAnswer called with invalid constraints.";
1367 LOG(LS_ERROR) << error;
1368 PostCreateSessionDescriptionFailure(observer, error);
1369 return;
1370 }
1371
Steve Anton8d3444d2017-10-20 15:30:51 -07001372 CreateAnswer(observer, offer_answer_options);
htaa2a49d92016-03-04 02:51:39 -08001373}
1374
1375void PeerConnection::CreateAnswer(CreateSessionDescriptionObserver* observer,
1376 const RTCOfferAnswerOptions& options) {
1377 TRACE_EVENT0("webrtc", "PeerConnection::CreateAnswer");
nisse7ce109a2017-01-31 00:57:56 -08001378 if (!observer) {
htaa2a49d92016-03-04 02:51:39 -08001379 LOG(LS_ERROR) << "CreateAnswer - observer is NULL.";
1380 return;
1381 }
1382
Steve Anton8d3444d2017-10-20 15:30:51 -07001383 if (IsClosed()) {
1384 std::string error = "CreateAnswer called when PeerConnection is closed.";
1385 LOG(LS_ERROR) << error;
1386 PostCreateSessionDescriptionFailure(observer, error);
1387 return;
1388 }
1389
Steve Anton75737c02017-11-06 10:37:17 -08001390 if (remote_description() &&
1391 remote_description()->type() != SessionDescriptionInterface::kOffer) {
Steve Anton8d3444d2017-10-20 15:30:51 -07001392 std::string error = "CreateAnswer called without remote offer.";
1393 LOG(LS_ERROR) << error;
1394 PostCreateSessionDescriptionFailure(observer, error);
1395 return;
1396 }
1397
htaa2a49d92016-03-04 02:51:39 -08001398 cricket::MediaSessionOptions session_options;
zhihuang1c378ed2017-08-17 14:10:50 -07001399 GetOptionsForAnswer(options, &session_options);
htaa2a49d92016-03-04 02:51:39 -08001400
Steve Antond25da372017-11-06 14:50:29 -08001401 webrtc_session_desc_factory_->CreateAnswer(observer, session_options);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001402}
1403
1404void PeerConnection::SetLocalDescription(
1405 SetSessionDescriptionObserver* observer,
1406 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001407 TRACE_EVENT0("webrtc", "PeerConnection::SetLocalDescription");
nisse7ce109a2017-01-31 00:57:56 -08001408 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001409 LOG(LS_ERROR) << "SetLocalDescription - observer is NULL.";
1410 return;
1411 }
1412 if (!desc) {
1413 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1414 return;
1415 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001416
1417 // Takes the ownership of |desc| regardless of the result.
1418 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1419
1420 if (IsClosed()) {
1421 std::string error = "Failed to set local " + desc->type() +
1422 " sdp: Called in wrong state: STATE_CLOSED";
1423 LOG(LS_ERROR) << error;
1424 PostSetSessionDescriptionFailure(observer, error);
1425 return;
1426 }
1427
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001428 // Update stats here so that we have the most recent stats for tracks and
1429 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001430 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001431 std::string error;
Steve Anton75737c02017-11-06 10:37:17 -08001432 if (!SetLocalDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001433 PostSetSessionDescriptionFailure(observer, error);
1434 return;
1435 }
deadbeefab9b2d12015-10-14 11:33:11 -07001436
1437 // If setting the description decided our SSL role, allocate any necessary
1438 // SCTP sids.
1439 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001440 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001441 AllocateSctpSids(role);
1442 }
1443
1444 // Update state and SSRC of local MediaStreams and DataChannels based on the
1445 // local session description.
1446 const cricket::ContentInfo* audio_content =
1447 GetFirstAudioContent(desc->description());
1448 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001449 if (audio_content->rejected) {
1450 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1451 } else {
1452 const cricket::AudioContentDescription* audio_desc =
1453 static_cast<const cricket::AudioContentDescription*>(
1454 audio_content->description);
1455 UpdateLocalTracks(audio_desc->streams(), audio_desc->type());
1456 }
deadbeefab9b2d12015-10-14 11:33:11 -07001457 }
1458
1459 const cricket::ContentInfo* video_content =
1460 GetFirstVideoContent(desc->description());
1461 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001462 if (video_content->rejected) {
1463 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1464 } else {
1465 const cricket::VideoContentDescription* video_desc =
1466 static_cast<const cricket::VideoContentDescription*>(
1467 video_content->description);
1468 UpdateLocalTracks(video_desc->streams(), video_desc->type());
1469 }
deadbeefab9b2d12015-10-14 11:33:11 -07001470 }
1471
1472 const cricket::ContentInfo* data_content =
1473 GetFirstDataContent(desc->description());
1474 if (data_content) {
1475 const cricket::DataContentDescription* data_desc =
1476 static_cast<const cricket::DataContentDescription*>(
1477 data_content->description);
1478 if (rtc::starts_with(data_desc->protocol().data(),
1479 cricket::kMediaProtocolRtpPrefix)) {
1480 UpdateLocalRtpDataChannels(data_desc->streams());
1481 }
1482 }
1483
1484 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001485 signaling_thread()->Post(RTC_FROM_HERE, this,
1486 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07001487
deadbeef42a42632017-03-10 15:18:00 -08001488 // According to JSEP, after setLocalDescription, changing the candidate pool
1489 // size is not allowed, and changing the set of ICE servers will not result
1490 // in new candidates being gathered.
1491 port_allocator_->FreezeCandidatePool();
1492
deadbeefcbecd352015-09-23 11:50:27 -07001493 // MaybeStartGathering needs to be called after posting
1494 // MSG_SET_SESSIONDESCRIPTION_SUCCESS, so that we don't signal any candidates
1495 // before signaling that SetLocalDescription completed.
Steve Antond25da372017-11-06 14:50:29 -08001496 transport_controller_->MaybeStartGathering();
deadbeef42a42632017-03-10 15:18:00 -08001497
1498 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1499 // TODO(deadbeef): We already had to hop to the network thread for
1500 // MaybeStartGathering...
1501 network_thread()->Invoke<void>(
1502 RTC_FROM_HERE,
1503 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1504 port_allocator_.get()));
1505 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001506}
1507
1508void PeerConnection::SetRemoteDescription(
1509 SetSessionDescriptionObserver* observer,
1510 SessionDescriptionInterface* desc) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001511 TRACE_EVENT0("webrtc", "PeerConnection::SetRemoteDescription");
nisse7ce109a2017-01-31 00:57:56 -08001512 if (!observer) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001513 LOG(LS_ERROR) << "SetRemoteDescription - observer is NULL.";
1514 return;
1515 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001516 if (!desc) {
1517 PostSetSessionDescriptionFailure(observer, "SessionDescription is NULL.");
1518 return;
1519 }
Steve Anton8d3444d2017-10-20 15:30:51 -07001520
1521 // Takes the ownership of |desc| regardless of the result.
1522 std::unique_ptr<SessionDescriptionInterface> desc_temp(desc);
1523
1524 if (IsClosed()) {
1525 std::string error = "Failed to set remote " + desc->type() +
1526 " sdp: Called in wrong state: STATE_CLOSED";
1527 LOG(LS_ERROR) << error;
1528 PostSetSessionDescriptionFailure(observer, error);
1529 return;
1530 }
1531
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001532 // Update stats here so that we have the most recent stats for tracks and
1533 // streams that might be removed by updating the session description.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001534 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001535 std::string error;
Steve Anton75737c02017-11-06 10:37:17 -08001536 if (!SetRemoteDescription(std::move(desc_temp), &error)) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001537 PostSetSessionDescriptionFailure(observer, error);
1538 return;
1539 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001540
deadbeefab9b2d12015-10-14 11:33:11 -07001541 // If setting the description decided our SSL role, allocate any necessary
1542 // SCTP sids.
1543 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08001544 if (data_channel_type() == cricket::DCT_SCTP && GetSctpSslRole(&role)) {
deadbeefab9b2d12015-10-14 11:33:11 -07001545 AllocateSctpSids(role);
1546 }
1547
1548 const cricket::SessionDescription* remote_desc = desc->description();
deadbeefbda7e0b2015-12-08 17:13:40 -08001549 const cricket::ContentInfo* audio_content = GetFirstAudioContent(remote_desc);
1550 const cricket::ContentInfo* video_content = GetFirstVideoContent(remote_desc);
1551 const cricket::AudioContentDescription* audio_desc =
1552 GetFirstAudioContentDescription(remote_desc);
1553 const cricket::VideoContentDescription* video_desc =
1554 GetFirstVideoContentDescription(remote_desc);
1555 const cricket::DataContentDescription* data_desc =
1556 GetFirstDataContentDescription(remote_desc);
1557
1558 // Check if the descriptions include streams, just in case the peer supports
1559 // MSID, but doesn't indicate so with "a=msid-semantic".
1560 if (remote_desc->msid_supported() ||
1561 (audio_desc && !audio_desc->streams().empty()) ||
1562 (video_desc && !video_desc->streams().empty())) {
1563 remote_peer_supports_msid_ = true;
1564 }
deadbeefab9b2d12015-10-14 11:33:11 -07001565
1566 // We wait to signal new streams until we finish processing the description,
1567 // since only at that point will new streams have all their tracks.
1568 rtc::scoped_refptr<StreamCollection> new_streams(StreamCollection::Create());
1569
Steve Anton8d3444d2017-10-20 15:30:51 -07001570 // TODO(steveanton): When removing RTP senders/receivers in response to a
1571 // rejected media section, there is some cleanup logic that expects the voice/
1572 // video channel to still be set. But in this method the voice/video channel
Steve Anton75737c02017-11-06 10:37:17 -08001573 // would have been destroyed by the SetRemoteDescription caller above so the
1574 // cleanup that relies on them fails to run. The RemoveTracks calls should be
1575 // moved to right before the DestroyChannel calls to fix this.
Steve Anton8d3444d2017-10-20 15:30:51 -07001576
deadbeefab9b2d12015-10-14 11:33:11 -07001577 // Find all audio rtp streams and create corresponding remote AudioTracks
1578 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001579 if (audio_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001580 if (audio_content->rejected) {
1581 RemoveTracks(cricket::MEDIA_TYPE_AUDIO);
1582 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001583 bool default_audio_track_needed =
1584 !remote_peer_supports_msid_ &&
1585 MediaContentDirectionHasSend(audio_desc->direction());
1586 UpdateRemoteStreamsList(GetActiveStreams(audio_desc),
1587 default_audio_track_needed, audio_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001588 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001589 }
deadbeefab9b2d12015-10-14 11:33:11 -07001590 }
1591
1592 // Find all video rtp streams and create corresponding remote VideoTracks
1593 // and MediaStreams.
deadbeefab9b2d12015-10-14 11:33:11 -07001594 if (video_content) {
deadbeeffaac4972015-11-12 15:33:07 -08001595 if (video_content->rejected) {
1596 RemoveTracks(cricket::MEDIA_TYPE_VIDEO);
1597 } else {
deadbeefbda7e0b2015-12-08 17:13:40 -08001598 bool default_video_track_needed =
1599 !remote_peer_supports_msid_ &&
1600 MediaContentDirectionHasSend(video_desc->direction());
1601 UpdateRemoteStreamsList(GetActiveStreams(video_desc),
1602 default_video_track_needed, video_desc->type(),
deadbeeffaac4972015-11-12 15:33:07 -08001603 new_streams);
deadbeeffaac4972015-11-12 15:33:07 -08001604 }
deadbeefab9b2d12015-10-14 11:33:11 -07001605 }
1606
1607 // Update the DataChannels with the information from the remote peer.
deadbeefbda7e0b2015-12-08 17:13:40 -08001608 if (data_desc) {
1609 if (rtc::starts_with(data_desc->protocol().data(),
deadbeefab9b2d12015-10-14 11:33:11 -07001610 cricket::kMediaProtocolRtpPrefix)) {
deadbeefbda7e0b2015-12-08 17:13:40 -08001611 UpdateRemoteRtpDataChannels(GetActiveStreams(data_desc));
deadbeefab9b2d12015-10-14 11:33:11 -07001612 }
1613 }
1614
1615 // Iterate new_streams and notify the observer about new MediaStreams.
1616 for (size_t i = 0; i < new_streams->count(); ++i) {
1617 MediaStreamInterface* new_stream = new_streams->at(i);
1618 stats_->AddStream(new_stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07001619 observer_->OnAddStream(
1620 rtc::scoped_refptr<MediaStreamInterface>(new_stream));
deadbeefab9b2d12015-10-14 11:33:11 -07001621 }
1622
deadbeefbda7e0b2015-12-08 17:13:40 -08001623 UpdateEndedRemoteMediaStreams();
deadbeefab9b2d12015-10-14 11:33:11 -07001624
1625 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07001626 signaling_thread()->Post(RTC_FROM_HERE, this,
1627 MSG_SET_SESSIONDESCRIPTION_SUCCESS, msg);
deadbeef42a42632017-03-10 15:18:00 -08001628
1629 if (desc->type() == SessionDescriptionInterface::kAnswer) {
1630 // TODO(deadbeef): We already had to hop to the network thread for
1631 // MaybeStartGathering...
1632 network_thread()->Invoke<void>(
1633 RTC_FROM_HERE,
1634 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1635 port_allocator_.get()));
1636 }
deadbeeffc648b62015-10-13 16:42:33 -07001637}
1638
deadbeef46c73892016-11-16 19:42:04 -08001639PeerConnectionInterface::RTCConfiguration PeerConnection::GetConfiguration() {
1640 return configuration_;
1641}
1642
deadbeef293e9262017-01-11 12:28:30 -08001643bool PeerConnection::SetConfiguration(const RTCConfiguration& configuration,
1644 RTCError* error) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001645 TRACE_EVENT0("webrtc", "PeerConnection::SetConfiguration");
deadbeef6de92f92016-12-12 18:49:32 -08001646
Steve Anton75737c02017-11-06 10:37:17 -08001647 if (local_description() && configuration.ice_candidate_pool_size !=
1648 configuration_.ice_candidate_pool_size) {
deadbeef6de92f92016-12-12 18:49:32 -08001649 LOG(LS_ERROR) << "Can't change candidate pool size after calling "
1650 "SetLocalDescription.";
deadbeef293e9262017-01-11 12:28:30 -08001651 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001652 }
Taylor Brandstettera1c30352016-05-13 08:15:11 -07001653
deadbeef293e9262017-01-11 12:28:30 -08001654 // The simplest (and most future-compatible) way to tell if the config was
1655 // modified in an invalid way is to copy each property we do support
1656 // modifying, then use operator==. There are far more properties we don't
1657 // support modifying than those we do, and more could be added.
1658 RTCConfiguration modified_config = configuration_;
1659 modified_config.servers = configuration.servers;
1660 modified_config.type = configuration.type;
1661 modified_config.ice_candidate_pool_size =
1662 configuration.ice_candidate_pool_size;
1663 modified_config.prune_turn_ports = configuration.prune_turn_ports;
skvladd1f5fda2017-02-03 16:54:05 -08001664 modified_config.ice_check_min_interval = configuration.ice_check_min_interval;
Jonas Orelandbdcee282017-10-10 14:01:40 +02001665 modified_config.turn_customizer = configuration.turn_customizer;
deadbeef293e9262017-01-11 12:28:30 -08001666 if (configuration != modified_config) {
1667 LOG(LS_ERROR) << "Modifying the configuration in an unsupported way.";
1668 return SafeSetError(RTCErrorType::INVALID_MODIFICATION, error);
1669 }
1670
Steve Anton038834f2017-07-14 15:59:59 -07001671 // Validate the modified configuration.
1672 RTCError validate_error = ValidateConfiguration(modified_config);
1673 if (!validate_error.ok()) {
1674 return SafeSetError(std::move(validate_error), error);
1675 }
1676
deadbeef293e9262017-01-11 12:28:30 -08001677 // Note that this isn't possible through chromium, since it's an unsigned
1678 // short in WebIDL.
1679 if (configuration.ice_candidate_pool_size < 0 ||
1680 configuration.ice_candidate_pool_size > UINT16_MAX) {
1681 return SafeSetError(RTCErrorType::INVALID_RANGE, error);
1682 }
1683
1684 // Parse ICE servers before hopping to network thread.
1685 cricket::ServerAddresses stun_servers;
1686 std::vector<cricket::RelayServerConfig> turn_servers;
1687 RTCErrorType parse_error =
1688 ParseIceServers(configuration.servers, &stun_servers, &turn_servers);
1689 if (parse_error != RTCErrorType::NONE) {
1690 return SafeSetError(parse_error, error);
1691 }
1692
1693 // In theory this shouldn't fail.
1694 if (!network_thread()->Invoke<bool>(
1695 RTC_FROM_HERE,
1696 rtc::Bind(&PeerConnection::ReconfigurePortAllocator_n, this,
1697 stun_servers, turn_servers, modified_config.type,
1698 modified_config.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02001699 modified_config.prune_turn_ports,
1700 modified_config.turn_customizer))) {
deadbeef293e9262017-01-11 12:28:30 -08001701 LOG(LS_ERROR) << "Failed to apply configuration to PortAllocator.";
1702 return SafeSetError(RTCErrorType::INTERNAL_ERROR, error);
1703 }
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07001704
deadbeefd1a38b52016-12-10 13:15:33 -08001705 // As described in JSEP, calling setConfiguration with new ICE servers or
1706 // candidate policy must set a "needs-ice-restart" bit so that the next offer
1707 // triggers an ICE restart which will pick up the changes.
deadbeef293e9262017-01-11 12:28:30 -08001708 if (modified_config.servers != configuration_.servers ||
1709 modified_config.type != configuration_.type ||
1710 modified_config.prune_turn_ports != configuration_.prune_turn_ports) {
Steve Antond25da372017-11-06 14:50:29 -08001711 transport_controller_->SetNeedsIceRestartFlag();
deadbeefd1a38b52016-12-10 13:15:33 -08001712 }
skvladd1f5fda2017-02-03 16:54:05 -08001713
1714 if (modified_config.ice_check_min_interval !=
1715 configuration_.ice_check_min_interval) {
Steve Antond25da372017-11-06 14:50:29 -08001716 transport_controller_->SetIceConfig(ParseIceConfig(modified_config));
skvladd1f5fda2017-02-03 16:54:05 -08001717 }
1718
deadbeef293e9262017-01-11 12:28:30 -08001719 configuration_ = modified_config;
1720 return SafeSetError(RTCErrorType::NONE, error);
buildbot@webrtc.org41451d42014-05-03 05:39:45 +00001721}
1722
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001723bool PeerConnection::AddIceCandidate(
1724 const IceCandidateInterface* ice_candidate) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001725 TRACE_EVENT0("webrtc", "PeerConnection::AddIceCandidate");
zhihuang29ff8442016-07-27 11:07:25 -07001726 if (IsClosed()) {
1727 return false;
1728 }
Steve Antond25da372017-11-06 14:50:29 -08001729
1730 if (!remote_description()) {
1731 LOG(LS_ERROR) << "ProcessIceMessage: ICE candidates can't be added "
1732 << "without any remote session description.";
1733 return false;
1734 }
1735
1736 if (!ice_candidate) {
1737 LOG(LS_ERROR) << "ProcessIceMessage: Candidate is NULL.";
1738 return false;
1739 }
1740
1741 bool valid = false;
1742 bool ready = ReadyToUseRemoteCandidate(ice_candidate, nullptr, &valid);
1743 if (!valid) {
1744 return false;
1745 }
1746
1747 // Add this candidate to the remote session description.
1748 if (!mutable_remote_description()->AddCandidate(ice_candidate)) {
1749 LOG(LS_ERROR) << "ProcessIceMessage: Candidate cannot be used.";
1750 return false;
1751 }
1752
1753 if (ready) {
1754 return UseCandidate(ice_candidate);
1755 } else {
1756 LOG(LS_INFO) << "ProcessIceMessage: Not ready to use candidate.";
1757 return true;
1758 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001759}
1760
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001761bool PeerConnection::RemoveIceCandidates(
1762 const std::vector<cricket::Candidate>& candidates) {
1763 TRACE_EVENT0("webrtc", "PeerConnection::RemoveIceCandidates");
Steve Antond25da372017-11-06 14:50:29 -08001764 if (!remote_description()) {
1765 LOG(LS_ERROR) << "RemoveRemoteIceCandidates: ICE candidates can't be "
1766 << "removed without any remote session description.";
1767 return false;
1768 }
1769
1770 if (candidates.empty()) {
1771 LOG(LS_ERROR) << "RemoveRemoteIceCandidates: candidates are empty.";
1772 return false;
1773 }
1774
1775 size_t number_removed =
1776 mutable_remote_description()->RemoveCandidates(candidates);
1777 if (number_removed != candidates.size()) {
1778 LOG(LS_ERROR) << "RemoveRemoteIceCandidates: Failed to remove candidates. "
1779 << "Requested " << candidates.size() << " but only "
1780 << number_removed << " are removed.";
1781 }
1782
1783 // Remove the candidates from the transport controller.
1784 std::string error;
1785 bool res = transport_controller_->RemoveRemoteCandidates(candidates, &error);
1786 if (!res && !error.empty()) {
1787 LOG(LS_ERROR) << "Error when removing remote candidates: " << error;
1788 }
1789 return true;
Honghai Zhang7fb69db2016-03-14 11:59:18 -07001790}
1791
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001792void PeerConnection::RegisterUMAObserver(UMAObserver* observer) {
Peter Boström1a9d6152015-12-08 22:15:17 +01001793 TRACE_EVENT0("webrtc", "PeerConnection::RegisterUmaObserver");
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001794 uma_observer_ = observer;
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001795
Steve Anton75737c02017-11-06 10:37:17 -08001796 if (transport_controller()) {
1797 transport_controller()->SetMetricsObserver(uma_observer_);
guoweis@webrtc.org7169afd2014-12-04 17:59:29 +00001798 }
1799
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001800 // Send information about IPv4/IPv6 status.
deadbeef293e9262017-01-11 12:28:30 -08001801 if (uma_observer_) {
Honghai Zhangd93f50c2016-10-05 11:47:22 -07001802 port_allocator_->SetMetricsObserver(uma_observer_);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001803 if (port_allocator_->flags() & cricket::PORTALLOCATOR_ENABLE_IPV6) {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001804 uma_observer_->IncrementEnumCounter(
1805 kEnumCounterAddressFamily, kPeerConnection_IPv6,
1806 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgb445f262014-05-23 22:19:37 +00001807 } else {
Guo-wei Shiehdfbe6792015-09-03 17:12:07 -07001808 uma_observer_->IncrementEnumCounter(
1809 kEnumCounterAddressFamily, kPeerConnection_IPv4,
1810 kPeerConnectionAddressFamilyCounter_Max);
mallinath@webrtc.orgd37bcfa2014-05-12 23:10:18 +00001811 }
1812 }
buildbot@webrtc.org1567b8c2014-05-08 19:54:16 +00001813}
1814
zstein4b979802017-06-02 14:37:37 -07001815RTCError PeerConnection::SetBitrate(const BitrateParameters& bitrate) {
Steve Anton978b8762017-09-29 12:15:02 -07001816 if (!worker_thread()->IsCurrent()) {
1817 return worker_thread()->Invoke<RTCError>(
zstein4b979802017-06-02 14:37:37 -07001818 RTC_FROM_HERE, rtc::Bind(&PeerConnection::SetBitrate, this, bitrate));
1819 }
1820
1821 const bool has_min = static_cast<bool>(bitrate.min_bitrate_bps);
1822 const bool has_current = static_cast<bool>(bitrate.current_bitrate_bps);
1823 const bool has_max = static_cast<bool>(bitrate.max_bitrate_bps);
1824 if (has_min && *bitrate.min_bitrate_bps < 0) {
1825 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1826 "min_bitrate_bps <= 0");
1827 }
1828 if (has_current) {
1829 if (has_min && *bitrate.current_bitrate_bps < *bitrate.min_bitrate_bps) {
1830 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1831 "current_bitrate_bps < min_bitrate_bps");
1832 } else if (*bitrate.current_bitrate_bps < 0) {
1833 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1834 "curent_bitrate_bps < 0");
1835 }
1836 }
1837 if (has_max) {
1838 if (has_current &&
1839 *bitrate.max_bitrate_bps < *bitrate.current_bitrate_bps) {
1840 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1841 "max_bitrate_bps < current_bitrate_bps");
1842 } else if (has_min && *bitrate.max_bitrate_bps < *bitrate.min_bitrate_bps) {
1843 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1844 "max_bitrate_bps < min_bitrate_bps");
1845 } else if (*bitrate.max_bitrate_bps < 0) {
1846 LOG_AND_RETURN_ERROR(RTCErrorType::INVALID_PARAMETER,
1847 "max_bitrate_bps < 0");
1848 }
1849 }
1850
1851 Call::Config::BitrateConfigMask mask;
1852 mask.min_bitrate_bps = bitrate.min_bitrate_bps;
1853 mask.start_bitrate_bps = bitrate.current_bitrate_bps;
1854 mask.max_bitrate_bps = bitrate.max_bitrate_bps;
1855
1856 RTC_DCHECK(call_.get());
1857 call_->SetBitrateConfigMask(mask);
1858
1859 return RTCError::OK();
1860}
1861
Alex Narest78609d52017-10-20 10:37:47 +02001862void PeerConnection::SetBitrateAllocationStrategy(
1863 std::unique_ptr<rtc::BitrateAllocationStrategy>
1864 bitrate_allocation_strategy) {
1865 rtc::Thread* worker_thread = factory_->worker_thread();
1866 if (!worker_thread->IsCurrent()) {
1867 rtc::BitrateAllocationStrategy* strategy_raw =
1868 bitrate_allocation_strategy.release();
1869 auto functor = [this, strategy_raw]() {
1870 call_->SetBitrateAllocationStrategy(
1871 rtc::WrapUnique<rtc::BitrateAllocationStrategy>(strategy_raw));
1872 };
1873 worker_thread->Invoke<void>(RTC_FROM_HERE, functor);
1874 return;
1875 }
1876 RTC_DCHECK(call_.get());
1877 call_->SetBitrateAllocationStrategy(std::move(bitrate_allocation_strategy));
1878}
1879
henrika5f6bf242017-11-01 11:06:56 +01001880void PeerConnection::SetAudioPlayout(bool playout) {
1881 if (!worker_thread()->IsCurrent()) {
1882 worker_thread()->Invoke<void>(
1883 RTC_FROM_HERE,
1884 rtc::Bind(&PeerConnection::SetAudioPlayout, this, playout));
1885 return;
1886 }
1887 auto audio_state =
1888 factory_->channel_manager()->media_engine()->GetAudioState();
1889 audio_state->SetPlayout(playout);
1890}
1891
1892void PeerConnection::SetAudioRecording(bool recording) {
1893 if (!worker_thread()->IsCurrent()) {
1894 worker_thread()->Invoke<void>(
1895 RTC_FROM_HERE,
1896 rtc::Bind(&PeerConnection::SetAudioRecording, this, recording));
1897 return;
1898 }
1899 auto audio_state =
1900 factory_->channel_manager()->media_engine()->GetAudioState();
1901 audio_state->SetRecording(recording);
1902}
1903
Steve Anton8c0f7a72017-10-03 10:03:10 -07001904std::unique_ptr<rtc::SSLCertificate>
1905PeerConnection::GetRemoteAudioSSLCertificate() {
Steve Anton75737c02017-11-06 10:37:17 -08001906 if (!voice_channel()) {
Steve Anton8c0f7a72017-10-03 10:03:10 -07001907 return nullptr;
1908 }
Steve Anton75737c02017-11-06 10:37:17 -08001909 return GetRemoteSSLCertificate(voice_channel()->transport_name());
Steve Anton8c0f7a72017-10-03 10:03:10 -07001910}
1911
ivoc14d5dbe2016-07-04 07:06:55 -07001912bool PeerConnection::StartRtcEventLog(rtc::PlatformFile file,
1913 int64_t max_size_bytes) {
Elad Alon99c3fe52017-10-13 16:29:40 +02001914 // TODO(eladalon): It would be better to not allow negative values into PC.
1915 const size_t max_size = (max_size_bytes < 0)
1916 ? RtcEventLog::kUnlimitedOutput
1917 : rtc::saturated_cast<size_t>(max_size_bytes);
1918 return StartRtcEventLog(
1919 rtc::MakeUnique<RtcEventLogOutputFile>(file, max_size));
1920}
1921
1922bool PeerConnection::StartRtcEventLog(
1923 std::unique_ptr<RtcEventLogOutput> output) {
Karl Wibergd6b48192017-10-16 23:01:06 +02001924 // TODO(eladalon): In C++14, this can be done with a lambda.
1925 struct Functor {
1926 bool operator()() { return pc->StartRtcEventLog_w(std::move(output)); }
1927 PeerConnection* const pc;
1928 std::unique_ptr<RtcEventLogOutput> output;
Elad Alon99c3fe52017-10-13 16:29:40 +02001929 };
Karl Wibergd6b48192017-10-16 23:01:06 +02001930 return worker_thread()->Invoke<bool>(RTC_FROM_HERE,
1931 Functor{this, std::move(output)});
ivoc14d5dbe2016-07-04 07:06:55 -07001932}
1933
1934void PeerConnection::StopRtcEventLog() {
Steve Anton978b8762017-09-29 12:15:02 -07001935 worker_thread()->Invoke<void>(
ivoc14d5dbe2016-07-04 07:06:55 -07001936 RTC_FROM_HERE, rtc::Bind(&PeerConnection::StopRtcEventLog_w, this));
1937}
1938
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001939const SessionDescriptionInterface* PeerConnection::local_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08001940 return pending_local_description_ ? pending_local_description_.get()
1941 : current_local_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001942}
1943
1944const SessionDescriptionInterface* PeerConnection::remote_description() const {
Steve Anton75737c02017-11-06 10:37:17 -08001945 return pending_remote_description_ ? pending_remote_description_.get()
1946 : current_remote_description_.get();
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001947}
1948
deadbeeffe4a8a42016-12-20 17:56:17 -08001949const SessionDescriptionInterface* PeerConnection::current_local_description()
1950 const {
Steve Anton75737c02017-11-06 10:37:17 -08001951 return current_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001952}
1953
1954const SessionDescriptionInterface* PeerConnection::current_remote_description()
1955 const {
Steve Anton75737c02017-11-06 10:37:17 -08001956 return current_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001957}
1958
1959const SessionDescriptionInterface* PeerConnection::pending_local_description()
1960 const {
Steve Anton75737c02017-11-06 10:37:17 -08001961 return pending_local_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001962}
1963
1964const SessionDescriptionInterface* PeerConnection::pending_remote_description()
1965 const {
Steve Anton75737c02017-11-06 10:37:17 -08001966 return pending_remote_description_.get();
deadbeeffe4a8a42016-12-20 17:56:17 -08001967}
1968
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001969void PeerConnection::Close() {
Peter Boström1a9d6152015-12-08 22:15:17 +01001970 TRACE_EVENT0("webrtc", "PeerConnection::Close");
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001971 // Update stats here so that we have the most recent stats for tracks and
1972 // streams before the channels are closed.
tommi@webrtc.org03505bc2014-07-14 20:15:26 +00001973 stats_->UpdateStats(kStatsOutputLevelStandard);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001974
Steve Anton75737c02017-11-06 10:37:17 -08001975 ChangeSignalingState(PeerConnectionInterface::kClosed);
1976 RemoveUnusedChannels(nullptr);
1977 RTC_DCHECK(voice_channels_.empty());
1978 RTC_DCHECK(video_channels_.empty());
1979 RTC_DCHECK(!rtp_data_channel_);
1980 RTC_DCHECK(!sctp_transport_);
1981
deadbeef42a42632017-03-10 15:18:00 -08001982 network_thread()->Invoke<void>(
1983 RTC_FROM_HERE,
1984 rtc::Bind(&cricket::PortAllocator::DiscardCandidatePool,
1985 port_allocator_.get()));
nisseeaabdf62017-05-05 02:23:02 -07001986
Steve Anton978b8762017-09-29 12:15:02 -07001987 worker_thread()->Invoke<void>(RTC_FROM_HERE, [this] {
eladalon248fd4f2017-09-06 05:18:15 -07001988 call_.reset();
1989 // The event log must outlive call (and any other object that uses it).
1990 event_log_.reset();
1991 });
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001992}
1993
buildbot@webrtc.orgd4e598d2014-07-29 17:36:52 +00001994void PeerConnection::OnMessage(rtc::Message* msg) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001995 switch (msg->message_id) {
henrike@webrtc.org28e20752013-07-10 00:45:36 +00001996 case MSG_SET_SESSIONDESCRIPTION_SUCCESS: {
1997 SetSessionDescriptionMsg* param =
1998 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
1999 param->observer->OnSuccess();
2000 delete param;
2001 break;
2002 }
2003 case MSG_SET_SESSIONDESCRIPTION_FAILED: {
2004 SetSessionDescriptionMsg* param =
2005 static_cast<SetSessionDescriptionMsg*>(msg->pdata);
2006 param->observer->OnFailure(param->error);
2007 delete param;
2008 break;
2009 }
deadbeefab9b2d12015-10-14 11:33:11 -07002010 case MSG_CREATE_SESSIONDESCRIPTION_FAILED: {
2011 CreateSessionDescriptionMsg* param =
2012 static_cast<CreateSessionDescriptionMsg*>(msg->pdata);
2013 param->observer->OnFailure(param->error);
2014 delete param;
2015 break;
2016 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002017 case MSG_GETSTATS: {
2018 GetStatsMsg* param = static_cast<GetStatsMsg*>(msg->pdata);
nissee8abe3e2017-01-18 05:00:34 -08002019 StatsReports reports;
2020 stats_->GetStats(param->track, &reports);
2021 param->observer->OnComplete(reports);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002022 delete param;
2023 break;
2024 }
deadbeefbd292462015-12-14 18:15:29 -08002025 case MSG_FREE_DATACHANNELS: {
2026 sctp_data_channels_to_free_.clear();
2027 break;
2028 }
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002029 default:
nisseeb4ca4e2017-01-12 02:24:27 -08002030 RTC_NOTREACHED() << "Not implemented";
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002031 break;
2032 }
2033}
2034
deadbeefab9b2d12015-10-14 11:33:11 -07002035void PeerConnection::CreateAudioReceiver(MediaStreamInterface* stream,
perkjd61bf802016-03-24 03:16:19 -07002036 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07002037 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08002038 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2039 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
deadbeefe814a0d2017-02-25 18:15:09 -08002040 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002041 new AudioRtpReceiver(track_id, ssrc, voice_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002042 stream->AddTrack(
2043 static_cast<AudioTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08002044 receivers_.push_back(receiver);
2045 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2046 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
2047 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002048}
2049
deadbeefab9b2d12015-10-14 11:33:11 -07002050void PeerConnection::CreateVideoReceiver(MediaStreamInterface* stream,
perkjf0dcfe22016-03-10 18:32:00 +01002051 const std::string& track_id,
deadbeefab9b2d12015-10-14 11:33:11 -07002052 uint32_t ssrc) {
zhihuang81c3a032016-11-17 12:06:24 -08002053 rtc::scoped_refptr<RtpReceiverProxyWithInternal<RtpReceiverInternal>>
2054 receiver = RtpReceiverProxyWithInternal<RtpReceiverInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002055 signaling_thread(), new VideoRtpReceiver(track_id, worker_thread(),
2056 ssrc, video_channel()));
deadbeefe814a0d2017-02-25 18:15:09 -08002057 stream->AddTrack(
2058 static_cast<VideoTrackInterface*>(receiver->internal()->track().get()));
zhihuang81c3a032016-11-17 12:06:24 -08002059 receivers_.push_back(receiver);
2060 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams;
2061 streams.push_back(rtc::scoped_refptr<MediaStreamInterface>(stream));
2062 observer_->OnAddTrack(receiver, streams);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002063}
2064
deadbeef70ab1a12015-09-28 16:53:55 -07002065// TODO(deadbeef): Keep RtpReceivers around even if track goes away in remote
2066// description.
Henrik Boström933d8b02017-10-10 10:05:16 -07002067rtc::scoped_refptr<RtpReceiverInterface> PeerConnection::RemoveAndStopReceiver(
2068 const std::string& track_id) {
perkjd61bf802016-03-24 03:16:19 -07002069 auto it = FindReceiverForTrack(track_id);
deadbeef70ab1a12015-09-28 16:53:55 -07002070 if (it == receivers_.end()) {
perkjd61bf802016-03-24 03:16:19 -07002071 LOG(LS_WARNING) << "RtpReceiver for track with id " << track_id
deadbeef70ab1a12015-09-28 16:53:55 -07002072 << " doesn't exist.";
Henrik Boström933d8b02017-10-10 10:05:16 -07002073 return nullptr;
deadbeef70ab1a12015-09-28 16:53:55 -07002074 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002075 (*it)->internal()->Stop();
2076 rtc::scoped_refptr<RtpReceiverInterface> receiver = *it;
2077 receivers_.erase(it);
2078 return receiver;
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002079}
2080
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002081void PeerConnection::AddAudioTrack(AudioTrackInterface* track,
2082 MediaStreamInterface* stream) {
2083 RTC_DCHECK(!IsClosed());
2084 auto sender = FindSenderForTrack(track);
2085 if (sender != senders_.end()) {
2086 // We already have a sender for this track, so just change the stream_id
2087 // so that it's correct in the next call to CreateOffer.
2088 (*sender)->internal()->set_stream_id(stream->label());
2089 return;
2090 }
2091
2092 // Normal case; we've never seen this track before.
2093 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2094 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
2095 signaling_thread(),
Steve Anton75737c02017-11-06 10:37:17 -08002096 new AudioRtpSender(track, {stream->label()}, voice_channel(),
2097 stats_.get()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002098 senders_.push_back(new_sender);
2099 // If the sender has already been configured in SDP, we call SetSsrc,
2100 // which will connect the sender to the underlying transport. This can
2101 // occur if a local session description that contains the ID of the sender
2102 // is set before AddStream is called. It can also occur if the local
2103 // session description is not changed and RemoveStream is called, and
2104 // later AddStream is called again with the same stream.
2105 const TrackInfo* track_info =
2106 FindTrackInfo(local_audio_tracks_, stream->label(), track->id());
2107 if (track_info) {
2108 new_sender->internal()->SetSsrc(track_info->ssrc);
2109 }
2110}
2111
2112// TODO(deadbeef): Don't destroy RtpSenders here; they should be kept around
2113// indefinitely, when we have unified plan SDP.
2114void PeerConnection::RemoveAudioTrack(AudioTrackInterface* track,
2115 MediaStreamInterface* stream) {
2116 RTC_DCHECK(!IsClosed());
2117 auto sender = FindSenderForTrack(track);
2118 if (sender == senders_.end()) {
2119 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2120 << " doesn't exist.";
2121 return;
2122 }
2123 (*sender)->internal()->Stop();
2124 senders_.erase(sender);
2125}
2126
2127void PeerConnection::AddVideoTrack(VideoTrackInterface* track,
2128 MediaStreamInterface* stream) {
2129 RTC_DCHECK(!IsClosed());
2130 auto sender = FindSenderForTrack(track);
2131 if (sender != senders_.end()) {
2132 // We already have a sender for this track, so just change the stream_id
2133 // so that it's correct in the next call to CreateOffer.
2134 (*sender)->internal()->set_stream_id(stream->label());
2135 return;
2136 }
2137
2138 // Normal case; we've never seen this track before.
2139 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>> new_sender =
2140 RtpSenderProxyWithInternal<RtpSenderInternal>::Create(
Steve Anton75737c02017-11-06 10:37:17 -08002141 signaling_thread(),
2142 new VideoRtpSender(track, {stream->label()}, video_channel()));
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002143 senders_.push_back(new_sender);
2144 const TrackInfo* track_info =
2145 FindTrackInfo(local_video_tracks_, stream->label(), track->id());
2146 if (track_info) {
2147 new_sender->internal()->SetSsrc(track_info->ssrc);
2148 }
2149}
2150
2151void PeerConnection::RemoveVideoTrack(VideoTrackInterface* track,
2152 MediaStreamInterface* stream) {
2153 RTC_DCHECK(!IsClosed());
2154 auto sender = FindSenderForTrack(track);
2155 if (sender == senders_.end()) {
2156 LOG(LS_WARNING) << "RtpSender for track with id " << track->id()
2157 << " doesn't exist.";
2158 return;
2159 }
2160 (*sender)->internal()->Stop();
2161 senders_.erase(sender);
2162}
2163
Steve Antonba818672017-11-06 10:21:57 -08002164void PeerConnection::SetIceConnectionState(IceConnectionState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002165 RTC_DCHECK(signaling_thread()->IsCurrent());
Steve Antonba818672017-11-06 10:21:57 -08002166 if (ice_connection_state_ == new_state) {
2167 return;
2168 }
2169
deadbeefcbecd352015-09-23 11:50:27 -07002170 // After transitioning to "closed", ignore any additional states from
Steve Antonba818672017-11-06 10:21:57 -08002171 // TransportController (such as "disconnected").
deadbeefab9b2d12015-10-14 11:33:11 -07002172 if (IsClosed()) {
deadbeefcbecd352015-09-23 11:50:27 -07002173 return;
2174 }
Steve Antonba818672017-11-06 10:21:57 -08002175
2176 LOG(LS_INFO) << "Changing IceConnectionState " << ice_connection_state_
2177 << " => " << new_state;
2178 RTC_DCHECK(ice_connection_state_ !=
2179 PeerConnectionInterface::kIceConnectionClosed);
2180
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002181 ice_connection_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002182 observer_->OnIceConnectionChange(ice_connection_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002183}
2184
2185void PeerConnection::OnIceGatheringChange(
2186 PeerConnectionInterface::IceGatheringState new_state) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002187 RTC_DCHECK(signaling_thread()->IsCurrent());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002188 if (IsClosed()) {
2189 return;
2190 }
2191 ice_gathering_state_ = new_state;
mallinath@webrtc.orgd3dc4242014-03-01 00:05:52 +00002192 observer_->OnIceGatheringChange(ice_gathering_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002193}
2194
jbauch81bf7b02017-03-25 08:31:12 -07002195void PeerConnection::OnIceCandidate(
2196 std::unique_ptr<IceCandidateInterface> candidate) {
deadbeef0a6c4ca2015-10-06 11:38:28 -07002197 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002198 if (IsClosed()) {
2199 return;
2200 }
jbauch81bf7b02017-03-25 08:31:12 -07002201 observer_->OnIceCandidate(candidate.get());
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002202}
2203
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002204void PeerConnection::OnIceCandidatesRemoved(
2205 const std::vector<cricket::Candidate>& candidates) {
2206 RTC_DCHECK(signaling_thread()->IsCurrent());
zhihuang29ff8442016-07-27 11:07:25 -07002207 if (IsClosed()) {
2208 return;
2209 }
Honghai Zhang7fb69db2016-03-14 11:59:18 -07002210 observer_->OnIceCandidatesRemoved(candidates);
2211}
2212
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002213void PeerConnection::ChangeSignalingState(
2214 PeerConnectionInterface::SignalingState signaling_state) {
Steve Antonba818672017-11-06 10:21:57 -08002215 RTC_DCHECK(signaling_thread()->IsCurrent());
2216 if (signaling_state_ == signaling_state) {
2217 return;
2218 }
2219 LOG(LS_INFO) << "Session: " << session_id()
2220 << " Old state: " << GetSignalingStateString(signaling_state_)
2221 << " New state: " << GetSignalingStateString(signaling_state);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002222 signaling_state_ = signaling_state;
2223 if (signaling_state == kClosed) {
2224 ice_connection_state_ = kIceConnectionClosed;
2225 observer_->OnIceConnectionChange(ice_connection_state_);
2226 if (ice_gathering_state_ != kIceGatheringComplete) {
2227 ice_gathering_state_ = kIceGatheringComplete;
2228 observer_->OnIceGatheringChange(ice_gathering_state_);
2229 }
2230 }
2231 observer_->OnSignalingChange(signaling_state_);
henrike@webrtc.org28e20752013-07-10 00:45:36 +00002232}
2233
deadbeefeb459812015-12-15 19:24:43 -08002234void PeerConnection::OnAudioTrackAdded(AudioTrackInterface* track,
2235 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002236 if (IsClosed()) {
2237 return;
2238 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002239 AddAudioTrack(track, stream);
2240 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002241}
2242
deadbeefeb459812015-12-15 19:24:43 -08002243void PeerConnection::OnAudioTrackRemoved(AudioTrackInterface* track,
2244 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002245 if (IsClosed()) {
2246 return;
2247 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002248 RemoveAudioTrack(track, stream);
2249 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002250}
2251
2252void PeerConnection::OnVideoTrackAdded(VideoTrackInterface* track,
2253 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002254 if (IsClosed()) {
2255 return;
2256 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002257 AddVideoTrack(track, stream);
2258 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002259}
2260
2261void PeerConnection::OnVideoTrackRemoved(VideoTrackInterface* track,
2262 MediaStreamInterface* stream) {
zhihuang29ff8442016-07-27 11:07:25 -07002263 if (IsClosed()) {
2264 return;
2265 }
korniltsev.anatolyec390b52017-07-24 17:00:25 -07002266 RemoveVideoTrack(track, stream);
2267 observer_->OnRenegotiationNeeded();
deadbeefeb459812015-12-15 19:24:43 -08002268}
2269
deadbeefab9b2d12015-10-14 11:33:11 -07002270void PeerConnection::PostSetSessionDescriptionFailure(
2271 SetSessionDescriptionObserver* observer,
2272 const std::string& error) {
2273 SetSessionDescriptionMsg* msg = new SetSessionDescriptionMsg(observer);
2274 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002275 signaling_thread()->Post(RTC_FROM_HERE, this,
2276 MSG_SET_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002277}
2278
2279void PeerConnection::PostCreateSessionDescriptionFailure(
2280 CreateSessionDescriptionObserver* observer,
2281 const std::string& error) {
2282 CreateSessionDescriptionMsg* msg = new CreateSessionDescriptionMsg(observer);
2283 msg->error = error;
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002284 signaling_thread()->Post(RTC_FROM_HERE, this,
2285 MSG_CREATE_SESSIONDESCRIPTION_FAILED, msg);
deadbeefab9b2d12015-10-14 11:33:11 -07002286}
2287
zhihuang1c378ed2017-08-17 14:10:50 -07002288void PeerConnection::GetOptionsForOffer(
deadbeefab9b2d12015-10-14 11:33:11 -07002289 const PeerConnectionInterface::RTCOfferAnswerOptions& rtc_options,
2290 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002291 ExtractSharedMediaSessionOptions(rtc_options, session_options);
2292
2293 // Figure out transceiver directional preferences.
2294 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2295 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2296
2297 // By default, generate sendrecv/recvonly m= sections.
2298 bool recv_audio = true;
2299 bool recv_video = true;
2300
2301 // By default, only offer a new m= section if we have media to send with it.
2302 bool offer_new_audio_description = send_audio;
2303 bool offer_new_video_description = send_video;
2304 bool offer_new_data_description = HasDataChannels();
2305
2306 // The "offer_to_receive_X" options allow those defaults to be overridden.
2307 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2308 recv_audio = (rtc_options.offer_to_receive_audio > 0);
2309 offer_new_audio_description =
2310 offer_new_audio_description || (rtc_options.offer_to_receive_audio > 0);
2311 }
2312 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2313 recv_video = (rtc_options.offer_to_receive_video > 0);
2314 offer_new_video_description =
2315 offer_new_video_description || (rtc_options.offer_to_receive_video > 0);
2316 }
2317
2318 rtc::Optional<size_t> audio_index;
2319 rtc::Optional<size_t> video_index;
2320 rtc::Optional<size_t> data_index;
2321 // If a current description exists, generate m= sections in the same order,
2322 // using the first audio/video/data section that appears and rejecting
2323 // extraneous ones.
Steve Anton75737c02017-11-06 10:37:17 -08002324 if (local_description()) {
zhihuang1c378ed2017-08-17 14:10:50 -07002325 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002326 local_description(),
zhihuang1c378ed2017-08-17 14:10:50 -07002327 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2328 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2329 &video_index, &data_index, session_options);
deadbeefab9b2d12015-10-14 11:33:11 -07002330 }
2331
zhihuang1c378ed2017-08-17 14:10:50 -07002332 // Add audio/video/data m= sections to the end if needed.
2333 if (!audio_index && offer_new_audio_description) {
2334 session_options->media_description_options.push_back(
2335 cricket::MediaDescriptionOptions(
2336 cricket::MEDIA_TYPE_AUDIO, cricket::CN_AUDIO,
2337 cricket::RtpTransceiverDirection(send_audio, recv_audio), false));
2338 audio_index = rtc::Optional<size_t>(
2339 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07002340 }
zhihuang1c378ed2017-08-17 14:10:50 -07002341 if (!video_index && offer_new_video_description) {
2342 session_options->media_description_options.push_back(
2343 cricket::MediaDescriptionOptions(
2344 cricket::MEDIA_TYPE_VIDEO, cricket::CN_VIDEO,
2345 cricket::RtpTransceiverDirection(send_video, recv_video), false));
2346 video_index = rtc::Optional<size_t>(
2347 session_options->media_description_options.size() - 1);
deadbeefc80741f2015-10-22 13:14:45 -07002348 }
zhihuang1c378ed2017-08-17 14:10:50 -07002349 if (!data_index && offer_new_data_description) {
2350 session_options->media_description_options.push_back(
2351 cricket::MediaDescriptionOptions(
2352 cricket::MEDIA_TYPE_DATA, cricket::CN_DATA,
2353 cricket::RtpTransceiverDirection(true, true), false));
2354 data_index = rtc::Optional<size_t>(
2355 session_options->media_description_options.size() - 1);
2356 }
2357
2358 cricket::MediaDescriptionOptions* audio_media_description_options =
2359 !audio_index ? nullptr
2360 : &session_options->media_description_options[*audio_index];
2361 cricket::MediaDescriptionOptions* video_media_description_options =
2362 !video_index ? nullptr
2363 : &session_options->media_description_options[*video_index];
2364 cricket::MediaDescriptionOptions* data_media_description_options =
2365 !data_index ? nullptr
2366 : &session_options->media_description_options[*data_index];
2367
2368 // Apply ICE restart flag and renomination flag.
2369 for (auto& options : session_options->media_description_options) {
2370 options.transport_options.ice_restart = rtc_options.ice_restart;
2371 options.transport_options.enable_ice_renomination =
2372 configuration_.enable_ice_renomination;
2373 }
2374
2375 AddRtpSenderOptions(senders_, audio_media_description_options,
2376 video_media_description_options);
2377 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
deadbeefc80741f2015-10-22 13:14:45 -07002378
zhihuang9763d562016-08-05 11:14:50 -07002379 // Intentionally unset the data channel type for RTP data channel with the
2380 // second condition. Otherwise the RTP data channels would be successfully
2381 // negotiated by default and the unit tests in WebRtcDataBrowserTest will fail
2382 // when building with chromium. We want to leave RTP data channels broken, so
2383 // people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002384 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2385 session_options->data_channel_type = data_channel_type();
deadbeefab9b2d12015-10-14 11:33:11 -07002386 }
zhihuang8f65cdf2016-05-06 18:40:30 -07002387
2388 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002389 session_options->crypto_options = factory_->options().crypto_options;
deadbeefab9b2d12015-10-14 11:33:11 -07002390}
2391
zhihuang1c378ed2017-08-17 14:10:50 -07002392void PeerConnection::GetOptionsForAnswer(
2393 const RTCOfferAnswerOptions& rtc_options,
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002394 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002395 ExtractSharedMediaSessionOptions(rtc_options, session_options);
Honghai Zhang4cedf2b2016-08-31 08:18:11 -07002396
zhihuang1c378ed2017-08-17 14:10:50 -07002397 // Figure out transceiver directional preferences.
2398 bool send_audio = HasRtpSender(cricket::MEDIA_TYPE_AUDIO);
2399 bool send_video = HasRtpSender(cricket::MEDIA_TYPE_VIDEO);
2400
2401 // By default, generate sendrecv/recvonly m= sections. The direction is also
2402 // restricted by the direction in the offer.
2403 bool recv_audio = true;
2404 bool recv_video = true;
2405
2406 // The "offer_to_receive_X" options allow those defaults to be overridden.
2407 if (rtc_options.offer_to_receive_audio != RTCOfferAnswerOptions::kUndefined) {
2408 recv_audio = (rtc_options.offer_to_receive_audio > 0);
deadbeef0ed85b22016-02-23 17:24:52 -08002409 }
zhihuang1c378ed2017-08-17 14:10:50 -07002410 if (rtc_options.offer_to_receive_video != RTCOfferAnswerOptions::kUndefined) {
2411 recv_video = (rtc_options.offer_to_receive_video > 0);
2412 }
2413
2414 rtc::Optional<size_t> audio_index;
2415 rtc::Optional<size_t> video_index;
2416 rtc::Optional<size_t> data_index;
Steve Anton75737c02017-11-06 10:37:17 -08002417 if (remote_description()) {
zhihuang141aacb2017-08-29 13:23:53 -07002418 // The pending remote description should be an offer.
Steve Anton75737c02017-11-06 10:37:17 -08002419 RTC_DCHECK(remote_description()->type() ==
zhihuang141aacb2017-08-29 13:23:53 -07002420 SessionDescriptionInterface::kOffer);
2421 // Generate m= sections that match those in the offer.
2422 // Note that mediasession.cc will handle intersection our preferred
2423 // direction with the offered direction.
2424 GenerateMediaDescriptionOptions(
Steve Anton75737c02017-11-06 10:37:17 -08002425 remote_description(),
zhihuang141aacb2017-08-29 13:23:53 -07002426 cricket::RtpTransceiverDirection(send_audio, recv_audio),
2427 cricket::RtpTransceiverDirection(send_video, recv_video), &audio_index,
2428 &video_index, &data_index, session_options);
2429 }
zhihuang1c378ed2017-08-17 14:10:50 -07002430
2431 cricket::MediaDescriptionOptions* audio_media_description_options =
2432 !audio_index ? nullptr
2433 : &session_options->media_description_options[*audio_index];
2434 cricket::MediaDescriptionOptions* video_media_description_options =
2435 !video_index ? nullptr
2436 : &session_options->media_description_options[*video_index];
2437 cricket::MediaDescriptionOptions* data_media_description_options =
2438 !data_index ? nullptr
2439 : &session_options->media_description_options[*data_index];
2440
2441 // Apply ICE renomination flag.
2442 for (auto& options : session_options->media_description_options) {
2443 options.transport_options.enable_ice_renomination =
2444 configuration_.enable_ice_renomination;
2445 }
2446
2447 AddRtpSenderOptions(senders_, audio_media_description_options,
2448 video_media_description_options);
2449 AddRtpDataChannelOptions(rtp_data_channels_, data_media_description_options);
2450
zhihuang9763d562016-08-05 11:14:50 -07002451 // Intentionally unset the data channel type for RTP data channel. Otherwise
2452 // the RTP data channels would be successfully negotiated by default and the
2453 // unit tests in WebRtcDataBrowserTest will fail when building with chromium.
2454 // We want to leave RTP data channels broken, so people won't try to use them.
Steve Anton75737c02017-11-06 10:37:17 -08002455 if (!rtp_data_channels_.empty() || data_channel_type() != cricket::DCT_RTP) {
2456 session_options->data_channel_type = data_channel_type();
deadbeef907abe42016-08-04 12:22:18 -07002457 }
zhihuangaf388472016-11-02 16:49:48 -07002458
zhihuang1c378ed2017-08-17 14:10:50 -07002459 session_options->rtcp_cname = rtcp_cname_;
jbauchcb560652016-08-04 05:20:32 -07002460 session_options->crypto_options = factory_->options().crypto_options;
htaa2a49d92016-03-04 02:51:39 -08002461}
2462
zhihuang1c378ed2017-08-17 14:10:50 -07002463void PeerConnection::GenerateMediaDescriptionOptions(
2464 const SessionDescriptionInterface* session_desc,
2465 cricket::RtpTransceiverDirection audio_direction,
2466 cricket::RtpTransceiverDirection video_direction,
2467 rtc::Optional<size_t>* audio_index,
2468 rtc::Optional<size_t>* video_index,
2469 rtc::Optional<size_t>* data_index,
htaa2a49d92016-03-04 02:51:39 -08002470 cricket::MediaSessionOptions* session_options) {
zhihuang1c378ed2017-08-17 14:10:50 -07002471 for (const cricket::ContentInfo& content :
2472 session_desc->description()->contents()) {
2473 if (IsAudioContent(&content)) {
2474 // If we already have an audio m= section, reject this extra one.
2475 if (*audio_index) {
2476 session_options->media_description_options.push_back(
2477 cricket::MediaDescriptionOptions(
2478 cricket::MEDIA_TYPE_AUDIO, content.name,
2479 cricket::RtpTransceiverDirection(false, false), true));
2480 } else {
2481 session_options->media_description_options.push_back(
2482 cricket::MediaDescriptionOptions(
2483 cricket::MEDIA_TYPE_AUDIO, content.name, audio_direction,
2484 !audio_direction.send && !audio_direction.recv));
2485 *audio_index = rtc::Optional<size_t>(
2486 session_options->media_description_options.size() - 1);
2487 }
2488 } else if (IsVideoContent(&content)) {
2489 // If we already have an video m= section, reject this extra one.
2490 if (*video_index) {
2491 session_options->media_description_options.push_back(
2492 cricket::MediaDescriptionOptions(
2493 cricket::MEDIA_TYPE_VIDEO, content.name,
2494 cricket::RtpTransceiverDirection(false, false), true));
2495 } else {
2496 session_options->media_description_options.push_back(
2497 cricket::MediaDescriptionOptions(
2498 cricket::MEDIA_TYPE_VIDEO, content.name, video_direction,
2499 !video_direction.send && !video_direction.recv));
2500 *video_index = rtc::Optional<size_t>(
2501 session_options->media_description_options.size() - 1);
2502 }
2503 } else {
2504 RTC_DCHECK(IsDataContent(&content));
2505 // If we already have an data m= section, reject this extra one.
2506 if (*data_index) {
2507 session_options->media_description_options.push_back(
2508 cricket::MediaDescriptionOptions(
2509 cricket::MEDIA_TYPE_DATA, content.name,
2510 cricket::RtpTransceiverDirection(false, false), true));
2511 } else {
2512 session_options->media_description_options.push_back(
2513 cricket::MediaDescriptionOptions(
2514 cricket::MEDIA_TYPE_DATA, content.name,
2515 // Direction for data sections is meaningless, but legacy
2516 // endpoints might expect sendrecv.
2517 cricket::RtpTransceiverDirection(true, true), false));
2518 *data_index = rtc::Optional<size_t>(
2519 session_options->media_description_options.size() - 1);
2520 }
2521 }
htaa2a49d92016-03-04 02:51:39 -08002522 }
deadbeefab9b2d12015-10-14 11:33:11 -07002523}
2524
deadbeeffaac4972015-11-12 15:33:07 -08002525void PeerConnection::RemoveTracks(cricket::MediaType media_type) {
2526 UpdateLocalTracks(std::vector<cricket::StreamParams>(), media_type);
deadbeefbda7e0b2015-12-08 17:13:40 -08002527 UpdateRemoteStreamsList(std::vector<cricket::StreamParams>(), false,
2528 media_type, nullptr);
deadbeeffaac4972015-11-12 15:33:07 -08002529}
2530
deadbeefab9b2d12015-10-14 11:33:11 -07002531void PeerConnection::UpdateRemoteStreamsList(
2532 const cricket::StreamParamsVec& streams,
deadbeefbda7e0b2015-12-08 17:13:40 -08002533 bool default_track_needed,
deadbeefab9b2d12015-10-14 11:33:11 -07002534 cricket::MediaType media_type,
2535 StreamCollection* new_streams) {
2536 TrackInfos* current_tracks = GetRemoteTracks(media_type);
2537
2538 // Find removed tracks. I.e., tracks where the track id or ssrc don't match
deadbeeffac06552015-11-25 11:26:01 -08002539 // the new StreamParam.
deadbeefab9b2d12015-10-14 11:33:11 -07002540 auto track_it = current_tracks->begin();
2541 while (track_it != current_tracks->end()) {
2542 const TrackInfo& info = *track_it;
2543 const cricket::StreamParams* params =
2544 cricket::GetStreamBySsrc(streams, info.ssrc);
deadbeefbda7e0b2015-12-08 17:13:40 -08002545 bool track_exists = params && params->id == info.track_id;
2546 // If this is a default track, and we still need it, don't remove it.
2547 if ((info.stream_label == kDefaultStreamLabel && default_track_needed) ||
2548 track_exists) {
2549 ++track_it;
2550 } else {
deadbeefab9b2d12015-10-14 11:33:11 -07002551 OnRemoteTrackRemoved(info.stream_label, info.track_id, media_type);
2552 track_it = current_tracks->erase(track_it);
deadbeefab9b2d12015-10-14 11:33:11 -07002553 }
2554 }
2555
2556 // Find new and active tracks.
2557 for (const cricket::StreamParams& params : streams) {
2558 // The sync_label is the MediaStream label and the |stream.id| is the
2559 // track id.
2560 const std::string& stream_label = params.sync_label;
2561 const std::string& track_id = params.id;
2562 uint32_t ssrc = params.first_ssrc();
2563
2564 rtc::scoped_refptr<MediaStreamInterface> stream =
2565 remote_streams_->find(stream_label);
2566 if (!stream) {
2567 // This is a new MediaStream. Create a new remote MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002568 stream = MediaStreamProxy::Create(rtc::Thread::Current(),
2569 MediaStream::Create(stream_label));
deadbeefab9b2d12015-10-14 11:33:11 -07002570 remote_streams_->AddStream(stream);
2571 new_streams->AddStream(stream);
2572 }
2573
2574 const TrackInfo* track_info =
2575 FindTrackInfo(*current_tracks, stream_label, track_id);
2576 if (!track_info) {
2577 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2578 OnRemoteTrackSeen(stream_label, track_id, ssrc, media_type);
2579 }
2580 }
deadbeefbda7e0b2015-12-08 17:13:40 -08002581
2582 // Add default track if necessary.
2583 if (default_track_needed) {
2584 rtc::scoped_refptr<MediaStreamInterface> default_stream =
2585 remote_streams_->find(kDefaultStreamLabel);
2586 if (!default_stream) {
2587 // Create the new default MediaStream.
perkjd61bf802016-03-24 03:16:19 -07002588 default_stream = MediaStreamProxy::Create(
2589 rtc::Thread::Current(), MediaStream::Create(kDefaultStreamLabel));
deadbeefbda7e0b2015-12-08 17:13:40 -08002590 remote_streams_->AddStream(default_stream);
2591 new_streams->AddStream(default_stream);
2592 }
2593 std::string default_track_id = (media_type == cricket::MEDIA_TYPE_AUDIO)
2594 ? kDefaultAudioTrackLabel
2595 : kDefaultVideoTrackLabel;
2596 const TrackInfo* default_track_info =
2597 FindTrackInfo(*current_tracks, kDefaultStreamLabel, default_track_id);
2598 if (!default_track_info) {
2599 current_tracks->push_back(
2600 TrackInfo(kDefaultStreamLabel, default_track_id, 0));
2601 OnRemoteTrackSeen(kDefaultStreamLabel, default_track_id, 0, media_type);
2602 }
2603 }
deadbeefab9b2d12015-10-14 11:33:11 -07002604}
2605
2606void PeerConnection::OnRemoteTrackSeen(const std::string& stream_label,
2607 const std::string& track_id,
2608 uint32_t ssrc,
2609 cricket::MediaType media_type) {
2610 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2611
2612 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002613 CreateAudioReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002614 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjf0dcfe22016-03-10 18:32:00 +01002615 CreateVideoReceiver(stream, track_id, ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002616 } else {
nisseeb4ca4e2017-01-12 02:24:27 -08002617 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002618 }
2619}
2620
2621void PeerConnection::OnRemoteTrackRemoved(const std::string& stream_label,
2622 const std::string& track_id,
2623 cricket::MediaType media_type) {
2624 MediaStreamInterface* stream = remote_streams_->find(stream_label);
2625
Henrik Boström933d8b02017-10-10 10:05:16 -07002626 rtc::scoped_refptr<RtpReceiverInterface> receiver;
deadbeefab9b2d12015-10-14 11:33:11 -07002627 if (media_type == cricket::MEDIA_TYPE_AUDIO) {
perkjd61bf802016-03-24 03:16:19 -07002628 // When the MediaEngine audio channel is destroyed, the RemoteAudioSource
2629 // will be notified which will end the AudioRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002630 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002631 rtc::scoped_refptr<AudioTrackInterface> audio_track =
2632 stream->FindAudioTrack(track_id);
2633 if (audio_track) {
deadbeefab9b2d12015-10-14 11:33:11 -07002634 stream->RemoveTrack(audio_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002635 }
2636 } else if (media_type == cricket::MEDIA_TYPE_VIDEO) {
perkjd61bf802016-03-24 03:16:19 -07002637 // Stopping or destroying a VideoRtpReceiver will end the
2638 // VideoRtpReceiver::track().
Henrik Boström933d8b02017-10-10 10:05:16 -07002639 receiver = RemoveAndStopReceiver(track_id);
deadbeefab9b2d12015-10-14 11:33:11 -07002640 rtc::scoped_refptr<VideoTrackInterface> video_track =
2641 stream->FindVideoTrack(track_id);
2642 if (video_track) {
perkjd61bf802016-03-24 03:16:19 -07002643 // There's no guarantee the track is still available, e.g. the track may
2644 // have been removed from the stream by an application.
deadbeefab9b2d12015-10-14 11:33:11 -07002645 stream->RemoveTrack(video_track);
deadbeefab9b2d12015-10-14 11:33:11 -07002646 }
2647 } else {
nisseede5da42017-01-12 05:15:36 -08002648 RTC_NOTREACHED() << "Invalid media type";
deadbeefab9b2d12015-10-14 11:33:11 -07002649 }
Henrik Boström933d8b02017-10-10 10:05:16 -07002650 if (receiver) {
2651 observer_->OnRemoveTrack(receiver);
2652 }
deadbeefab9b2d12015-10-14 11:33:11 -07002653}
2654
2655void PeerConnection::UpdateEndedRemoteMediaStreams() {
2656 std::vector<rtc::scoped_refptr<MediaStreamInterface>> streams_to_remove;
2657 for (size_t i = 0; i < remote_streams_->count(); ++i) {
2658 MediaStreamInterface* stream = remote_streams_->at(i);
2659 if (stream->GetAudioTracks().empty() && stream->GetVideoTracks().empty()) {
2660 streams_to_remove.push_back(stream);
2661 }
2662 }
2663
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002664 for (auto& stream : streams_to_remove) {
deadbeefab9b2d12015-10-14 11:33:11 -07002665 remote_streams_->RemoveStream(stream);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002666 observer_->OnRemoveStream(std::move(stream));
deadbeefab9b2d12015-10-14 11:33:11 -07002667 }
2668}
2669
deadbeefab9b2d12015-10-14 11:33:11 -07002670void PeerConnection::UpdateLocalTracks(
2671 const std::vector<cricket::StreamParams>& streams,
2672 cricket::MediaType media_type) {
2673 TrackInfos* current_tracks = GetLocalTracks(media_type);
2674
2675 // Find removed tracks. I.e., tracks where the track id, stream label or ssrc
2676 // don't match the new StreamParam.
2677 TrackInfos::iterator track_it = current_tracks->begin();
2678 while (track_it != current_tracks->end()) {
2679 const TrackInfo& info = *track_it;
2680 const cricket::StreamParams* params =
2681 cricket::GetStreamBySsrc(streams, info.ssrc);
2682 if (!params || params->id != info.track_id ||
2683 params->sync_label != info.stream_label) {
2684 OnLocalTrackRemoved(info.stream_label, info.track_id, info.ssrc,
2685 media_type);
2686 track_it = current_tracks->erase(track_it);
2687 } else {
2688 ++track_it;
2689 }
2690 }
2691
2692 // Find new and active tracks.
2693 for (const cricket::StreamParams& params : streams) {
2694 // The sync_label is the MediaStream label and the |stream.id| is the
2695 // track id.
2696 const std::string& stream_label = params.sync_label;
2697 const std::string& track_id = params.id;
2698 uint32_t ssrc = params.first_ssrc();
2699 const TrackInfo* track_info =
2700 FindTrackInfo(*current_tracks, stream_label, track_id);
2701 if (!track_info) {
2702 current_tracks->push_back(TrackInfo(stream_label, track_id, ssrc));
2703 OnLocalTrackSeen(stream_label, track_id, params.first_ssrc(), media_type);
2704 }
2705 }
2706}
2707
2708void PeerConnection::OnLocalTrackSeen(const std::string& stream_label,
2709 const std::string& track_id,
2710 uint32_t ssrc,
2711 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002712 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002713 if (!sender) {
2714 LOG(LS_WARNING) << "An unknown RtpSender with id " << track_id
2715 << " has been configured in the local description.";
deadbeefab9b2d12015-10-14 11:33:11 -07002716 return;
2717 }
2718
deadbeeffac06552015-11-25 11:26:01 -08002719 if (sender->media_type() != media_type) {
2720 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2721 << " description with an unexpected media type.";
2722 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002723 }
deadbeeffac06552015-11-25 11:26:01 -08002724
2725 sender->set_stream_id(stream_label);
2726 sender->SetSsrc(ssrc);
deadbeefab9b2d12015-10-14 11:33:11 -07002727}
2728
2729void PeerConnection::OnLocalTrackRemoved(const std::string& stream_label,
2730 const std::string& track_id,
2731 uint32_t ssrc,
2732 cricket::MediaType media_type) {
deadbeefa601f5c2016-06-06 14:27:39 -07002733 RtpSenderInternal* sender = FindSenderById(track_id);
deadbeeffac06552015-11-25 11:26:01 -08002734 if (!sender) {
2735 // This is the normal case. I.e., RemoveStream has been called and the
deadbeefab9b2d12015-10-14 11:33:11 -07002736 // SessionDescriptions has been renegotiated.
2737 return;
2738 }
deadbeeffac06552015-11-25 11:26:01 -08002739
2740 // A sender has been removed from the SessionDescription but it's still
2741 // associated with the PeerConnection. This only occurs if the SDP doesn't
2742 // match with the calls to CreateSender, AddStream and RemoveStream.
2743 if (sender->media_type() != media_type) {
2744 LOG(LS_WARNING) << "An RtpSender has been configured in the local"
2745 << " description with an unexpected media type.";
2746 return;
deadbeefab9b2d12015-10-14 11:33:11 -07002747 }
deadbeeffac06552015-11-25 11:26:01 -08002748
2749 sender->SetSsrc(0);
deadbeefab9b2d12015-10-14 11:33:11 -07002750}
2751
2752void PeerConnection::UpdateLocalRtpDataChannels(
2753 const cricket::StreamParamsVec& streams) {
2754 std::vector<std::string> existing_channels;
2755
2756 // Find new and active data channels.
2757 for (const cricket::StreamParams& params : streams) {
2758 // |it->sync_label| is actually the data channel label. The reason is that
2759 // we use the same naming of data channels as we do for
2760 // MediaStreams and Tracks.
2761 // For MediaStreams, the sync_label is the MediaStream label and the
2762 // track label is the same as |streamid|.
2763 const std::string& channel_label = params.sync_label;
2764 auto data_channel_it = rtp_data_channels_.find(channel_label);
nisse7ce109a2017-01-31 00:57:56 -08002765 if (data_channel_it == rtp_data_channels_.end()) {
2766 LOG(LS_ERROR) << "channel label not found";
deadbeefab9b2d12015-10-14 11:33:11 -07002767 continue;
2768 }
2769 // Set the SSRC the data channel should use for sending.
2770 data_channel_it->second->SetSendSsrc(params.first_ssrc());
2771 existing_channels.push_back(data_channel_it->first);
2772 }
2773
2774 UpdateClosingRtpDataChannels(existing_channels, true);
2775}
2776
2777void PeerConnection::UpdateRemoteRtpDataChannels(
2778 const cricket::StreamParamsVec& streams) {
2779 std::vector<std::string> existing_channels;
2780
2781 // Find new and active data channels.
2782 for (const cricket::StreamParams& params : streams) {
2783 // The data channel label is either the mslabel or the SSRC if the mslabel
2784 // does not exist. Ex a=ssrc:444330170 mslabel:test1.
2785 std::string label = params.sync_label.empty()
2786 ? rtc::ToString(params.first_ssrc())
2787 : params.sync_label;
2788 auto data_channel_it = rtp_data_channels_.find(label);
2789 if (data_channel_it == rtp_data_channels_.end()) {
2790 // This is a new data channel.
2791 CreateRemoteRtpDataChannel(label, params.first_ssrc());
2792 } else {
2793 data_channel_it->second->SetReceiveSsrc(params.first_ssrc());
2794 }
2795 existing_channels.push_back(label);
2796 }
2797
2798 UpdateClosingRtpDataChannels(existing_channels, false);
2799}
2800
2801void PeerConnection::UpdateClosingRtpDataChannels(
2802 const std::vector<std::string>& active_channels,
2803 bool is_local_update) {
2804 auto it = rtp_data_channels_.begin();
2805 while (it != rtp_data_channels_.end()) {
2806 DataChannel* data_channel = it->second;
2807 if (std::find(active_channels.begin(), active_channels.end(),
2808 data_channel->label()) != active_channels.end()) {
2809 ++it;
2810 continue;
2811 }
2812
2813 if (is_local_update) {
2814 data_channel->SetSendSsrc(0);
2815 } else {
2816 data_channel->RemotePeerRequestClose();
2817 }
2818
2819 if (data_channel->state() == DataChannel::kClosed) {
2820 rtp_data_channels_.erase(it);
2821 it = rtp_data_channels_.begin();
2822 } else {
2823 ++it;
2824 }
2825 }
2826}
2827
2828void PeerConnection::CreateRemoteRtpDataChannel(const std::string& label,
2829 uint32_t remote_ssrc) {
2830 rtc::scoped_refptr<DataChannel> channel(
2831 InternalCreateDataChannel(label, nullptr));
2832 if (!channel.get()) {
2833 LOG(LS_WARNING) << "Remote peer requested a DataChannel but"
2834 << "CreateDataChannel failed.";
2835 return;
2836 }
2837 channel->SetReceiveSsrc(remote_ssrc);
deadbeefa601f5c2016-06-06 14:27:39 -07002838 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2839 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002840 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002841}
2842
2843rtc::scoped_refptr<DataChannel> PeerConnection::InternalCreateDataChannel(
2844 const std::string& label,
2845 const InternalDataChannelInit* config) {
2846 if (IsClosed()) {
2847 return nullptr;
2848 }
Steve Anton75737c02017-11-06 10:37:17 -08002849 if (data_channel_type() == cricket::DCT_NONE) {
deadbeefab9b2d12015-10-14 11:33:11 -07002850 LOG(LS_ERROR)
2851 << "InternalCreateDataChannel: Data is not supported in this call.";
2852 return nullptr;
2853 }
2854 InternalDataChannelInit new_config =
2855 config ? (*config) : InternalDataChannelInit();
Steve Anton75737c02017-11-06 10:37:17 -08002856 if (data_channel_type() == cricket::DCT_SCTP) {
deadbeefab9b2d12015-10-14 11:33:11 -07002857 if (new_config.id < 0) {
2858 rtc::SSLRole role;
Steve Anton75737c02017-11-06 10:37:17 -08002859 if ((GetSctpSslRole(&role)) &&
deadbeefab9b2d12015-10-14 11:33:11 -07002860 !sid_allocator_.AllocateSid(role, &new_config.id)) {
2861 LOG(LS_ERROR) << "No id can be allocated for the SCTP data channel.";
2862 return nullptr;
2863 }
2864 } else if (!sid_allocator_.ReserveSid(new_config.id)) {
2865 LOG(LS_ERROR) << "Failed to create a SCTP data channel "
2866 << "because the id is already in use or out of range.";
2867 return nullptr;
2868 }
2869 }
2870
Steve Anton75737c02017-11-06 10:37:17 -08002871 rtc::scoped_refptr<DataChannel> channel(
2872 DataChannel::Create(this, data_channel_type(), label, new_config));
deadbeefab9b2d12015-10-14 11:33:11 -07002873 if (!channel) {
2874 sid_allocator_.ReleaseSid(new_config.id);
2875 return nullptr;
2876 }
2877
2878 if (channel->data_channel_type() == cricket::DCT_RTP) {
2879 if (rtp_data_channels_.find(channel->label()) != rtp_data_channels_.end()) {
2880 LOG(LS_ERROR) << "DataChannel with label " << channel->label()
2881 << " already exists.";
2882 return nullptr;
2883 }
2884 rtp_data_channels_[channel->label()] = channel;
2885 } else {
2886 RTC_DCHECK(channel->data_channel_type() == cricket::DCT_SCTP);
2887 sctp_data_channels_.push_back(channel);
2888 channel->SignalClosed.connect(this,
2889 &PeerConnection::OnSctpDataChannelClosed);
2890 }
2891
hbos82ebe022016-11-14 01:41:09 -08002892 SignalDataChannelCreated(channel.get());
deadbeefab9b2d12015-10-14 11:33:11 -07002893 return channel;
2894}
2895
2896bool PeerConnection::HasDataChannels() const {
2897 return !rtp_data_channels_.empty() || !sctp_data_channels_.empty();
2898}
2899
2900void PeerConnection::AllocateSctpSids(rtc::SSLRole role) {
2901 for (const auto& channel : sctp_data_channels_) {
2902 if (channel->id() < 0) {
2903 int sid;
2904 if (!sid_allocator_.AllocateSid(role, &sid)) {
2905 LOG(LS_ERROR) << "Failed to allocate SCTP sid.";
2906 continue;
2907 }
2908 channel->SetSctpSid(sid);
2909 }
2910 }
2911}
2912
2913void PeerConnection::OnSctpDataChannelClosed(DataChannel* channel) {
deadbeefbd292462015-12-14 18:15:29 -08002914 RTC_DCHECK(signaling_thread()->IsCurrent());
deadbeefab9b2d12015-10-14 11:33:11 -07002915 for (auto it = sctp_data_channels_.begin(); it != sctp_data_channels_.end();
2916 ++it) {
2917 if (it->get() == channel) {
2918 if (channel->id() >= 0) {
2919 sid_allocator_.ReleaseSid(channel->id());
2920 }
deadbeefbd292462015-12-14 18:15:29 -08002921 // Since this method is triggered by a signal from the DataChannel,
2922 // we can't free it directly here; we need to free it asynchronously.
2923 sctp_data_channels_to_free_.push_back(*it);
deadbeefab9b2d12015-10-14 11:33:11 -07002924 sctp_data_channels_.erase(it);
Taylor Brandstetter5d97a9a2016-06-10 14:17:27 -07002925 signaling_thread()->Post(RTC_FROM_HERE, this, MSG_FREE_DATACHANNELS,
2926 nullptr);
deadbeefab9b2d12015-10-14 11:33:11 -07002927 return;
2928 }
2929 }
2930}
2931
deadbeefab9b2d12015-10-14 11:33:11 -07002932void PeerConnection::OnDataChannelDestroyed() {
2933 // Use a temporary copy of the RTP/SCTP DataChannel list because the
2934 // DataChannel may callback to us and try to modify the list.
2935 std::map<std::string, rtc::scoped_refptr<DataChannel>> temp_rtp_dcs;
2936 temp_rtp_dcs.swap(rtp_data_channels_);
2937 for (const auto& kv : temp_rtp_dcs) {
2938 kv.second->OnTransportChannelDestroyed();
2939 }
2940
2941 std::vector<rtc::scoped_refptr<DataChannel>> temp_sctp_dcs;
2942 temp_sctp_dcs.swap(sctp_data_channels_);
2943 for (const auto& channel : temp_sctp_dcs) {
2944 channel->OnTransportChannelDestroyed();
2945 }
2946}
2947
2948void PeerConnection::OnDataChannelOpenMessage(
2949 const std::string& label,
2950 const InternalDataChannelInit& config) {
2951 rtc::scoped_refptr<DataChannel> channel(
2952 InternalCreateDataChannel(label, &config));
2953 if (!channel.get()) {
2954 LOG(LS_ERROR) << "Failed to create DataChannel from the OPEN message.";
2955 return;
2956 }
2957
deadbeefa601f5c2016-06-06 14:27:39 -07002958 rtc::scoped_refptr<DataChannelInterface> proxy_channel =
2959 DataChannelProxy::Create(signaling_thread(), channel);
Taylor Brandstetter98cde262016-05-31 13:02:21 -07002960 observer_->OnDataChannel(std::move(proxy_channel));
deadbeefab9b2d12015-10-14 11:33:11 -07002961}
2962
zhihuang1c378ed2017-08-17 14:10:50 -07002963bool PeerConnection::HasRtpSender(cricket::MediaType type) const {
2964 return std::find_if(
2965 senders_.begin(), senders_.end(),
2966 [type](const rtc::scoped_refptr<
2967 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2968 return sender->media_type() == type;
2969 }) != senders_.end();
2970}
2971
deadbeefa601f5c2016-06-06 14:27:39 -07002972RtpSenderInternal* PeerConnection::FindSenderById(const std::string& id) {
2973 auto it = std::find_if(
2974 senders_.begin(), senders_.end(),
2975 [id](const rtc::scoped_refptr<
2976 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
2977 return sender->id() == id;
2978 });
2979 return it != senders_.end() ? (*it)->internal() : nullptr;
deadbeeffac06552015-11-25 11:26:01 -08002980}
2981
deadbeefa601f5c2016-06-06 14:27:39 -07002982std::vector<
2983 rtc::scoped_refptr<RtpSenderProxyWithInternal<RtpSenderInternal>>>::iterator
deadbeef70ab1a12015-09-28 16:53:55 -07002984PeerConnection::FindSenderForTrack(MediaStreamTrackInterface* track) {
2985 return std::find_if(
2986 senders_.begin(), senders_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002987 [track](const rtc::scoped_refptr<
2988 RtpSenderProxyWithInternal<RtpSenderInternal>>& sender) {
deadbeef70ab1a12015-09-28 16:53:55 -07002989 return sender->track() == track;
2990 });
2991}
2992
deadbeefa601f5c2016-06-06 14:27:39 -07002993std::vector<rtc::scoped_refptr<
2994 RtpReceiverProxyWithInternal<RtpReceiverInternal>>>::iterator
perkjd61bf802016-03-24 03:16:19 -07002995PeerConnection::FindReceiverForTrack(const std::string& track_id) {
deadbeef70ab1a12015-09-28 16:53:55 -07002996 return std::find_if(
2997 receivers_.begin(), receivers_.end(),
deadbeefa601f5c2016-06-06 14:27:39 -07002998 [track_id](const rtc::scoped_refptr<
2999 RtpReceiverProxyWithInternal<RtpReceiverInternal>>& receiver) {
perkjd61bf802016-03-24 03:16:19 -07003000 return receiver->id() == track_id;
deadbeef70ab1a12015-09-28 16:53:55 -07003001 });
3002}
3003
deadbeefab9b2d12015-10-14 11:33:11 -07003004PeerConnection::TrackInfos* PeerConnection::GetRemoteTracks(
3005 cricket::MediaType media_type) {
3006 RTC_DCHECK(media_type == cricket::MEDIA_TYPE_AUDIO ||
3007 media_type == cricket::MEDIA_TYPE_VIDEO);
3008 return (media_type == cricket::MEDIA_TYPE_AUDIO) ? &remote_audio_tracks_
3009 : &remote_video_tracks_;
3010}
3011
3012PeerConnection::TrackInfos* PeerConnection::GetLocalTracks(
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) ? &local_audio_tracks_
3017 : &local_video_tracks_;
3018}
3019
3020const PeerConnection::TrackInfo* PeerConnection::FindTrackInfo(
3021 const PeerConnection::TrackInfos& infos,
3022 const std::string& stream_label,
3023 const std::string track_id) const {
3024 for (const TrackInfo& track_info : infos) {
3025 if (track_info.stream_label == stream_label &&
3026 track_info.track_id == track_id) {
3027 return &track_info;
3028 }
3029 }
3030 return nullptr;
3031}
3032
3033DataChannel* PeerConnection::FindDataChannelBySid(int sid) const {
3034 for (const auto& channel : sctp_data_channels_) {
3035 if (channel->id() == sid) {
3036 return channel;
3037 }
3038 }
3039 return nullptr;
3040}
3041
deadbeef91dd5672016-05-18 16:55:30 -07003042bool PeerConnection::InitializePortAllocator_n(
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003043 const RTCConfiguration& configuration) {
3044 cricket::ServerAddresses stun_servers;
3045 std::vector<cricket::RelayServerConfig> turn_servers;
deadbeef293e9262017-01-11 12:28:30 -08003046 if (ParseIceServers(configuration.servers, &stun_servers, &turn_servers) !=
3047 RTCErrorType::NONE) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003048 return false;
3049 }
3050
Taylor Brandstetterf8e65772016-06-27 17:20:15 -07003051 port_allocator_->Initialize();
3052
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003053 // To handle both internal and externally created port allocator, we will
3054 // enable BUNDLE here.
3055 int portallocator_flags = port_allocator_->flags();
3056 portallocator_flags |= cricket::PORTALLOCATOR_ENABLE_SHARED_SOCKET |
zhihuangb09b3f92017-03-07 14:40:51 -08003057 cricket::PORTALLOCATOR_ENABLE_IPV6 |
3058 cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI;
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003059 // If the disable-IPv6 flag was specified, we'll not override it
3060 // by experiment.
3061 if (configuration.disable_ipv6) {
3062 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
sprangc1b57a12017-02-28 08:50:47 -08003063 } else if (webrtc::field_trial::FindFullName("WebRTC-IPv6Default")
3064 .find("Disabled") == 0) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003065 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6);
3066 }
3067
zhihuangb09b3f92017-03-07 14:40:51 -08003068 if (configuration.disable_ipv6_on_wifi) {
3069 portallocator_flags &= ~(cricket::PORTALLOCATOR_ENABLE_IPV6_ON_WIFI);
3070 LOG(LS_INFO) << "IPv6 candidates on Wi-Fi are disabled.";
3071 }
3072
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003073 if (configuration.tcp_candidate_policy == kTcpCandidatePolicyDisabled) {
3074 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_TCP;
3075 LOG(LS_INFO) << "TCP candidates are disabled.";
3076 }
3077
honghaiz60347052016-05-31 18:29:12 -07003078 if (configuration.candidate_network_policy ==
3079 kCandidateNetworkPolicyLowCost) {
3080 portallocator_flags |= cricket::PORTALLOCATOR_DISABLE_COSTLY_NETWORKS;
3081 LOG(LS_INFO) << "Do not gather candidates on high-cost networks";
3082 }
3083
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003084 port_allocator_->set_flags(portallocator_flags);
3085 // No step delay is used while allocating ports.
3086 port_allocator_->set_step_delay(cricket::kMinimumStepDelay);
3087 port_allocator_->set_candidate_filter(
3088 ConvertIceTransportTypeToCandidateFilter(configuration.type));
deadbeefd21eab32017-07-26 16:50:11 -07003089 port_allocator_->set_max_ipv6_networks(configuration.max_ipv6_networks);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003090
3091 // Call this last since it may create pooled allocator sessions using the
3092 // properties set above.
3093 port_allocator_->SetConfiguration(stun_servers, turn_servers,
Honghai Zhangb9e7b4a2016-06-30 20:52:02 -07003094 configuration.ice_candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003095 configuration.prune_turn_ports,
3096 configuration.turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003097 return true;
3098}
3099
deadbeef91dd5672016-05-18 16:55:30 -07003100bool PeerConnection::ReconfigurePortAllocator_n(
deadbeef293e9262017-01-11 12:28:30 -08003101 const cricket::ServerAddresses& stun_servers,
3102 const std::vector<cricket::RelayServerConfig>& turn_servers,
3103 IceTransportsType type,
3104 int candidate_pool_size,
Jonas Orelandbdcee282017-10-10 14:01:40 +02003105 bool prune_turn_ports,
3106 webrtc::TurnCustomizer* turn_customizer) {
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003107 port_allocator_->set_candidate_filter(
deadbeef293e9262017-01-11 12:28:30 -08003108 ConvertIceTransportTypeToCandidateFilter(type));
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003109 // Call this last since it may create pooled allocator sessions using the
3110 // candidate filter set above.
deadbeef6de92f92016-12-12 18:49:32 -08003111 return port_allocator_->SetConfiguration(
Jonas Orelandbdcee282017-10-10 14:01:40 +02003112 stun_servers, turn_servers, candidate_pool_size, prune_turn_ports,
3113 turn_customizer);
Taylor Brandstettera1c30352016-05-13 08:15:11 -07003114}
3115
Steve Antonba818672017-11-06 10:21:57 -08003116cricket::ChannelManager* PeerConnection::channel_manager() const {
3117 return factory_->channel_manager();
3118}
3119
3120MetricsObserverInterface* PeerConnection::metrics_observer() const {
3121 return uma_observer_;
3122}
3123
Elad Alon99c3fe52017-10-13 16:29:40 +02003124bool PeerConnection::StartRtcEventLog_w(
3125 std::unique_ptr<RtcEventLogOutput> output) {
zhihuang77985012017-02-07 15:45:16 -08003126 if (!event_log_) {
3127 return false;
3128 }
Elad Alon99c3fe52017-10-13 16:29:40 +02003129 return event_log_->StartLogging(std::move(output));
ivoc14d5dbe2016-07-04 07:06:55 -07003130}
3131
3132void PeerConnection::StopRtcEventLog_w() {
zhihuang77985012017-02-07 15:45:16 -08003133 if (event_log_) {
3134 event_log_->StopLogging();
3135 }
ivoc14d5dbe2016-07-04 07:06:55 -07003136}
nisseeaabdf62017-05-05 02:23:02 -07003137
Steve Anton75737c02017-11-06 10:37:17 -08003138cricket::BaseChannel* PeerConnection::GetChannel(
3139 const std::string& content_name) {
3140 if (voice_channel() && voice_channel()->content_name() == content_name) {
3141 return voice_channel();
3142 }
3143 if (video_channel() && video_channel()->content_name() == content_name) {
3144 return video_channel();
3145 }
3146 if (rtp_data_channel() &&
3147 rtp_data_channel()->content_name() == content_name) {
3148 return rtp_data_channel();
3149 }
3150 return nullptr;
3151}
3152
3153bool PeerConnection::GetSctpSslRole(rtc::SSLRole* role) {
3154 if (!local_description() || !remote_description()) {
3155 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get the "
3156 << "SSL Role of the SCTP transport.";
3157 return false;
3158 }
3159 if (!sctp_transport_) {
3160 LOG(LS_INFO) << "Non-rejected SCTP m= section is needed to get the "
3161 << "SSL Role of the SCTP transport.";
3162 return false;
3163 }
3164
3165 return transport_controller_->GetSslRole(*sctp_transport_name_, role);
3166}
3167
3168bool PeerConnection::GetSslRole(const std::string& content_name,
3169 rtc::SSLRole* role) {
3170 if (!local_description() || !remote_description()) {
3171 LOG(LS_INFO) << "Local and Remote descriptions must be applied to get the "
3172 << "SSL Role of the session.";
3173 return false;
3174 }
3175
3176 return transport_controller_->GetSslRole(GetTransportName(content_name),
3177 role);
3178}
3179
Steve Anton75737c02017-11-06 10:37:17 -08003180bool PeerConnection::SetLocalDescription(
3181 std::unique_ptr<SessionDescriptionInterface> desc,
3182 std::string* err_desc) {
3183 RTC_DCHECK(signaling_thread()->IsCurrent());
3184
3185 // Validate SDP.
3186 if (!ValidateSessionDescription(desc.get(), cricket::CS_LOCAL, err_desc)) {
3187 return false;
3188 }
3189
3190 // Update the initial_offerer flag if this session is the initial_offerer.
3191 Action action = GetAction(desc->type());
3192 if (!initial_offerer_.has_value()) {
3193 initial_offerer_.emplace(action == kOffer);
3194 if (*initial_offerer_) {
3195 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLING);
3196 } else {
3197 transport_controller_->SetIceRole(cricket::ICEROLE_CONTROLLED);
3198 }
3199 }
3200
3201 if (action == kAnswer) {
3202 current_local_description_ = std::move(desc);
3203 pending_local_description_ = nullptr;
3204 current_remote_description_ = std::move(pending_remote_description_);
3205 } else {
3206 pending_local_description_ = std::move(desc);
3207 }
3208
3209 // Transport and Media channels will be created only when offer is set.
3210 if (action == kOffer && !CreateChannels(local_description()->description())) {
3211 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3212 // is applied. Restore back to old description.
3213 return BadLocalSdp(local_description()->type(), kCreateChannelFailed,
3214 err_desc);
3215 }
3216
3217 // Remove unused channels if MediaContentDescription is rejected.
3218 RemoveUnusedChannels(local_description()->description());
3219
3220 if (!UpdateSessionState(action, cricket::CS_LOCAL, err_desc)) {
3221 return false;
3222 }
3223 if (remote_description()) {
3224 // Now that we have a local description, we can push down remote candidates.
3225 UseCandidatesInSessionDescription(remote_description());
3226 }
3227
3228 pending_ice_restarts_.clear();
3229 if (error() != ERROR_NONE) {
3230 return BadLocalSdp(local_description()->type(), GetSessionErrorMsg(),
3231 err_desc);
3232 }
3233 return true;
3234}
3235
3236bool PeerConnection::SetRemoteDescription(
3237 std::unique_ptr<SessionDescriptionInterface> desc,
3238 std::string* err_desc) {
3239 RTC_DCHECK(signaling_thread()->IsCurrent());
3240
3241 // Validate SDP.
3242 if (!ValidateSessionDescription(desc.get(), cricket::CS_REMOTE, err_desc)) {
3243 return false;
3244 }
3245
3246 // Hold this pointer so candidates can be copied to it later in the method.
3247 SessionDescriptionInterface* desc_ptr = desc.get();
3248
3249 const SessionDescriptionInterface* old_remote_description =
3250 remote_description();
3251 // Grab ownership of the description being replaced for the remainder of this
3252 // method, since it's used below as |old_remote_description|.
3253 std::unique_ptr<SessionDescriptionInterface> replaced_remote_description;
3254 Action action = GetAction(desc->type());
3255 if (action == kAnswer) {
3256 replaced_remote_description = pending_remote_description_
3257 ? std::move(pending_remote_description_)
3258 : std::move(current_remote_description_);
3259 current_remote_description_ = std::move(desc);
3260 pending_remote_description_ = nullptr;
3261 current_local_description_ = std::move(pending_local_description_);
3262 } else {
3263 replaced_remote_description = std::move(pending_remote_description_);
3264 pending_remote_description_ = std::move(desc);
3265 }
3266
3267 // Transport and Media channels will be created only when offer is set.
3268 if (action == kOffer &&
3269 !CreateChannels(remote_description()->description())) {
3270 // TODO(mallinath) - Handle CreateChannel failure, as new local description
3271 // is applied. Restore back to old description.
3272 return BadRemoteSdp(remote_description()->type(), kCreateChannelFailed,
3273 err_desc);
3274 }
3275
3276 // Remove unused channels if MediaContentDescription is rejected.
3277 RemoveUnusedChannels(remote_description()->description());
3278
3279 // NOTE: Candidates allocation will be initiated only when SetLocalDescription
3280 // is called.
3281 if (!UpdateSessionState(action, cricket::CS_REMOTE, err_desc)) {
3282 return false;
3283 }
3284
3285 if (local_description() &&
3286 !UseCandidatesInSessionDescription(remote_description())) {
3287 return BadRemoteSdp(remote_description()->type(), kInvalidCandidates,
3288 err_desc);
3289 }
3290
3291 if (old_remote_description) {
3292 for (const cricket::ContentInfo& content :
3293 old_remote_description->description()->contents()) {
3294 // Check if this new SessionDescription contains new ICE ufrag and
3295 // password that indicates the remote peer requests an ICE restart.
3296 // TODO(deadbeef): When we start storing both the current and pending
3297 // remote description, this should reset pending_ice_restarts and compare
3298 // against the current description.
3299 if (CheckForRemoteIceRestart(old_remote_description, remote_description(),
3300 content.name)) {
3301 if (action == kOffer) {
3302 pending_ice_restarts_.insert(content.name);
3303 }
3304 } else {
3305 // We retain all received candidates only if ICE is not restarted.
3306 // When ICE is restarted, all previous candidates belong to an old
3307 // generation and should not be kept.
3308 // TODO(deadbeef): This goes against the W3C spec which says the remote
3309 // description should only contain candidates from the last set remote
3310 // description plus any candidates added since then. We should remove
3311 // this once we're sure it won't break anything.
3312 WebRtcSessionDescriptionFactory::CopyCandidatesFromSessionDescription(
3313 old_remote_description, content.name, desc_ptr);
3314 }
3315 }
3316 }
3317
3318 if (error() != ERROR_NONE) {
3319 return BadRemoteSdp(remote_description()->type(), GetSessionErrorMsg(),
3320 err_desc);
3321 }
3322
3323 // Set the the ICE connection state to connecting since the connection may
3324 // become writable with peer reflexive candidates before any remote candidate
3325 // is signaled.
3326 // TODO(pthatcher): This is a short-term solution for crbug/446908. A real fix
3327 // is to have a new signal the indicates a change in checking state from the
3328 // transport and expose a new checking() member from transport that can be
3329 // read to determine the current checking state. The existing SignalConnecting
3330 // actually means "gathering candidates", so cannot be be used here.
3331 if (remote_description()->type() != SessionDescriptionInterface::kOffer &&
3332 ice_connection_state() == PeerConnectionInterface::kIceConnectionNew) {
3333 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
3334 }
3335 return true;
3336}
3337
3338// TODO(steveanton): Eventually it'd be nice to store the channels as a single
3339// vector of BaseChannel pointers instead of separate voice and video channel
3340// vectors. At that point, this will become a simple getter.
3341std::vector<cricket::BaseChannel*> PeerConnection::Channels() const {
3342 std::vector<cricket::BaseChannel*> channels;
3343 channels.insert(channels.end(), voice_channels_.begin(),
3344 voice_channels_.end());
3345 channels.insert(channels.end(), video_channels_.begin(),
3346 video_channels_.end());
3347 if (rtp_data_channel_) {
3348 channels.push_back(rtp_data_channel_);
3349 }
3350 return channels;
3351}
3352
3353void PeerConnection::SetError(Error error, const std::string& error_desc) {
3354 RTC_DCHECK(signaling_thread()->IsCurrent());
3355 if (error != error_) {
3356 error_ = error;
3357 error_desc_ = error_desc;
3358 }
3359}
3360
3361bool PeerConnection::UpdateSessionState(Action action,
3362 cricket::ContentSource source,
3363 std::string* err_desc) {
3364 RTC_DCHECK(signaling_thread()->IsCurrent());
3365
3366 // If there's already a pending error then no state transition should happen.
3367 // But all call-sites should be verifying this before calling us!
3368 RTC_DCHECK(error() == ERROR_NONE);
3369 std::string td_err;
3370 if (action == kOffer) {
3371 if (!PushdownTransportDescription(source, cricket::CA_OFFER, &td_err)) {
3372 return BadOfferSdp(source, MakeTdErrorString(td_err), err_desc);
3373 }
3374 ChangeSignalingState(source == cricket::CS_LOCAL
3375 ? PeerConnectionInterface::kHaveLocalOffer
3376 : PeerConnectionInterface::kHaveRemoteOffer);
3377 if (!PushdownMediaDescription(cricket::CA_OFFER, source, err_desc)) {
3378 SetError(ERROR_CONTENT, *err_desc);
3379 }
3380 if (error() != ERROR_NONE) {
3381 return BadOfferSdp(source, GetSessionErrorMsg(), err_desc);
3382 }
3383 } else if (action == kPrAnswer) {
3384 if (!PushdownTransportDescription(source, cricket::CA_PRANSWER, &td_err)) {
3385 return BadPranswerSdp(source, MakeTdErrorString(td_err), err_desc);
3386 }
3387 EnableChannels();
3388 ChangeSignalingState(source == cricket::CS_LOCAL
3389 ? PeerConnectionInterface::kHaveLocalPrAnswer
3390 : PeerConnectionInterface::kHaveRemotePrAnswer);
3391 if (!PushdownMediaDescription(cricket::CA_PRANSWER, source, err_desc)) {
3392 SetError(ERROR_CONTENT, *err_desc);
3393 }
3394 if (error() != ERROR_NONE) {
3395 return BadPranswerSdp(source, GetSessionErrorMsg(), err_desc);
3396 }
3397 } else if (action == kAnswer) {
3398 const cricket::ContentGroup* local_bundle =
3399 local_description()->description()->GetGroupByName(
3400 cricket::GROUP_TYPE_BUNDLE);
3401 const cricket::ContentGroup* remote_bundle =
3402 remote_description()->description()->GetGroupByName(
3403 cricket::GROUP_TYPE_BUNDLE);
3404 if (local_bundle && remote_bundle) {
3405 // The answerer decides the transport to bundle on.
3406 const cricket::ContentGroup* answer_bundle =
3407 (source == cricket::CS_LOCAL ? local_bundle : remote_bundle);
3408 if (!EnableBundle(*answer_bundle)) {
3409 LOG(LS_WARNING) << "Failed to enable BUNDLE.";
3410 return BadAnswerSdp(source, kEnableBundleFailed, err_desc);
3411 }
3412 }
3413 // Only push down the transport description after enabling BUNDLE; we don't
3414 // want to push down a description on a transport about to be destroyed.
3415 if (!PushdownTransportDescription(source, cricket::CA_ANSWER, &td_err)) {
3416 return BadAnswerSdp(source, MakeTdErrorString(td_err), err_desc);
3417 }
3418 EnableChannels();
3419 ChangeSignalingState(PeerConnectionInterface::kStable);
3420 if (!PushdownMediaDescription(cricket::CA_ANSWER, source, err_desc)) {
3421 SetError(ERROR_CONTENT, *err_desc);
3422 }
3423 if (error() != ERROR_NONE) {
3424 return BadAnswerSdp(source, GetSessionErrorMsg(), err_desc);
3425 }
3426 }
3427 return true;
3428}
3429
3430PeerConnection::Action PeerConnection::GetAction(const std::string& type) {
3431 if (type == SessionDescriptionInterface::kOffer) {
3432 return PeerConnection::kOffer;
3433 } else if (type == SessionDescriptionInterface::kPrAnswer) {
3434 return PeerConnection::kPrAnswer;
3435 } else if (type == SessionDescriptionInterface::kAnswer) {
3436 return PeerConnection::kAnswer;
3437 }
3438 RTC_NOTREACHED() << "unknown action type";
3439 return PeerConnection::kOffer;
3440}
3441
3442bool PeerConnection::PushdownMediaDescription(cricket::ContentAction action,
3443 cricket::ContentSource source,
3444 std::string* err) {
3445 const SessionDescription* sdesc =
3446 (source == cricket::CS_LOCAL ? local_description() : remote_description())
3447 ->description();
3448 RTC_DCHECK(sdesc);
3449 bool all_success = true;
3450 for (auto* channel : Channels()) {
3451 // TODO(steveanton): Add support for multiple channels of the same type.
3452 const ContentInfo* content_info =
3453 cricket::GetFirstMediaContent(sdesc->contents(), channel->media_type());
3454 if (!content_info) {
3455 continue;
3456 }
3457 const MediaContentDescription* content_desc =
3458 static_cast<const MediaContentDescription*>(content_info->description);
3459 if (content_desc && !content_info->rejected) {
3460 bool success = (source == cricket::CS_LOCAL)
3461 ? channel->SetLocalContent(content_desc, action, err)
3462 : channel->SetRemoteContent(content_desc, action, err);
3463 if (!success) {
3464 all_success = false;
3465 break;
3466 }
3467 }
3468 }
3469 // Need complete offer/answer with an SCTP m= section before starting SCTP,
3470 // according to https://tools.ietf.org/html/draft-ietf-mmusic-sctp-sdp-19
3471 if (sctp_transport_ && local_description() && remote_description() &&
3472 cricket::GetFirstDataContent(local_description()->description()) &&
3473 cricket::GetFirstDataContent(remote_description()->description())) {
3474 all_success &= network_thread()->Invoke<bool>(
3475 RTC_FROM_HERE,
3476 rtc::Bind(&PeerConnection::PushdownSctpParameters_n, this, source));
3477 }
3478 return all_success;
3479}
3480
3481bool PeerConnection::PushdownSctpParameters_n(cricket::ContentSource source) {
3482 RTC_DCHECK(network_thread()->IsCurrent());
3483 RTC_DCHECK(local_description());
3484 RTC_DCHECK(remote_description());
3485 // Apply the SCTP port (which is hidden inside a DataCodec structure...)
3486 // When we support "max-message-size", that would also be pushed down here.
3487 return sctp_transport_->Start(
3488 GetSctpPort(local_description()->description()),
3489 GetSctpPort(remote_description()->description()));
3490}
3491
3492bool PeerConnection::PushdownTransportDescription(cricket::ContentSource source,
3493 cricket::ContentAction action,
3494 std::string* error_desc) {
3495 RTC_DCHECK(signaling_thread()->IsCurrent());
3496
3497 if (source == cricket::CS_LOCAL) {
3498 return PushdownLocalTransportDescription(local_description()->description(),
3499 action, error_desc);
3500 }
3501 return PushdownRemoteTransportDescription(remote_description()->description(),
3502 action, error_desc);
3503}
3504
3505bool PeerConnection::PushdownLocalTransportDescription(
3506 const SessionDescription* sdesc,
3507 cricket::ContentAction action,
3508 std::string* err) {
3509 RTC_DCHECK(signaling_thread()->IsCurrent());
3510
3511 if (!sdesc) {
3512 return false;
3513 }
3514
3515 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3516 if (!transport_controller_->SetLocalTransportDescription(
3517 tinfo.content_name, tinfo.description, action, err)) {
3518 return false;
3519 }
3520 }
3521
3522 return true;
3523}
3524
3525bool PeerConnection::PushdownRemoteTransportDescription(
3526 const SessionDescription* sdesc,
3527 cricket::ContentAction action,
3528 std::string* err) {
3529 RTC_DCHECK(signaling_thread()->IsCurrent());
3530
3531 if (!sdesc) {
3532 return false;
3533 }
3534
3535 for (const TransportInfo& tinfo : sdesc->transport_infos()) {
3536 if (!transport_controller_->SetRemoteTransportDescription(
3537 tinfo.content_name, tinfo.description, action, err)) {
3538 return false;
3539 }
3540 }
3541
3542 return true;
3543}
3544
3545bool PeerConnection::GetTransportDescription(
3546 const SessionDescription* description,
3547 const std::string& content_name,
3548 cricket::TransportDescription* tdesc) {
3549 if (!description || !tdesc) {
3550 return false;
3551 }
3552 const TransportInfo* transport_info =
3553 description->GetTransportInfoByName(content_name);
3554 if (!transport_info) {
3555 return false;
3556 }
3557 *tdesc = transport_info->description;
3558 return true;
3559}
3560
3561bool PeerConnection::EnableBundle(const cricket::ContentGroup& bundle) {
3562 const std::string* first_content_name = bundle.FirstContentName();
3563 if (!first_content_name) {
3564 LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
3565 return false;
3566 }
3567 const std::string& transport_name = *first_content_name;
3568
3569 auto maybe_set_transport = [this, bundle,
3570 transport_name](cricket::BaseChannel* ch) {
3571 if (!ch || !bundle.HasContentName(ch->content_name())) {
3572 return true;
3573 }
3574
3575 std::string old_transport_name = ch->transport_name();
3576 if (old_transport_name == transport_name) {
3577 LOG(LS_INFO) << "BUNDLE already enabled for " << ch->content_name()
3578 << " on " << transport_name << ".";
3579 return true;
3580 }
3581
3582 cricket::DtlsTransportInternal* rtp_dtls_transport =
3583 transport_controller_->CreateDtlsTransport(
3584 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3585 bool need_rtcp = (ch->rtcp_dtls_transport() != nullptr);
3586 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
3587 if (need_rtcp) {
3588 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
3589 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3590 }
3591
3592 ch->SetTransports(rtp_dtls_transport, rtcp_dtls_transport);
3593 LOG(LS_INFO) << "Enabled BUNDLE for " << ch->content_name() << " on "
3594 << transport_name << ".";
3595 transport_controller_->DestroyDtlsTransport(
3596 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
3597 // If the channel needs rtcp, it means that the channel used to have a
3598 // rtcp transport which needs to be deleted now.
3599 if (need_rtcp) {
3600 transport_controller_->DestroyDtlsTransport(
3601 old_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
3602 }
3603 return true;
3604 };
3605
3606 if (!maybe_set_transport(voice_channel()) ||
3607 !maybe_set_transport(video_channel()) ||
3608 !maybe_set_transport(rtp_data_channel())) {
3609 return false;
3610 }
3611 // For SCTP, transport creation/deletion happens here instead of in the
3612 // object itself.
3613 if (sctp_transport_) {
3614 RTC_DCHECK(sctp_transport_name_);
3615 RTC_DCHECK(sctp_content_name_);
3616 if (transport_name != *sctp_transport_name_ &&
3617 bundle.HasContentName(*sctp_content_name_)) {
3618 network_thread()->Invoke<void>(
3619 RTC_FROM_HERE, rtc::Bind(&PeerConnection::ChangeSctpTransport_n, this,
3620 transport_name));
3621 }
3622 }
3623
3624 return true;
3625}
3626
Steve Anton75737c02017-11-06 10:37:17 -08003627cricket::IceConfig PeerConnection::ParseIceConfig(
3628 const PeerConnectionInterface::RTCConfiguration& config) const {
3629 cricket::ContinualGatheringPolicy gathering_policy;
3630 // TODO(honghaiz): Add the third continual gathering policy in
3631 // PeerConnectionInterface and map it to GATHER_CONTINUALLY_AND_RECOVER.
3632 switch (config.continual_gathering_policy) {
3633 case PeerConnectionInterface::GATHER_ONCE:
3634 gathering_policy = cricket::GATHER_ONCE;
3635 break;
3636 case PeerConnectionInterface::GATHER_CONTINUALLY:
3637 gathering_policy = cricket::GATHER_CONTINUALLY;
3638 break;
3639 default:
3640 RTC_NOTREACHED();
3641 gathering_policy = cricket::GATHER_ONCE;
3642 }
3643 cricket::IceConfig ice_config;
3644 ice_config.receiving_timeout = config.ice_connection_receiving_timeout;
3645 ice_config.prioritize_most_likely_candidate_pairs =
3646 config.prioritize_most_likely_ice_candidate_pairs;
3647 ice_config.backup_connection_ping_interval =
3648 config.ice_backup_candidate_pair_ping_interval;
3649 ice_config.continual_gathering_policy = gathering_policy;
3650 ice_config.presume_writable_when_fully_relayed =
3651 config.presume_writable_when_fully_relayed;
3652 ice_config.ice_check_min_interval = config.ice_check_min_interval;
3653 ice_config.regather_all_networks_interval_range =
3654 config.ice_regather_interval_range;
3655 return ice_config;
3656}
3657
Steve Anton75737c02017-11-06 10:37:17 -08003658bool PeerConnection::GetLocalTrackIdBySsrc(uint32_t ssrc,
3659 std::string* track_id) {
3660 if (!local_description()) {
3661 return false;
3662 }
3663 return webrtc::GetTrackIdBySsrc(local_description()->description(), ssrc,
3664 track_id);
3665}
3666
3667bool PeerConnection::GetRemoteTrackIdBySsrc(uint32_t ssrc,
3668 std::string* track_id) {
3669 if (!remote_description()) {
3670 return false;
3671 }
3672 return webrtc::GetTrackIdBySsrc(remote_description()->description(), ssrc,
3673 track_id);
3674}
3675
3676bool PeerConnection::SendData(const cricket::SendDataParams& params,
3677 const rtc::CopyOnWriteBuffer& payload,
3678 cricket::SendDataResult* result) {
3679 if (!rtp_data_channel_ && !sctp_transport_) {
3680 LOG(LS_ERROR) << "SendData called when rtp_data_channel_ "
3681 << "and sctp_transport_ are NULL.";
3682 return false;
3683 }
3684 return rtp_data_channel_
3685 ? rtp_data_channel_->SendData(params, payload, result)
3686 : network_thread()->Invoke<bool>(
3687 RTC_FROM_HERE,
3688 Bind(&cricket::SctpTransportInternal::SendData,
3689 sctp_transport_.get(), params, payload, result));
3690}
3691
3692bool PeerConnection::ConnectDataChannel(DataChannel* webrtc_data_channel) {
3693 if (!rtp_data_channel_ && !sctp_transport_) {
3694 // Don't log an error here, because DataChannels are expected to call
3695 // ConnectDataChannel in this state. It's the only way to initially tell
3696 // whether or not the underlying transport is ready.
3697 return false;
3698 }
3699 if (rtp_data_channel_) {
3700 rtp_data_channel_->SignalReadyToSendData.connect(
3701 webrtc_data_channel, &DataChannel::OnChannelReady);
3702 rtp_data_channel_->SignalDataReceived.connect(webrtc_data_channel,
3703 &DataChannel::OnDataReceived);
3704 } else {
3705 SignalSctpReadyToSendData.connect(webrtc_data_channel,
3706 &DataChannel::OnChannelReady);
3707 SignalSctpDataReceived.connect(webrtc_data_channel,
3708 &DataChannel::OnDataReceived);
3709 SignalSctpStreamClosedRemotely.connect(
3710 webrtc_data_channel, &DataChannel::OnStreamClosedRemotely);
3711 }
3712 return true;
3713}
3714
3715void PeerConnection::DisconnectDataChannel(DataChannel* webrtc_data_channel) {
3716 if (!rtp_data_channel_ && !sctp_transport_) {
3717 LOG(LS_ERROR) << "DisconnectDataChannel called when rtp_data_channel_ and "
3718 "sctp_transport_ are NULL.";
3719 return;
3720 }
3721 if (rtp_data_channel_) {
3722 rtp_data_channel_->SignalReadyToSendData.disconnect(webrtc_data_channel);
3723 rtp_data_channel_->SignalDataReceived.disconnect(webrtc_data_channel);
3724 } else {
3725 SignalSctpReadyToSendData.disconnect(webrtc_data_channel);
3726 SignalSctpDataReceived.disconnect(webrtc_data_channel);
3727 SignalSctpStreamClosedRemotely.disconnect(webrtc_data_channel);
3728 }
3729}
3730
3731void PeerConnection::AddSctpDataStream(int sid) {
3732 if (!sctp_transport_) {
3733 LOG(LS_ERROR) << "AddSctpDataStream called when sctp_transport_ is NULL.";
3734 return;
3735 }
3736 network_thread()->Invoke<void>(
3737 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::OpenStream,
3738 sctp_transport_.get(), sid));
3739}
3740
3741void PeerConnection::RemoveSctpDataStream(int sid) {
3742 if (!sctp_transport_) {
3743 LOG(LS_ERROR) << "RemoveSctpDataStream called when sctp_transport_ is "
3744 << "NULL.";
3745 return;
3746 }
3747 network_thread()->Invoke<void>(
3748 RTC_FROM_HERE, rtc::Bind(&cricket::SctpTransportInternal::ResetStream,
3749 sctp_transport_.get(), sid));
3750}
3751
3752bool PeerConnection::ReadyToSendData() const {
3753 return (rtp_data_channel_ && rtp_data_channel_->ready_to_send_data()) ||
3754 sctp_ready_to_send_data_;
3755}
3756
3757std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_s() {
3758 RTC_DCHECK(signaling_thread()->IsCurrent());
3759 ChannelNamePairs channel_name_pairs;
3760 if (voice_channel()) {
3761 channel_name_pairs.voice = rtc::Optional<ChannelNamePair>(ChannelNamePair(
3762 voice_channel()->content_name(), voice_channel()->transport_name()));
3763 }
3764 if (video_channel()) {
3765 channel_name_pairs.video = rtc::Optional<ChannelNamePair>(ChannelNamePair(
3766 video_channel()->content_name(), video_channel()->transport_name()));
3767 }
3768 if (rtp_data_channel()) {
3769 channel_name_pairs.data = rtc::Optional<ChannelNamePair>(
3770 ChannelNamePair(rtp_data_channel()->content_name(),
3771 rtp_data_channel()->transport_name()));
3772 }
3773 if (sctp_transport_) {
3774 RTC_DCHECK(sctp_content_name_);
3775 RTC_DCHECK(sctp_transport_name_);
3776 channel_name_pairs.data = rtc::Optional<ChannelNamePair>(
3777 ChannelNamePair(*sctp_content_name_, *sctp_transport_name_));
3778 }
3779 return GetSessionStats(channel_name_pairs);
3780}
3781
3782std::unique_ptr<SessionStats> PeerConnection::GetSessionStats(
3783 const ChannelNamePairs& channel_name_pairs) {
3784 if (network_thread()->IsCurrent()) {
3785 return GetSessionStats_n(channel_name_pairs);
3786 }
3787 return network_thread()->Invoke<std::unique_ptr<SessionStats>>(
3788 RTC_FROM_HERE,
3789 rtc::Bind(&PeerConnection::GetSessionStats_n, this, channel_name_pairs));
3790}
3791
3792bool PeerConnection::GetLocalCertificate(
3793 const std::string& transport_name,
3794 rtc::scoped_refptr<rtc::RTCCertificate>* certificate) {
3795 return transport_controller_->GetLocalCertificate(transport_name,
3796 certificate);
3797}
3798
3799std::unique_ptr<rtc::SSLCertificate> PeerConnection::GetRemoteSSLCertificate(
3800 const std::string& transport_name) {
3801 return transport_controller_->GetRemoteSSLCertificate(transport_name);
3802}
3803
3804cricket::DataChannelType PeerConnection::data_channel_type() const {
3805 return data_channel_type_;
3806}
3807
3808bool PeerConnection::IceRestartPending(const std::string& content_name) const {
3809 return pending_ice_restarts_.find(content_name) !=
3810 pending_ice_restarts_.end();
3811}
3812
Steve Anton75737c02017-11-06 10:37:17 -08003813bool PeerConnection::NeedsIceRestart(const std::string& content_name) const {
3814 return transport_controller_->NeedsIceRestart(content_name);
3815}
3816
3817void PeerConnection::OnCertificateReady(
3818 const rtc::scoped_refptr<rtc::RTCCertificate>& certificate) {
3819 transport_controller_->SetLocalCertificate(certificate);
3820}
3821
3822void PeerConnection::OnDtlsSrtpSetupFailure(cricket::BaseChannel*, bool rtcp) {
3823 SetError(ERROR_TRANSPORT,
3824 rtcp ? kDtlsSrtpSetupFailureRtcp : kDtlsSrtpSetupFailureRtp);
3825}
3826
3827void PeerConnection::OnTransportControllerConnectionState(
3828 cricket::IceConnectionState state) {
3829 switch (state) {
3830 case cricket::kIceConnectionConnecting:
3831 // If the current state is Connected or Completed, then there were
3832 // writable channels but now there are not, so the next state must
3833 // be Disconnected.
3834 // kIceConnectionConnecting is currently used as the default,
3835 // un-connected state by the TransportController, so its only use is
3836 // detecting disconnections.
3837 if (ice_connection_state_ ==
3838 PeerConnectionInterface::kIceConnectionConnected ||
3839 ice_connection_state_ ==
3840 PeerConnectionInterface::kIceConnectionCompleted) {
3841 SetIceConnectionState(
3842 PeerConnectionInterface::kIceConnectionDisconnected);
3843 }
3844 break;
3845 case cricket::kIceConnectionFailed:
3846 SetIceConnectionState(PeerConnectionInterface::kIceConnectionFailed);
3847 break;
3848 case cricket::kIceConnectionConnected:
3849 LOG(LS_INFO) << "Changing to ICE connected state because "
3850 << "all transports are writable.";
3851 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3852 break;
3853 case cricket::kIceConnectionCompleted:
3854 LOG(LS_INFO) << "Changing to ICE completed state because "
3855 << "all transports are complete.";
3856 if (ice_connection_state_ !=
3857 PeerConnectionInterface::kIceConnectionConnected) {
3858 // If jumping directly from "checking" to "connected",
3859 // signal "connected" first.
3860 SetIceConnectionState(PeerConnectionInterface::kIceConnectionConnected);
3861 }
3862 SetIceConnectionState(PeerConnectionInterface::kIceConnectionCompleted);
3863 if (metrics_observer()) {
3864 ReportTransportStats();
3865 }
3866 break;
3867 default:
3868 RTC_NOTREACHED();
3869 }
3870}
3871
3872void PeerConnection::OnTransportControllerCandidatesGathered(
3873 const std::string& transport_name,
3874 const cricket::Candidates& candidates) {
3875 RTC_DCHECK(signaling_thread()->IsCurrent());
3876 int sdp_mline_index;
3877 if (!GetLocalCandidateMediaIndex(transport_name, &sdp_mline_index)) {
3878 LOG(LS_ERROR) << "OnTransportControllerCandidatesGathered: content name "
3879 << transport_name << " not found";
3880 return;
3881 }
3882
3883 for (cricket::Candidates::const_iterator citer = candidates.begin();
3884 citer != candidates.end(); ++citer) {
3885 // Use transport_name as the candidate media id.
3886 std::unique_ptr<JsepIceCandidate> candidate(
3887 new JsepIceCandidate(transport_name, sdp_mline_index, *citer));
3888 if (local_description()) {
3889 mutable_local_description()->AddCandidate(candidate.get());
3890 }
3891 OnIceCandidate(std::move(candidate));
3892 }
3893}
3894
3895void PeerConnection::OnTransportControllerCandidatesRemoved(
3896 const std::vector<cricket::Candidate>& candidates) {
3897 RTC_DCHECK(signaling_thread()->IsCurrent());
3898 // Sanity check.
3899 for (const cricket::Candidate& candidate : candidates) {
3900 if (candidate.transport_name().empty()) {
3901 LOG(LS_ERROR) << "OnTransportControllerCandidatesRemoved: "
3902 << "empty content name in candidate "
3903 << candidate.ToString();
3904 return;
3905 }
3906 }
3907
3908 if (local_description()) {
3909 mutable_local_description()->RemoveCandidates(candidates);
3910 }
3911 OnIceCandidatesRemoved(candidates);
3912}
3913
3914void PeerConnection::OnTransportControllerDtlsHandshakeError(
3915 rtc::SSLHandshakeError error) {
3916 if (metrics_observer()) {
3917 metrics_observer()->IncrementEnumCounter(
3918 webrtc::kEnumCounterDtlsHandshakeError, static_cast<int>(error),
3919 static_cast<int>(rtc::SSLHandshakeError::MAX_VALUE));
3920 }
3921}
3922
3923// Enabling voice and video (and RTP data) channels.
3924void PeerConnection::EnableChannels() {
3925 for (cricket::VoiceChannel* voice_channel : voice_channels_) {
3926 if (!voice_channel->enabled()) {
3927 voice_channel->Enable(true);
3928 }
3929 }
3930
3931 for (cricket::VideoChannel* video_channel : video_channels_) {
3932 if (!video_channel->enabled()) {
3933 video_channel->Enable(true);
3934 }
3935 }
3936
3937 if (rtp_data_channel_ && !rtp_data_channel_->enabled())
3938 rtp_data_channel_->Enable(true);
3939}
3940
3941// Returns the media index for a local ice candidate given the content name.
3942bool PeerConnection::GetLocalCandidateMediaIndex(
3943 const std::string& content_name,
3944 int* sdp_mline_index) {
3945 if (!local_description() || !sdp_mline_index) {
3946 return false;
3947 }
3948
3949 bool content_found = false;
3950 const ContentInfos& contents = local_description()->description()->contents();
3951 for (size_t index = 0; index < contents.size(); ++index) {
3952 if (contents[index].name == content_name) {
3953 *sdp_mline_index = static_cast<int>(index);
3954 content_found = true;
3955 break;
3956 }
3957 }
3958 return content_found;
3959}
3960
3961bool PeerConnection::UseCandidatesInSessionDescription(
3962 const SessionDescriptionInterface* remote_desc) {
3963 if (!remote_desc) {
3964 return true;
3965 }
3966 bool ret = true;
3967
3968 for (size_t m = 0; m < remote_desc->number_of_mediasections(); ++m) {
3969 const IceCandidateCollection* candidates = remote_desc->candidates(m);
3970 for (size_t n = 0; n < candidates->count(); ++n) {
3971 const IceCandidateInterface* candidate = candidates->at(n);
3972 bool valid = false;
3973 if (!ReadyToUseRemoteCandidate(candidate, remote_desc, &valid)) {
3974 if (valid) {
3975 LOG(LS_INFO) << "UseCandidatesInSessionDescription: Not ready to use "
3976 << "candidate.";
3977 }
3978 continue;
3979 }
3980 ret = UseCandidate(candidate);
3981 if (!ret) {
3982 break;
3983 }
3984 }
3985 }
3986 return ret;
3987}
3988
3989bool PeerConnection::UseCandidate(const IceCandidateInterface* candidate) {
3990 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
3991 size_t remote_content_size =
3992 remote_description()->description()->contents().size();
3993 if (mediacontent_index >= remote_content_size) {
3994 LOG(LS_ERROR) << "UseCandidate: Invalid candidate media index.";
3995 return false;
3996 }
3997
3998 cricket::ContentInfo content =
3999 remote_description()->description()->contents()[mediacontent_index];
4000 std::vector<cricket::Candidate> candidates;
4001 candidates.push_back(candidate->candidate());
4002 // Invoking BaseSession method to handle remote candidates.
4003 std::string error;
4004 if (transport_controller_->AddRemoteCandidates(content.name, candidates,
4005 &error)) {
4006 // Candidates successfully submitted for checking.
4007 if (ice_connection_state_ == PeerConnectionInterface::kIceConnectionNew ||
4008 ice_connection_state_ ==
4009 PeerConnectionInterface::kIceConnectionDisconnected) {
4010 // If state is New, then the session has just gotten its first remote ICE
4011 // candidates, so go to Checking.
4012 // If state is Disconnected, the session is re-using old candidates or
4013 // receiving additional ones, so go to Checking.
4014 // If state is Connected, stay Connected.
4015 // TODO(bemasc): If state is Connected, and the new candidates are for a
4016 // newly added transport, then the state actually _should_ move to
4017 // checking. Add a way to distinguish that case.
4018 SetIceConnectionState(PeerConnectionInterface::kIceConnectionChecking);
4019 }
4020 // TODO(bemasc): If state is Completed, go back to Connected.
4021 } else {
4022 if (!error.empty()) {
4023 LOG(LS_WARNING) << error;
4024 }
4025 }
4026 return true;
4027}
4028
4029void PeerConnection::RemoveUnusedChannels(const SessionDescription* desc) {
4030 // TODO(steveanton): Add support for multiple audio/video channels.
4031 // Destroy video channel first since it may have a pointer to the
4032 // voice channel.
4033 const cricket::ContentInfo* video_info = cricket::GetFirstVideoContent(desc);
4034 if ((!video_info || video_info->rejected) && video_channel()) {
4035 RemoveAndDestroyVideoChannel(video_channel());
4036 }
4037
4038 const cricket::ContentInfo* voice_info = cricket::GetFirstAudioContent(desc);
4039 if ((!voice_info || voice_info->rejected) && voice_channel()) {
4040 RemoveAndDestroyVoiceChannel(voice_channel());
4041 }
4042
4043 const cricket::ContentInfo* data_info = cricket::GetFirstDataContent(desc);
4044 if (!data_info || data_info->rejected) {
4045 if (rtp_data_channel_) {
4046 DestroyDataChannel();
4047 }
4048 if (sctp_transport_) {
4049 OnDataChannelDestroyed();
4050 network_thread()->Invoke<void>(
4051 RTC_FROM_HERE,
4052 rtc::Bind(&PeerConnection::DestroySctpTransport_n, this));
4053 }
4054 }
4055}
4056
4057// Returns the name of the transport channel when BUNDLE is enabled, or nullptr
4058// if the channel is not part of any bundle.
4059const std::string* PeerConnection::GetBundleTransportName(
4060 const cricket::ContentInfo* content,
4061 const cricket::ContentGroup* bundle) {
4062 if (!bundle) {
4063 return nullptr;
4064 }
4065 const std::string* first_content_name = bundle->FirstContentName();
4066 if (!first_content_name) {
4067 LOG(LS_WARNING) << "Tried to BUNDLE with no contents.";
4068 return nullptr;
4069 }
4070 if (!bundle->HasContentName(content->name)) {
4071 LOG(LS_WARNING) << content->name << " is not part of any bundle group";
4072 return nullptr;
4073 }
4074 LOG(LS_INFO) << "Bundling " << content->name << " on " << *first_content_name;
4075 return first_content_name;
4076}
4077
4078bool PeerConnection::CreateChannels(const SessionDescription* desc) {
4079 // TODO(steveanton): Add support for multiple audio/video channels.
4080 const cricket::ContentGroup* bundle_group = nullptr;
4081 if (configuration_.bundle_policy ==
4082 PeerConnectionInterface::kBundlePolicyMaxBundle) {
4083 bundle_group = desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4084 if (!bundle_group) {
4085 LOG(LS_WARNING) << "max-bundle specified without BUNDLE specified";
4086 return false;
4087 }
4088 }
4089 // Creating the media channels and transport proxies.
4090 const cricket::ContentInfo* voice = cricket::GetFirstAudioContent(desc);
4091 if (voice && !voice->rejected && !voice_channel()) {
4092 if (!CreateVoiceChannel(voice,
4093 GetBundleTransportName(voice, bundle_group))) {
4094 LOG(LS_ERROR) << "Failed to create voice channel.";
4095 return false;
4096 }
4097 }
4098
4099 const cricket::ContentInfo* video = cricket::GetFirstVideoContent(desc);
4100 if (video && !video->rejected && !video_channel()) {
4101 if (!CreateVideoChannel(video,
4102 GetBundleTransportName(video, bundle_group))) {
4103 LOG(LS_ERROR) << "Failed to create video channel.";
4104 return false;
4105 }
4106 }
4107
4108 const cricket::ContentInfo* data = cricket::GetFirstDataContent(desc);
4109 if (data_channel_type_ != cricket::DCT_NONE && data && !data->rejected &&
4110 !rtp_data_channel_ && !sctp_transport_) {
4111 if (!CreateDataChannel(data, GetBundleTransportName(data, bundle_group))) {
4112 LOG(LS_ERROR) << "Failed to create data channel.";
4113 return false;
4114 }
4115 }
4116
4117 return true;
4118}
4119
4120bool PeerConnection::CreateVoiceChannel(const cricket::ContentInfo* content,
4121 const std::string* bundle_transport) {
4122 // TODO(steveanton): Check to see if it's safe to create multiple voice
4123 // channels.
4124 RTC_DCHECK(voice_channels_.empty());
4125
4126 std::string transport_name =
4127 bundle_transport ? *bundle_transport : content->name;
4128
4129 cricket::DtlsTransportInternal* rtp_dtls_transport =
4130 transport_controller_->CreateDtlsTransport(
4131 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4132 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4133 if (configuration_.rtcp_mux_policy !=
4134 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4135 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4136 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4137 }
4138
4139 cricket::VoiceChannel* voice_channel = channel_manager()->CreateVoiceChannel(
4140 call_.get(), configuration_.media_config, rtp_dtls_transport,
4141 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4142 content->name, SrtpRequired(), audio_options_);
4143 if (!voice_channel) {
4144 transport_controller_->DestroyDtlsTransport(
4145 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4146 if (rtcp_dtls_transport) {
4147 transport_controller_->DestroyDtlsTransport(
4148 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4149 }
4150 return false;
4151 }
4152
4153 voice_channels_.push_back(voice_channel);
4154
4155 voice_channel->SignalRtcpMuxFullyActive.connect(
4156 this, &PeerConnection::DestroyRtcpTransport_n);
4157 voice_channel->SignalDtlsSrtpSetupFailure.connect(
4158 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4159
Steve Antond25da372017-11-06 14:50:29 -08004160 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver>(
4161 voice_channel, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
Steve Anton75737c02017-11-06 10:37:17 -08004162 voice_channel->SignalSentPacket.connect(this,
4163 &PeerConnection::OnSentPacket_w);
4164 return true;
4165}
4166
4167bool PeerConnection::CreateVideoChannel(const cricket::ContentInfo* content,
4168 const std::string* bundle_transport) {
4169 // TODO(steveanton): Check to see if it's safe to create multiple video
4170 // channels.
4171 RTC_DCHECK(video_channels_.empty());
4172
4173 std::string transport_name =
4174 bundle_transport ? *bundle_transport : content->name;
4175
4176 cricket::DtlsTransportInternal* rtp_dtls_transport =
4177 transport_controller_->CreateDtlsTransport(
4178 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4179 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4180 if (configuration_.rtcp_mux_policy !=
4181 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4182 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4183 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4184 }
4185
4186 cricket::VideoChannel* video_channel = channel_manager()->CreateVideoChannel(
4187 call_.get(), configuration_.media_config, rtp_dtls_transport,
4188 rtcp_dtls_transport, transport_controller_->signaling_thread(),
4189 content->name, SrtpRequired(), video_options_);
4190
4191 if (!video_channel) {
4192 transport_controller_->DestroyDtlsTransport(
4193 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4194 if (rtcp_dtls_transport) {
4195 transport_controller_->DestroyDtlsTransport(
4196 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4197 }
4198 return false;
4199 }
4200
4201 video_channels_.push_back(video_channel);
4202
4203 video_channel->SignalRtcpMuxFullyActive.connect(
4204 this, &PeerConnection::DestroyRtcpTransport_n);
4205 video_channel->SignalDtlsSrtpSetupFailure.connect(
4206 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4207
Steve Antond25da372017-11-06 14:50:29 -08004208 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver>(
4209 video_channel, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
Steve Anton75737c02017-11-06 10:37:17 -08004210 video_channel->SignalSentPacket.connect(this,
4211 &PeerConnection::OnSentPacket_w);
4212 return true;
4213}
4214
4215bool PeerConnection::CreateDataChannel(const cricket::ContentInfo* content,
4216 const std::string* bundle_transport) {
4217 const std::string transport_name =
4218 bundle_transport ? *bundle_transport : content->name;
4219 bool sctp = (data_channel_type_ == cricket::DCT_SCTP);
4220 if (sctp) {
4221 if (!sctp_factory_) {
4222 LOG(LS_ERROR)
4223 << "Trying to create SCTP transport, but didn't compile with "
4224 "SCTP support (HAVE_SCTP)";
4225 return false;
4226 }
4227 if (!network_thread()->Invoke<bool>(
4228 RTC_FROM_HERE, rtc::Bind(&PeerConnection::CreateSctpTransport_n,
4229 this, content->name, transport_name))) {
4230 return false;
4231 }
4232 } else {
4233 std::string transport_name =
4234 bundle_transport ? *bundle_transport : content->name;
4235 cricket::DtlsTransportInternal* rtp_dtls_transport =
4236 transport_controller_->CreateDtlsTransport(
4237 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4238 cricket::DtlsTransportInternal* rtcp_dtls_transport = nullptr;
4239 if (configuration_.rtcp_mux_policy !=
4240 PeerConnectionInterface::kRtcpMuxPolicyRequire) {
4241 rtcp_dtls_transport = transport_controller_->CreateDtlsTransport(
4242 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4243 }
4244
4245 rtp_data_channel_ = channel_manager()->CreateRtpDataChannel(
4246 configuration_.media_config, rtp_dtls_transport, rtcp_dtls_transport,
4247 transport_controller_->signaling_thread(), content->name,
4248 SrtpRequired());
4249
4250 if (!rtp_data_channel_) {
4251 transport_controller_->DestroyDtlsTransport(
4252 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4253 if (rtcp_dtls_transport) {
4254 transport_controller_->DestroyDtlsTransport(
4255 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4256 }
4257 return false;
4258 }
4259
4260 rtp_data_channel_->SignalRtcpMuxFullyActive.connect(
4261 this, &PeerConnection::DestroyRtcpTransport_n);
4262 rtp_data_channel_->SignalDtlsSrtpSetupFailure.connect(
4263 this, &PeerConnection::OnDtlsSrtpSetupFailure);
4264 rtp_data_channel_->SignalSentPacket.connect(
4265 this, &PeerConnection::OnSentPacket_w);
4266 }
4267
Steve Antond25da372017-11-06 14:50:29 -08004268 for (const auto& channel : sctp_data_channels_) {
4269 channel->OnTransportChannelCreated();
4270 }
Steve Anton75737c02017-11-06 10:37:17 -08004271
4272 return true;
4273}
4274
4275Call::Stats PeerConnection::GetCallStats() {
4276 if (!worker_thread()->IsCurrent()) {
4277 return worker_thread()->Invoke<Call::Stats>(
4278 RTC_FROM_HERE, rtc::Bind(&PeerConnection::GetCallStats, this));
4279 }
4280 if (call_) {
4281 return call_->GetStats();
4282 } else {
4283 return Call::Stats();
4284 }
4285}
4286
4287std::unique_ptr<SessionStats> PeerConnection::GetSessionStats_n(
4288 const ChannelNamePairs& channel_name_pairs) {
4289 RTC_DCHECK(network_thread()->IsCurrent());
4290 std::unique_ptr<SessionStats> session_stats(new SessionStats());
4291 for (const auto channel_name_pair :
4292 {&channel_name_pairs.voice, &channel_name_pairs.video,
4293 &channel_name_pairs.data}) {
4294 if (*channel_name_pair) {
4295 cricket::TransportStats transport_stats;
4296 if (!transport_controller_->GetStats((*channel_name_pair)->transport_name,
4297 &transport_stats)) {
4298 return nullptr;
4299 }
4300 session_stats->proxy_to_transport[(*channel_name_pair)->content_name] =
4301 (*channel_name_pair)->transport_name;
4302 session_stats->transport_stats[(*channel_name_pair)->transport_name] =
4303 std::move(transport_stats);
4304 }
4305 }
4306 return session_stats;
4307}
4308
4309bool PeerConnection::CreateSctpTransport_n(const std::string& content_name,
4310 const std::string& transport_name) {
4311 RTC_DCHECK(network_thread()->IsCurrent());
4312 RTC_DCHECK(sctp_factory_);
4313 cricket::DtlsTransportInternal* tc =
4314 transport_controller_->CreateDtlsTransport_n(
4315 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4316 sctp_transport_ = sctp_factory_->CreateSctpTransport(tc);
4317 RTC_DCHECK(sctp_transport_);
4318 sctp_invoker_.reset(new rtc::AsyncInvoker());
4319 sctp_transport_->SignalReadyToSendData.connect(
4320 this, &PeerConnection::OnSctpTransportReadyToSendData_n);
4321 sctp_transport_->SignalDataReceived.connect(
4322 this, &PeerConnection::OnSctpTransportDataReceived_n);
4323 sctp_transport_->SignalStreamClosedRemotely.connect(
4324 this, &PeerConnection::OnSctpStreamClosedRemotely_n);
4325 sctp_transport_name_ = rtc::Optional<std::string>(transport_name);
4326 sctp_content_name_ = rtc::Optional<std::string>(content_name);
4327 return true;
4328}
4329
4330void PeerConnection::ChangeSctpTransport_n(const std::string& transport_name) {
4331 RTC_DCHECK(network_thread()->IsCurrent());
4332 RTC_DCHECK(sctp_transport_);
4333 RTC_DCHECK(sctp_transport_name_);
4334 std::string old_sctp_transport_name = *sctp_transport_name_;
4335 sctp_transport_name_ = rtc::Optional<std::string>(transport_name);
4336 cricket::DtlsTransportInternal* tc =
4337 transport_controller_->CreateDtlsTransport_n(
4338 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4339 sctp_transport_->SetTransportChannel(tc);
4340 transport_controller_->DestroyDtlsTransport_n(
4341 old_sctp_transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4342}
4343
4344void PeerConnection::DestroySctpTransport_n() {
4345 RTC_DCHECK(network_thread()->IsCurrent());
4346 sctp_transport_.reset(nullptr);
4347 sctp_content_name_.reset();
4348 sctp_transport_name_.reset();
4349 sctp_invoker_.reset(nullptr);
4350 sctp_ready_to_send_data_ = false;
4351}
4352
4353void PeerConnection::OnSctpTransportReadyToSendData_n() {
4354 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4355 RTC_DCHECK(network_thread()->IsCurrent());
4356 // Note: Cannot use rtc::Bind here because it will grab a reference to
4357 // PeerConnection and potentially cause PeerConnection to live longer than
4358 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4359 // be destroyed before PeerConnection is destroyed, and at that point all
4360 // pending tasks will be cleared.
4361 sctp_invoker_->AsyncInvoke<void>(RTC_FROM_HERE, signaling_thread(), [this] {
4362 OnSctpTransportReadyToSendData_s(true);
4363 });
4364}
4365
4366void PeerConnection::OnSctpTransportReadyToSendData_s(bool ready) {
4367 RTC_DCHECK(signaling_thread()->IsCurrent());
4368 sctp_ready_to_send_data_ = ready;
4369 SignalSctpReadyToSendData(ready);
4370}
4371
4372void PeerConnection::OnSctpTransportDataReceived_n(
4373 const cricket::ReceiveDataParams& params,
4374 const rtc::CopyOnWriteBuffer& payload) {
4375 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4376 RTC_DCHECK(network_thread()->IsCurrent());
4377 // Note: Cannot use rtc::Bind here because it will grab a reference to
4378 // PeerConnection and potentially cause PeerConnection to live longer than
4379 // expected. It is safe not to grab a reference since the sctp_invoker_ will
4380 // be destroyed before PeerConnection is destroyed, and at that point all
4381 // pending tasks will be cleared.
4382 sctp_invoker_->AsyncInvoke<void>(
4383 RTC_FROM_HERE, signaling_thread(), [this, params, payload] {
4384 OnSctpTransportDataReceived_s(params, payload);
4385 });
4386}
4387
4388void PeerConnection::OnSctpTransportDataReceived_s(
4389 const cricket::ReceiveDataParams& params,
4390 const rtc::CopyOnWriteBuffer& payload) {
4391 RTC_DCHECK(signaling_thread()->IsCurrent());
4392 if (params.type == cricket::DMT_CONTROL && IsOpenMessage(payload)) {
4393 // Received OPEN message; parse and signal that a new data channel should
4394 // be created.
4395 std::string label;
4396 InternalDataChannelInit config;
4397 config.id = params.ssrc;
4398 if (!ParseDataChannelOpenMessage(payload, &label, &config)) {
4399 LOG(LS_WARNING) << "Failed to parse the OPEN message for sid "
4400 << params.ssrc;
4401 return;
4402 }
4403 config.open_handshake_role = InternalDataChannelInit::kAcker;
4404 OnDataChannelOpenMessage(label, config);
4405 } else {
4406 // Otherwise just forward the signal.
4407 SignalSctpDataReceived(params, payload);
4408 }
4409}
4410
4411void PeerConnection::OnSctpStreamClosedRemotely_n(int sid) {
4412 RTC_DCHECK(data_channel_type_ == cricket::DCT_SCTP);
4413 RTC_DCHECK(network_thread()->IsCurrent());
4414 sctp_invoker_->AsyncInvoke<void>(
4415 RTC_FROM_HERE, signaling_thread(),
4416 rtc::Bind(&sigslot::signal1<int>::operator(),
4417 &SignalSctpStreamClosedRemotely, sid));
4418}
4419
4420// Returns false if bundle is enabled and rtcp_mux is disabled.
4421bool PeerConnection::ValidateBundleSettings(const SessionDescription* desc) {
4422 bool bundle_enabled = desc->HasGroup(cricket::GROUP_TYPE_BUNDLE);
4423 if (!bundle_enabled)
4424 return true;
4425
4426 const cricket::ContentGroup* bundle_group =
4427 desc->GetGroupByName(cricket::GROUP_TYPE_BUNDLE);
4428 RTC_DCHECK(bundle_group != NULL);
4429
4430 const cricket::ContentInfos& contents = desc->contents();
4431 for (cricket::ContentInfos::const_iterator citer = contents.begin();
4432 citer != contents.end(); ++citer) {
4433 const cricket::ContentInfo* content = (&*citer);
4434 RTC_DCHECK(content != NULL);
4435 if (bundle_group->HasContentName(content->name) && !content->rejected &&
4436 content->type == cricket::NS_JINGLE_RTP) {
4437 if (!HasRtcpMuxEnabled(content))
4438 return false;
4439 }
4440 }
4441 // RTCP-MUX is enabled in all the contents.
4442 return true;
4443}
4444
4445bool PeerConnection::HasRtcpMuxEnabled(const cricket::ContentInfo* content) {
4446 const cricket::MediaContentDescription* description =
4447 static_cast<cricket::MediaContentDescription*>(content->description);
4448 return description->rtcp_mux();
4449}
4450
4451bool PeerConnection::ValidateSessionDescription(
4452 const SessionDescriptionInterface* sdesc,
4453 cricket::ContentSource source,
4454 std::string* err_desc) {
4455 std::string type;
4456 if (error() != ERROR_NONE) {
4457 return BadSdp(source, type, GetSessionErrorMsg(), err_desc);
4458 }
4459
4460 if (!sdesc || !sdesc->description()) {
4461 return BadSdp(source, type, kInvalidSdp, err_desc);
4462 }
4463
4464 type = sdesc->type();
4465 Action action = GetAction(sdesc->type());
4466 if (source == cricket::CS_LOCAL) {
4467 if (!ExpectSetLocalDescription(action))
4468 return BadLocalSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4469 } else {
4470 if (!ExpectSetRemoteDescription(action))
4471 return BadRemoteSdp(type, BadStateErrMsg(signaling_state()), err_desc);
4472 }
4473
4474 // Verify crypto settings.
4475 std::string crypto_error;
4476 if ((webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED ||
4477 dtls_enabled_) &&
4478 !VerifyCrypto(sdesc->description(), dtls_enabled_, &crypto_error)) {
4479 return BadSdp(source, type, crypto_error, err_desc);
4480 }
4481
4482 // Verify ice-ufrag and ice-pwd.
4483 if (!VerifyIceUfragPwdPresent(sdesc->description())) {
4484 return BadSdp(source, type, kSdpWithoutIceUfragPwd, err_desc);
4485 }
4486
4487 if (!ValidateBundleSettings(sdesc->description())) {
4488 return BadSdp(source, type, kBundleWithoutRtcpMux, err_desc);
4489 }
4490
4491 // TODO(skvlad): When the local rtcp-mux policy is Require, reject any
4492 // m-lines that do not rtcp-mux enabled.
4493
4494 // Verify m-lines in Answer when compared against Offer.
4495 if (action == kAnswer || action == kPrAnswer) {
4496 const cricket::SessionDescription* offer_desc =
4497 (source == cricket::CS_LOCAL) ? remote_description()->description()
4498 : local_description()->description();
4499 if (!MediaSectionsHaveSameCount(offer_desc, sdesc->description()) ||
4500 !MediaSectionsInSameOrder(offer_desc, sdesc->description())) {
4501 return BadAnswerSdp(source, kMlineMismatchInAnswer, err_desc);
4502 }
4503 } else {
4504 const cricket::SessionDescription* current_desc = nullptr;
4505 if (source == cricket::CS_LOCAL && local_description()) {
4506 current_desc = local_description()->description();
4507 } else if (source == cricket::CS_REMOTE && remote_description()) {
4508 current_desc = remote_description()->description();
4509 }
4510 // The re-offers should respect the order of m= sections in current
4511 // description. See RFC3264 Section 8 paragraph 4 for more details.
4512 if (current_desc &&
4513 !MediaSectionsInSameOrder(current_desc, sdesc->description())) {
4514 return BadOfferSdp(source, kMlineMismatchInSubsequentOffer, err_desc);
4515 }
4516 }
4517
4518 return true;
4519}
4520
4521bool PeerConnection::ExpectSetLocalDescription(Action action) {
4522 PeerConnectionInterface::SignalingState state = signaling_state();
4523 if (action == kOffer) {
4524 return (state == PeerConnectionInterface::kStable) ||
4525 (state == PeerConnectionInterface::kHaveLocalOffer);
4526 } else { // Answer or PrAnswer
4527 return (state == PeerConnectionInterface::kHaveRemoteOffer) ||
4528 (state == PeerConnectionInterface::kHaveLocalPrAnswer);
4529 }
4530}
4531
4532bool PeerConnection::ExpectSetRemoteDescription(Action action) {
4533 PeerConnectionInterface::SignalingState state = signaling_state();
4534 if (action == kOffer) {
4535 return (state == PeerConnectionInterface::kStable) ||
4536 (state == PeerConnectionInterface::kHaveRemoteOffer);
4537 } else { // Answer or PrAnswer.
4538 return (state == PeerConnectionInterface::kHaveLocalOffer) ||
4539 (state == PeerConnectionInterface::kHaveRemotePrAnswer);
4540 }
4541}
4542
4543std::string PeerConnection::GetSessionErrorMsg() {
4544 std::ostringstream desc;
4545 desc << kSessionError << GetErrorCodeString(error()) << ". ";
4546 desc << kSessionErrorDesc << error_desc() << ".";
4547 return desc.str();
4548}
4549
4550// We need to check the local/remote description for the Transport instead of
4551// the session, because a new Transport added during renegotiation may have
4552// them unset while the session has them set from the previous negotiation.
4553// Not doing so may trigger the auto generation of transport description and
4554// mess up DTLS identity information, ICE credential, etc.
4555bool PeerConnection::ReadyToUseRemoteCandidate(
4556 const IceCandidateInterface* candidate,
4557 const SessionDescriptionInterface* remote_desc,
4558 bool* valid) {
4559 *valid = true;
4560
4561 const SessionDescriptionInterface* current_remote_desc =
4562 remote_desc ? remote_desc : remote_description();
4563
4564 if (!current_remote_desc) {
4565 return false;
4566 }
4567
4568 size_t mediacontent_index = static_cast<size_t>(candidate->sdp_mline_index());
4569 size_t remote_content_size =
4570 current_remote_desc->description()->contents().size();
4571 if (mediacontent_index >= remote_content_size) {
4572 LOG(LS_ERROR) << "ReadyToUseRemoteCandidate: Invalid candidate media index "
4573 << mediacontent_index;
4574
4575 *valid = false;
4576 return false;
4577 }
4578
4579 cricket::ContentInfo content =
4580 current_remote_desc->description()->contents()[mediacontent_index];
4581
4582 const std::string transport_name = GetTransportName(content.name);
4583 if (transport_name.empty()) {
4584 return false;
4585 }
4586 return transport_controller_->ReadyForRemoteCandidates(transport_name);
4587}
4588
4589bool PeerConnection::SrtpRequired() const {
4590 return dtls_enabled_ ||
4591 webrtc_session_desc_factory_->SdesPolicy() == cricket::SEC_REQUIRED;
4592}
4593
4594void PeerConnection::OnTransportControllerGatheringState(
4595 cricket::IceGatheringState state) {
4596 RTC_DCHECK(signaling_thread()->IsCurrent());
4597 if (state == cricket::kIceGatheringGathering) {
4598 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringGathering);
4599 } else if (state == cricket::kIceGatheringComplete) {
4600 OnIceGatheringChange(PeerConnectionInterface::kIceGatheringComplete);
4601 }
4602}
4603
4604void PeerConnection::ReportTransportStats() {
4605 // Use a set so we don't report the same stats twice if two channels share
4606 // a transport.
4607 std::set<std::string> transport_names;
4608 if (voice_channel()) {
4609 transport_names.insert(voice_channel()->transport_name());
4610 }
4611 if (video_channel()) {
4612 transport_names.insert(video_channel()->transport_name());
4613 }
4614 if (rtp_data_channel()) {
4615 transport_names.insert(rtp_data_channel()->transport_name());
4616 }
4617 if (sctp_transport_name_) {
4618 transport_names.insert(*sctp_transport_name_);
4619 }
4620 for (const auto& name : transport_names) {
4621 cricket::TransportStats stats;
4622 if (transport_controller_->GetStats(name, &stats)) {
4623 ReportBestConnectionState(stats);
4624 ReportNegotiatedCiphers(stats);
4625 }
4626 }
4627}
4628// Walk through the ConnectionInfos to gather best connection usage
4629// for IPv4 and IPv6.
4630void PeerConnection::ReportBestConnectionState(
4631 const cricket::TransportStats& stats) {
4632 RTC_DCHECK(metrics_observer());
4633 for (cricket::TransportChannelStatsList::const_iterator it =
4634 stats.channel_stats.begin();
4635 it != stats.channel_stats.end(); ++it) {
4636 for (cricket::ConnectionInfos::const_iterator it_info =
4637 it->connection_infos.begin();
4638 it_info != it->connection_infos.end(); ++it_info) {
4639 if (!it_info->best_connection) {
4640 continue;
4641 }
4642
4643 PeerConnectionEnumCounterType type = kPeerConnectionEnumCounterMax;
4644 const cricket::Candidate& local = it_info->local_candidate;
4645 const cricket::Candidate& remote = it_info->remote_candidate;
4646
4647 // Increment the counter for IceCandidatePairType.
4648 if (local.protocol() == cricket::TCP_PROTOCOL_NAME ||
4649 (local.type() == RELAY_PORT_TYPE &&
4650 local.relay_protocol() == cricket::TCP_PROTOCOL_NAME)) {
4651 type = kEnumCounterIceCandidatePairTypeTcp;
4652 } else if (local.protocol() == cricket::UDP_PROTOCOL_NAME) {
4653 type = kEnumCounterIceCandidatePairTypeUdp;
4654 } else {
4655 RTC_CHECK(0);
4656 }
4657 metrics_observer()->IncrementEnumCounter(
4658 type, GetIceCandidatePairCounter(local, remote),
4659 kIceCandidatePairMax);
4660
4661 // Increment the counter for IP type.
4662 if (local.address().family() == AF_INET) {
4663 metrics_observer()->IncrementEnumCounter(
4664 kEnumCounterAddressFamily, kBestConnections_IPv4,
4665 kPeerConnectionAddressFamilyCounter_Max);
4666
4667 } else if (local.address().family() == AF_INET6) {
4668 metrics_observer()->IncrementEnumCounter(
4669 kEnumCounterAddressFamily, kBestConnections_IPv6,
4670 kPeerConnectionAddressFamilyCounter_Max);
4671 } else {
4672 RTC_CHECK(0);
4673 }
4674
4675 return;
4676 }
4677 }
4678}
4679
4680void PeerConnection::ReportNegotiatedCiphers(
4681 const cricket::TransportStats& stats) {
4682 RTC_DCHECK(metrics_observer());
4683 if (!dtls_enabled_ || stats.channel_stats.empty()) {
4684 return;
4685 }
4686
4687 int srtp_crypto_suite = stats.channel_stats[0].srtp_crypto_suite;
4688 int ssl_cipher_suite = stats.channel_stats[0].ssl_cipher_suite;
4689 if (srtp_crypto_suite == rtc::SRTP_INVALID_CRYPTO_SUITE &&
4690 ssl_cipher_suite == rtc::TLS_NULL_WITH_NULL_NULL) {
4691 return;
4692 }
4693
4694 PeerConnectionEnumCounterType srtp_counter_type;
4695 PeerConnectionEnumCounterType ssl_counter_type;
4696 if (stats.transport_name == cricket::CN_AUDIO) {
4697 srtp_counter_type = kEnumCounterAudioSrtpCipher;
4698 ssl_counter_type = kEnumCounterAudioSslCipher;
4699 } else if (stats.transport_name == cricket::CN_VIDEO) {
4700 srtp_counter_type = kEnumCounterVideoSrtpCipher;
4701 ssl_counter_type = kEnumCounterVideoSslCipher;
4702 } else if (stats.transport_name == cricket::CN_DATA) {
4703 srtp_counter_type = kEnumCounterDataSrtpCipher;
4704 ssl_counter_type = kEnumCounterDataSslCipher;
4705 } else {
4706 RTC_NOTREACHED();
4707 return;
4708 }
4709
4710 if (srtp_crypto_suite != rtc::SRTP_INVALID_CRYPTO_SUITE) {
4711 metrics_observer()->IncrementSparseEnumCounter(srtp_counter_type,
4712 srtp_crypto_suite);
4713 }
4714 if (ssl_cipher_suite != rtc::TLS_NULL_WITH_NULL_NULL) {
4715 metrics_observer()->IncrementSparseEnumCounter(ssl_counter_type,
4716 ssl_cipher_suite);
4717 }
4718}
4719
4720void PeerConnection::OnSentPacket_w(const rtc::SentPacket& sent_packet) {
4721 RTC_DCHECK(worker_thread()->IsCurrent());
4722 RTC_DCHECK(call_);
4723 call_->OnSentPacket(sent_packet);
4724}
4725
4726const std::string PeerConnection::GetTransportName(
4727 const std::string& content_name) {
4728 cricket::BaseChannel* channel = GetChannel(content_name);
4729 if (!channel) {
4730 if (sctp_transport_) {
4731 RTC_DCHECK(sctp_content_name_);
4732 RTC_DCHECK(sctp_transport_name_);
4733 if (content_name == *sctp_content_name_) {
4734 return *sctp_transport_name_;
4735 }
4736 }
4737 // Return an empty string if failed to retrieve the transport name.
4738 return "";
4739 }
4740 return channel->transport_name();
4741}
4742
4743void PeerConnection::DestroyRtcpTransport_n(const std::string& transport_name) {
4744 RTC_DCHECK(network_thread()->IsCurrent());
4745 transport_controller_->DestroyDtlsTransport_n(
4746 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4747}
4748
4749void PeerConnection::RemoveAndDestroyVideoChannel(
4750 cricket::VideoChannel* video_channel) {
4751 auto it =
4752 std::find(video_channels_.begin(), video_channels_.end(), video_channel);
4753 RTC_DCHECK(it != video_channels_.end());
4754 if (it == video_channels_.end()) {
4755 return;
4756 }
4757 video_channels_.erase(it);
4758 DestroyVideoChannel(video_channel);
4759}
4760
4761void PeerConnection::DestroyVideoChannel(cricket::VideoChannel* video_channel) {
Steve Antond25da372017-11-06 14:50:29 -08004762 SetChannelOnSendersAndReceivers<VideoRtpSender, VideoRtpReceiver,
4763 cricket::VideoChannel>(
4764 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_VIDEO);
Steve Anton75737c02017-11-06 10:37:17 -08004765 RTC_DCHECK(video_channel->rtp_dtls_transport());
4766 const std::string transport_name =
4767 video_channel->rtp_dtls_transport()->transport_name();
4768 const bool need_to_delete_rtcp =
4769 (video_channel->rtcp_dtls_transport() != nullptr);
4770 // The above need to be cached before destroying the video channel so that we
4771 // do not access uninitialized memory.
4772 channel_manager()->DestroyVideoChannel(video_channel);
4773 transport_controller_->DestroyDtlsTransport(
4774 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4775 if (need_to_delete_rtcp) {
4776 transport_controller_->DestroyDtlsTransport(
4777 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4778 }
4779}
4780
4781void PeerConnection::RemoveAndDestroyVoiceChannel(
4782 cricket::VoiceChannel* voice_channel) {
4783 auto it =
4784 std::find(voice_channels_.begin(), voice_channels_.end(), voice_channel);
4785 RTC_DCHECK(it != voice_channels_.end());
4786 if (it == voice_channels_.end()) {
4787 return;
4788 }
4789 voice_channels_.erase(it);
4790 DestroyVoiceChannel(voice_channel);
4791}
4792
4793void PeerConnection::DestroyVoiceChannel(cricket::VoiceChannel* voice_channel) {
Steve Antond25da372017-11-06 14:50:29 -08004794 SetChannelOnSendersAndReceivers<AudioRtpSender, AudioRtpReceiver,
4795 cricket::VoiceChannel>(
4796 nullptr, senders_, receivers_, cricket::MEDIA_TYPE_AUDIO);
Steve Anton75737c02017-11-06 10:37:17 -08004797 RTC_DCHECK(voice_channel->rtp_dtls_transport());
4798 const std::string transport_name =
4799 voice_channel->rtp_dtls_transport()->transport_name();
4800 const bool need_to_delete_rtcp =
4801 (voice_channel->rtcp_dtls_transport() != nullptr);
4802 // The above need to be cached before destroying the video channel so that we
4803 // do not access uninitialized memory.
4804 channel_manager()->DestroyVoiceChannel(voice_channel);
4805 transport_controller_->DestroyDtlsTransport(
4806 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4807 if (need_to_delete_rtcp) {
4808 transport_controller_->DestroyDtlsTransport(
4809 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4810 }
4811}
4812
4813void PeerConnection::DestroyDataChannel() {
4814 OnDataChannelDestroyed();
4815 RTC_DCHECK(rtp_data_channel_->rtp_dtls_transport());
4816 std::string transport_name;
4817 transport_name = rtp_data_channel_->rtp_dtls_transport()->transport_name();
4818 bool need_to_delete_rtcp =
4819 (rtp_data_channel_->rtcp_dtls_transport() != nullptr);
4820 channel_manager()->DestroyRtpDataChannel(rtp_data_channel_);
4821 rtp_data_channel_ = nullptr;
4822 transport_controller_->DestroyDtlsTransport(
4823 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTP);
4824 if (need_to_delete_rtcp) {
4825 transport_controller_->DestroyDtlsTransport(
4826 transport_name, cricket::ICE_CANDIDATE_COMPONENT_RTCP);
4827 }
4828}
4829
henrike@webrtc.org28e20752013-07-10 00:45:36 +00004830} // namespace webrtc